models.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. from itertools import count, groupby
  4. from mptt.models import MPTTModel, TreeForeignKey
  5. from django.conf import settings
  6. from django.contrib.auth.models import User
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.contenttypes.fields import GenericRelation
  9. from django.contrib.postgres.fields import ArrayField
  10. from django.core.exceptions import ValidationError
  11. from django.core.validators import MaxValueValidator, MinValueValidator
  12. from django.db import models
  13. from django.db.models import Count, Q, ObjectDoesNotExist
  14. from django.db.models.expressions import RawSQL
  15. from django.urls import reverse
  16. from django.utils.encoding import python_2_unicode_compatible
  17. from circuits.models import Circuit
  18. from extras.models import CustomFieldModel, CustomField, CustomFieldValue, ImageAttachment
  19. from extras.rpc import RPC_CLIENTS
  20. from tenancy.models import Tenant
  21. from utilities.fields import ColorField, NullableCharField
  22. from utilities.managers import NaturalOrderByManager
  23. from utilities.models import CreatedUpdatedModel
  24. from utilities.utils import csv_format
  25. from .constants import *
  26. from .fields import ASNField, MACAddressField
  27. #
  28. # Regions
  29. #
  30. @python_2_unicode_compatible
  31. class Region(MPTTModel):
  32. """
  33. Sites can be grouped within geographic Regions.
  34. """
  35. parent = TreeForeignKey(
  36. 'self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE
  37. )
  38. name = models.CharField(max_length=50, unique=True)
  39. slug = models.SlugField(unique=True)
  40. csv_headers = [
  41. 'name', 'slug', 'parent',
  42. ]
  43. class MPTTMeta:
  44. order_insertion_by = ['name']
  45. def __str__(self):
  46. return self.name
  47. def get_absolute_url(self):
  48. return "{}?region={}".format(reverse('dcim:site_list'), self.slug)
  49. def to_csv(self):
  50. return csv_format([
  51. self.name,
  52. self.slug,
  53. self.parent.name if self.parent else None,
  54. ])
  55. #
  56. # Sites
  57. #
  58. class SiteManager(NaturalOrderByManager):
  59. def get_queryset(self):
  60. return self.natural_order_by('name')
  61. @python_2_unicode_compatible
  62. class Site(CreatedUpdatedModel, CustomFieldModel):
  63. """
  64. A Site represents a geographic location within a network; typically a building or campus. The optional facility
  65. field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
  66. """
  67. name = models.CharField(max_length=50, unique=True)
  68. slug = models.SlugField(unique=True)
  69. region = models.ForeignKey('Region', related_name='sites', blank=True, null=True, on_delete=models.SET_NULL)
  70. tenant = models.ForeignKey(Tenant, related_name='sites', blank=True, null=True, on_delete=models.PROTECT)
  71. facility = models.CharField(max_length=50, blank=True)
  72. asn = ASNField(blank=True, null=True, verbose_name='ASN')
  73. physical_address = models.CharField(max_length=200, blank=True)
  74. shipping_address = models.CharField(max_length=200, blank=True)
  75. contact_name = models.CharField(max_length=50, blank=True)
  76. contact_phone = models.CharField(max_length=20, blank=True)
  77. contact_email = models.EmailField(blank=True, verbose_name="Contact E-mail")
  78. comments = models.TextField(blank=True)
  79. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  80. images = GenericRelation(ImageAttachment)
  81. objects = SiteManager()
  82. csv_headers = [
  83. 'name', 'slug', 'region', 'tenant', 'facility', 'asn', 'contact_name', 'contact_phone', 'contact_email',
  84. ]
  85. class Meta:
  86. ordering = ['name']
  87. def __str__(self):
  88. return self.name
  89. def get_absolute_url(self):
  90. return reverse('dcim:site', args=[self.slug])
  91. def to_csv(self):
  92. return csv_format([
  93. self.name,
  94. self.slug,
  95. self.region.name if self.region else None,
  96. self.tenant.name if self.tenant else None,
  97. self.facility,
  98. self.asn,
  99. self.contact_name,
  100. self.contact_phone,
  101. self.contact_email,
  102. ])
  103. @property
  104. def count_prefixes(self):
  105. return self.prefixes.count()
  106. @property
  107. def count_vlans(self):
  108. return self.vlans.count()
  109. @property
  110. def count_racks(self):
  111. return Rack.objects.filter(site=self).count()
  112. @property
  113. def count_devices(self):
  114. return Device.objects.filter(site=self).count()
  115. @property
  116. def count_circuits(self):
  117. return Circuit.objects.filter(terminations__site=self).count()
  118. #
  119. # Racks
  120. #
  121. @python_2_unicode_compatible
  122. class RackGroup(models.Model):
  123. """
  124. Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
  125. example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
  126. campus. If a Site instead represents a single building, a RackGroup might represent a single room or floor.
  127. """
  128. name = models.CharField(max_length=50)
  129. slug = models.SlugField()
  130. site = models.ForeignKey('Site', related_name='rack_groups', on_delete=models.CASCADE)
  131. csv_headers = [
  132. 'site', 'name', 'slug',
  133. ]
  134. class Meta:
  135. ordering = ['site', 'name']
  136. unique_together = [
  137. ['site', 'name'],
  138. ['site', 'slug'],
  139. ]
  140. def __str__(self):
  141. return self.name
  142. def get_absolute_url(self):
  143. return "{}?group_id={}".format(reverse('dcim:rack_list'), self.pk)
  144. def to_csv(self):
  145. return csv_format([
  146. self.site,
  147. self.name,
  148. self.slug,
  149. ])
  150. @python_2_unicode_compatible
  151. class RackRole(models.Model):
  152. """
  153. Racks can be organized by functional role, similar to Devices.
  154. """
  155. name = models.CharField(max_length=50, unique=True)
  156. slug = models.SlugField(unique=True)
  157. color = ColorField()
  158. class Meta:
  159. ordering = ['name']
  160. def __str__(self):
  161. return self.name
  162. def get_absolute_url(self):
  163. return "{}?role={}".format(reverse('dcim:rack_list'), self.slug)
  164. class RackManager(NaturalOrderByManager):
  165. def get_queryset(self):
  166. return self.natural_order_by('site__name', 'name')
  167. @python_2_unicode_compatible
  168. class Rack(CreatedUpdatedModel, CustomFieldModel):
  169. """
  170. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  171. Each Rack is assigned to a Site and (optionally) a RackGroup.
  172. """
  173. name = models.CharField(max_length=50)
  174. facility_id = NullableCharField(max_length=50, blank=True, null=True, verbose_name='Facility ID')
  175. site = models.ForeignKey('Site', related_name='racks', on_delete=models.PROTECT)
  176. group = models.ForeignKey('RackGroup', related_name='racks', blank=True, null=True, on_delete=models.SET_NULL)
  177. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='racks', on_delete=models.PROTECT)
  178. role = models.ForeignKey('RackRole', related_name='racks', blank=True, null=True, on_delete=models.PROTECT)
  179. type = models.PositiveSmallIntegerField(choices=RACK_TYPE_CHOICES, blank=True, null=True, verbose_name='Type')
  180. width = models.PositiveSmallIntegerField(choices=RACK_WIDTH_CHOICES, default=RACK_WIDTH_19IN, verbose_name='Width',
  181. help_text='Rail-to-rail width')
  182. u_height = models.PositiveSmallIntegerField(default=42, verbose_name='Height (U)',
  183. validators=[MinValueValidator(1), MaxValueValidator(100)])
  184. desc_units = models.BooleanField(default=False, verbose_name='Descending units',
  185. help_text='Units are numbered top-to-bottom')
  186. comments = models.TextField(blank=True)
  187. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  188. images = GenericRelation(ImageAttachment)
  189. objects = RackManager()
  190. csv_headers = [
  191. 'site', 'group_name', 'name', 'facility_id', 'tenant', 'role', 'type', 'width', 'u_height', 'desc_units',
  192. ]
  193. class Meta:
  194. ordering = ['site', 'name']
  195. unique_together = [
  196. ['site', 'name'],
  197. ['site', 'facility_id'],
  198. ]
  199. def __str__(self):
  200. return self.display_name or super(Rack, self).__str__()
  201. def get_absolute_url(self):
  202. return reverse('dcim:rack', args=[self.pk])
  203. def clean(self):
  204. # Validate that Rack is tall enough to house the installed Devices
  205. if self.pk:
  206. top_device = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('-position').first()
  207. if top_device:
  208. min_height = top_device.position + top_device.device_type.u_height - 1
  209. if self.u_height < min_height:
  210. raise ValidationError({
  211. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  212. min_height
  213. )
  214. })
  215. def save(self, *args, **kwargs):
  216. # Record the original site assignment for this rack.
  217. _site_id = None
  218. if self.pk:
  219. _site_id = Rack.objects.get(pk=self.pk).site_id
  220. super(Rack, self).save(*args, **kwargs)
  221. # Update racked devices if the assigned Site has been changed.
  222. if _site_id is not None and self.site_id != _site_id:
  223. Device.objects.filter(rack=self).update(site_id=self.site.pk)
  224. def to_csv(self):
  225. return csv_format([
  226. self.site.name,
  227. self.group.name if self.group else None,
  228. self.name,
  229. self.facility_id,
  230. self.tenant.name if self.tenant else None,
  231. self.role.name if self.role else None,
  232. self.get_type_display() if self.type else None,
  233. self.width,
  234. self.u_height,
  235. self.desc_units,
  236. ])
  237. @property
  238. def units(self):
  239. if self.desc_units:
  240. return range(1, self.u_height + 1)
  241. else:
  242. return reversed(range(1, self.u_height + 1))
  243. @property
  244. def display_name(self):
  245. if self.facility_id:
  246. return "{} ({})".format(self.name, self.facility_id)
  247. elif self.name:
  248. return self.name
  249. return ""
  250. def get_rack_units(self, face=RACK_FACE_FRONT, exclude=None, remove_redundant=False):
  251. """
  252. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  253. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  254. :param face: Rack face (front or rear)
  255. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  256. :param remove_redundant: If True, rack units occupied by a device already listed will be omitted
  257. """
  258. elevation = OrderedDict()
  259. for u in self.units:
  260. elevation[u] = {'id': u, 'name': 'U{}'.format(u), 'face': face, 'device': None}
  261. # Add devices to rack units list
  262. if self.pk:
  263. for device in Device.objects.select_related('device_type__manufacturer', 'device_role')\
  264. .annotate(devicebay_count=Count('device_bays'))\
  265. .exclude(pk=exclude)\
  266. .filter(rack=self, position__gt=0)\
  267. .filter(Q(face=face) | Q(device_type__is_full_depth=True)):
  268. if remove_redundant:
  269. elevation[device.position]['device'] = device
  270. for u in range(device.position + 1, device.position + device.device_type.u_height):
  271. elevation.pop(u, None)
  272. else:
  273. for u in range(device.position, device.position + device.device_type.u_height):
  274. elevation[u]['device'] = device
  275. return [u for u in elevation.values()]
  276. def get_front_elevation(self):
  277. return self.get_rack_units(face=RACK_FACE_FRONT, remove_redundant=True)
  278. def get_rear_elevation(self):
  279. return self.get_rack_units(face=RACK_FACE_REAR, remove_redundant=True)
  280. def get_available_units(self, u_height=1, rack_face=None, exclude=list()):
  281. """
  282. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  283. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  284. position to another within a rack).
  285. :param u_height: Minimum number of contiguous free units required
  286. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  287. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  288. """
  289. # Gather all devices which consume U space within the rack
  290. devices = self.devices.select_related('device_type').filter(position__gte=1).exclude(pk__in=exclude)
  291. # Initialize the rack unit skeleton
  292. units = list(range(1, self.u_height + 1))
  293. # Remove units consumed by installed devices
  294. for d in devices:
  295. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  296. for u in range(d.position, d.position + d.device_type.u_height):
  297. try:
  298. units.remove(u)
  299. except ValueError:
  300. # Found overlapping devices in the rack!
  301. pass
  302. # Remove units without enough space above them to accommodate a device of the specified height
  303. available_units = []
  304. for u in units:
  305. if set(range(u, u + u_height)).issubset(units):
  306. available_units.append(u)
  307. return list(reversed(available_units))
  308. def get_reserved_units(self):
  309. """
  310. Return a dictionary mapping all reserved units within the rack to their reservation.
  311. """
  312. reserved_units = {}
  313. for r in self.reservations.all():
  314. for u in r.units:
  315. reserved_units[u] = r
  316. return reserved_units
  317. def get_0u_devices(self):
  318. return self.devices.filter(position=0)
  319. def get_utilization(self):
  320. """
  321. Determine the utilization rate of the rack and return it as a percentage.
  322. """
  323. u_available = len(self.get_available_units())
  324. return int(float(self.u_height - u_available) / self.u_height * 100)
  325. @python_2_unicode_compatible
  326. class RackReservation(models.Model):
  327. """
  328. One or more reserved units within a Rack.
  329. """
  330. rack = models.ForeignKey('Rack', related_name='reservations', on_delete=models.CASCADE)
  331. units = ArrayField(models.PositiveSmallIntegerField())
  332. created = models.DateTimeField(auto_now_add=True)
  333. user = models.ForeignKey(User, editable=False, on_delete=models.PROTECT)
  334. description = models.CharField(max_length=100)
  335. class Meta:
  336. ordering = ['created']
  337. def __str__(self):
  338. return "Reservation for rack {}".format(self.rack)
  339. def clean(self):
  340. if self.units:
  341. # Validate that all specified units exist in the Rack.
  342. invalid_units = [u for u in self.units if u not in self.rack.units]
  343. if invalid_units:
  344. raise ValidationError({
  345. 'units': "Invalid unit(s) for {}U rack: {}".format(
  346. self.rack.u_height,
  347. ', '.join([str(u) for u in invalid_units]),
  348. ),
  349. })
  350. # Check that none of the units has already been reserved for this Rack.
  351. reserved_units = []
  352. for resv in self.rack.reservations.exclude(pk=self.pk):
  353. reserved_units += resv.units
  354. conflicting_units = [u for u in self.units if u in reserved_units]
  355. if conflicting_units:
  356. raise ValidationError({
  357. 'units': 'The following units have already been reserved: {}'.format(
  358. ', '.join([str(u) for u in conflicting_units]),
  359. )
  360. })
  361. @property
  362. def unit_list(self):
  363. """
  364. Express the assigned units as a string of summarized ranges. For example:
  365. [0, 1, 2, 10, 14, 15, 16] => "0-2, 10, 14-16"
  366. """
  367. group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x))
  368. return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group)
  369. #
  370. # Device Types
  371. #
  372. @python_2_unicode_compatible
  373. class Manufacturer(models.Model):
  374. """
  375. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  376. """
  377. name = models.CharField(max_length=50, unique=True)
  378. slug = models.SlugField(unique=True)
  379. csv_headers = [
  380. 'name', 'slug',
  381. ]
  382. class Meta:
  383. ordering = ['name']
  384. def __str__(self):
  385. return self.name
  386. def get_absolute_url(self):
  387. return "{}?manufacturer={}".format(reverse('dcim:devicetype_list'), self.slug)
  388. def to_csv(self):
  389. return csv_format([
  390. self.name,
  391. self.slug,
  392. ])
  393. @python_2_unicode_compatible
  394. class DeviceType(models.Model, CustomFieldModel):
  395. """
  396. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  397. well as high-level functional role(s).
  398. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  399. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  400. * 1 ConsolePortTemplate
  401. * 2 PowerPortTemplates
  402. * 48 InterfaceTemplates
  403. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  404. DeviceType) are automatically created as well.
  405. """
  406. manufacturer = models.ForeignKey('Manufacturer', related_name='device_types', on_delete=models.PROTECT)
  407. model = models.CharField(max_length=50)
  408. slug = models.SlugField()
  409. part_number = models.CharField(max_length=50, blank=True, help_text="Discrete part number (optional)")
  410. u_height = models.PositiveSmallIntegerField(verbose_name='Height (U)', default=1)
  411. is_full_depth = models.BooleanField(default=True, verbose_name="Is full depth",
  412. help_text="Device consumes both front and rear rack faces")
  413. interface_ordering = models.PositiveSmallIntegerField(choices=IFACE_ORDERING_CHOICES,
  414. default=IFACE_ORDERING_POSITION)
  415. is_console_server = models.BooleanField(default=False, verbose_name='Is a console server',
  416. help_text="This type of device has console server ports")
  417. is_pdu = models.BooleanField(default=False, verbose_name='Is a PDU',
  418. help_text="This type of device has power outlets")
  419. is_network_device = models.BooleanField(default=True, verbose_name='Is a network device',
  420. help_text="This type of device has network interfaces")
  421. subdevice_role = models.NullBooleanField(default=None, verbose_name='Parent/child status',
  422. choices=SUBDEVICE_ROLE_CHOICES,
  423. help_text="Parent devices house child devices in device bays. Select "
  424. "\"None\" if this device type is neither a parent nor a child.")
  425. comments = models.TextField(blank=True)
  426. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  427. csv_headers = [
  428. 'manufacturer', 'model', 'slug', 'part_number', 'u_height', 'is_full_depth', 'is_console_server',
  429. 'is_pdu', 'is_network_device', 'subdevice_role', 'interface_ordering',
  430. ]
  431. class Meta:
  432. ordering = ['manufacturer', 'model']
  433. unique_together = [
  434. ['manufacturer', 'model'],
  435. ['manufacturer', 'slug'],
  436. ]
  437. def __str__(self):
  438. return self.model
  439. def __init__(self, *args, **kwargs):
  440. super(DeviceType, self).__init__(*args, **kwargs)
  441. # Save a copy of u_height for validation in clean()
  442. self._original_u_height = self.u_height
  443. def get_absolute_url(self):
  444. return reverse('dcim:devicetype', args=[self.pk])
  445. def to_csv(self):
  446. return csv_format([
  447. self.manufacturer.name,
  448. self.model,
  449. self.slug,
  450. self.part_number,
  451. self.u_height,
  452. self.is_full_depth,
  453. self.is_console_server,
  454. self.is_pdu,
  455. self.is_network_device,
  456. self.get_subdevice_role_display() if self.subdevice_role else None,
  457. self.get_interface_ordering_display(),
  458. ])
  459. def clean(self):
  460. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  461. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  462. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  463. if self.pk is not None and self.u_height > self._original_u_height:
  464. for d in Device.objects.filter(device_type=self, position__isnull=False):
  465. face_required = None if self.is_full_depth else d.face
  466. u_available = d.rack.get_available_units(u_height=self.u_height, rack_face=face_required,
  467. exclude=[d.pk])
  468. if d.position not in u_available:
  469. raise ValidationError({
  470. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  471. "{}U".format(d, d.rack, self.u_height)
  472. })
  473. if not self.is_console_server and self.cs_port_templates.count():
  474. raise ValidationError({
  475. 'is_console_server': "Must delete all console server port templates associated with this device before "
  476. "declassifying it as a console server."
  477. })
  478. if not self.is_pdu and self.power_outlet_templates.count():
  479. raise ValidationError({
  480. 'is_pdu': "Must delete all power outlet templates associated with this device before declassifying it "
  481. "as a PDU."
  482. })
  483. if not self.is_network_device and self.interface_templates.filter(mgmt_only=False).count():
  484. raise ValidationError({
  485. 'is_network_device': "Must delete all non-management-only interface templates associated with this "
  486. "device before declassifying it as a network device."
  487. })
  488. if self.subdevice_role != SUBDEVICE_ROLE_PARENT and self.device_bay_templates.count():
  489. raise ValidationError({
  490. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  491. "declassifying it as a parent device."
  492. })
  493. if self.u_height and self.subdevice_role == SUBDEVICE_ROLE_CHILD:
  494. raise ValidationError({
  495. 'u_height': "Child device types must be 0U."
  496. })
  497. @property
  498. def full_name(self):
  499. return '{} {}'.format(self.manufacturer.name, self.model)
  500. @property
  501. def is_parent_device(self):
  502. return bool(self.subdevice_role)
  503. @property
  504. def is_child_device(self):
  505. return bool(self.subdevice_role is False)
  506. @python_2_unicode_compatible
  507. class ConsolePortTemplate(models.Model):
  508. """
  509. A template for a ConsolePort to be created for a new Device.
  510. """
  511. device_type = models.ForeignKey('DeviceType', related_name='console_port_templates', on_delete=models.CASCADE)
  512. name = models.CharField(max_length=50)
  513. class Meta:
  514. ordering = ['device_type', 'name']
  515. unique_together = ['device_type', 'name']
  516. def __str__(self):
  517. return self.name
  518. @python_2_unicode_compatible
  519. class ConsoleServerPortTemplate(models.Model):
  520. """
  521. A template for a ConsoleServerPort to be created for a new Device.
  522. """
  523. device_type = models.ForeignKey('DeviceType', related_name='cs_port_templates', on_delete=models.CASCADE)
  524. name = models.CharField(max_length=50)
  525. class Meta:
  526. ordering = ['device_type', 'name']
  527. unique_together = ['device_type', 'name']
  528. def __str__(self):
  529. return self.name
  530. @python_2_unicode_compatible
  531. class PowerPortTemplate(models.Model):
  532. """
  533. A template for a PowerPort to be created for a new Device.
  534. """
  535. device_type = models.ForeignKey('DeviceType', related_name='power_port_templates', on_delete=models.CASCADE)
  536. name = models.CharField(max_length=50)
  537. class Meta:
  538. ordering = ['device_type', 'name']
  539. unique_together = ['device_type', 'name']
  540. def __str__(self):
  541. return self.name
  542. @python_2_unicode_compatible
  543. class PowerOutletTemplate(models.Model):
  544. """
  545. A template for a PowerOutlet to be created for a new Device.
  546. """
  547. device_type = models.ForeignKey('DeviceType', related_name='power_outlet_templates', on_delete=models.CASCADE)
  548. name = models.CharField(max_length=50)
  549. class Meta:
  550. ordering = ['device_type', 'name']
  551. unique_together = ['device_type', 'name']
  552. def __str__(self):
  553. return self.name
  554. class InterfaceQuerySet(models.QuerySet):
  555. def order_naturally(self, method=IFACE_ORDERING_POSITION):
  556. """
  557. Naturally order interfaces by their type and numeric position. The sort method must be one of the defined
  558. IFACE_ORDERING_CHOICES (typically indicated by a parent Device's DeviceType).
  559. To order interfaces naturally, the `name` field is split into six distinct components: leading text (type),
  560. slot, subslot, position, channel, and virtual circuit:
  561. {type}{slot}/{subslot}/{position}/{subposition}:{channel}.{vc}
  562. Components absent from the interface name are ignored. For example, an interface named GigabitEthernet1/2/3
  563. would be parsed as follows:
  564. name = 'GigabitEthernet'
  565. slot = 1
  566. subslot = 2
  567. position = 3
  568. subposition = 0
  569. channel = None
  570. vc = 0
  571. The original `name` field is taken as a whole to serve as a fallback in the event interfaces do not match any of
  572. the prescribed fields.
  573. """
  574. sql_col = '{}.name'.format(self.model._meta.db_table)
  575. ordering = {
  576. IFACE_ORDERING_POSITION: (
  577. '_slot', '_subslot', '_position', '_subposition', '_channel', '_vc', '_type', '_id', 'name',
  578. ),
  579. IFACE_ORDERING_NAME: (
  580. '_type', '_slot', '_subslot', '_position', '_subposition', '_channel', '_vc', '_id', 'name',
  581. ),
  582. }[method]
  583. TYPE_RE = r"SUBSTRING({} FROM '^([^0-9]+)')"
  584. ID_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9]+)([0-9]+)$') AS integer)"
  585. SLOT_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9]+)([0-9]+)\/') AS integer)"
  586. SUBSLOT_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9]+)(?:[0-9]+\/)([0-9]+)') AS integer)"
  587. POSITION_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9]+)(?:[0-9]+\/){{2}}([0-9]+)') AS integer)"
  588. SUBPOSITION_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9]+)(?:[0-9]+\/){{3}}([0-9]+)') AS integer)"
  589. CHANNEL_RE = r"COALESCE(CAST(SUBSTRING({} FROM ':([0-9]+)(\.[0-9]+)?$') AS integer), 0)"
  590. VC_RE = r"COALESCE(CAST(SUBSTRING({} FROM '\.([0-9]+)$') AS integer), 0)"
  591. fields = {
  592. '_type': RawSQL(TYPE_RE.format(sql_col), []),
  593. '_id': RawSQL(ID_RE.format(sql_col), []),
  594. '_slot': RawSQL(SLOT_RE.format(sql_col), []),
  595. '_subslot': RawSQL(SUBSLOT_RE.format(sql_col), []),
  596. '_position': RawSQL(POSITION_RE.format(sql_col), []),
  597. '_subposition': RawSQL(SUBPOSITION_RE.format(sql_col), []),
  598. '_channel': RawSQL(CHANNEL_RE.format(sql_col), []),
  599. '_vc': RawSQL(VC_RE.format(sql_col), []),
  600. }
  601. return self.annotate(**fields).order_by(*ordering)
  602. def connectable(self):
  603. """
  604. Return only physical interfaces which are capable of being connected to other interfaces (i.e. not virtual or
  605. wireless).
  606. """
  607. return self.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES)
  608. @python_2_unicode_compatible
  609. class InterfaceTemplate(models.Model):
  610. """
  611. A template for a physical data interface on a new Device.
  612. """
  613. device_type = models.ForeignKey('DeviceType', related_name='interface_templates', on_delete=models.CASCADE)
  614. name = models.CharField(max_length=64)
  615. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_10GE_SFP_PLUS)
  616. mgmt_only = models.BooleanField(default=False, verbose_name='Management only')
  617. objects = InterfaceQuerySet.as_manager()
  618. class Meta:
  619. ordering = ['device_type', 'name']
  620. unique_together = ['device_type', 'name']
  621. def __str__(self):
  622. return self.name
  623. @python_2_unicode_compatible
  624. class DeviceBayTemplate(models.Model):
  625. """
  626. A template for a DeviceBay to be created for a new parent Device.
  627. """
  628. device_type = models.ForeignKey('DeviceType', related_name='device_bay_templates', on_delete=models.CASCADE)
  629. name = models.CharField(max_length=50)
  630. class Meta:
  631. ordering = ['device_type', 'name']
  632. unique_together = ['device_type', 'name']
  633. def __str__(self):
  634. return self.name
  635. #
  636. # Devices
  637. #
  638. @python_2_unicode_compatible
  639. class DeviceRole(models.Model):
  640. """
  641. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  642. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  643. virtual machines as well.
  644. """
  645. name = models.CharField(max_length=50, unique=True)
  646. slug = models.SlugField(unique=True)
  647. color = ColorField()
  648. vm_role = models.BooleanField(
  649. default=True,
  650. verbose_name="VM Role",
  651. help_text="Virtual machines may be assigned to this role"
  652. )
  653. class Meta:
  654. ordering = ['name']
  655. def __str__(self):
  656. return self.name
  657. def get_absolute_url(self):
  658. return "{}?role={}".format(reverse('dcim:device_list'), self.slug)
  659. @python_2_unicode_compatible
  660. class Platform(models.Model):
  661. """
  662. Platform refers to the software or firmware running on a Device; for example, "Cisco IOS-XR" or "Juniper Junos".
  663. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  664. specifying an remote procedure call (RPC) client.
  665. """
  666. name = models.CharField(max_length=50, unique=True)
  667. slug = models.SlugField(unique=True)
  668. napalm_driver = models.CharField(max_length=50, blank=True, verbose_name='NAPALM driver',
  669. help_text="The name of the NAPALM driver to use when interacting with devices.")
  670. rpc_client = models.CharField(max_length=30, choices=RPC_CLIENT_CHOICES, blank=True,
  671. verbose_name='Legacy RPC client')
  672. class Meta:
  673. ordering = ['name']
  674. def __str__(self):
  675. return self.name
  676. def get_absolute_url(self):
  677. return "{}?platform={}".format(reverse('dcim:device_list'), self.slug)
  678. class DeviceManager(NaturalOrderByManager):
  679. def get_queryset(self):
  680. return self.natural_order_by('name')
  681. @python_2_unicode_compatible
  682. class Device(CreatedUpdatedModel, CustomFieldModel):
  683. """
  684. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  685. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  686. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  687. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  688. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  689. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  690. creation of a Device.
  691. """
  692. device_type = models.ForeignKey('DeviceType', related_name='instances', on_delete=models.PROTECT)
  693. device_role = models.ForeignKey('DeviceRole', related_name='devices', on_delete=models.PROTECT)
  694. tenant = models.ForeignKey(Tenant, blank=True, null=True, related_name='devices', on_delete=models.PROTECT)
  695. platform = models.ForeignKey('Platform', related_name='devices', blank=True, null=True, on_delete=models.SET_NULL)
  696. name = NullableCharField(max_length=64, blank=True, null=True, unique=True)
  697. serial = models.CharField(max_length=50, blank=True, verbose_name='Serial number')
  698. asset_tag = NullableCharField(
  699. max_length=50, blank=True, null=True, unique=True, verbose_name='Asset tag',
  700. help_text='A unique tag used to identify this device'
  701. )
  702. site = models.ForeignKey('Site', related_name='devices', on_delete=models.PROTECT)
  703. rack = models.ForeignKey('Rack', related_name='devices', blank=True, null=True, on_delete=models.PROTECT)
  704. position = models.PositiveSmallIntegerField(
  705. blank=True, null=True, validators=[MinValueValidator(1)], verbose_name='Position (U)',
  706. help_text='The lowest-numbered unit occupied by the device'
  707. )
  708. face = models.PositiveSmallIntegerField(blank=True, null=True, choices=RACK_FACE_CHOICES, verbose_name='Rack face')
  709. status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=STATUS_ACTIVE, verbose_name='Status')
  710. primary_ip4 = models.OneToOneField(
  711. 'ipam.IPAddress', related_name='primary_ip4_for', on_delete=models.SET_NULL, blank=True, null=True,
  712. verbose_name='Primary IPv4'
  713. )
  714. primary_ip6 = models.OneToOneField(
  715. 'ipam.IPAddress', related_name='primary_ip6_for', on_delete=models.SET_NULL, blank=True, null=True,
  716. verbose_name='Primary IPv6'
  717. )
  718. cluster = models.ForeignKey(
  719. to='virtualization.Cluster',
  720. on_delete=models.SET_NULL,
  721. related_name='devices',
  722. blank=True,
  723. null=True
  724. )
  725. comments = models.TextField(blank=True)
  726. custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id')
  727. images = GenericRelation(ImageAttachment)
  728. objects = DeviceManager()
  729. csv_headers = [
  730. 'name', 'device_role', 'tenant', 'manufacturer', 'model_name', 'platform', 'serial', 'asset_tag', 'status',
  731. 'site', 'rack_group', 'rack_name', 'position', 'face',
  732. ]
  733. class Meta:
  734. ordering = ['name']
  735. unique_together = ['rack', 'position', 'face']
  736. permissions = (
  737. ('napalm_read', 'Read-only access to devices via NAPALM'),
  738. ('napalm_write', 'Read/write access to devices via NAPALM'),
  739. )
  740. def __str__(self):
  741. return self.display_name or super(Device, self).__str__()
  742. def get_absolute_url(self):
  743. return reverse('dcim:device', args=[self.pk])
  744. def clean(self):
  745. # Validate site/rack combination
  746. if self.rack and self.site != self.rack.site:
  747. raise ValidationError({
  748. 'rack': "Rack {} does not belong to site {}.".format(self.rack, self.site),
  749. })
  750. if self.rack is None:
  751. if self.face is not None:
  752. raise ValidationError({
  753. 'face': "Cannot select a rack face without assigning a rack.",
  754. })
  755. if self.position:
  756. raise ValidationError({
  757. 'face': "Cannot select a rack position without assigning a rack.",
  758. })
  759. # Validate position/face combination
  760. if self.position and self.face is None:
  761. raise ValidationError({
  762. 'face': "Must specify rack face when defining rack position.",
  763. })
  764. if self.rack:
  765. try:
  766. # Child devices cannot be assigned to a rack face/unit
  767. if self.device_type.is_child_device and self.face is not None:
  768. raise ValidationError({
  769. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  770. "parent device."
  771. })
  772. if self.device_type.is_child_device and self.position:
  773. raise ValidationError({
  774. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  775. "the parent device."
  776. })
  777. # Validate rack space
  778. rack_face = self.face if not self.device_type.is_full_depth else None
  779. exclude_list = [self.pk] if self.pk else []
  780. try:
  781. available_units = self.rack.get_available_units(
  782. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  783. )
  784. if self.position and self.position not in available_units:
  785. raise ValidationError({
  786. 'position': "U{} is already occupied or does not have sufficient space to accommodate a(n) "
  787. "{} ({}U).".format(self.position, self.device_type, self.device_type.u_height)
  788. })
  789. except Rack.DoesNotExist:
  790. pass
  791. except DeviceType.DoesNotExist:
  792. pass
  793. # Validate primary IPv4 address
  794. if self.primary_ip4 and (
  795. self.primary_ip4.interface is None or
  796. self.primary_ip4.interface.device != self
  797. ) and (
  798. self.primary_ip4.nat_inside.interface is None or
  799. self.primary_ip4.nat_inside.interface.device != self
  800. ):
  801. raise ValidationError({
  802. 'primary_ip4': "The specified IP address ({}) is not assigned to this device.".format(self.primary_ip4),
  803. })
  804. # Validate primary IPv6 address
  805. if self.primary_ip6 and (
  806. self.primary_ip6.interface is None or
  807. self.primary_ip6.interface.device != self
  808. ) and (
  809. self.primary_ip6.nat_inside.interface is None or
  810. self.primary_ip6.nat_inside.interface.device != self
  811. ):
  812. raise ValidationError({
  813. 'primary_ip6': "The specified IP address ({}) is not assigned to this device.".format(self.primary_ip6),
  814. })
  815. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  816. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  817. raise ValidationError({
  818. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  819. })
  820. def save(self, *args, **kwargs):
  821. is_new = not bool(self.pk)
  822. super(Device, self).save(*args, **kwargs)
  823. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  824. if is_new:
  825. ConsolePort.objects.bulk_create(
  826. [ConsolePort(device=self, name=template.name) for template in
  827. self.device_type.console_port_templates.all()]
  828. )
  829. ConsoleServerPort.objects.bulk_create(
  830. [ConsoleServerPort(device=self, name=template.name) for template in
  831. self.device_type.cs_port_templates.all()]
  832. )
  833. PowerPort.objects.bulk_create(
  834. [PowerPort(device=self, name=template.name) for template in
  835. self.device_type.power_port_templates.all()]
  836. )
  837. PowerOutlet.objects.bulk_create(
  838. [PowerOutlet(device=self, name=template.name) for template in
  839. self.device_type.power_outlet_templates.all()]
  840. )
  841. Interface.objects.bulk_create(
  842. [Interface(device=self, name=template.name, form_factor=template.form_factor,
  843. mgmt_only=template.mgmt_only) for template in self.device_type.interface_templates.all()]
  844. )
  845. DeviceBay.objects.bulk_create(
  846. [DeviceBay(device=self, name=template.name) for template in
  847. self.device_type.device_bay_templates.all()]
  848. )
  849. # Update Site and Rack assignment for any child Devices
  850. Device.objects.filter(parent_bay__device=self).update(site=self.site, rack=self.rack)
  851. def to_csv(self):
  852. return csv_format([
  853. self.name or '',
  854. self.device_role.name,
  855. self.tenant.name if self.tenant else None,
  856. self.device_type.manufacturer.name,
  857. self.device_type.model,
  858. self.platform.name if self.platform else None,
  859. self.serial,
  860. self.asset_tag,
  861. self.get_status_display(),
  862. self.site.name,
  863. self.rack.group.name if self.rack and self.rack.group else None,
  864. self.rack.name if self.rack else None,
  865. self.position,
  866. self.get_face_display(),
  867. ])
  868. @property
  869. def display_name(self):
  870. if self.name:
  871. return self.name
  872. elif hasattr(self, 'device_type'):
  873. return "{}".format(self.device_type)
  874. return ""
  875. @property
  876. def identifier(self):
  877. """
  878. Return the device name if set; otherwise return the Device's primary key as {pk}
  879. """
  880. if self.name is not None:
  881. return self.name
  882. return '{{{}}}'.format(self.pk)
  883. @property
  884. def primary_ip(self):
  885. if settings.PREFER_IPV4 and self.primary_ip4:
  886. return self.primary_ip4
  887. elif self.primary_ip6:
  888. return self.primary_ip6
  889. elif self.primary_ip4:
  890. return self.primary_ip4
  891. else:
  892. return None
  893. def get_children(self):
  894. """
  895. Return the set of child Devices installed in DeviceBays within this Device.
  896. """
  897. return Device.objects.filter(parent_bay__device=self.pk)
  898. def get_status_class(self):
  899. return DEVICE_STATUS_CLASSES[self.status]
  900. def get_rpc_client(self):
  901. """
  902. Return the appropriate RPC (e.g. NETCONF, ssh, etc.) client for this device's platform, if one is defined.
  903. """
  904. if not self.platform:
  905. return None
  906. return RPC_CLIENTS.get(self.platform.rpc_client)
  907. #
  908. # Console ports
  909. #
  910. @python_2_unicode_compatible
  911. class ConsolePort(models.Model):
  912. """
  913. A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
  914. """
  915. device = models.ForeignKey('Device', related_name='console_ports', on_delete=models.CASCADE)
  916. name = models.CharField(max_length=50)
  917. cs_port = models.OneToOneField('ConsoleServerPort', related_name='connected_console', on_delete=models.SET_NULL,
  918. verbose_name='Console server port', blank=True, null=True)
  919. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  920. csv_headers = ['console_server', 'cs_port', 'device', 'console_port', 'connection_status']
  921. class Meta:
  922. ordering = ['device', 'name']
  923. unique_together = ['device', 'name']
  924. def __str__(self):
  925. return self.name
  926. # Used for connections export
  927. def to_csv(self):
  928. return csv_format([
  929. self.cs_port.device.identifier if self.cs_port else None,
  930. self.cs_port.name if self.cs_port else None,
  931. self.device.identifier,
  932. self.name,
  933. self.get_connection_status_display(),
  934. ])
  935. #
  936. # Console server ports
  937. #
  938. class ConsoleServerPortManager(models.Manager):
  939. def get_queryset(self):
  940. """
  941. Include the trailing numeric portion of each port name to allow for proper ordering.
  942. For example:
  943. Port 1, Port 2, Port 3 ... Port 9, Port 10, Port 11 ...
  944. Instead of:
  945. Port 1, Port 10, Port 11 ... Port 19, Port 2, Port 20 ...
  946. """
  947. return super(ConsoleServerPortManager, self).get_queryset().extra(select={
  948. 'name_as_integer': "CAST(substring(dcim_consoleserverport.name FROM '[0-9]+$') AS INTEGER)",
  949. }).order_by('device', 'name_as_integer')
  950. @python_2_unicode_compatible
  951. class ConsoleServerPort(models.Model):
  952. """
  953. A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
  954. """
  955. device = models.ForeignKey('Device', related_name='cs_ports', on_delete=models.CASCADE)
  956. name = models.CharField(max_length=50)
  957. objects = ConsoleServerPortManager()
  958. class Meta:
  959. unique_together = ['device', 'name']
  960. def __str__(self):
  961. return self.name
  962. #
  963. # Power ports
  964. #
  965. @python_2_unicode_compatible
  966. class PowerPort(models.Model):
  967. """
  968. A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
  969. """
  970. device = models.ForeignKey('Device', related_name='power_ports', on_delete=models.CASCADE)
  971. name = models.CharField(max_length=50)
  972. power_outlet = models.OneToOneField('PowerOutlet', related_name='connected_port', on_delete=models.SET_NULL,
  973. blank=True, null=True)
  974. connection_status = models.NullBooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED)
  975. csv_headers = ['pdu', 'power_outlet', 'device', 'power_port', 'connection_status']
  976. class Meta:
  977. ordering = ['device', 'name']
  978. unique_together = ['device', 'name']
  979. def __str__(self):
  980. return self.name
  981. # Used for connections export
  982. def to_csv(self):
  983. return csv_format([
  984. self.power_outlet.device.identifier if self.power_outlet else None,
  985. self.power_outlet.name if self.power_outlet else None,
  986. self.device.identifier,
  987. self.name,
  988. self.get_connection_status_display(),
  989. ])
  990. #
  991. # Power outlets
  992. #
  993. class PowerOutletManager(models.Manager):
  994. def get_queryset(self):
  995. return super(PowerOutletManager, self).get_queryset().extra(select={
  996. 'name_padded': "CONCAT(SUBSTRING(dcim_poweroutlet.name FROM '^[^0-9]+'), "
  997. "LPAD(SUBSTRING(dcim_poweroutlet.name FROM '[0-9\/]+$'), 8, '0'))",
  998. }).order_by('device', 'name_padded')
  999. @python_2_unicode_compatible
  1000. class PowerOutlet(models.Model):
  1001. """
  1002. A physical power outlet (output) within a Device which provides power to a PowerPort.
  1003. """
  1004. device = models.ForeignKey('Device', related_name='power_outlets', on_delete=models.CASCADE)
  1005. name = models.CharField(max_length=50)
  1006. objects = PowerOutletManager()
  1007. class Meta:
  1008. unique_together = ['device', 'name']
  1009. def __str__(self):
  1010. return self.name
  1011. #
  1012. # Interfaces
  1013. #
  1014. @python_2_unicode_compatible
  1015. class Interface(models.Model):
  1016. """
  1017. A network interface within a Device or VirtualMachine. A physical Interface can connect to exactly one other
  1018. Interface via the creation of an InterfaceConnection.
  1019. """
  1020. device = models.ForeignKey(
  1021. to='Device',
  1022. on_delete=models.CASCADE,
  1023. related_name='interfaces',
  1024. null=True,
  1025. blank=True
  1026. )
  1027. virtual_machine = models.ForeignKey(
  1028. to='virtualization.VirtualMachine',
  1029. on_delete=models.CASCADE,
  1030. related_name='interfaces',
  1031. null=True,
  1032. blank=True
  1033. )
  1034. lag = models.ForeignKey(
  1035. to='self',
  1036. on_delete=models.SET_NULL,
  1037. related_name='member_interfaces',
  1038. null=True,
  1039. blank=True,
  1040. verbose_name='Parent LAG'
  1041. )
  1042. name = models.CharField(max_length=64)
  1043. form_factor = models.PositiveSmallIntegerField(choices=IFACE_FF_CHOICES, default=IFACE_FF_10GE_SFP_PLUS)
  1044. enabled = models.BooleanField(default=True)
  1045. mac_address = MACAddressField(null=True, blank=True, verbose_name='MAC Address')
  1046. mtu = models.PositiveSmallIntegerField(blank=True, null=True, verbose_name='MTU')
  1047. mgmt_only = models.BooleanField(
  1048. default=False,
  1049. verbose_name='OOB Management',
  1050. help_text="This interface is used only for out-of-band management"
  1051. )
  1052. description = models.CharField(max_length=100, blank=True)
  1053. objects = InterfaceQuerySet.as_manager()
  1054. class Meta:
  1055. ordering = ['device', 'name']
  1056. unique_together = ['device', 'name']
  1057. def __str__(self):
  1058. return self.name
  1059. def clean(self):
  1060. # An Interface must belong to a Device *or* to a VirtualMachine
  1061. if self.device and self.virtual_machine:
  1062. raise ValidationError("An interface cannot belong to both a device and a virtual machine.")
  1063. if not self.device and not self.virtual_machine:
  1064. raise ValidationError("An interface must belong to either a device or a virtual machine.")
  1065. # VM interfaces must be virtual
  1066. if self.virtual_machine and self.form_factor not in VIRTUAL_IFACE_TYPES:
  1067. raise ValidationError({
  1068. 'form_factor': "Virtual machines cannot have physical interfaces."
  1069. })
  1070. # Virtual interfaces cannot be connected
  1071. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.is_connected:
  1072. raise ValidationError({
  1073. 'form_factor': "Virtual and wireless interfaces cannot be connected to another interface or circuit. "
  1074. "Disconnect the interface or choose a suitable form factor."
  1075. })
  1076. # An interface's LAG must belong to the same device
  1077. if self.lag and self.lag.device != self.device:
  1078. raise ValidationError({
  1079. 'lag': "The selected LAG interface ({}) belongs to a different device ({}).".format(
  1080. self.lag.name, self.lag.device.name
  1081. )
  1082. })
  1083. # A virtual interface cannot have a parent LAG
  1084. if self.form_factor in NONCONNECTABLE_IFACE_TYPES and self.lag is not None:
  1085. raise ValidationError({
  1086. 'lag': "{} interfaces cannot have a parent LAG interface.".format(self.get_form_factor_display())
  1087. })
  1088. # Only a LAG can have LAG members
  1089. if self.form_factor != IFACE_FF_LAG and self.member_interfaces.exists():
  1090. raise ValidationError({
  1091. 'form_factor': "Cannot change interface form factor; it has LAG members ({}).".format(
  1092. ", ".join([iface.name for iface in self.member_interfaces.all()])
  1093. )
  1094. })
  1095. @property
  1096. def parent(self):
  1097. return self.device or self.virtual_machine
  1098. @property
  1099. def is_virtual(self):
  1100. return self.form_factor in VIRTUAL_IFACE_TYPES
  1101. @property
  1102. def is_wireless(self):
  1103. return self.form_factor in WIRELESS_IFACE_TYPES
  1104. @property
  1105. def is_lag(self):
  1106. return self.form_factor == IFACE_FF_LAG
  1107. @property
  1108. def is_connected(self):
  1109. try:
  1110. return bool(self.circuit_termination)
  1111. except ObjectDoesNotExist:
  1112. pass
  1113. return bool(self.connection)
  1114. @property
  1115. def connection(self):
  1116. try:
  1117. return self.connected_as_a
  1118. except ObjectDoesNotExist:
  1119. pass
  1120. try:
  1121. return self.connected_as_b
  1122. except ObjectDoesNotExist:
  1123. pass
  1124. return None
  1125. @property
  1126. def connected_interface(self):
  1127. try:
  1128. if self.connected_as_a:
  1129. return self.connected_as_a.interface_b
  1130. except ObjectDoesNotExist:
  1131. pass
  1132. try:
  1133. if self.connected_as_b:
  1134. return self.connected_as_b.interface_a
  1135. except ObjectDoesNotExist:
  1136. pass
  1137. return None
  1138. class InterfaceConnection(models.Model):
  1139. """
  1140. An InterfaceConnection represents a symmetrical, one-to-one connection between two Interfaces. There is no
  1141. significant difference between the interface_a and interface_b fields.
  1142. """
  1143. interface_a = models.OneToOneField('Interface', related_name='connected_as_a', on_delete=models.CASCADE)
  1144. interface_b = models.OneToOneField('Interface', related_name='connected_as_b', on_delete=models.CASCADE)
  1145. connection_status = models.BooleanField(choices=CONNECTION_STATUS_CHOICES, default=CONNECTION_STATUS_CONNECTED,
  1146. verbose_name='Status')
  1147. csv_headers = ['device_a', 'interface_a', 'device_b', 'interface_b', 'connection_status']
  1148. def clean(self):
  1149. try:
  1150. if self.interface_a == self.interface_b:
  1151. raise ValidationError({
  1152. 'interface_b': "Cannot connect an interface to itself."
  1153. })
  1154. except ObjectDoesNotExist:
  1155. pass
  1156. # Used for connections export
  1157. def to_csv(self):
  1158. return csv_format([
  1159. self.interface_a.device.identifier,
  1160. self.interface_a.name,
  1161. self.interface_b.device.identifier,
  1162. self.interface_b.name,
  1163. self.get_connection_status_display(),
  1164. ])
  1165. #
  1166. # Device bays
  1167. #
  1168. @python_2_unicode_compatible
  1169. class DeviceBay(models.Model):
  1170. """
  1171. An empty space within a Device which can house a child device
  1172. """
  1173. device = models.ForeignKey('Device', related_name='device_bays', on_delete=models.CASCADE)
  1174. name = models.CharField(max_length=50, verbose_name='Name')
  1175. installed_device = models.OneToOneField('Device', related_name='parent_bay', on_delete=models.SET_NULL, blank=True,
  1176. null=True)
  1177. class Meta:
  1178. ordering = ['device', 'name']
  1179. unique_together = ['device', 'name']
  1180. def __str__(self):
  1181. return '{} - {}'.format(self.device.name, self.name)
  1182. def clean(self):
  1183. # Validate that the parent Device can have DeviceBays
  1184. if not self.device.device_type.is_parent_device:
  1185. raise ValidationError("This type of device ({}) does not support device bays.".format(
  1186. self.device.device_type
  1187. ))
  1188. # Cannot install a device into itself, obviously
  1189. if self.device == self.installed_device:
  1190. raise ValidationError("Cannot install a device into itself.")
  1191. #
  1192. # Inventory items
  1193. #
  1194. @python_2_unicode_compatible
  1195. class InventoryItem(models.Model):
  1196. """
  1197. An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
  1198. InventoryItems are used only for inventory purposes.
  1199. """
  1200. device = models.ForeignKey('Device', related_name='inventory_items', on_delete=models.CASCADE)
  1201. parent = models.ForeignKey('self', related_name='child_items', blank=True, null=True, on_delete=models.CASCADE)
  1202. name = models.CharField(max_length=50, verbose_name='Name')
  1203. manufacturer = models.ForeignKey(
  1204. 'Manufacturer', models.PROTECT, related_name='inventory_items', blank=True, null=True
  1205. )
  1206. part_id = models.CharField(max_length=50, verbose_name='Part ID', blank=True)
  1207. serial = models.CharField(max_length=50, verbose_name='Serial number', blank=True)
  1208. asset_tag = NullableCharField(
  1209. max_length=50, blank=True, null=True, unique=True, verbose_name='Asset tag',
  1210. help_text='A unique tag used to identify this item'
  1211. )
  1212. discovered = models.BooleanField(default=False, verbose_name='Discovered')
  1213. description = models.CharField(max_length=100, blank=True)
  1214. class Meta:
  1215. ordering = ['device__id', 'parent__id', 'name']
  1216. unique_together = ['device', 'parent', 'name']
  1217. def __str__(self):
  1218. return self.name