devices.py 32 KB

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