__init__.py 11 KB

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