devices.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. from collections import OrderedDict
  2. import yaml
  3. from django.contrib.contenttypes.fields import GenericRelation
  4. from django.core.exceptions import ValidationError
  5. from django.core.validators import MaxValueValidator, MinValueValidator
  6. from django.db import models
  7. from django.db.models import F, ProtectedError
  8. from django.urls import reverse
  9. from django.utils.safestring import mark_safe
  10. from dcim.choices import *
  11. from dcim.constants import *
  12. from extras.models import ConfigContextModel
  13. from extras.querysets import ConfigContextModelQuerySet
  14. from extras.utils import extras_features
  15. from netbox.config import ConfigItem
  16. from netbox.models import OrganizationalModel, PrimaryModel
  17. from utilities.choices import ColorChoices
  18. from utilities.fields import ColorField, NaturalOrderingField
  19. from .device_components import *
  20. __all__ = (
  21. 'Device',
  22. 'DeviceRole',
  23. 'DeviceType',
  24. 'Manufacturer',
  25. 'Module',
  26. 'ModuleType',
  27. 'Platform',
  28. 'VirtualChassis',
  29. )
  30. #
  31. # Device Types
  32. #
  33. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  34. class Manufacturer(OrganizationalModel):
  35. """
  36. A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
  37. """
  38. name = models.CharField(
  39. max_length=100,
  40. unique=True
  41. )
  42. slug = models.SlugField(
  43. max_length=100,
  44. unique=True
  45. )
  46. description = models.CharField(
  47. max_length=200,
  48. blank=True
  49. )
  50. # Generic relations
  51. contacts = GenericRelation(
  52. to='tenancy.ContactAssignment'
  53. )
  54. class Meta:
  55. ordering = ['name']
  56. def __str__(self):
  57. return self.name
  58. def get_absolute_url(self):
  59. return reverse('dcim:manufacturer', args=[self.pk])
  60. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  61. class DeviceType(PrimaryModel):
  62. """
  63. A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
  64. well as high-level functional role(s).
  65. Each DeviceType can have an arbitrary number of component templates assigned to it, which define console, power, and
  66. interface objects. For example, a Juniper EX4300-48T DeviceType would have:
  67. * 1 ConsolePortTemplate
  68. * 2 PowerPortTemplates
  69. * 48 InterfaceTemplates
  70. When a new Device of this type is created, the appropriate console, power, and interface objects (as defined by the
  71. DeviceType) are automatically created as well.
  72. """
  73. manufacturer = models.ForeignKey(
  74. to='dcim.Manufacturer',
  75. on_delete=models.PROTECT,
  76. related_name='device_types'
  77. )
  78. model = models.CharField(
  79. max_length=100
  80. )
  81. slug = models.SlugField(
  82. max_length=100
  83. )
  84. part_number = models.CharField(
  85. max_length=50,
  86. blank=True,
  87. help_text='Discrete part number (optional)'
  88. )
  89. u_height = models.PositiveSmallIntegerField(
  90. default=1,
  91. verbose_name='Height (U)'
  92. )
  93. is_full_depth = models.BooleanField(
  94. default=True,
  95. verbose_name='Is full depth',
  96. help_text='Device consumes both front and rear rack faces'
  97. )
  98. subdevice_role = models.CharField(
  99. max_length=50,
  100. choices=SubdeviceRoleChoices,
  101. blank=True,
  102. verbose_name='Parent/child status',
  103. help_text='Parent devices house child devices in device bays. Leave blank '
  104. 'if this device type is neither a parent nor a child.'
  105. )
  106. airflow = models.CharField(
  107. max_length=50,
  108. choices=DeviceAirflowChoices,
  109. blank=True
  110. )
  111. front_image = models.ImageField(
  112. upload_to='devicetype-images',
  113. blank=True
  114. )
  115. rear_image = models.ImageField(
  116. upload_to='devicetype-images',
  117. blank=True
  118. )
  119. comments = models.TextField(
  120. blank=True
  121. )
  122. clone_fields = [
  123. 'manufacturer', 'u_height', 'is_full_depth', 'subdevice_role', 'airflow',
  124. ]
  125. class Meta:
  126. ordering = ['manufacturer', 'model']
  127. unique_together = [
  128. ['manufacturer', 'model'],
  129. ['manufacturer', 'slug'],
  130. ]
  131. def __str__(self):
  132. return self.model
  133. def __init__(self, *args, **kwargs):
  134. super().__init__(*args, **kwargs)
  135. # Save a copy of u_height for validation in clean()
  136. self._original_u_height = self.u_height
  137. # Save references to the original front/rear images
  138. self._original_front_image = self.front_image
  139. self._original_rear_image = self.rear_image
  140. def get_absolute_url(self):
  141. return reverse('dcim:devicetype', args=[self.pk])
  142. def to_yaml(self):
  143. data = OrderedDict((
  144. ('manufacturer', self.manufacturer.name),
  145. ('model', self.model),
  146. ('slug', self.slug),
  147. ('part_number', self.part_number),
  148. ('u_height', self.u_height),
  149. ('is_full_depth', self.is_full_depth),
  150. ('subdevice_role', self.subdevice_role),
  151. ('airflow', self.airflow),
  152. ('comments', self.comments),
  153. ))
  154. # Component templates
  155. if self.consoleporttemplates.exists():
  156. data['console-ports'] = [
  157. {
  158. 'name': c.name,
  159. 'type': c.type,
  160. 'label': c.label,
  161. 'description': c.description,
  162. }
  163. for c in self.consoleporttemplates.all()
  164. ]
  165. if self.consoleserverporttemplates.exists():
  166. data['console-server-ports'] = [
  167. {
  168. 'name': c.name,
  169. 'type': c.type,
  170. 'label': c.label,
  171. 'description': c.description,
  172. }
  173. for c in self.consoleserverporttemplates.all()
  174. ]
  175. if self.powerporttemplates.exists():
  176. data['power-ports'] = [
  177. {
  178. 'name': c.name,
  179. 'type': c.type,
  180. 'maximum_draw': c.maximum_draw,
  181. 'allocated_draw': c.allocated_draw,
  182. 'label': c.label,
  183. 'description': c.description,
  184. }
  185. for c in self.powerporttemplates.all()
  186. ]
  187. if self.poweroutlettemplates.exists():
  188. data['power-outlets'] = [
  189. {
  190. 'name': c.name,
  191. 'type': c.type,
  192. 'power_port': c.power_port.name if c.power_port else None,
  193. 'feed_leg': c.feed_leg,
  194. 'label': c.label,
  195. 'description': c.description,
  196. }
  197. for c in self.poweroutlettemplates.all()
  198. ]
  199. if self.interfacetemplates.exists():
  200. data['interfaces'] = [
  201. {
  202. 'name': c.name,
  203. 'type': c.type,
  204. 'mgmt_only': c.mgmt_only,
  205. 'label': c.label,
  206. 'description': c.description,
  207. }
  208. for c in self.interfacetemplates.all()
  209. ]
  210. if self.frontporttemplates.exists():
  211. data['front-ports'] = [
  212. {
  213. 'name': c.name,
  214. 'type': c.type,
  215. 'rear_port': c.rear_port.name,
  216. 'rear_port_position': c.rear_port_position,
  217. 'label': c.label,
  218. 'description': c.description,
  219. }
  220. for c in self.frontporttemplates.all()
  221. ]
  222. if self.rearporttemplates.exists():
  223. data['rear-ports'] = [
  224. {
  225. 'name': c.name,
  226. 'type': c.type,
  227. 'positions': c.positions,
  228. 'label': c.label,
  229. 'description': c.description,
  230. }
  231. for c in self.rearporttemplates.all()
  232. ]
  233. if self.modulebaytemplates.exists():
  234. data['module-bays'] = [
  235. {
  236. 'name': c.name,
  237. 'label': c.label,
  238. 'description': c.description,
  239. }
  240. for c in self.modulebaytemplates.all()
  241. ]
  242. if self.devicebaytemplates.exists():
  243. data['device-bays'] = [
  244. {
  245. 'name': c.name,
  246. 'label': c.label,
  247. 'description': c.description,
  248. }
  249. for c in self.devicebaytemplates.all()
  250. ]
  251. return yaml.dump(dict(data), sort_keys=False)
  252. def clean(self):
  253. super().clean()
  254. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  255. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  256. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  257. if self.pk and self.u_height > self._original_u_height:
  258. for d in Device.objects.filter(device_type=self, position__isnull=False):
  259. face_required = None if self.is_full_depth else d.face
  260. u_available = d.rack.get_available_units(
  261. u_height=self.u_height,
  262. rack_face=face_required,
  263. exclude=[d.pk]
  264. )
  265. if d.position not in u_available:
  266. raise ValidationError({
  267. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  268. "{}U".format(d, d.rack, self.u_height)
  269. })
  270. # If modifying the height of an existing DeviceType to 0U, check for any instances assigned to a rack position.
  271. elif self.pk and self._original_u_height > 0 and self.u_height == 0:
  272. racked_instance_count = Device.objects.filter(
  273. device_type=self,
  274. position__isnull=False
  275. ).count()
  276. if racked_instance_count:
  277. url = f"{reverse('dcim:device_list')}?manufactuer_id={self.manufacturer_id}&device_type_id={self.pk}"
  278. raise ValidationError({
  279. 'u_height': mark_safe(
  280. f'Unable to set 0U height: Found <a href="{url}">{racked_instance_count} instances</a> already '
  281. f'mounted within racks.'
  282. )
  283. })
  284. if (
  285. self.subdevice_role != SubdeviceRoleChoices.ROLE_PARENT
  286. ) and self.devicebaytemplates.count():
  287. raise ValidationError({
  288. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  289. "declassifying it as a parent device."
  290. })
  291. if self.u_height and self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD:
  292. raise ValidationError({
  293. 'u_height': "Child device types must be 0U."
  294. })
  295. def save(self, *args, **kwargs):
  296. ret = super().save(*args, **kwargs)
  297. # Delete any previously uploaded image files that are no longer in use
  298. if self.front_image != self._original_front_image:
  299. self._original_front_image.delete(save=False)
  300. if self.rear_image != self._original_rear_image:
  301. self._original_rear_image.delete(save=False)
  302. return ret
  303. def delete(self, *args, **kwargs):
  304. super().delete(*args, **kwargs)
  305. # Delete any uploaded image files
  306. if self.front_image:
  307. self.front_image.delete(save=False)
  308. if self.rear_image:
  309. self.rear_image.delete(save=False)
  310. @property
  311. def is_parent_device(self):
  312. return self.subdevice_role == SubdeviceRoleChoices.ROLE_PARENT
  313. @property
  314. def is_child_device(self):
  315. return self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD
  316. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  317. class ModuleType(PrimaryModel):
  318. """
  319. A ModuleType represents a hardware element that can be installed within a device and which houses additional
  320. components; for example, a line card within a chassis-based switch such as the Cisco Catalyst 6500. Like a
  321. DeviceType, each ModuleType can have console, power, interface, and pass-through port templates assigned to it. It
  322. cannot, however house device bays or module bays.
  323. """
  324. manufacturer = models.ForeignKey(
  325. to='dcim.Manufacturer',
  326. on_delete=models.PROTECT,
  327. related_name='module_types'
  328. )
  329. model = models.CharField(
  330. max_length=100
  331. )
  332. part_number = models.CharField(
  333. max_length=50,
  334. blank=True,
  335. help_text='Discrete part number (optional)'
  336. )
  337. comments = models.TextField(
  338. blank=True
  339. )
  340. clone_fields = ('manufacturer',)
  341. class Meta:
  342. ordering = ('manufacturer', 'model')
  343. unique_together = (
  344. ('manufacturer', 'model'),
  345. )
  346. def __str__(self):
  347. return self.model
  348. def get_absolute_url(self):
  349. return reverse('dcim:moduletype', args=[self.pk])
  350. def to_yaml(self):
  351. data = OrderedDict((
  352. ('manufacturer', self.manufacturer.name),
  353. ('model', self.model),
  354. ('part_number', self.part_number),
  355. ('comments', self.comments),
  356. ))
  357. # Component templates
  358. if self.consoleporttemplates.exists():
  359. data['console-ports'] = [
  360. {
  361. 'name': c.name,
  362. 'type': c.type,
  363. 'label': c.label,
  364. 'description': c.description,
  365. }
  366. for c in self.consoleporttemplates.all()
  367. ]
  368. if self.consoleserverporttemplates.exists():
  369. data['console-server-ports'] = [
  370. {
  371. 'name': c.name,
  372. 'type': c.type,
  373. 'label': c.label,
  374. 'description': c.description,
  375. }
  376. for c in self.consoleserverporttemplates.all()
  377. ]
  378. if self.powerporttemplates.exists():
  379. data['power-ports'] = [
  380. {
  381. 'name': c.name,
  382. 'type': c.type,
  383. 'maximum_draw': c.maximum_draw,
  384. 'allocated_draw': c.allocated_draw,
  385. 'label': c.label,
  386. 'description': c.description,
  387. }
  388. for c in self.powerporttemplates.all()
  389. ]
  390. if self.poweroutlettemplates.exists():
  391. data['power-outlets'] = [
  392. {
  393. 'name': c.name,
  394. 'type': c.type,
  395. 'power_port': c.power_port.name if c.power_port else None,
  396. 'feed_leg': c.feed_leg,
  397. 'label': c.label,
  398. 'description': c.description,
  399. }
  400. for c in self.poweroutlettemplates.all()
  401. ]
  402. if self.interfacetemplates.exists():
  403. data['interfaces'] = [
  404. {
  405. 'name': c.name,
  406. 'type': c.type,
  407. 'mgmt_only': c.mgmt_only,
  408. 'label': c.label,
  409. 'description': c.description,
  410. }
  411. for c in self.interfacetemplates.all()
  412. ]
  413. if self.frontporttemplates.exists():
  414. data['front-ports'] = [
  415. {
  416. 'name': c.name,
  417. 'type': c.type,
  418. 'rear_port': c.rear_port.name,
  419. 'rear_port_position': c.rear_port_position,
  420. 'label': c.label,
  421. 'description': c.description,
  422. }
  423. for c in self.frontporttemplates.all()
  424. ]
  425. if self.rearporttemplates.exists():
  426. data['rear-ports'] = [
  427. {
  428. 'name': c.name,
  429. 'type': c.type,
  430. 'positions': c.positions,
  431. 'label': c.label,
  432. 'description': c.description,
  433. }
  434. for c in self.rearporttemplates.all()
  435. ]
  436. return yaml.dump(dict(data), sort_keys=False)
  437. #
  438. # Devices
  439. #
  440. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  441. class DeviceRole(OrganizationalModel):
  442. """
  443. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  444. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  445. virtual machines as well.
  446. """
  447. name = models.CharField(
  448. max_length=100,
  449. unique=True
  450. )
  451. slug = models.SlugField(
  452. max_length=100,
  453. unique=True
  454. )
  455. color = ColorField(
  456. default=ColorChoices.COLOR_GREY
  457. )
  458. vm_role = models.BooleanField(
  459. default=True,
  460. verbose_name='VM Role',
  461. help_text='Virtual machines may be assigned to this role'
  462. )
  463. description = models.CharField(
  464. max_length=200,
  465. blank=True,
  466. )
  467. class Meta:
  468. ordering = ['name']
  469. def __str__(self):
  470. return self.name
  471. def get_absolute_url(self):
  472. return reverse('dcim:devicerole', args=[self.pk])
  473. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  474. class Platform(OrganizationalModel):
  475. """
  476. Platform refers to the software or firmware running on a Device. For example, "Cisco IOS-XR" or "Juniper Junos".
  477. NetBox uses Platforms to determine how to interact with devices when pulling inventory data or other information by
  478. specifying a NAPALM driver.
  479. """
  480. name = models.CharField(
  481. max_length=100,
  482. unique=True
  483. )
  484. slug = models.SlugField(
  485. max_length=100,
  486. unique=True
  487. )
  488. manufacturer = models.ForeignKey(
  489. to='dcim.Manufacturer',
  490. on_delete=models.PROTECT,
  491. related_name='platforms',
  492. blank=True,
  493. null=True,
  494. help_text='Optionally limit this platform to devices of a certain manufacturer'
  495. )
  496. napalm_driver = models.CharField(
  497. max_length=50,
  498. blank=True,
  499. verbose_name='NAPALM driver',
  500. help_text='The name of the NAPALM driver to use when interacting with devices'
  501. )
  502. napalm_args = models.JSONField(
  503. blank=True,
  504. null=True,
  505. verbose_name='NAPALM arguments',
  506. help_text='Additional arguments to pass when initiating the NAPALM driver (JSON format)'
  507. )
  508. description = models.CharField(
  509. max_length=200,
  510. blank=True
  511. )
  512. class Meta:
  513. ordering = ['name']
  514. def __str__(self):
  515. return self.name
  516. def get_absolute_url(self):
  517. return reverse('dcim:platform', args=[self.pk])
  518. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  519. class Device(PrimaryModel, ConfigContextModel):
  520. """
  521. A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
  522. DeviceRole, and (optionally) a Platform. Device names are not required, however if one is set it must be unique.
  523. Each Device must be assigned to a site, and optionally to a rack within that site. Associating a device with a
  524. particular rack face or unit is optional (for example, vertically mounted PDUs do not consume rack units).
  525. When a new Device is created, console/power/interface/device bay components are created along with it as dictated
  526. by the component templates assigned to its DeviceType. Components can also be added, modified, or deleted after the
  527. creation of a Device.
  528. """
  529. device_type = models.ForeignKey(
  530. to='dcim.DeviceType',
  531. on_delete=models.PROTECT,
  532. related_name='instances'
  533. )
  534. device_role = models.ForeignKey(
  535. to='dcim.DeviceRole',
  536. on_delete=models.PROTECT,
  537. related_name='devices'
  538. )
  539. tenant = models.ForeignKey(
  540. to='tenancy.Tenant',
  541. on_delete=models.PROTECT,
  542. related_name='devices',
  543. blank=True,
  544. null=True
  545. )
  546. platform = models.ForeignKey(
  547. to='dcim.Platform',
  548. on_delete=models.SET_NULL,
  549. related_name='devices',
  550. blank=True,
  551. null=True
  552. )
  553. name = models.CharField(
  554. max_length=64,
  555. blank=True,
  556. null=True
  557. )
  558. _name = NaturalOrderingField(
  559. target_field='name',
  560. max_length=100,
  561. blank=True,
  562. null=True
  563. )
  564. serial = models.CharField(
  565. max_length=50,
  566. blank=True,
  567. verbose_name='Serial number'
  568. )
  569. asset_tag = models.CharField(
  570. max_length=50,
  571. blank=True,
  572. null=True,
  573. unique=True,
  574. verbose_name='Asset tag',
  575. help_text='A unique tag used to identify this device'
  576. )
  577. site = models.ForeignKey(
  578. to='dcim.Site',
  579. on_delete=models.PROTECT,
  580. related_name='devices'
  581. )
  582. location = models.ForeignKey(
  583. to='dcim.Location',
  584. on_delete=models.PROTECT,
  585. related_name='devices',
  586. blank=True,
  587. null=True
  588. )
  589. rack = models.ForeignKey(
  590. to='dcim.Rack',
  591. on_delete=models.PROTECT,
  592. related_name='devices',
  593. blank=True,
  594. null=True
  595. )
  596. position = models.PositiveSmallIntegerField(
  597. blank=True,
  598. null=True,
  599. validators=[MinValueValidator(1)],
  600. verbose_name='Position (U)',
  601. help_text='The lowest-numbered unit occupied by the device'
  602. )
  603. face = models.CharField(
  604. max_length=50,
  605. blank=True,
  606. choices=DeviceFaceChoices,
  607. verbose_name='Rack face'
  608. )
  609. status = models.CharField(
  610. max_length=50,
  611. choices=DeviceStatusChoices,
  612. default=DeviceStatusChoices.STATUS_ACTIVE
  613. )
  614. airflow = models.CharField(
  615. max_length=50,
  616. choices=DeviceAirflowChoices,
  617. blank=True
  618. )
  619. primary_ip4 = models.OneToOneField(
  620. to='ipam.IPAddress',
  621. on_delete=models.SET_NULL,
  622. related_name='+',
  623. blank=True,
  624. null=True,
  625. verbose_name='Primary IPv4'
  626. )
  627. primary_ip6 = models.OneToOneField(
  628. to='ipam.IPAddress',
  629. on_delete=models.SET_NULL,
  630. related_name='+',
  631. blank=True,
  632. null=True,
  633. verbose_name='Primary IPv6'
  634. )
  635. cluster = models.ForeignKey(
  636. to='virtualization.Cluster',
  637. on_delete=models.SET_NULL,
  638. related_name='devices',
  639. blank=True,
  640. null=True
  641. )
  642. virtual_chassis = models.ForeignKey(
  643. to='VirtualChassis',
  644. on_delete=models.SET_NULL,
  645. related_name='members',
  646. blank=True,
  647. null=True
  648. )
  649. vc_position = models.PositiveSmallIntegerField(
  650. blank=True,
  651. null=True,
  652. validators=[MaxValueValidator(255)]
  653. )
  654. vc_priority = models.PositiveSmallIntegerField(
  655. blank=True,
  656. null=True,
  657. validators=[MaxValueValidator(255)]
  658. )
  659. comments = models.TextField(
  660. blank=True
  661. )
  662. # Generic relations
  663. contacts = GenericRelation(
  664. to='tenancy.ContactAssignment'
  665. )
  666. images = GenericRelation(
  667. to='extras.ImageAttachment'
  668. )
  669. objects = ConfigContextModelQuerySet.as_manager()
  670. clone_fields = [
  671. 'device_type', 'device_role', 'tenant', 'platform', 'site', 'location', 'rack', 'status', 'airflow', 'cluster',
  672. ]
  673. class Meta:
  674. ordering = ('_name', 'pk') # Name may be null
  675. unique_together = (
  676. ('site', 'tenant', 'name'), # See validate_unique below
  677. ('rack', 'position', 'face'),
  678. ('virtual_chassis', 'vc_position'),
  679. )
  680. def __str__(self):
  681. if self.name and self.asset_tag:
  682. return f'{self.name} ({self.asset_tag})'
  683. elif self.name:
  684. return self.name
  685. elif self.virtual_chassis:
  686. return f'{self.virtual_chassis.name}:{self.vc_position} ({self.pk})'
  687. elif self.device_type:
  688. return f'{self.device_type.manufacturer} {self.device_type.model} ({self.pk})'
  689. return super().__str__()
  690. def get_absolute_url(self):
  691. return reverse('dcim:device', args=[self.pk])
  692. def validate_unique(self, exclude=None):
  693. # Check for a duplicate name on a device assigned to the same Site and no Tenant. This is necessary
  694. # because Django does not consider two NULL fields to be equal, and thus will not trigger a violation
  695. # of the uniqueness constraint without manual intervention.
  696. if self.name and hasattr(self, 'site') and self.tenant is None:
  697. if Device.objects.exclude(pk=self.pk).filter(
  698. name=self.name,
  699. site=self.site,
  700. tenant__isnull=True
  701. ):
  702. raise ValidationError({
  703. 'name': 'A device with this name already exists.'
  704. })
  705. super().validate_unique(exclude)
  706. def clean(self):
  707. super().clean()
  708. # Validate site/location/rack combination
  709. if self.rack and self.site != self.rack.site:
  710. raise ValidationError({
  711. 'rack': f"Rack {self.rack} does not belong to site {self.site}.",
  712. })
  713. if self.location and self.site != self.location.site:
  714. raise ValidationError({
  715. 'location': f"Location {self.location} does not belong to site {self.site}.",
  716. })
  717. if self.rack and self.location and self.rack.location != self.location:
  718. raise ValidationError({
  719. 'rack': f"Rack {self.rack} does not belong to location {self.location}.",
  720. })
  721. elif self.rack:
  722. self.location = self.rack.location
  723. if self.rack is None:
  724. if self.face:
  725. raise ValidationError({
  726. 'face': "Cannot select a rack face without assigning a rack.",
  727. })
  728. if self.position:
  729. raise ValidationError({
  730. 'position': "Cannot select a rack position without assigning a rack.",
  731. })
  732. # Validate position/face combination
  733. if self.position and not self.face:
  734. raise ValidationError({
  735. 'face': "Must specify rack face when defining rack position.",
  736. })
  737. # Prevent 0U devices from being assigned to a specific position
  738. if self.position and self.device_type.u_height == 0:
  739. raise ValidationError({
  740. 'position': f"A U0 device type ({self.device_type}) cannot be assigned to a rack position."
  741. })
  742. if self.rack:
  743. try:
  744. # Child devices cannot be assigned to a rack face/unit
  745. if self.device_type.is_child_device and self.face:
  746. raise ValidationError({
  747. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  748. "parent device."
  749. })
  750. if self.device_type.is_child_device and self.position:
  751. raise ValidationError({
  752. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  753. "the parent device."
  754. })
  755. # Validate rack space
  756. rack_face = self.face if not self.device_type.is_full_depth else None
  757. exclude_list = [self.pk] if self.pk else []
  758. available_units = self.rack.get_available_units(
  759. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  760. )
  761. if self.position and self.position not in available_units:
  762. raise ValidationError({
  763. 'position': f"U{self.position} is already occupied or does not have sufficient space to "
  764. f"accommodate this device type: {self.device_type} ({self.device_type.u_height}U)"
  765. })
  766. except DeviceType.DoesNotExist:
  767. pass
  768. # Validate primary IP addresses
  769. vc_interfaces = self.vc_interfaces(if_master=False)
  770. if self.primary_ip4:
  771. if self.primary_ip4.family != 4:
  772. raise ValidationError({
  773. 'primary_ip4': f"{self.primary_ip4} is not an IPv4 address."
  774. })
  775. if self.primary_ip4.assigned_object in vc_interfaces:
  776. pass
  777. elif self.primary_ip4.nat_inside is not None and self.primary_ip4.nat_inside.assigned_object in vc_interfaces:
  778. pass
  779. else:
  780. raise ValidationError({
  781. 'primary_ip4': f"The specified IP address ({self.primary_ip4}) is not assigned to this device."
  782. })
  783. if self.primary_ip6:
  784. if self.primary_ip6.family != 6:
  785. raise ValidationError({
  786. 'primary_ip6': f"{self.primary_ip6} is not an IPv6 address."
  787. })
  788. if self.primary_ip6.assigned_object in vc_interfaces:
  789. pass
  790. elif self.primary_ip6.nat_inside is not None and self.primary_ip6.nat_inside.assigned_object in vc_interfaces:
  791. pass
  792. else:
  793. raise ValidationError({
  794. 'primary_ip6': f"The specified IP address ({self.primary_ip6}) is not assigned to this device."
  795. })
  796. # Validate manufacturer/platform
  797. if hasattr(self, 'device_type') and self.platform:
  798. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  799. raise ValidationError({
  800. 'platform': "The assigned platform is limited to {} device types, but this device's type belongs "
  801. "to {}.".format(self.platform.manufacturer, self.device_type.manufacturer)
  802. })
  803. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  804. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  805. raise ValidationError({
  806. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  807. })
  808. # Validate virtual chassis assignment
  809. if self.virtual_chassis and self.vc_position is None:
  810. raise ValidationError({
  811. 'vc_position': "A device assigned to a virtual chassis must have its position defined."
  812. })
  813. def save(self, *args, **kwargs):
  814. is_new = not bool(self.pk)
  815. # Inherit airflow attribute from DeviceType if not set
  816. if is_new and not self.airflow:
  817. self.airflow = self.device_type.airflow
  818. super().save(*args, **kwargs)
  819. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  820. if is_new:
  821. ConsolePort.objects.bulk_create(
  822. [x.instantiate(device=self) for x in self.device_type.consoleporttemplates.all()]
  823. )
  824. ConsoleServerPort.objects.bulk_create(
  825. [x.instantiate(device=self) for x in self.device_type.consoleserverporttemplates.all()]
  826. )
  827. PowerPort.objects.bulk_create(
  828. [x.instantiate(device=self) for x in self.device_type.powerporttemplates.all()]
  829. )
  830. PowerOutlet.objects.bulk_create(
  831. [x.instantiate(device=self) for x in self.device_type.poweroutlettemplates.all()]
  832. )
  833. Interface.objects.bulk_create(
  834. [x.instantiate(device=self) for x in self.device_type.interfacetemplates.all()]
  835. )
  836. RearPort.objects.bulk_create(
  837. [x.instantiate(device=self) for x in self.device_type.rearporttemplates.all()]
  838. )
  839. FrontPort.objects.bulk_create(
  840. [x.instantiate(device=self) for x in self.device_type.frontporttemplates.all()]
  841. )
  842. ModuleBay.objects.bulk_create(
  843. [x.instantiate(device=self) for x in self.device_type.modulebaytemplates.all()]
  844. )
  845. DeviceBay.objects.bulk_create(
  846. [x.instantiate(device=self) for x in self.device_type.devicebaytemplates.all()]
  847. )
  848. # Avoid bulk_create to handle MPTT
  849. for x in self.device_type.inventoryitemtemplates.all():
  850. x.instantiate(device=self).save()
  851. # Update Site and Rack assignment for any child Devices
  852. devices = Device.objects.filter(parent_bay__device=self)
  853. for device in devices:
  854. device.site = self.site
  855. device.rack = self.rack
  856. device.save()
  857. @property
  858. def identifier(self):
  859. """
  860. Return the device name if set; otherwise return the Device's primary key as {pk}
  861. """
  862. if self.name is not None:
  863. return self.name
  864. return '{{{}}}'.format(self.pk)
  865. @property
  866. def primary_ip(self):
  867. if ConfigItem('PREFER_IPV4')() and self.primary_ip4:
  868. return self.primary_ip4
  869. elif self.primary_ip6:
  870. return self.primary_ip6
  871. elif self.primary_ip4:
  872. return self.primary_ip4
  873. else:
  874. return None
  875. @property
  876. def interfaces_count(self):
  877. return self.vc_interfaces().count()
  878. def get_vc_master(self):
  879. """
  880. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  881. """
  882. return self.virtual_chassis.master if self.virtual_chassis else None
  883. def vc_interfaces(self, if_master=True):
  884. """
  885. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  886. Device belonging to the same VirtualChassis.
  887. :param if_master: If True, return VC member interfaces only if this Device is the VC master.
  888. """
  889. filter = Q(device=self)
  890. if self.virtual_chassis and (self.virtual_chassis.master == self or not if_master):
  891. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  892. return Interface.objects.filter(filter)
  893. def get_cables(self, pk_list=False):
  894. """
  895. Return a QuerySet or PK list matching all Cables connected to a component of this Device.
  896. """
  897. from .cables import Cable
  898. cable_pks = []
  899. for component_model in [
  900. ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, FrontPort, RearPort
  901. ]:
  902. cable_pks += component_model.objects.filter(
  903. device=self, cable__isnull=False
  904. ).values_list('cable', flat=True)
  905. if pk_list:
  906. return cable_pks
  907. return Cable.objects.filter(pk__in=cable_pks)
  908. def get_children(self):
  909. """
  910. Return the set of child Devices installed in DeviceBays within this Device.
  911. """
  912. return Device.objects.filter(parent_bay__device=self.pk)
  913. def get_status_class(self):
  914. return DeviceStatusChoices.colors.get(self.status, 'secondary')
  915. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  916. class Module(PrimaryModel, ConfigContextModel):
  917. """
  918. A Module represents a field-installable component within a Device which may itself hold multiple device components
  919. (for example, a line card within a chassis switch). Modules are instantiated from ModuleTypes.
  920. """
  921. device = models.ForeignKey(
  922. to='dcim.Device',
  923. on_delete=models.CASCADE,
  924. related_name='modules'
  925. )
  926. module_bay = models.OneToOneField(
  927. to='dcim.ModuleBay',
  928. on_delete=models.CASCADE,
  929. related_name='installed_module'
  930. )
  931. module_type = models.ForeignKey(
  932. to='dcim.ModuleType',
  933. on_delete=models.PROTECT,
  934. related_name='instances'
  935. )
  936. serial = models.CharField(
  937. max_length=50,
  938. blank=True,
  939. verbose_name='Serial number'
  940. )
  941. asset_tag = models.CharField(
  942. max_length=50,
  943. blank=True,
  944. null=True,
  945. unique=True,
  946. verbose_name='Asset tag',
  947. help_text='A unique tag used to identify this device'
  948. )
  949. comments = models.TextField(
  950. blank=True
  951. )
  952. clone_fields = ('device', 'module_type')
  953. class Meta:
  954. ordering = ('module_bay',)
  955. def __str__(self):
  956. return str(self.module_type)
  957. def get_absolute_url(self):
  958. return reverse('dcim:module', args=[self.pk])
  959. def save(self, *args, **kwargs):
  960. is_new = not bool(self.pk)
  961. super().save(*args, **kwargs)
  962. # If this is a new Module, instantiate all its related components per the ModuleType definition
  963. if is_new:
  964. ConsolePort.objects.bulk_create(
  965. [x.instantiate(device=self.device, module=self) for x in self.module_type.consoleporttemplates.all()]
  966. )
  967. ConsoleServerPort.objects.bulk_create(
  968. [x.instantiate(device=self.device, module=self) for x in self.module_type.consoleserverporttemplates.all()]
  969. )
  970. PowerPort.objects.bulk_create(
  971. [x.instantiate(device=self.device, module=self) for x in self.module_type.powerporttemplates.all()]
  972. )
  973. PowerOutlet.objects.bulk_create(
  974. [x.instantiate(device=self.device, module=self) for x in self.module_type.poweroutlettemplates.all()]
  975. )
  976. Interface.objects.bulk_create(
  977. [x.instantiate(device=self.device, module=self) for x in self.module_type.interfacetemplates.all()]
  978. )
  979. RearPort.objects.bulk_create(
  980. [x.instantiate(device=self.device, module=self) for x in self.module_type.rearporttemplates.all()]
  981. )
  982. FrontPort.objects.bulk_create(
  983. [x.instantiate(device=self.device, module=self) for x in self.module_type.frontporttemplates.all()]
  984. )
  985. #
  986. # Virtual chassis
  987. #
  988. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  989. class VirtualChassis(PrimaryModel):
  990. """
  991. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  992. """
  993. master = models.OneToOneField(
  994. to='Device',
  995. on_delete=models.PROTECT,
  996. related_name='vc_master_for',
  997. blank=True,
  998. null=True
  999. )
  1000. name = models.CharField(
  1001. max_length=64
  1002. )
  1003. domain = models.CharField(
  1004. max_length=30,
  1005. blank=True
  1006. )
  1007. class Meta:
  1008. ordering = ['name']
  1009. verbose_name_plural = 'virtual chassis'
  1010. def __str__(self):
  1011. return self.name
  1012. def get_absolute_url(self):
  1013. return reverse('dcim:virtualchassis', kwargs={'pk': self.pk})
  1014. def clean(self):
  1015. super().clean()
  1016. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  1017. # VirtualChassis.)
  1018. if self.pk and self.master and self.master not in self.members.all():
  1019. raise ValidationError({
  1020. 'master': f"The selected master ({self.master}) is not assigned to this virtual chassis."
  1021. })
  1022. def delete(self, *args, **kwargs):
  1023. # Check for LAG interfaces split across member chassis
  1024. interfaces = Interface.objects.filter(
  1025. device__in=self.members.all(),
  1026. lag__isnull=False
  1027. ).exclude(
  1028. lag__device=F('device')
  1029. )
  1030. if interfaces:
  1031. raise ProtectedError(
  1032. f"Unable to delete virtual chassis {self}. There are member interfaces which form a cross-chassis LAG",
  1033. interfaces
  1034. )
  1035. return super().delete(*args, **kwargs)