devices.py 37 KB

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