devices.py 40 KB

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