__init__.py 10 KB

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