racks.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. from collections import OrderedDict
  2. from django.conf import settings
  3. from django.contrib.auth.models import User
  4. from django.contrib.contenttypes.fields import GenericRelation
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.contrib.postgres.fields import ArrayField
  7. from django.core.exceptions import ValidationError
  8. from django.core.validators import MaxValueValidator, MinValueValidator
  9. from django.db import models
  10. from django.db.models import Count, Sum
  11. from django.urls import reverse
  12. from dcim.choices import *
  13. from dcim.constants import *
  14. from dcim.svg import RackElevationSVG
  15. from extras.utils import extras_features
  16. from netbox.models import OrganizationalModel, PrimaryModel
  17. from utilities.choices import ColorChoices
  18. from utilities.fields import ColorField, NaturalOrderingField
  19. from utilities.querysets import RestrictedQuerySet
  20. from utilities.utils import array_to_string
  21. from .device_components import PowerOutlet, PowerPort
  22. from .devices import Device
  23. from .power import PowerFeed
  24. __all__ = (
  25. 'Rack',
  26. 'RackReservation',
  27. 'RackRole',
  28. )
  29. #
  30. # Racks
  31. #
  32. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  33. class RackRole(OrganizationalModel):
  34. """
  35. Racks can be organized by functional role, similar to Devices.
  36. """
  37. name = models.CharField(
  38. max_length=100,
  39. unique=True
  40. )
  41. slug = models.SlugField(
  42. max_length=100,
  43. unique=True
  44. )
  45. color = ColorField(
  46. default=ColorChoices.COLOR_GREY
  47. )
  48. description = models.CharField(
  49. max_length=200,
  50. blank=True,
  51. )
  52. objects = RestrictedQuerySet.as_manager()
  53. class Meta:
  54. ordering = ['name']
  55. def __str__(self):
  56. return self.name
  57. def get_absolute_url(self):
  58. return reverse('dcim:rackrole', args=[self.pk])
  59. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  60. class Rack(PrimaryModel):
  61. """
  62. Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
  63. Each Rack is assigned to a Site and (optionally) a Location.
  64. """
  65. name = models.CharField(
  66. max_length=100
  67. )
  68. _name = NaturalOrderingField(
  69. target_field='name',
  70. max_length=100,
  71. blank=True
  72. )
  73. facility_id = models.CharField(
  74. max_length=50,
  75. blank=True,
  76. null=True,
  77. verbose_name='Facility ID',
  78. help_text='Locally-assigned identifier'
  79. )
  80. site = models.ForeignKey(
  81. to='dcim.Site',
  82. on_delete=models.PROTECT,
  83. related_name='racks'
  84. )
  85. location = models.ForeignKey(
  86. to='dcim.Location',
  87. on_delete=models.SET_NULL,
  88. related_name='racks',
  89. blank=True,
  90. null=True
  91. )
  92. tenant = models.ForeignKey(
  93. to='tenancy.Tenant',
  94. on_delete=models.PROTECT,
  95. related_name='racks',
  96. blank=True,
  97. null=True
  98. )
  99. status = models.CharField(
  100. max_length=50,
  101. choices=RackStatusChoices,
  102. default=RackStatusChoices.STATUS_ACTIVE
  103. )
  104. role = models.ForeignKey(
  105. to='dcim.RackRole',
  106. on_delete=models.PROTECT,
  107. related_name='racks',
  108. blank=True,
  109. null=True,
  110. help_text='Functional role'
  111. )
  112. serial = models.CharField(
  113. max_length=50,
  114. blank=True,
  115. verbose_name='Serial number'
  116. )
  117. asset_tag = models.CharField(
  118. max_length=50,
  119. blank=True,
  120. null=True,
  121. unique=True,
  122. verbose_name='Asset tag',
  123. help_text='A unique tag used to identify this rack'
  124. )
  125. type = models.CharField(
  126. choices=RackTypeChoices,
  127. max_length=50,
  128. blank=True,
  129. verbose_name='Type'
  130. )
  131. width = models.PositiveSmallIntegerField(
  132. choices=RackWidthChoices,
  133. default=RackWidthChoices.WIDTH_19IN,
  134. verbose_name='Width',
  135. help_text='Rail-to-rail width'
  136. )
  137. u_height = models.PositiveSmallIntegerField(
  138. default=RACK_U_HEIGHT_DEFAULT,
  139. verbose_name='Height (U)',
  140. validators=[MinValueValidator(1), MaxValueValidator(100)],
  141. help_text='Height in rack units'
  142. )
  143. desc_units = models.BooleanField(
  144. default=False,
  145. verbose_name='Descending units',
  146. help_text='Units are numbered top-to-bottom'
  147. )
  148. outer_width = models.PositiveSmallIntegerField(
  149. blank=True,
  150. null=True,
  151. help_text='Outer dimension of rack (width)'
  152. )
  153. outer_depth = models.PositiveSmallIntegerField(
  154. blank=True,
  155. null=True,
  156. help_text='Outer dimension of rack (depth)'
  157. )
  158. outer_unit = models.CharField(
  159. max_length=50,
  160. choices=RackDimensionUnitChoices,
  161. blank=True,
  162. )
  163. comments = models.TextField(
  164. blank=True
  165. )
  166. images = GenericRelation(
  167. to='extras.ImageAttachment'
  168. )
  169. objects = RestrictedQuerySet.as_manager()
  170. clone_fields = [
  171. 'site', 'location', 'tenant', 'status', 'role', 'type', 'width', 'u_height', 'desc_units', 'outer_width',
  172. 'outer_depth', 'outer_unit',
  173. ]
  174. class Meta:
  175. ordering = ('site', 'location', '_name', 'pk') # (site, location, name) may be non-unique
  176. unique_together = (
  177. # Name and facility_id must be unique *only* within a Location
  178. ('location', 'name'),
  179. ('location', 'facility_id'),
  180. )
  181. def __str__(self):
  182. if self.facility_id:
  183. return f'{self.name} ({self.facility_id})'
  184. return self.name
  185. def get_absolute_url(self):
  186. return reverse('dcim:rack', args=[self.pk])
  187. def clean(self):
  188. super().clean()
  189. # Validate location/site assignment
  190. if self.site and self.location and self.location.site != self.site:
  191. raise ValidationError(f"Assigned location must belong to parent site ({self.site}).")
  192. # Validate outer dimensions and unit
  193. if (self.outer_width is not None or self.outer_depth is not None) and not self.outer_unit:
  194. raise ValidationError("Must specify a unit when setting an outer width/depth")
  195. elif self.outer_width is None and self.outer_depth is None:
  196. self.outer_unit = ''
  197. if self.pk:
  198. # Validate that Rack is tall enough to house the installed Devices
  199. top_device = Device.objects.filter(
  200. rack=self
  201. ).exclude(
  202. position__isnull=True
  203. ).order_by('-position').first()
  204. if top_device:
  205. min_height = top_device.position + top_device.device_type.u_height - 1
  206. if self.u_height < min_height:
  207. raise ValidationError({
  208. 'u_height': "Rack must be at least {}U tall to house currently installed devices.".format(
  209. min_height
  210. )
  211. })
  212. # Validate that Rack was assigned a Location of its same site, if applicable
  213. if self.location:
  214. if self.location.site != self.site:
  215. raise ValidationError({
  216. 'location': f"Location must be from the same site, {self.site}."
  217. })
  218. @property
  219. def units(self):
  220. if self.desc_units:
  221. return range(1, self.u_height + 1)
  222. else:
  223. return reversed(range(1, self.u_height + 1))
  224. def get_status_class(self):
  225. return RackStatusChoices.CSS_CLASSES.get(self.status)
  226. def get_rack_units(self, user=None, face=DeviceFaceChoices.FACE_FRONT, exclude=None, expand_devices=True):
  227. """
  228. Return a list of rack units as dictionaries. Example: {'device': None, 'face': 0, 'id': 48, 'name': 'U48'}
  229. Each key 'device' is either a Device or None. By default, multi-U devices are repeated for each U they occupy.
  230. :param face: Rack face (front or rear)
  231. :param user: User instance to be used for evaluating device view permissions. If None, all devices
  232. will be included.
  233. :param exclude: PK of a Device to exclude (optional); helpful when relocating a Device within a Rack
  234. :param expand_devices: When True, all units that a device occupies will be listed with each containing a
  235. reference to the device. When False, only the bottom most unit for a device is included and that unit
  236. contains a height attribute for the device
  237. """
  238. elevation = OrderedDict()
  239. for u in self.units:
  240. elevation[u] = {
  241. 'id': u,
  242. 'name': f'U{u}',
  243. 'face': face,
  244. 'device': None,
  245. 'occupied': False
  246. }
  247. # Add devices to rack units list
  248. if self.pk:
  249. # Retrieve all devices installed within the rack
  250. queryset = Device.objects.prefetch_related(
  251. 'device_type',
  252. 'device_type__manufacturer',
  253. 'device_role'
  254. ).annotate(
  255. devicebay_count=Count('devicebays')
  256. ).exclude(
  257. pk=exclude
  258. ).filter(
  259. rack=self,
  260. position__gt=0,
  261. device_type__u_height__gt=0
  262. ).filter(
  263. Q(face=face) | Q(device_type__is_full_depth=True)
  264. )
  265. # Determine which devices the user has permission to view
  266. permitted_device_ids = []
  267. if user is not None:
  268. permitted_device_ids = self.devices.restrict(user, 'view').values_list('pk', flat=True)
  269. for device in queryset:
  270. if expand_devices:
  271. for u in range(device.position, device.position + device.device_type.u_height):
  272. if user is None or device.pk in permitted_device_ids:
  273. elevation[u]['device'] = device
  274. elevation[u]['occupied'] = True
  275. else:
  276. if user is None or device.pk in permitted_device_ids:
  277. elevation[device.position]['device'] = device
  278. elevation[device.position]['occupied'] = True
  279. elevation[device.position]['height'] = device.device_type.u_height
  280. for u in range(device.position + 1, device.position + device.device_type.u_height):
  281. elevation.pop(u, None)
  282. return [u for u in elevation.values()]
  283. def get_available_units(self, u_height=1, rack_face=None, exclude=None):
  284. """
  285. Return a list of units within the rack available to accommodate a device of a given U height (default 1).
  286. Optionally exclude one or more devices when calculating empty units (needed when moving a device from one
  287. position to another within a rack).
  288. :param u_height: Minimum number of contiguous free units required
  289. :param rack_face: The face of the rack (front or rear) required; 'None' if device is full depth
  290. :param exclude: List of devices IDs to exclude (useful when moving a device within a rack)
  291. """
  292. # Gather all devices which consume U space within the rack
  293. devices = self.devices.prefetch_related('device_type').filter(position__gte=1)
  294. if exclude is not None:
  295. devices = devices.exclude(pk__in=exclude)
  296. # Initialize the rack unit skeleton
  297. units = list(range(1, self.u_height + 1))
  298. # Remove units consumed by installed devices
  299. for d in devices:
  300. if rack_face is None or d.face == rack_face or d.device_type.is_full_depth:
  301. for u in range(d.position, d.position + d.device_type.u_height):
  302. try:
  303. units.remove(u)
  304. except ValueError:
  305. # Found overlapping devices in the rack!
  306. pass
  307. # Remove units without enough space above them to accommodate a device of the specified height
  308. available_units = []
  309. for u in units:
  310. if set(range(u, u + u_height)).issubset(units):
  311. available_units.append(u)
  312. return list(reversed(available_units))
  313. def get_reserved_units(self):
  314. """
  315. Return a dictionary mapping all reserved units within the rack to their reservation.
  316. """
  317. reserved_units = {}
  318. for r in self.reservations.all():
  319. for u in r.units:
  320. reserved_units[u] = r
  321. return reserved_units
  322. def get_elevation_svg(
  323. self,
  324. face=DeviceFaceChoices.FACE_FRONT,
  325. user=None,
  326. unit_width=settings.RACK_ELEVATION_DEFAULT_UNIT_WIDTH,
  327. unit_height=settings.RACK_ELEVATION_DEFAULT_UNIT_HEIGHT,
  328. legend_width=RACK_ELEVATION_LEGEND_WIDTH_DEFAULT,
  329. include_images=True,
  330. base_url=None
  331. ):
  332. """
  333. Return an SVG of the rack elevation
  334. :param face: Enum of [front, rear] representing the desired side of the rack elevation to render
  335. :param user: User instance to be used for evaluating device view permissions. If None, all devices
  336. will be included.
  337. :param unit_width: Width in pixels for the rendered drawing
  338. :param unit_height: Height of each rack unit for the rendered drawing. Note this is not the total
  339. height of the elevation
  340. :param legend_width: Width of the unit legend, in pixels
  341. :param include_images: Embed front/rear device images where available
  342. :param base_url: Base URL for links and images. If none, URLs will be relative.
  343. """
  344. elevation = RackElevationSVG(self, user=user, include_images=include_images, base_url=base_url)
  345. return elevation.render(face, unit_width, unit_height, legend_width)
  346. def get_0u_devices(self):
  347. return self.devices.filter(position=0)
  348. def get_utilization(self):
  349. """
  350. Determine the utilization rate of the rack and return it as a percentage. Occupied and reserved units both count
  351. as utilized.
  352. """
  353. # Determine unoccupied units
  354. available_units = self.get_available_units()
  355. # Remove reserved units
  356. for u in self.get_reserved_units():
  357. if u in available_units:
  358. available_units.remove(u)
  359. occupied_unit_count = self.u_height - len(available_units)
  360. percentage = int(float(occupied_unit_count) / self.u_height * 100)
  361. return percentage
  362. def get_power_utilization(self):
  363. """
  364. Determine the utilization rate of power in the rack and return it as a percentage.
  365. """
  366. powerfeeds = PowerFeed.objects.filter(rack=self)
  367. available_power_total = sum(pf.available_power for pf in powerfeeds)
  368. if not available_power_total:
  369. return 0
  370. pf_powerports = PowerPort.objects.filter(
  371. _cable_peer_type=ContentType.objects.get_for_model(PowerFeed),
  372. _cable_peer_id__in=powerfeeds.values_list('id', flat=True)
  373. )
  374. poweroutlets = PowerOutlet.objects.filter(power_port_id__in=pf_powerports)
  375. allocated_draw_total = PowerPort.objects.filter(
  376. _cable_peer_type=ContentType.objects.get_for_model(PowerOutlet),
  377. _cable_peer_id__in=poweroutlets.values_list('id', flat=True)
  378. ).aggregate(Sum('allocated_draw'))['allocated_draw__sum'] or 0
  379. return int(allocated_draw_total / available_power_total * 100)
  380. @extras_features('custom_fields', 'custom_links', 'export_templates', 'tags', 'webhooks')
  381. class RackReservation(PrimaryModel):
  382. """
  383. One or more reserved units within a Rack.
  384. """
  385. rack = models.ForeignKey(
  386. to='dcim.Rack',
  387. on_delete=models.CASCADE,
  388. related_name='reservations'
  389. )
  390. units = ArrayField(
  391. base_field=models.PositiveSmallIntegerField()
  392. )
  393. tenant = models.ForeignKey(
  394. to='tenancy.Tenant',
  395. on_delete=models.PROTECT,
  396. related_name='rackreservations',
  397. blank=True,
  398. null=True
  399. )
  400. user = models.ForeignKey(
  401. to=User,
  402. on_delete=models.PROTECT
  403. )
  404. description = models.CharField(
  405. max_length=200
  406. )
  407. objects = RestrictedQuerySet.as_manager()
  408. class Meta:
  409. ordering = ['created', 'pk']
  410. def __str__(self):
  411. return "Reservation for rack {}".format(self.rack)
  412. def get_absolute_url(self):
  413. return reverse('dcim:rackreservation', args=[self.pk])
  414. def clean(self):
  415. super().clean()
  416. if hasattr(self, 'rack') and self.units:
  417. # Validate that all specified units exist in the Rack.
  418. invalid_units = [u for u in self.units if u not in self.rack.units]
  419. if invalid_units:
  420. raise ValidationError({
  421. 'units': "Invalid unit(s) for {}U rack: {}".format(
  422. self.rack.u_height,
  423. ', '.join([str(u) for u in invalid_units]),
  424. ),
  425. })
  426. # Check that none of the units has already been reserved for this Rack.
  427. reserved_units = []
  428. for resv in self.rack.reservations.exclude(pk=self.pk):
  429. reserved_units += resv.units
  430. conflicting_units = [u for u in self.units if u in reserved_units]
  431. if conflicting_units:
  432. raise ValidationError({
  433. 'units': 'The following units have already been reserved: {}'.format(
  434. ', '.join([str(u) for u in conflicting_units]),
  435. )
  436. })
  437. @property
  438. def unit_list(self):
  439. return array_to_string(self.units)