elevations.py 7.9 KB

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