devices.py 32 KB

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