racks.py 18 KB

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