elevations.py 9.1 KB

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