racks.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import svgwrite
  2. from django.conf import settings
  3. from django.urls import reverse
  4. from django.utils.http import urlencode
  5. from utilities.utils import foreground_color
  6. from dcim.choices import DeviceFaceChoices
  7. from dcim.constants import RACK_ELEVATION_BORDER_WIDTH
  8. __all__ = (
  9. 'RackElevationSVG',
  10. )
  11. def get_device_name(device):
  12. if device.virtual_chassis:
  13. return f'{device.virtual_chassis.name}:{device.vc_position}'
  14. elif device.name:
  15. return device.name
  16. else:
  17. return str(device.device_type)
  18. class RackElevationSVG:
  19. """
  20. Use this class to render a rack elevation as an SVG image.
  21. :param rack: A NetBox Rack instance
  22. :param user: User instance. If specified, only devices viewable by this user will be fully displayed.
  23. :param include_images: If true, the SVG document will embed front/rear device face images, where available
  24. :param base_url: Base URL for links within the SVG document. If none, links will be relative.
  25. """
  26. def __init__(self, rack, user=None, include_images=True, base_url=None):
  27. self.rack = rack
  28. self.include_images = include_images
  29. if base_url is not None:
  30. self.base_url = base_url.rstrip('/')
  31. else:
  32. self.base_url = ''
  33. # Determine the subset of devices within this rack that are viewable by the user, if any
  34. permitted_devices = self.rack.devices
  35. if user is not None:
  36. permitted_devices = permitted_devices.restrict(user, 'view')
  37. self.permitted_device_ids = permitted_devices.values_list('pk', flat=True)
  38. @staticmethod
  39. def _get_device_description(device):
  40. return '{} ({}) — {} {} ({}U) {} {}'.format(
  41. device.name,
  42. device.device_role,
  43. device.device_type.manufacturer.name,
  44. device.device_type.model,
  45. device.device_type.u_height,
  46. device.asset_tag or '',
  47. device.serial or ''
  48. )
  49. @staticmethod
  50. def _add_gradient(drawing, id_, color):
  51. gradient = drawing.linearGradient(
  52. start=(0, 0),
  53. end=(0, 25),
  54. spreadMethod='repeat',
  55. id_=id_,
  56. gradientTransform='rotate(45, 0, 0)',
  57. gradientUnits='userSpaceOnUse'
  58. )
  59. gradient.add_stop_color(offset='0%', color='#f7f7f7')
  60. gradient.add_stop_color(offset='50%', color='#f7f7f7')
  61. gradient.add_stop_color(offset='50%', color=color)
  62. gradient.add_stop_color(offset='100%', color=color)
  63. drawing.defs.add(gradient)
  64. @staticmethod
  65. def _setup_drawing(width, height):
  66. drawing = svgwrite.Drawing(size=(width, height))
  67. # add the stylesheet
  68. with open('{}/rack_elevation.css'.format(settings.STATIC_ROOT)) as css_file:
  69. drawing.defs.add(drawing.style(css_file.read()))
  70. # add gradients
  71. RackElevationSVG._add_gradient(drawing, 'reserved', '#c7c7ff')
  72. RackElevationSVG._add_gradient(drawing, 'occupied', '#d7d7d7')
  73. RackElevationSVG._add_gradient(drawing, 'blocked', '#ffc0c0')
  74. return drawing
  75. def _draw_device_front(self, drawing, device, start, end, text):
  76. name = get_device_name(device)
  77. if device.devicebay_count:
  78. name += ' ({}/{})'.format(device.get_children().count(), device.devicebay_count)
  79. color = device.device_role.color
  80. link = drawing.add(
  81. drawing.a(
  82. href='{}{}'.format(self.base_url, reverse('dcim:device', kwargs={'pk': device.pk})),
  83. target='_top',
  84. fill='black'
  85. )
  86. )
  87. link.set_desc(self._get_device_description(device))
  88. link.add(drawing.rect(start, end, style='fill: #{}'.format(color), class_='slot'))
  89. hex_color = '#{}'.format(foreground_color(color))
  90. link.add(drawing.text(str(name), insert=text, fill=hex_color))
  91. # Embed front device type image if one exists
  92. if self.include_images and device.device_type.front_image:
  93. image = drawing.image(
  94. href=device.device_type.front_image.url,
  95. insert=start,
  96. size=end,
  97. class_='device-image'
  98. )
  99. image.fit(scale='slice')
  100. link.add(image)
  101. link.add(drawing.text(str(name), insert=text, stroke='black',
  102. stroke_width='0.2em', stroke_linejoin='round', class_='device-image-label'))
  103. link.add(drawing.text(str(name), insert=text, fill='white', class_='device-image-label'))
  104. def _draw_device_rear(self, drawing, device, start, end, text):
  105. link = drawing.add(
  106. drawing.a(
  107. href='{}{}'.format(self.base_url, reverse('dcim:device', kwargs={'pk': device.pk})),
  108. target='_top',
  109. fill='black'
  110. )
  111. )
  112. link.set_desc(self._get_device_description(device))
  113. link.add(drawing.rect(start, end, class_="slot blocked"))
  114. link.add(drawing.text(get_device_name(device), insert=text))
  115. # Embed rear device type image if one exists
  116. if self.include_images and device.device_type.rear_image:
  117. image = drawing.image(
  118. href=device.device_type.rear_image.url,
  119. insert=start,
  120. size=end,
  121. class_='device-image'
  122. )
  123. image.fit(scale='slice')
  124. link.add(image)
  125. link.add(drawing.text(get_device_name(device), insert=text, stroke='black',
  126. stroke_width='0.2em', stroke_linejoin='round', class_='device-image-label'))
  127. link.add(drawing.text(get_device_name(device), insert=text, fill='white', class_='device-image-label'))
  128. @staticmethod
  129. def _draw_empty(drawing, rack, start, end, text, id_, face_id, class_, reservation):
  130. link_url = '{}?{}'.format(
  131. reverse('dcim:device_add'),
  132. urlencode({
  133. 'site': rack.site.pk,
  134. 'location': rack.location.pk if rack.location else '',
  135. 'rack': rack.pk,
  136. 'face': face_id,
  137. 'position': id_
  138. })
  139. )
  140. link = drawing.add(
  141. drawing.a(href=link_url, target='_top')
  142. )
  143. if reservation:
  144. link.set_desc('{} — {} · {}'.format(
  145. reservation.description, reservation.user, reservation.created
  146. ))
  147. link.add(drawing.rect(start, end, class_=class_))
  148. link.add(drawing.text("add device", insert=text, class_='add-device'))
  149. def merge_elevations(self, face):
  150. elevation = self.rack.get_rack_units(face=face, expand_devices=False)
  151. if face == DeviceFaceChoices.FACE_REAR:
  152. other_face = DeviceFaceChoices.FACE_FRONT
  153. else:
  154. other_face = DeviceFaceChoices.FACE_REAR
  155. other = self.rack.get_rack_units(face=other_face)
  156. unit_cursor = 0
  157. for u in elevation:
  158. o = other[unit_cursor]
  159. if not u['device'] and o['device'] and o['device'].device_type.is_full_depth:
  160. u['device'] = o['device']
  161. u['height'] = 1
  162. unit_cursor += u.get('height', 1)
  163. return elevation
  164. def render(self, face, unit_width, unit_height, legend_width):
  165. """
  166. Return an SVG document representing a rack elevation.
  167. """
  168. drawing = self._setup_drawing(
  169. unit_width + legend_width + RACK_ELEVATION_BORDER_WIDTH * 2,
  170. unit_height * self.rack.u_height + RACK_ELEVATION_BORDER_WIDTH * 2
  171. )
  172. reserved_units = self.rack.get_reserved_units()
  173. unit_cursor = 0
  174. for ru in range(0, self.rack.u_height):
  175. start_y = ru * unit_height
  176. position_coordinates = (legend_width / 2, start_y + unit_height / 2 + RACK_ELEVATION_BORDER_WIDTH)
  177. unit = ru + 1 if self.rack.desc_units else self.rack.u_height - ru
  178. drawing.add(
  179. drawing.text(str(unit), position_coordinates, class_="unit")
  180. )
  181. for unit in self.merge_elevations(face):
  182. # Loop through all units in the elevation
  183. device = unit['device']
  184. height = unit.get('height', 1)
  185. # Setup drawing coordinates
  186. x_offset = legend_width + RACK_ELEVATION_BORDER_WIDTH
  187. y_offset = unit_cursor * unit_height + RACK_ELEVATION_BORDER_WIDTH
  188. end_y = unit_height * height
  189. start_cordinates = (x_offset, y_offset)
  190. end_cordinates = (unit_width, end_y)
  191. text_cordinates = (x_offset + (unit_width / 2), y_offset + end_y / 2)
  192. # Draw the device
  193. if device and device.face == face and device.pk in self.permitted_device_ids:
  194. self._draw_device_front(drawing, device, start_cordinates, end_cordinates, text_cordinates)
  195. elif device and device.device_type.is_full_depth and device.pk in self.permitted_device_ids:
  196. self._draw_device_rear(drawing, device, start_cordinates, end_cordinates, text_cordinates)
  197. elif device:
  198. # Devices which the user does not have permission to view are rendered only as unavailable space
  199. drawing.add(drawing.rect(start_cordinates, end_cordinates, class_='blocked'))
  200. else:
  201. # Draw shallow devices, reservations, or empty units
  202. class_ = 'slot'
  203. reservation = reserved_units.get(unit["id"])
  204. if device:
  205. class_ += ' occupied'
  206. if reservation:
  207. class_ += ' reserved'
  208. self._draw_empty(
  209. drawing,
  210. self.rack,
  211. start_cordinates,
  212. end_cordinates,
  213. text_cordinates,
  214. unit["id"],
  215. face,
  216. class_,
  217. reservation
  218. )
  219. unit_cursor += height
  220. # Wrap the drawing with a border
  221. border_width = RACK_ELEVATION_BORDER_WIDTH
  222. border_offset = RACK_ELEVATION_BORDER_WIDTH / 2
  223. frame = drawing.rect(
  224. insert=(legend_width + border_offset, border_offset),
  225. size=(unit_width + border_width, self.rack.u_height * unit_height + border_width),
  226. class_='rack'
  227. )
  228. drawing.add(frame)
  229. return drawing