elevations.py 7.4 KB

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