devices.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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', '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. 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 reverse('dcim:manufacturer', args=[self.pk])
  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(PrimaryModel):
  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. objects = RestrictedQuerySet.as_manager()
  121. clone_fields = [
  122. 'manufacturer', 'u_height', 'is_full_depth', 'subdevice_role',
  123. ]
  124. class Meta:
  125. ordering = ['manufacturer', 'model']
  126. unique_together = [
  127. ['manufacturer', 'model'],
  128. ['manufacturer', 'slug'],
  129. ]
  130. def __str__(self):
  131. return self.model
  132. def __init__(self, *args, **kwargs):
  133. super().__init__(*args, **kwargs)
  134. # Save a copy of u_height for validation in clean()
  135. self._original_u_height = self.u_height
  136. # Save references to the original front/rear images
  137. self._original_front_image = self.front_image
  138. self._original_rear_image = self.rear_image
  139. def get_absolute_url(self):
  140. return reverse('dcim:devicetype', args=[self.pk])
  141. def to_yaml(self):
  142. data = OrderedDict((
  143. ('manufacturer', self.manufacturer.name),
  144. ('model', self.model),
  145. ('slug', self.slug),
  146. ('part_number', self.part_number),
  147. ('u_height', self.u_height),
  148. ('is_full_depth', self.is_full_depth),
  149. ('subdevice_role', self.subdevice_role),
  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. }
  159. for c in self.consoleporttemplates.all()
  160. ]
  161. if self.consoleserverporttemplates.exists():
  162. data['console-server-ports'] = [
  163. {
  164. 'name': c.name,
  165. 'type': c.type,
  166. }
  167. for c in self.consoleserverporttemplates.all()
  168. ]
  169. if self.powerporttemplates.exists():
  170. data['power-ports'] = [
  171. {
  172. 'name': c.name,
  173. 'type': c.type,
  174. 'maximum_draw': c.maximum_draw,
  175. 'allocated_draw': c.allocated_draw,
  176. }
  177. for c in self.powerporttemplates.all()
  178. ]
  179. if self.poweroutlettemplates.exists():
  180. data['power-outlets'] = [
  181. {
  182. 'name': c.name,
  183. 'type': c.type,
  184. 'power_port': c.power_port.name if c.power_port else None,
  185. 'feed_leg': c.feed_leg,
  186. }
  187. for c in self.poweroutlettemplates.all()
  188. ]
  189. if self.interfacetemplates.exists():
  190. data['interfaces'] = [
  191. {
  192. 'name': c.name,
  193. 'type': c.type,
  194. 'mgmt_only': c.mgmt_only,
  195. }
  196. for c in self.interfacetemplates.all()
  197. ]
  198. if self.frontporttemplates.exists():
  199. data['front-ports'] = [
  200. {
  201. 'name': c.name,
  202. 'type': c.type,
  203. 'rear_port': c.rear_port.name,
  204. 'rear_port_position': c.rear_port_position,
  205. }
  206. for c in self.frontporttemplates.all()
  207. ]
  208. if self.rearporttemplates.exists():
  209. data['rear-ports'] = [
  210. {
  211. 'name': c.name,
  212. 'type': c.type,
  213. 'positions': c.positions,
  214. }
  215. for c in self.rearporttemplates.all()
  216. ]
  217. if self.devicebaytemplates.exists():
  218. data['device-bays'] = [
  219. {
  220. 'name': c.name,
  221. }
  222. for c in self.devicebaytemplates.all()
  223. ]
  224. return yaml.dump(dict(data), sort_keys=False)
  225. def clean(self):
  226. super().clean()
  227. # If editing an existing DeviceType to have a larger u_height, first validate that *all* instances of it have
  228. # room to expand within their racks. This validation will impose a very high performance penalty when there are
  229. # many instances to check, but increasing the u_height of a DeviceType should be a very rare occurrence.
  230. if self.pk and self.u_height > self._original_u_height:
  231. for d in Device.objects.filter(device_type=self, position__isnull=False):
  232. face_required = None if self.is_full_depth else d.face
  233. u_available = d.rack.get_available_units(
  234. u_height=self.u_height,
  235. rack_face=face_required,
  236. exclude=[d.pk]
  237. )
  238. if d.position not in u_available:
  239. raise ValidationError({
  240. 'u_height': "Device {} in rack {} does not have sufficient space to accommodate a height of "
  241. "{}U".format(d, d.rack, self.u_height)
  242. })
  243. # If modifying the height of an existing DeviceType to 0U, check for any instances assigned to a rack position.
  244. elif self.pk and self._original_u_height > 0 and self.u_height == 0:
  245. racked_instance_count = Device.objects.filter(
  246. device_type=self,
  247. position__isnull=False
  248. ).count()
  249. if racked_instance_count:
  250. url = f"{reverse('dcim:device_list')}?manufactuer_id={self.manufacturer_id}&device_type_id={self.pk}"
  251. raise ValidationError({
  252. 'u_height': mark_safe(
  253. f'Unable to set 0U height: Found <a href="{url}">{racked_instance_count} instances</a> already '
  254. f'mounted within racks.'
  255. )
  256. })
  257. if (
  258. self.subdevice_role != SubdeviceRoleChoices.ROLE_PARENT
  259. ) and self.devicebaytemplates.count():
  260. raise ValidationError({
  261. 'subdevice_role': "Must delete all device bay templates associated with this device before "
  262. "declassifying it as a parent device."
  263. })
  264. if self.u_height and self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD:
  265. raise ValidationError({
  266. 'u_height': "Child device types must be 0U."
  267. })
  268. def save(self, *args, **kwargs):
  269. ret = super().save(*args, **kwargs)
  270. # Delete any previously uploaded image files that are no longer in use
  271. if self.front_image != self._original_front_image:
  272. self._original_front_image.delete(save=False)
  273. if self.rear_image != self._original_rear_image:
  274. self._original_rear_image.delete(save=False)
  275. return ret
  276. def delete(self, *args, **kwargs):
  277. super().delete(*args, **kwargs)
  278. # Delete any uploaded image files
  279. if self.front_image:
  280. self.front_image.delete(save=False)
  281. if self.rear_image:
  282. self.rear_image.delete(save=False)
  283. @property
  284. def is_parent_device(self):
  285. return self.subdevice_role == SubdeviceRoleChoices.ROLE_PARENT
  286. @property
  287. def is_child_device(self):
  288. return self.subdevice_role == SubdeviceRoleChoices.ROLE_CHILD
  289. #
  290. # Devices
  291. #
  292. @extras_features('custom_fields', 'export_templates', 'webhooks')
  293. class DeviceRole(OrganizationalModel):
  294. """
  295. Devices are organized by functional role; for example, "Core Switch" or "File Server". Each DeviceRole is assigned a
  296. color to be used when displaying rack elevations. The vm_role field determines whether the role is applicable to
  297. virtual machines as well.
  298. """
  299. name = models.CharField(
  300. max_length=100,
  301. unique=True
  302. )
  303. slug = models.SlugField(
  304. max_length=100,
  305. unique=True
  306. )
  307. color = ColorField(
  308. default=ColorChoices.COLOR_GREY
  309. )
  310. vm_role = models.BooleanField(
  311. default=True,
  312. verbose_name='VM Role',
  313. help_text='Virtual machines may be assigned to this role'
  314. )
  315. description = models.CharField(
  316. max_length=200,
  317. blank=True,
  318. )
  319. objects = RestrictedQuerySet.as_manager()
  320. csv_headers = ['name', 'slug', 'color', 'vm_role', 'description']
  321. class Meta:
  322. ordering = ['name']
  323. def __str__(self):
  324. return self.name
  325. def get_absolute_url(self):
  326. return reverse('dcim:devicerole', args=[self.pk])
  327. def to_csv(self):
  328. return (
  329. self.name,
  330. self.slug,
  331. self.color,
  332. self.vm_role,
  333. self.description,
  334. )
  335. @extras_features('custom_fields', 'export_templates', 'webhooks')
  336. class Platform(OrganizationalModel):
  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 reverse('dcim:platform', args=[self.pk])
  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(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. primary_ip4 = models.OneToOneField(
  488. to='ipam.IPAddress',
  489. on_delete=models.SET_NULL,
  490. related_name='primary_ip4_for',
  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='primary_ip6_for',
  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. images = GenericRelation(
  531. to='extras.ImageAttachment'
  532. )
  533. secrets = GenericRelation(
  534. to='secrets.Secret',
  535. content_type_field='assigned_object_type',
  536. object_id_field='assigned_object_id',
  537. related_query_name='device'
  538. )
  539. objects = ConfigContextModelQuerySet.as_manager()
  540. csv_headers = [
  541. 'name', 'device_role', 'tenant', 'manufacturer', 'device_type', 'platform', 'serial', 'asset_tag', 'status',
  542. 'site', 'location', 'rack_name', 'position', 'face', 'comments',
  543. ]
  544. clone_fields = [
  545. 'device_type', 'device_role', 'tenant', 'platform', 'site', 'location', 'rack', 'status', 'cluster',
  546. ]
  547. class Meta:
  548. ordering = ('_name', 'pk') # Name may be null
  549. unique_together = (
  550. ('site', 'tenant', 'name'), # See validate_unique below
  551. ('rack', 'position', 'face'),
  552. ('virtual_chassis', 'vc_position'),
  553. )
  554. def __str__(self):
  555. if self.name:
  556. return self.name
  557. elif self.virtual_chassis:
  558. return f'{self.virtual_chassis.name}:{self.vc_position} ({self.pk})'
  559. elif self.device_type:
  560. return f'{self.device_type.manufacturer} {self.device_type.model} ({self.pk})'
  561. return super().__str__()
  562. def get_absolute_url(self):
  563. return reverse('dcim:device', args=[self.pk])
  564. def validate_unique(self, exclude=None):
  565. # Check for a duplicate name on a device assigned to the same Site and no Tenant. This is necessary
  566. # because Django does not consider two NULL fields to be equal, and thus will not trigger a violation
  567. # of the uniqueness constraint without manual intervention.
  568. if self.name and hasattr(self, 'site') and self.tenant is None:
  569. if Device.objects.exclude(pk=self.pk).filter(
  570. name=self.name,
  571. site=self.site,
  572. tenant__isnull=True
  573. ):
  574. raise ValidationError({
  575. 'name': 'A device with this name already exists.'
  576. })
  577. super().validate_unique(exclude)
  578. def clean(self):
  579. super().clean()
  580. # Validate site/location/rack combination
  581. if self.rack and self.site != self.rack.site:
  582. raise ValidationError({
  583. 'rack': f"Rack {self.rack} does not belong to site {self.site}.",
  584. })
  585. if self.location and self.site != self.location.site:
  586. raise ValidationError({
  587. 'location': f"Location {self.location} does not belong to site {self.site}.",
  588. })
  589. if self.rack and self.location and self.rack.location != self.location:
  590. raise ValidationError({
  591. 'rack': f"Rack {self.rack} does not belong to location {self.location}.",
  592. })
  593. elif self.rack:
  594. self.location = self.rack.location
  595. if self.rack is None:
  596. if self.face:
  597. raise ValidationError({
  598. 'face': "Cannot select a rack face without assigning a rack.",
  599. })
  600. if self.position:
  601. raise ValidationError({
  602. 'position': "Cannot select a rack position without assigning a rack.",
  603. })
  604. # Validate position/face combination
  605. if self.position and not self.face:
  606. raise ValidationError({
  607. 'face': "Must specify rack face when defining rack position.",
  608. })
  609. # Prevent 0U devices from being assigned to a specific position
  610. if self.position and self.device_type.u_height == 0:
  611. raise ValidationError({
  612. 'position': f"A U0 device type ({self.device_type}) cannot be assigned to a rack position."
  613. })
  614. if self.rack:
  615. try:
  616. # Child devices cannot be assigned to a rack face/unit
  617. if self.device_type.is_child_device and self.face:
  618. raise ValidationError({
  619. 'face': "Child device types cannot be assigned to a rack face. This is an attribute of the "
  620. "parent device."
  621. })
  622. if self.device_type.is_child_device and self.position:
  623. raise ValidationError({
  624. 'position': "Child device types cannot be assigned to a rack position. This is an attribute of "
  625. "the parent device."
  626. })
  627. # Validate rack space
  628. rack_face = self.face if not self.device_type.is_full_depth else None
  629. exclude_list = [self.pk] if self.pk else []
  630. available_units = self.rack.get_available_units(
  631. u_height=self.device_type.u_height, rack_face=rack_face, exclude=exclude_list
  632. )
  633. if self.position and self.position not in available_units:
  634. raise ValidationError({
  635. 'position': f"U{self.position} is already occupied or does not have sufficient space to "
  636. f"accommodate this device type: {self.device_type} ({self.device_type.u_height}U)"
  637. })
  638. except DeviceType.DoesNotExist:
  639. pass
  640. # Validate primary IP addresses
  641. vc_interfaces = self.vc_interfaces()
  642. if self.primary_ip4:
  643. if self.primary_ip4.family != 4:
  644. raise ValidationError({
  645. 'primary_ip4': f"{self.primary_ip4} is not an IPv4 address."
  646. })
  647. if self.primary_ip4.assigned_object in vc_interfaces:
  648. pass
  649. elif self.primary_ip4.nat_inside is not None and self.primary_ip4.nat_inside.assigned_object in vc_interfaces:
  650. pass
  651. else:
  652. raise ValidationError({
  653. 'primary_ip4': f"The specified IP address ({self.primary_ip4}) is not assigned to this device."
  654. })
  655. if self.primary_ip6:
  656. if self.primary_ip6.family != 6:
  657. raise ValidationError({
  658. 'primary_ip6': f"{self.primary_ip6} is not an IPv6 address."
  659. })
  660. if self.primary_ip6.assigned_object in vc_interfaces:
  661. pass
  662. elif self.primary_ip6.nat_inside is not None and self.primary_ip6.nat_inside.assigned_object in vc_interfaces:
  663. pass
  664. else:
  665. raise ValidationError({
  666. 'primary_ip6': f"The specified IP address ({self.primary_ip6}) is not assigned to this device."
  667. })
  668. # Validate manufacturer/platform
  669. if hasattr(self, 'device_type') and self.platform:
  670. if self.platform.manufacturer and self.platform.manufacturer != self.device_type.manufacturer:
  671. raise ValidationError({
  672. 'platform': "The assigned platform is limited to {} device types, but this device's type belongs "
  673. "to {}.".format(self.platform.manufacturer, self.device_type.manufacturer)
  674. })
  675. # A Device can only be assigned to a Cluster in the same Site (or no Site)
  676. if self.cluster and self.cluster.site is not None and self.cluster.site != self.site:
  677. raise ValidationError({
  678. 'cluster': "The assigned cluster belongs to a different site ({})".format(self.cluster.site)
  679. })
  680. # Validate virtual chassis assignment
  681. if self.virtual_chassis and self.vc_position is None:
  682. raise ValidationError({
  683. 'vc_position': "A device assigned to a virtual chassis must have its position defined."
  684. })
  685. def save(self, *args, **kwargs):
  686. is_new = not bool(self.pk)
  687. super().save(*args, **kwargs)
  688. # If this is a new Device, instantiate all of the related components per the DeviceType definition
  689. if is_new:
  690. ConsolePort.objects.bulk_create(
  691. [x.instantiate(self) for x in self.device_type.consoleporttemplates.all()]
  692. )
  693. ConsoleServerPort.objects.bulk_create(
  694. [x.instantiate(self) for x in self.device_type.consoleserverporttemplates.all()]
  695. )
  696. PowerPort.objects.bulk_create(
  697. [x.instantiate(self) for x in self.device_type.powerporttemplates.all()]
  698. )
  699. PowerOutlet.objects.bulk_create(
  700. [x.instantiate(self) for x in self.device_type.poweroutlettemplates.all()]
  701. )
  702. Interface.objects.bulk_create(
  703. [x.instantiate(self) for x in self.device_type.interfacetemplates.all()]
  704. )
  705. RearPort.objects.bulk_create(
  706. [x.instantiate(self) for x in self.device_type.rearporttemplates.all()]
  707. )
  708. FrontPort.objects.bulk_create(
  709. [x.instantiate(self) for x in self.device_type.frontporttemplates.all()]
  710. )
  711. DeviceBay.objects.bulk_create(
  712. [x.instantiate(self) for x in self.device_type.devicebaytemplates.all()]
  713. )
  714. # Update Site and Rack assignment for any child Devices
  715. devices = Device.objects.filter(parent_bay__device=self)
  716. for device in devices:
  717. device.site = self.site
  718. device.rack = self.rack
  719. device.save()
  720. def to_csv(self):
  721. return (
  722. self.name or '',
  723. self.device_role.name,
  724. self.tenant.name if self.tenant else None,
  725. self.device_type.manufacturer.name,
  726. self.device_type.model,
  727. self.platform.name if self.platform else None,
  728. self.serial,
  729. self.asset_tag,
  730. self.get_status_display(),
  731. self.site.name,
  732. self.rack.location.name if self.rack and self.rack.location else None,
  733. self.rack.name if self.rack else None,
  734. self.position,
  735. self.get_face_display(),
  736. self.comments,
  737. )
  738. @property
  739. def identifier(self):
  740. """
  741. Return the device name if set; otherwise return the Device's primary key as {pk}
  742. """
  743. if self.name is not None:
  744. return self.name
  745. return '{{{}}}'.format(self.pk)
  746. @property
  747. def primary_ip(self):
  748. if settings.PREFER_IPV4 and self.primary_ip4:
  749. return self.primary_ip4
  750. elif self.primary_ip6:
  751. return self.primary_ip6
  752. elif self.primary_ip4:
  753. return self.primary_ip4
  754. else:
  755. return None
  756. @property
  757. def interfaces_count(self):
  758. if self.virtual_chassis and self.virtual_chassis.master == self:
  759. return self.vc_interfaces().count()
  760. return self.interfaces.count()
  761. def get_vc_master(self):
  762. """
  763. If this Device is a VirtualChassis member, return the VC master. Otherwise, return None.
  764. """
  765. return self.virtual_chassis.master if self.virtual_chassis else None
  766. def vc_interfaces(self, if_master=False):
  767. """
  768. Return a QuerySet matching all Interfaces assigned to this Device or, if this Device is a VC master, to another
  769. Device belonging to the same VirtualChassis.
  770. :param if_master: If True, return VC member interfaces only if this Device is the VC master.
  771. """
  772. filter = Q(device=self)
  773. if self.virtual_chassis and (not if_master or self.virtual_chassis.master == self):
  774. filter |= Q(device__virtual_chassis=self.virtual_chassis, mgmt_only=False)
  775. return Interface.objects.filter(filter)
  776. def get_cables(self, pk_list=False):
  777. """
  778. Return a QuerySet or PK list matching all Cables connected to a component of this Device.
  779. """
  780. from .cables import Cable
  781. cable_pks = []
  782. for component_model in [
  783. ConsolePort, ConsoleServerPort, PowerPort, PowerOutlet, Interface, FrontPort, RearPort
  784. ]:
  785. cable_pks += component_model.objects.filter(
  786. device=self, cable__isnull=False
  787. ).values_list('cable', flat=True)
  788. if pk_list:
  789. return cable_pks
  790. return Cable.objects.filter(pk__in=cable_pks)
  791. def get_children(self):
  792. """
  793. Return the set of child Devices installed in DeviceBays within this Device.
  794. """
  795. return Device.objects.filter(parent_bay__device=self.pk)
  796. def get_status_class(self):
  797. return DeviceStatusChoices.CSS_CLASSES.get(self.status)
  798. #
  799. # Virtual chassis
  800. #
  801. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  802. class VirtualChassis(PrimaryModel):
  803. """
  804. A collection of Devices which operate with a shared control plane (e.g. a switch stack).
  805. """
  806. master = models.OneToOneField(
  807. to='Device',
  808. on_delete=models.PROTECT,
  809. related_name='vc_master_for',
  810. blank=True,
  811. null=True
  812. )
  813. name = models.CharField(
  814. max_length=64
  815. )
  816. domain = models.CharField(
  817. max_length=30,
  818. blank=True
  819. )
  820. objects = RestrictedQuerySet.as_manager()
  821. csv_headers = ['name', 'domain', 'master']
  822. class Meta:
  823. ordering = ['name']
  824. verbose_name_plural = 'virtual chassis'
  825. def __str__(self):
  826. return self.name
  827. def get_absolute_url(self):
  828. return reverse('dcim:virtualchassis', kwargs={'pk': self.pk})
  829. def clean(self):
  830. super().clean()
  831. # Verify that the selected master device has been assigned to this VirtualChassis. (Skip when creating a new
  832. # VirtualChassis.)
  833. if self.pk and self.master and self.master not in self.members.all():
  834. raise ValidationError({
  835. 'master': f"The selected master ({self.master}) is not assigned to this virtual chassis."
  836. })
  837. def delete(self, *args, **kwargs):
  838. # Check for LAG interfaces split across member chassis
  839. interfaces = Interface.objects.filter(
  840. device__in=self.members.all(),
  841. lag__isnull=False
  842. ).exclude(
  843. lag__device=F('device')
  844. )
  845. if interfaces:
  846. raise ProtectedError(
  847. f"Unable to delete virtual chassis {self}. There are member interfaces which form a cross-chassis LAG",
  848. interfaces
  849. )
  850. return super().delete(*args, **kwargs)
  851. def to_csv(self):
  852. return (
  853. self.name,
  854. self.domain,
  855. self.master.name if self.master else None,
  856. )