racks.py 18 KB

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