racks.py 21 KB

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