elevations.py 9.1 KB

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