devices.py 32 KB

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