racks.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. import decimal
  2. from functools import cached_property
  3. from django.conf import settings
  4. from django.contrib.contenttypes.fields import GenericRelation
  5. from django.contrib.postgres.fields import ArrayField
  6. from django.core.exceptions import ValidationError
  7. from django.core.validators import MaxValueValidator, MinValueValidator
  8. from django.db import models
  9. from django.db.models import Count
  10. from django.utils.translation import gettext_lazy as _
  11. from dcim.choices import *
  12. from dcim.constants import *
  13. from dcim.svg import RackElevationSVG
  14. from netbox.choices import ColorChoices
  15. from netbox.models import OrganizationalModel, PrimaryModel
  16. from netbox.models.mixins import WeightMixin
  17. from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
  18. from utilities.conversion import to_grams
  19. from utilities.data import array_to_string, drange
  20. from utilities.fields import ColorField
  21. from .device_components import PowerPort
  22. from .devices import Device, Module
  23. from .power import PowerFeed
  24. __all__ = (
  25. 'Rack',
  26. 'RackReservation',
  27. 'RackRole',
  28. 'RackType',
  29. )
  30. #
  31. # Rack Types
  32. #
  33. class RackBase(WeightMixin, PrimaryModel):
  34. """
  35. Base class for RackType & Rack. Holds
  36. """
  37. width = models.PositiveSmallIntegerField(
  38. choices=RackWidthChoices,
  39. default=RackWidthChoices.WIDTH_19IN,
  40. verbose_name=_('width'),
  41. help_text=_('Rail-to-rail width')
  42. )
  43. # Numbering
  44. u_height = models.PositiveSmallIntegerField(
  45. default=RACK_U_HEIGHT_DEFAULT,
  46. verbose_name=_('height (U)'),
  47. validators=[MinValueValidator(1), MaxValueValidator(RACK_U_HEIGHT_MAX)],
  48. help_text=_('Height in rack units')
  49. )
  50. starting_unit = models.PositiveSmallIntegerField(
  51. default=RACK_STARTING_UNIT_DEFAULT,
  52. verbose_name=_('starting unit'),
  53. validators=[MinValueValidator(1)],
  54. help_text=_('Starting unit for rack')
  55. )
  56. desc_units = models.BooleanField(
  57. default=False,
  58. verbose_name=_('descending units'),
  59. help_text=_('Units are numbered top-to-bottom')
  60. )
  61. # Dimensions
  62. outer_width = models.PositiveSmallIntegerField(
  63. verbose_name=_('outer width'),
  64. blank=True,
  65. null=True,
  66. help_text=_('Outer dimension of rack (width)')
  67. )
  68. outer_depth = models.PositiveSmallIntegerField(
  69. verbose_name=_('outer depth'),
  70. blank=True,
  71. null=True,
  72. help_text=_('Outer dimension of rack (depth)')
  73. )
  74. outer_unit = models.CharField(
  75. verbose_name=_('outer unit'),
  76. max_length=50,
  77. choices=RackDimensionUnitChoices,
  78. blank=True,
  79. null=True
  80. )
  81. mounting_depth = models.PositiveSmallIntegerField(
  82. verbose_name=_('mounting depth'),
  83. blank=True,
  84. null=True,
  85. help_text=(_(
  86. 'Maximum depth of a mounted device, in millimeters. For four-post racks, this is the distance between the '
  87. 'front and rear rails.'
  88. ))
  89. )
  90. # Weight
  91. # WeightMixin provides weight, weight_unit, and _abs_weight
  92. max_weight = models.PositiveIntegerField(
  93. verbose_name=_('max weight'),
  94. blank=True,
  95. null=True,
  96. help_text=_('Maximum load capacity for the rack')
  97. )
  98. # Stores the normalized max weight (in grams) for database ordering
  99. _abs_max_weight = models.PositiveBigIntegerField(
  100. blank=True,
  101. null=True
  102. )
  103. class Meta:
  104. abstract = True
  105. class RackType(RackBase):
  106. """
  107. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  108. Each Rack is assigned to a Site and (optionally) a Location.
  109. """
  110. form_factor = models.CharField(
  111. choices=RackFormFactorChoices,
  112. max_length=50,
  113. verbose_name=_('form factor')
  114. )
  115. manufacturer = models.ForeignKey(
  116. to='dcim.Manufacturer',
  117. on_delete=models.PROTECT,
  118. related_name='rack_types'
  119. )
  120. model = models.CharField(
  121. verbose_name=_('model'),
  122. max_length=100
  123. )
  124. slug = models.SlugField(
  125. verbose_name=_('slug'),
  126. max_length=100,
  127. unique=True
  128. )
  129. clone_fields = (
  130. 'manufacturer', 'form_factor', 'width', 'u_height', 'desc_units', 'outer_width', 'outer_depth',
  131. 'outer_unit', 'mounting_depth', 'weight', 'max_weight', 'weight_unit',
  132. )
  133. prerequisite_models = (
  134. 'dcim.Manufacturer',
  135. )
  136. class Meta:
  137. ordering = ('manufacturer', 'model')
  138. constraints = (
  139. models.UniqueConstraint(
  140. fields=('manufacturer', 'model'),
  141. name='%(app_label)s_%(class)s_unique_manufacturer_model'
  142. ),
  143. models.UniqueConstraint(
  144. fields=('manufacturer', 'slug'),
  145. name='%(app_label)s_%(class)s_unique_manufacturer_slug'
  146. ),
  147. )
  148. verbose_name = _('rack type')
  149. verbose_name_plural = _('rack types')
  150. def __str__(self):
  151. return self.model
  152. @property
  153. def full_name(self):
  154. return f"{self.manufacturer} {self.model}"
  155. def clean(self):
  156. super().clean()
  157. # Validate outer dimensions and unit
  158. if (self.outer_width is not None or self.outer_depth is not None) and not self.outer_unit:
  159. raise ValidationError(_("Must specify a unit when setting an outer width/depth"))
  160. # Validate max_weight and weight_unit
  161. if self.max_weight and not self.weight_unit:
  162. raise ValidationError(_("Must specify a unit when setting a maximum weight"))
  163. def save(self, *args, **kwargs):
  164. # Store the given max weight (if any) in grams for use in database ordering
  165. if self.max_weight and self.weight_unit:
  166. self._abs_max_weight = to_grams(self.max_weight, self.weight_unit)
  167. else:
  168. self._abs_max_weight = None
  169. # Clear unit if outer width & depth are not set
  170. if self.outer_width is None and self.outer_depth is None:
  171. self.outer_unit = None
  172. super().save(*args, **kwargs)
  173. # Update all Racks associated with this RackType
  174. for rack in self.racks.all():
  175. rack.snapshot()
  176. rack.copy_racktype_attrs()
  177. rack.save()
  178. @property
  179. def units(self):
  180. """
  181. Return a list of unit numbers, top to bottom.
  182. """
  183. if self.desc_units:
  184. return drange(decimal.Decimal(self.starting_unit), self.u_height + self.starting_unit, 0.5)
  185. return drange(self.u_height + decimal.Decimal(0.5) + self.starting_unit - 1, 0.5 + self.starting_unit - 1, -0.5)
  186. #
  187. # Racks
  188. #
  189. class RackRole(OrganizationalModel):
  190. """
  191. Racks can be organized by functional role, similar to Devices.
  192. """
  193. color = ColorField(
  194. verbose_name=_('color'),
  195. default=ColorChoices.COLOR_GREY
  196. )
  197. class Meta:
  198. ordering = ('name',)
  199. verbose_name = _('rack role')
  200. verbose_name_plural = _('rack roles')
  201. class Rack(ContactsMixin, ImageAttachmentsMixin, RackBase):
  202. """
  203. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  204. Each Rack is assigned to a Site and (optionally) a Location.
  205. """
  206. # Fields which cannot be set locally if a RackType is assigned
  207. RACKTYPE_FIELDS = (
  208. 'form_factor', 'width', 'u_height', 'starting_unit', 'desc_units', 'outer_width', 'outer_depth',
  209. 'outer_unit', 'mounting_depth', 'weight', 'weight_unit', 'max_weight',
  210. )
  211. form_factor = models.CharField(
  212. choices=RackFormFactorChoices,
  213. max_length=50,
  214. blank=True,
  215. null=True,
  216. verbose_name=_('form factor')
  217. )
  218. rack_type = models.ForeignKey(
  219. to='dcim.RackType',
  220. on_delete=models.PROTECT,
  221. related_name='racks',
  222. blank=True,
  223. null=True,
  224. )
  225. name = models.CharField(
  226. verbose_name=_('name'),
  227. max_length=100,
  228. db_collation="natural_sort"
  229. )
  230. facility_id = models.CharField(
  231. max_length=50,
  232. blank=True,
  233. null=True,
  234. verbose_name=_('facility ID'),
  235. help_text=_("Locally-assigned identifier")
  236. )
  237. site = models.ForeignKey(
  238. to='dcim.Site',
  239. on_delete=models.PROTECT,
  240. related_name='racks'
  241. )
  242. location = models.ForeignKey(
  243. to='dcim.Location',
  244. on_delete=models.SET_NULL,
  245. related_name='racks',
  246. blank=True,
  247. null=True
  248. )
  249. tenant = models.ForeignKey(
  250. to='tenancy.Tenant',
  251. on_delete=models.PROTECT,
  252. related_name='racks',
  253. blank=True,
  254. null=True
  255. )
  256. status = models.CharField(
  257. verbose_name=_('status'),
  258. max_length=50,
  259. choices=RackStatusChoices,
  260. default=RackStatusChoices.STATUS_ACTIVE
  261. )
  262. role = models.ForeignKey(
  263. to='dcim.RackRole',
  264. on_delete=models.PROTECT,
  265. related_name='racks',
  266. blank=True,
  267. null=True,
  268. help_text=_('Functional role')
  269. )
  270. serial = models.CharField(
  271. max_length=50,
  272. blank=True,
  273. verbose_name=_('serial number')
  274. )
  275. asset_tag = models.CharField(
  276. max_length=50,
  277. blank=True,
  278. null=True,
  279. unique=True,
  280. verbose_name=_('asset tag'),
  281. help_text=_('A unique tag used to identify this rack')
  282. )
  283. airflow = models.CharField(
  284. verbose_name=_('airflow'),
  285. max_length=50,
  286. choices=RackAirflowChoices,
  287. blank=True,
  288. null=True
  289. )
  290. # Generic relations
  291. vlan_groups = GenericRelation(
  292. to='ipam.VLANGroup',
  293. content_type_field='scope_type',
  294. object_id_field='scope_id',
  295. related_query_name='rack'
  296. )
  297. clone_fields = (
  298. 'site', 'location', 'tenant', 'status', 'role', 'form_factor', 'width', 'airflow', 'u_height', 'desc_units',
  299. 'outer_width', 'outer_depth', 'outer_unit', 'mounting_depth', 'weight', 'max_weight', 'weight_unit',
  300. )
  301. prerequisite_models = (
  302. 'dcim.Site',
  303. )
  304. class Meta:
  305. ordering = ('site', 'location', 'name', 'pk') # (site, location, name) may be non-unique
  306. constraints = (
  307. # Name and facility_id must be unique *only* within a Location
  308. models.UniqueConstraint(
  309. fields=('location', 'name'),
  310. name='%(app_label)s_%(class)s_unique_location_name'
  311. ),
  312. models.UniqueConstraint(
  313. fields=('location', 'facility_id'),
  314. name='%(app_label)s_%(class)s_unique_location_facility_id'
  315. ),
  316. )
  317. verbose_name = _('rack')
  318. verbose_name_plural = _('racks')
  319. def __str__(self):
  320. if self.facility_id:
  321. return f'{self.name} ({self.facility_id})'
  322. return self.name
  323. def clean(self):
  324. super().clean()
  325. # Validate location/site assignment
  326. if self.site and self.location and self.location.site != self.site:
  327. raise ValidationError(_("Assigned location must belong to parent site ({site}).").format(site=self.site))
  328. # Validate outer dimensions and unit
  329. if (self.outer_width is not None or self.outer_depth is not None) and not self.outer_unit:
  330. raise ValidationError(_("Must specify a unit when setting an outer width/depth"))
  331. # Validate max_weight and weight_unit
  332. if self.max_weight and not self.weight_unit:
  333. raise ValidationError(_("Must specify a unit when setting a maximum weight"))
  334. if not self._state.adding:
  335. mounted_devices = Device.objects.filter(rack=self).exclude(position__isnull=True).order_by('position')
  336. effective_u_height = self.rack_type.u_height if self.rack_type else self.u_height
  337. effective_starting_unit = self.rack_type.starting_unit if self.rack_type else self.starting_unit
  338. # Validate that Rack is tall enough to house the highest mounted Device
  339. if top_device := mounted_devices.last():
  340. min_height = top_device.position + top_device.device_type.u_height - effective_starting_unit
  341. if effective_u_height < min_height:
  342. field = 'rack_type' if self.rack_type else 'u_height'
  343. raise ValidationError({
  344. field: _(
  345. "Rack must be at least {min_height}U tall to house currently installed devices."
  346. ).format(min_height=min_height)
  347. })
  348. # Validate that the Rack's starting unit is less than or equal to the position of the lowest mounted Device
  349. if last_device := mounted_devices.first():
  350. if effective_starting_unit > last_device.position:
  351. field = 'rack_type' if self.rack_type else 'starting_unit'
  352. raise ValidationError({
  353. field: _("Rack unit numbering must begin at {position} or less to house "
  354. "currently installed devices.").format(position=last_device.position)
  355. })
  356. # Validate that Rack was assigned a Location of its same site, if applicable
  357. if self.location:
  358. if self.location.site != self.site:
  359. raise ValidationError({
  360. 'location': _("Location must be from the same site, {site}.").format(site=self.site)
  361. })
  362. def save(self, *args, **kwargs):
  363. self.copy_racktype_attrs()
  364. # Store the given max weight (if any) in grams for use in database ordering
  365. if self.max_weight and self.weight_unit:
  366. self._abs_max_weight = to_grams(self.max_weight, self.weight_unit)
  367. else:
  368. self._abs_max_weight = None
  369. # Clear unit if outer width & depth are not set
  370. if self.outer_width is None and self.outer_depth is None:
  371. self.outer_unit = None
  372. super().save(*args, **kwargs)
  373. def copy_racktype_attrs(self):
  374. """
  375. Copy physical attributes from the assigned RackType (if any).
  376. """
  377. if self.rack_type:
  378. for field_name in self.RACKTYPE_FIELDS:
  379. setattr(self, field_name, getattr(self.rack_type, field_name))
  380. @property
  381. def units(self):
  382. """
  383. Return a list of unit numbers, top to bottom.
  384. """
  385. if self.desc_units:
  386. return drange(decimal.Decimal(self.starting_unit), self.u_height + self.starting_unit, 0.5)
  387. return drange(self.u_height + decimal.Decimal(0.5) + self.starting_unit - 1, 0.5 + self.starting_unit - 1, -0.5)
  388. def get_status_color(self):
  389. return RackStatusChoices.colors.get(self.status)
  390. def get_rack_units(self, user=None, face=DeviceFaceChoices.FACE_FRONT, exclude=None, expand_devices=True):
  391. """
  392. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  393. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  394. :param face: Rack face (front or rear)
  395. :param user: User instance to be used for evaluating device view permissions. If None, all devices
  396. will be included.
  397. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  398. :param expand_devices: When True, all units that a device occupies will be listed with each containing a
  399. reference to the device. When False, only the bottom most unit for a device is included and that unit
  400. contains a height attribute for the device
  401. """
  402. elevation = {}
  403. for u in self.units:
  404. u_name = f'U{u}'.split('.')[0] if not u % 1 else f'U{u}'
  405. elevation[u] = {
  406. 'id': u,
  407. 'name': u_name,
  408. 'face': face,
  409. 'device': None,
  410. 'occupied': False
  411. }
  412. # Add devices to rack units list
  413. if not self._state.adding:
  414. # Retrieve all devices installed within the rack
  415. devices = Device.objects.prefetch_related(
  416. 'device_type',
  417. 'device_type__manufacturer',
  418. 'role'
  419. ).annotate(
  420. devicebay_count=Count('devicebays')
  421. ).exclude(
  422. pk=exclude
  423. ).filter(
  424. rack=self,
  425. position__gt=0,
  426. device_type__u_height__gt=0
  427. ).filter(
  428. Q(face=face) | Q(device_type__is_full_depth=True)
  429. )
  430. # Determine which devices the user has permission to view
  431. permitted_device_ids = []
  432. if user is not None:
  433. permitted_device_ids = self.devices.restrict(user, 'view').values_list('pk', flat=True)
  434. for device in devices:
  435. if expand_devices:
  436. for u in drange(device.position, device.position + device.device_type.u_height, 0.5):
  437. if user is None or device.pk in permitted_device_ids:
  438. elevation[u]['device'] = device
  439. elevation[u]['occupied'] = True
  440. else:
  441. if user is None or device.pk in permitted_device_ids:
  442. elevation[device.position]['device'] = device
  443. elevation[device.position]['occupied'] = True
  444. elevation[device.position]['height'] = device.device_type.u_height
  445. return [u for u in elevation.values()]
  446. def get_available_units(self, u_height=1, rack_face=None, exclude=None, ignore_excluded_devices=False):
  447. """
  448. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  449. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  450. position to another within a rack).
  451. :param u_height: Minimum number of contiguous free units required
  452. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  453. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  454. :param ignore_excluded_devices: Ignore devices that are marked to exclude from utilization calculations
  455. """
  456. # Gather all devices which consume U space within the rack
  457. devices = self.devices.prefetch_related('device_type').filter(position__gte=1)
  458. if ignore_excluded_devices:
  459. devices = devices.exclude(device_type__exclude_from_utilization=True)
  460. if exclude is not None:
  461. devices = devices.exclude(pk__in=exclude)
  462. # Initialize the rack unit skeleton
  463. units = list(self.units)
  464. # Remove units consumed by installed devices
  465. for d in devices:
  466. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  467. for u in drange(d.position, d.position + d.device_type.u_height, 0.5):
  468. try:
  469. units.remove(u)
  470. except ValueError:
  471. # Found overlapping devices in the rack!
  472. pass
  473. # Remove units without enough space above them to accommodate a device of the specified height
  474. available_units = []
  475. for u in units:
  476. if set(drange(u, u + decimal.Decimal(u_height), 0.5)).issubset(units):
  477. available_units.append(u)
  478. return list(reversed(available_units))
  479. def get_reserved_units(self):
  480. """
  481. Return a dictionary mapping all reserved units within the rack to their reservation.
  482. """
  483. reserved_units = {}
  484. for reservation in self.reservations.all():
  485. for u in reservation.units:
  486. reserved_units[u] = reservation
  487. return reserved_units
  488. def get_elevation_svg(
  489. self,
  490. face=DeviceFaceChoices.FACE_FRONT,
  491. user=None,
  492. unit_width=None,
  493. unit_height=None,
  494. legend_width=RACK_ELEVATION_DEFAULT_LEGEND_WIDTH,
  495. margin_width=RACK_ELEVATION_DEFAULT_MARGIN_WIDTH,
  496. include_images=True,
  497. base_url=None,
  498. highlight_params=None
  499. ):
  500. """
  501. Return an SVG of the rack elevation
  502. :param face: Enum of [front, rear] representing the desired side of the rack elevation to render
  503. :param user: User instance to be used for evaluating device view permissions. If None, all devices
  504. will be included.
  505. :param unit_width: Width in pixels for the rendered drawing
  506. :param unit_height: Height of each rack unit for the rendered drawing. Note this is not the total
  507. height of the elevation
  508. :param legend_width: Width of the unit legend, in pixels
  509. :param margin_width: Width of the rigth-hand margin, in pixels
  510. :param include_images: Embed front/rear device images where available
  511. :param base_url: Base URL for links and images. If none, URLs will be relative.
  512. """
  513. elevation = RackElevationSVG(
  514. self,
  515. unit_width=unit_width,
  516. unit_height=unit_height,
  517. legend_width=legend_width,
  518. margin_width=margin_width,
  519. user=user,
  520. include_images=include_images,
  521. base_url=base_url,
  522. highlight_params=highlight_params
  523. )
  524. return elevation.render(face)
  525. def get_0u_devices(self):
  526. return self.devices.filter(position=0)
  527. def get_utilization(self):
  528. """
  529. Determine the utilization rate of the rack and return it as a percentage. Occupied and reserved units both count
  530. as utilized.
  531. """
  532. # Determine unoccupied units
  533. total_units = len(list(self.units))
  534. available_units = self.get_available_units(u_height=0.5, ignore_excluded_devices=True)
  535. # Remove reserved units
  536. for ru in self.get_reserved_units():
  537. for u in drange(ru, ru + 1, 0.5):
  538. if u in available_units:
  539. available_units.remove(u)
  540. occupied_unit_count = total_units - len(available_units)
  541. percentage = float(occupied_unit_count) / total_units * 100
  542. return percentage
  543. def get_power_utilization(self):
  544. """
  545. Determine the utilization rate of power in the rack and return it as a percentage.
  546. """
  547. powerfeeds = PowerFeed.objects.filter(rack=self)
  548. available_power_total = sum(pf.available_power for pf in powerfeeds)
  549. if not available_power_total:
  550. return 0
  551. powerports = []
  552. for powerfeed in powerfeeds:
  553. powerports.extend([
  554. peer for peer in powerfeed.link_peers if isinstance(peer, PowerPort)
  555. ])
  556. allocated_draw = sum([
  557. powerport.get_power_draw()['allocated'] for powerport in powerports
  558. ])
  559. return round(allocated_draw / available_power_total * 100, 1)
  560. @cached_property
  561. def total_weight(self):
  562. total_weight = sum(
  563. device.device_type._abs_weight
  564. for device in self.devices.exclude(device_type___abs_weight__isnull=True).prefetch_related('device_type')
  565. )
  566. total_weight += sum(
  567. module.module_type._abs_weight
  568. for module in Module.objects.filter(device__rack=self)
  569. .exclude(module_type___abs_weight__isnull=True)
  570. .prefetch_related('module_type')
  571. )
  572. if self._abs_weight:
  573. total_weight += self._abs_weight
  574. return round(total_weight / 1000, 2)
  575. class RackReservation(PrimaryModel):
  576. """
  577. One or more reserved units within a Rack.
  578. """
  579. rack = models.ForeignKey(
  580. to='dcim.Rack',
  581. on_delete=models.CASCADE,
  582. related_name='reservations'
  583. )
  584. units = ArrayField(
  585. verbose_name=_('units'),
  586. base_field=models.PositiveSmallIntegerField()
  587. )
  588. tenant = models.ForeignKey(
  589. to='tenancy.Tenant',
  590. on_delete=models.PROTECT,
  591. related_name='rackreservations',
  592. blank=True,
  593. null=True
  594. )
  595. user = models.ForeignKey(
  596. to=settings.AUTH_USER_MODEL,
  597. on_delete=models.PROTECT
  598. )
  599. description = models.CharField(
  600. verbose_name=_('description'),
  601. max_length=200
  602. )
  603. clone_fields = ('rack', 'user', 'tenant')
  604. prerequisite_models = (
  605. 'dcim.Rack',
  606. )
  607. class Meta:
  608. ordering = ['created', 'pk']
  609. verbose_name = _('rack reservation')
  610. verbose_name_plural = _('rack reservations')
  611. def __str__(self):
  612. return "Reservation for rack {}".format(self.rack)
  613. def clean(self):
  614. super().clean()
  615. if hasattr(self, 'rack') and self.units:
  616. # Validate that all specified units exist in the Rack.
  617. invalid_units = [u for u in self.units if u not in self.rack.units]
  618. if invalid_units:
  619. raise ValidationError({
  620. 'units': _("Invalid unit(s) for {height}U rack: {unit_list}").format(
  621. height=self.rack.u_height,
  622. unit_list=', '.join([str(u) for u in invalid_units])
  623. ),
  624. })
  625. # Check that none of the units has already been reserved for this Rack.
  626. reserved_units = []
  627. for resv in self.rack.reservations.exclude(pk=self.pk):
  628. reserved_units += resv.units
  629. conflicting_units = [u for u in self.units if u in reserved_units]
  630. if conflicting_units:
  631. raise ValidationError({
  632. 'units': _('The following units have already been reserved: {unit_list}').format(
  633. unit_list=', '.join([str(u) for u in conflicting_units])
  634. )
  635. })
  636. @property
  637. def unit_list(self):
  638. return array_to_string(self.units)