devices.py 45 KB

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