elevations.py 8.2 KB

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