racks.py 21 KB

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