__init__.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import collections
  2. import inspect
  3. from packaging import version
  4. from django.apps import AppConfig
  5. from django.core.exceptions import ImproperlyConfigured
  6. from django.template.loader import get_template
  7. from extras.registry import registry
  8. from utilities.choices import ButtonColorChoices
  9. from extras.plugins.utils import import_object
  10. # Initialize plugin registry stores
  11. registry['plugin_template_extensions'] = collections.defaultdict(list)
  12. registry['plugin_menu_items'] = {}
  13. #
  14. # Plugin AppConfig class
  15. #
  16. class PluginConfig(AppConfig):
  17. """
  18. Subclass of Django's built-in AppConfig class, to be used for NetBox plugins.
  19. """
  20. # Plugin metadata
  21. author = ''
  22. author_email = ''
  23. description = ''
  24. version = ''
  25. # Root URL path under /plugins. If not set, the plugin's label will be used.
  26. base_url = None
  27. # Minimum/maximum compatible versions of NetBox
  28. min_version = None
  29. max_version = None
  30. # Default configuration parameters
  31. default_settings = {}
  32. # Mandatory configuration parameters
  33. required_settings = []
  34. # Middleware classes provided by the plugin
  35. middleware = []
  36. # Cacheops configuration. Cache all operations by default.
  37. caching_config = {
  38. '*': {'ops': 'all'},
  39. }
  40. # Default integration paths. Plugin authors can override these to customize the paths to
  41. # integrated components.
  42. template_extensions = 'template_content.template_extensions'
  43. menu_items = 'navigation.menu_items'
  44. def ready(self):
  45. # Register template content
  46. template_extensions = import_object(f"{self.__module__}.{self.template_extensions}")
  47. if template_extensions is not None:
  48. register_template_extensions(template_extensions)
  49. # Register navigation menu items (if defined)
  50. menu_items = import_object(f"{self.__module__}.{self.menu_items}")
  51. if menu_items is not None:
  52. register_menu_items(self.verbose_name, menu_items)
  53. @classmethod
  54. def validate(cls, user_config, netbox_version):
  55. # Enforce version constraints
  56. current_version = version.parse(netbox_version)
  57. if cls.min_version is not None:
  58. min_version = version.parse(cls.min_version)
  59. if current_version < min_version:
  60. raise ImproperlyConfigured(
  61. f"Plugin {cls.__module__} requires NetBox minimum version {cls.min_version}."
  62. )
  63. if cls.max_version is not None:
  64. max_version = version.parse(cls.max_version)
  65. if current_version > max_version:
  66. raise ImproperlyConfigured(
  67. f"Plugin {cls.__module__} requires NetBox maximum version {cls.max_version}."
  68. )
  69. # Verify required configuration settings
  70. for setting in cls.required_settings:
  71. if setting not in user_config:
  72. raise ImproperlyConfigured(
  73. f"Plugin {cls.__module__} requires '{setting}' to be present in the PLUGINS_CONFIG section of "
  74. f"configuration.py."
  75. )
  76. # Apply default configuration values
  77. for setting, value in cls.default_settings.items():
  78. if setting not in user_config:
  79. user_config[setting] = value
  80. #
  81. # Template content injection
  82. #
  83. class PluginTemplateExtension:
  84. """
  85. This class is used to register plugin content to be injected into core NetBox templates. It contains methods
  86. that are overridden by plugin authors to return template content.
  87. The `model` attribute on the class defines the which model detail page this class renders content for. It
  88. should be set as a string in the form '<app_label>.<model_name>'. render() provides the following context data:
  89. * object - The object being viewed
  90. * request - The current request
  91. * settings - Global NetBox settings
  92. * config - Plugin-specific configuration parameters
  93. """
  94. model = None
  95. def __init__(self, context):
  96. self.context = context
  97. def render(self, template_name, extra_context=None):
  98. """
  99. Convenience method for rendering the specified Django template using the default context data. An additional
  100. context dictionary may be passed as `extra_context`.
  101. """
  102. if extra_context is None:
  103. extra_context = {}
  104. elif not isinstance(extra_context, dict):
  105. raise TypeError("extra_context must be a dictionary")
  106. return get_template(template_name).render({**self.context, **extra_context})
  107. def left_page(self):
  108. """
  109. Content that will be rendered on the left of the detail page view. Content should be returned as an
  110. HTML string. Note that content does not need to be marked as safe because this is automatically handled.
  111. """
  112. raise NotImplementedError
  113. def right_page(self):
  114. """
  115. Content that will be rendered on the right of the detail page view. Content should be returned as an
  116. HTML string. Note that content does not need to be marked as safe because this is automatically handled.
  117. """
  118. raise NotImplementedError
  119. def full_width_page(self):
  120. """
  121. Content that will be rendered within the full width of the detail page view. Content should be returned as an
  122. HTML string. Note that content does not need to be marked as safe because this is automatically handled.
  123. """
  124. raise NotImplementedError
  125. def buttons(self):
  126. """
  127. Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content
  128. should be returned as an HTML string. Note that content does not need to be marked as safe because this is
  129. automatically handled.
  130. """
  131. raise NotImplementedError
  132. def register_template_extensions(class_list):
  133. """
  134. Register a list of PluginTemplateExtension classes
  135. """
  136. # Validation
  137. for template_extension in class_list:
  138. if not inspect.isclass(template_extension):
  139. raise TypeError(f"PluginTemplateExtension class {template_extension} was passes as an instance!")
  140. if not issubclass(template_extension, PluginTemplateExtension):
  141. raise TypeError(f"{template_extension} is not a subclass of extras.plugins.PluginTemplateExtension!")
  142. if template_extension.model is None:
  143. raise TypeError(f"PluginTemplateExtension class {template_extension} does not define a valid model!")
  144. registry['plugin_template_extensions'][template_extension.model].append(template_extension)
  145. #
  146. # Navigation menu links
  147. #
  148. class PluginMenuItem:
  149. """
  150. This class represents a navigation menu item. This constitutes primary link and its text, but also allows for
  151. specifying additional link buttons that appear to the right of the item in the van menu.
  152. Links are specified as Django reverse URL strings.
  153. Buttons are each specified as a list of PluginMenuButton instances.
  154. """
  155. permissions = []
  156. buttons = []
  157. def __init__(self, link, link_text, permissions=None, buttons=None):
  158. self.link = link
  159. self.link_text = link_text
  160. if permissions is not None:
  161. if type(permissions) not in (list, tuple):
  162. raise TypeError("Permissions must be passed as a tuple or list.")
  163. self.permissions = permissions
  164. if buttons is not None:
  165. if type(buttons) not in (list, tuple):
  166. raise TypeError("Buttons must be passed as a tuple or list.")
  167. self.buttons = buttons
  168. class PluginMenuButton:
  169. """
  170. This class represents a button within a PluginMenuItem. Note that button colors should come from
  171. ButtonColorChoices.
  172. """
  173. color = ButtonColorChoices.DEFAULT
  174. permissions = []
  175. def __init__(self, link, title, icon_class, color=None, permissions=None):
  176. self.link = link
  177. self.title = title
  178. self.icon_class = icon_class
  179. if permissions is not None:
  180. if type(permissions) not in (list, tuple):
  181. raise TypeError("Permissions must be passed as a tuple or list.")
  182. self.permissions = permissions
  183. if color is not None:
  184. if color not in ButtonColorChoices.values():
  185. raise ValueError("Button color must be a choice within ButtonColorChoices.")
  186. self.color = color
  187. def register_menu_items(section_name, class_list):
  188. """
  189. Register a list of PluginMenuItem instances for a given menu section (e.g. plugin name)
  190. """
  191. # Validation
  192. for menu_link in class_list:
  193. if not isinstance(menu_link, PluginMenuItem):
  194. raise TypeError(f"{menu_link} must be an instance of extras.plugins.PluginMenuItem")
  195. for button in menu_link.buttons:
  196. if not isinstance(button, PluginMenuButton):
  197. raise TypeError(f"{button} must be an instance of extras.plugins.PluginMenuButton")
  198. registry['plugin_menu_items'][section_name] = class_list