devices.py 43 KB

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