Merge pull request #4385 from netbox-community/3351-plugins

Implements 3351 plugins
This commit is contained in:
Jeremy Stretch 2020-03-27 14:19:11 -04:00 committed by GitHub
commit 8c7b3a1f9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 1305 additions and 5 deletions

View File

@ -299,6 +299,39 @@ Determine how many objects to display per page within each list of objects.
---
## PLUGINS_CONFIG
Default: Empty
This parameter holds configuration settings for individual NetBox plugins. It is defined as a dictionary, with each key using the name of an installed plugin. The specific parameters supported are unique to each plugin: Reference the plugin's documentation to determine the supported parameters. An example configuration is shown below:
```python
PLUGINS_CONFIG = {
'plugin1': {
'foo': 123,
'bar': True
},
'plugin2': {
'foo': 456,
},
}
```
Note that `PLUGINS_ENABLED` must be set to True for this to take effect.
---
## PLUGINS_ENABLED
Default: `False`
Enable [NetBox plugins](../../plugins/).
!!! warning
Plugins extend NetBox by allowing external code to run with the same access and privileges as NetBox itself. Only install plugins from trusted sources. The NetBox maintainers make absolutely no guarantees about the integrity or security of your installation with plugins enabled.
---
## PREFER_IPV4
Default: False

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

375
docs/plugins/development.md Normal file
View File

@ -0,0 +1,375 @@
# Plugin Development
This documentation covers the development of custom plugins for NetBox. Plugins are essentially self-contained [Django apps](https://docs.djangoproject.com/en/stable/) which integrate with NetBox to provide custom functionality. Since the development of Django apps is already very well-documented, we'll only be covering the aspects that are specific to NetBox.
Plugins can do a lot, including:
* Create Django models to store data in the database
* Provide their own "pages" (views) in the web user interface
* Inject template content and navigation links
* Establish their own REST API endpoints
* Add custom request/response middleware
However, keep in mind that each piece of functionality is entirely optional. For example, if your plugin merely adds a piece of middleware or an API endpoint for existing data, there's no need to define any new models.
## Initial Setup
## Plugin Structure
Although the specific structure of a plugin is largely left to the discretion of its authors, a typical NetBox plugin looks something like this:
```no-highlight
plugin_name/
- plugin_name/
- templates/
- plugin_name/
- *.html
- __init__.py
- middleware.py
- navigation.py
- signals.py
- template_content.py
- urls.py
- views.py
- README
- setup.py
```
The top level is the project root. Immediately within the root should exist several items:
* `setup.py` - This is a standard installation script used to install the plugin package within the Python environment.
* `README` - A brief introduction to your plugin, how to install and configure it, where to find help, and any other pertinent information. It is recommended to write README files using a markup language such as Markdown.
* The plugin source directory, with the same name as your plugin.
The plugin source directory contains all of the actual Python code and other resources used by your plugin. Its structure is left to the author's discretion, however it is recommended to follow best practices as outlined in the [Django documentation](https://docs.djangoproject.com/en/stable/intro/reusable-apps/). At a minimum, this directory **must** contain an `__init__.py` file containing an instance of NetBox's `PluginConfig` class.
### Create setup.py
`setup.py` is the [setup script](https://docs.python.org/3.6/distutils/setupscript.html) we'll use to install our plugin once it's finished. The primary function of this script is to call the setuptools library's `setup()` function to create a Python distribution package. We can pass a number of keyword arguments to inform the package creation as well as to provide metadata about the plugin. An example `setup.py` is below:
```python
from setuptools import find_packages, setup
setup(
name='netbox-animal-sounds',
version='0.1',
description='Show animals and the sounds they make',
url='https://github.com/example-org/animal-sounds',
author='Author Name',
author_email='author@example.com',
license='Apache 2.0',
install_requires=[],
packages=find_packages(),
include_package_data=True,
entry_points={
'netbox_plugins': 'netbox_animal_sounds=netbox_animal_sounds:AnimalSoundsConfig'
}
)
```
Many of these are self-explanatory, but for more information, see the [setuptools documentation](https://setuptools.readthedocs.io/en/latest/setuptools.html). The key requirement for a NetBox plugin is the presence of an entry point for `netbox_plugins` pointing to the `PluginConfig` subclass, which we'll create next.
### Define a PluginConfig
The `PluginConfig` class is a NetBox-specific wrapper around Django's built-in [`AppConfig`](https://docs.djangoproject.com/en/stable/ref/applications/) class. It is used to declare NetBox plugin functionality within a Python package. Each plugin should provide its own subclass, defining its name, metadata, and default and required configuration parameters. An example is below:
```python
from extras.plugins import PluginConfig
class AnimalSoundsConfig(PluginConfig):
name = 'netbox_animal_sounds'
verbose_name = 'Animal Sounds Plugin'
version = '0.1'
author = 'Author Name'
description = 'Show animals and the sounds they make'
base_url = 'animal-sounds'
required_settings = []
default_settings = {
'loud': False
}
```
#### PluginConfig Attributes
| Name | Description |
| ---- | ----------- |
| `name` | Raw plugin name; same as the plugin's source directory |
| `verbose_name` | Human-friendly name for the plugin |
| `version` | Current release ([semantic versioning](https://semver.org/) is encouraged) |
| `description` | Brief description of the plugin's purpose |
| `author_name` | Name of plugin's author |
| `author_email` | Author's public email address |
| `base_url` | Base path to use for plugin URLs (optional). If not specified, the project's `name` will be used. |
| `required_settings` | A list of any configuration parameters that **must** be defined by the user |
| `default_settings` | A dictionary of configuration parameters and their default values |
| `min_version` | Minimum version of NetBox with which the plugin is compatible |
| `max_version` | Maximum version of NetBox with which the plugin is compatible |
| `middleware` | A list of middleware classes to append after NetBox's build-in middleware |
| `caching_config` | Plugin-specific cache configuration
| `template_extensions` | The dotted path to the list of template extension classes (default: `template_content.template_extensions`) |
| `menu_items` | The dotted path to the list of menu items provided by the plugin (default: `navigation.menu_items`) |
### Install the Plugin for Development
To ease development, it is recommended to go ahead and install the plugin at this point using setuptools' `develop` mode. This will create symbolic links within your Python environment to the plugin development directory. Call `setup.py` from the plugin's root directory with the `develop` argument (instead of `install`):
```no-highlight
$ python setup.py develop
```
## Database Models
If your plugin introduces a new type of object in NetBox, you'll probably want to create a [Django model](https://docs.djangoproject.com/en/stable/topics/db/models/) for it. A model is essentially a Python representation of a database table, with attributes that represent individual columns. Model instances can be created, manipulated, and deleted using [queries](https://docs.djangoproject.com/en/stable/topics/db/queries/). Models must be defined within a file named `models.py`.
Below is an example `models.py` file containing a model with two character fields:
```python
from django.db import models
class Animal(models.Model):
name = models.CharField(max_length=50)
sound = models.CharField(max_length=50)
def __str__(self):
return self.name
```
Once you have defined the model(s) for your plugin, you'll need to create the database schema migrations. A migration file is essentially a set of instructions for manipulating the PostgreSQL database to support your new model, or to alter existing models. Creating migrations can usually be done automatically using Django's `makemigrations` management command.
!!! note
A plugin must be installed before it can be used with Django management commands. If you skipped this step above, run `python setup.py develop` from the plugin's root directory.
```no-highlight
$ ./manage.py makemigrations netbox_animal_sounds
Migrations for 'netbox_animal_sounds':
/home/jstretch/animal_sounds/netbox_animal_sounds/migrations/0001_initial.py
- Create model Animal
```
Next, we can apply the migration to the database with the `migrate` command:
```no-highlight
$ ./manage.py migrate netbox_animal_sounds
Operations to perform:
Apply all migrations: netbox_animal_sounds
Running migrations:
Applying netbox_animal_sounds.0001_initial... OK
```
For more background on schema migrations, see the [Django documentation](https://docs.djangoproject.com/en/stable/topics/migrations/).
### Using the Django Admin Interface
Plugins can optionally expose their models via Django's built-in [administrative interface](https://docs.djangoproject.com/en/stable/ref/contrib/admin/). This can greatly improve troubleshooting ability, particularly during development. To expose a model, simply register it with Netbox's `admin_site` object. An example `admin.py` file for the above model is shown below:
```python
from django.contrib import admin
from netbox.admin import admin_site
from .models import Animal
@admin.register(Animal, site=admin_site)
class AnimalAdmin(admin.ModelAdmin):
list_display = ('name', 'sound')
```
This will display the plugin and its model in the admin UI. Staff users can create, change, and delete model instances via the admin UI without needing to create a custom view.
![NetBox plugin in the admin UI](../media/plugins/plugin_admin_ui.png)
## Views
If your plugin needs its own page or pages in the NetBox web UI, you'll need to define views. A view is a particular page tied to a URL within NetBox, which renders content using a template. Views are typically defined in `views.py`, and URL patterns in `urls.py`. As an example, let's write a view which displays a random animal and the sound it makes. First, we'll create the view in `views.py`:
```python
from django.shortcuts import render
from django.views.generic import View
from .models import Animal
class RandomAnimalSoundView(View):
def get(self, request):
# Retrieve a random animal
animal = Animal.objects.order_by('?').first()
return render(request, 'netbox_animal_sounds/animal_sound.html', {
'animal': animal,
})
```
This view retrieves a random animal from the database and and passes it as a context variable when rendering a template named `animal_sound.html`, which doesn't exist yet. To create this template, first create a directory named `templates/netbox_animal_sounds/` within the plugin source directory. (We use the plugin's name as a subdirectory to guard against naming collisions with other plugins.) Then, create `animal_sound.html`:
```jinja2
{% extends '_base.html' %}
{% block content %}
{% if animal %}
The {{ animal.name }} says {{ animal.sound }}
{% else %}
No animals have been created yet!
{% endif %}
{% endblock %}
```
The first line of the template instructs Django to extend the NetBox base template and inject our custom content within its `content` block.
!!! note
Django renders templates with its own custom [template language](https://docs.djangoproject.com/en/stable/topics/templates/#the-django-template-language). This is very similar to Jinja2, however there are some important differences to be aware of.
Finally, to make the view accessible to users, we need to register a URL for it. We do this in `urls.py` by defining a `urlpatterns` variable containing a list of paths.
```python
from django.urls import path
from .views import RandomAnimalSoundView
urlpatterns = [
path('random-sound/', RandomAnimalSoundView.as_view(), name='random_sound')
]
```
A URL pattern has three components:
* `route` - The unique portion of the URL dedicated to this view
* `view` - The view itself
* `name` - A short name used to identify the URL path internally
This makes our view accessible at the URL `/plugins/animal-sounds/random-sound/`. (Remember, our `AnimalSoundsConfig` class sets our plugin's base URL to `animal-sounds`.) Viewing this URL should show the base NetBox template with our custom content inside it.
## REST API Endpoints
Plugins can declare custom endpoints on NetBox's REST API to retrieve or manipulate models or other data. These behave very similarly to views, except that instead of rendering arbitrary content using a template, data is returned in JSON format using a serializer. NetBox uses the [Django REST Framework](https://www.django-rest-framework.org/), which makes writing API serializers and views very simple.
First, we'll create a serializer for our `Animal` model, in `api/serializers.py`:
```python
from rest_framework.serializers import ModelSerializer
from netbox_animal_sounds.models import Animal
class AnimalSerializer(ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'sound')
```
Next, we'll create a generic API viewset that allows basic CRUD (create, read, update, and delete) operations for Animal instances. This is defined in `api/views.py`:
```python
from rest_framework.viewsets import ModelViewSet
from netbox_animal_sounds.models import Animal
from .serializers import AnimalSerializer
class AnimalViewSet(ModelViewSet):
queryset = Animal.objects.all()
serializer_class = AnimalSerializer
```
Finally, we'll register a URL for our endpoint in `api/urls.py`. This file **must** define a variable named `urlpatterns`.
```python
from rest_framework import routers
from .views import AnimalViewSet
router = routers.DefaultRouter()
router.register('animals', AnimalViewSet)
urlpatterns = router.urls
```
With these three components in place, we can request `/api/plugins/animal-sounds/animals/` to retrieve a list of all Animal objects defined.
![NetBox REST API plugin endpoint](../media/plugins/plugin_rest_api_endpoint.png)
!!! note
This example is provided as a minimal reference implementation only. It does not address authentication, performance, or myriad other concerns that plugin authors should have.
## Navigation Menu Items
To make its views easily accessible to users, a plugin can inject items in NetBox's navigation menu under the "Plugins" header. Menu items are added by defining a list of PluginMenuItem instances. By default, this should be a variable named `menu_items` in the file `navigation.py`. An example is shown below.
```python
from extras.plugins import PluginMenuButton, PluginMenuItem
from utilities.choices import ButtonColorChoices
menu_items = (
PluginMenuItem(
link='plugins:netbox_animal_sounds:random_sound',
link_text='Random sound',
buttons=(
PluginMenuButton('home', 'Button A', 'fa-info', ButtonColorChoices.BLUE),
PluginMenuButton('home', 'Button B', 'fa-warning', ButtonColorChoices.GREEN),
)
),
)
```
A `PluginMenuItem` has the following attributes:
* `link` - The name of the URL path to which this menu item links
* `link_text` - The text presented to the user
* `permissions` - A list of permissions required to display this link (optional)
* `buttons` - An iterable of PluginMenuButton instances to display (optional)
A `PluginMenuButton` has the following attributes:
* `link` - The name of the URL path to which this button links
* `title` - The tooltip text (displayed when the mouse hovers over the button)
* `icon_class` - Button icon CSS class
* `color` - One of the choices provided by `ButtonColorChoices` (optional)
* `permissions` - A list of permissions required to display this button (optional)
## Extending Core Templates
Plugins can inject custom content into certain areas of the detail views of applicable models. This is accomplished by subclassing `PluginTemplateExtension`, designating a particular NetBox model, and defining the desired methods to render custom content. Four methods are available:
* `left_page()` - Inject content on the left side of the page
* `right_page()` - Inject content on the right side of the page
* `full_width_page()` - Inject content across the entire bottom of the page
* `buttons()` - Add buttons to the top of the page
Additionally, a `render()` method is available for convenience. This method accepts the name of a template to render, and any additional context data you want to pass. Its use is optional, however.
When a PluginTemplateExtension is instantiated, context data is assigned to `self.context`. Available data include:
* `object` - The object being viewed
* `request` - The current request
* `settings` - Global NetBox settings
* `config` - Plugin-specific configuration parameters
For example, accessing `{{ request.user }}` within a template will return the current user.
Declared subclasses should be gathered into a list or tuple for integration with NetBox. By default, NetBox looks for an iterable named `template_extensions` within a `template_content.py` file. (This can be overridden by setting `template_extensions` to a custom value on the plugin's PluginConfig.) An example is below.
```python
from extras.plugins import PluginTemplateExtension
class AddSiteAnimal(PluginTemplateExtension):
model = 'dcim.site'
def full_width_page(self):
return self.render('netbox_animal_sounds/site.html')
class AddRackAnimal(PluginTemplateExtension):
model = 'dcim.rack'
def left_page(self):
extra_data = {'foo': 123}
return self.render('netbox_animal_sounds/rack.html', extra_data)
template_extensions = [AddSiteAnimal, AddRackAnimal]
```
## Caching Configuration
By default, all query operations within a plugin are cached. To change this, define a caching configuration under the PluginConfig class' `caching_config` attribute. An example configuration is below:
```python
class MyPluginConfig(PluginConfig):
...
caching_config = {
'my_plugin.foo': {
'ops': 'get',
'timeout': 60 * 15,
},
}
```
See the [django-cacheops](https://github.com/Suor/django-cacheops) documentation for more detail on configuring caching.

71
docs/plugins/index.md Normal file
View File

@ -0,0 +1,71 @@
# Plugins
Plugins are packaged [Django](https://docs.djangoproject.com/) apps that can be installed alongside NetBox to provide custom functionality not present in the core application. Plugins can introduce their own models and views, but cannot interfere with existing components. A NetBox user may opt to install plugins provided by the community or build his or her own.
Plugins are supported on NetBox v2.8 and later.
## Capabilities
The NetBox plugin architecture allows for the following:
* **Add new data models.** A plugin can introduce one or more models to hold data. (A model is essentially a table in the SQL database.)
* **Add new URLs and views.** Plugins can register URLs under the `/plugins` root path to provide browsable views for users.
* **Add content to existing model templates.** A template content class can be used to inject custom HTML content within the view of a core NetBox model. This content can appear in the left side, right side, or bottom of the page.
* **Add navigation menu items.** Each plugin can register new links in the navigation menu. Each link may have a set of buttons for specific actions, similar to the built-in navigation items.
* **Add custom middleware.** Custom Django middleware can be registered by each plugin.
* **Declare configuration parameters.** Each plugin can define required, optional, and default configuration parameters within its unique namespace. Plug configuration parameter are defined by the user under `PLUGINS_CONFIG` in `configuration.py`.
* **Limit installation by NetBox version.** A plugin can specify a minimum and/or maximum NetBox version with which it is compatible.
## Limitations
Either by policy or by technical limitation, the interaction of plugins with NetBox core is restricted in certain ways. A plugin may not:
* **Modify core models.** Plugins may not alter, remove, or override core NetBox models in any way. This rule is in place to ensure the integrity of the core data model.
* **Register URLs outside the `/plugins` root.** All plugin URLs are restricted to this path to prevent path collisions with core or other plugins.
* **Override core templates.** Plugins can inject additional content where supported, but may not manipulate or remove core content.
* **Modify core settings.** A configuration registry is provided for plugins, however they cannot alter or delete the core configuration.
* **Disable core components.** Plugins are not permitted to disable or hide core NetBox components.
## Installing Plugins
The instructions below detail the process for installing and enabling a NetBox plugin.
### Install Package
Download and install the plugin package per its installation instructions. Plugins published via PyPI are typically installed using pip. Be sure to install the plugin within NetBox's virtual environment.
```no-highlight
$ source /opt/netbox/venv/bin/activate
(venv) $ pip install <package>
```
Alternatively, you may wish to install the plugin manually by running `python setup.py install`. If you are developing a plugin and want to install it only temporarily, run `python setup.py develop` instead.
### Enable Plugins
In `configuration.py`, ensure the `PLUGINS_ENABLED` parameter is set to True:
```python
PLUGINS_ENABLED = True
```
### Configure Plugin
If the plugin requires any configuration, define it in `configuration.py` under the `PLUGINS_CONFIG` parameter. The available configuration parameters should be detailed in the plugin's README file.
```no-highlight
PLUGINS_CONFIG = {
'plugin_name': {
'foo': 'bar',
'buzz': 'bazz'
}
}
```
### Restart WSGI Service
Restart the WSGI service to load the new plugin:
```no-highlight
# sudo systemctl restart netbox
```

View File

@ -54,6 +54,9 @@ nav:
- Reports: 'additional-features/reports.md'
- Tags: 'additional-features/tags.md'
- Webhooks: 'additional-features/webhooks.md'
- Plugins:
- Using Plugins: 'plugins/index.md'
- Developing Plugins: 'plugins/development.md'
- Administration:
- Replicating NetBox: 'administration/replicating-netbox.md'
- NetBox Shell: 'administration/netbox-shell.md'

View File

@ -0,0 +1,214 @@
import collections
import inspect
from django.apps import AppConfig
from django.template.loader import get_template
from django.utils.module_loading import import_string
from extras.registry import registry
from utilities.choices import ButtonColorChoices
# Initialize plugin registry stores
registry['plugin_template_extensions'] = collections.defaultdict(list)
registry['plugin_menu_items'] = {}
#
# Plugin AppConfig class
#
class PluginConfig(AppConfig):
"""
Subclass of Django's built-in AppConfig class, to be used for NetBox plugins.
"""
# Plugin metadata
author = ''
author_email = ''
description = ''
version = ''
# Root URL path under /plugins. If not set, the plugin's label will be used.
base_url = None
# Minimum/maximum compatible versions of NetBox
min_version = None
max_version = None
# Default configuration parameters
default_settings = {}
# Mandatory configuration parameters
required_settings = []
# Middleware classes provided by the plugin
middleware = []
# Caching configuration
caching_config = {}
# Default integration paths. Plugin authors can override these to customize the paths to
# integrated components.
template_extensions = 'template_content.template_extensions'
menu_items = 'navigation.menu_items'
def ready(self):
# Register template content
try:
template_extensions = import_string(f"{self.__module__}.{self.template_extensions}")
register_template_extensions(template_extensions)
except ImportError:
pass
# Register navigation menu items (if defined)
try:
menu_items = import_string(f"{self.__module__}.{self.menu_items}")
register_menu_items(self.verbose_name, menu_items)
except ImportError:
pass
#
# Template content injection
#
class PluginTemplateExtension:
"""
This class is used to register plugin content to be injected into core NetBox templates. It contains methods
that are overridden by plugin authors to return template content.
The `model` attribute on the class defines the which model detail page this class renders content for. It
should be set as a string in the form '<app_label>.<model_name>'. render() provides the following context data:
* object - The object being viewed
* request - The current request
* settings - Global NetBox settings
* config - Plugin-specific configuration parameters
"""
model = None
def __init__(self, context):
self.context = context
def render(self, template_name, extra_context=None):
"""
Convenience method for rendering the specified Django template using the default context data. An additional
context dictionary may be passed as `extra_context`.
"""
if extra_context is None:
extra_context = {}
elif not isinstance(extra_context, dict):
raise TypeError("extra_context must be a dictionary")
return get_template(template_name).render({**self.context, **extra_context})
def left_page(self):
"""
Content that will be rendered on the left of the detail page view. Content should be returned as an
HTML string. Note that content does not need to be marked as safe because this is automatically handled.
"""
raise NotImplementedError
def right_page(self):
"""
Content that will be rendered on the right of the detail page view. Content should be returned as an
HTML string. Note that content does not need to be marked as safe because this is automatically handled.
"""
raise NotImplementedError
def full_width_page(self):
"""
Content that will be rendered within the full width of the detail page view. Content should be returned as an
HTML string. Note that content does not need to be marked as safe because this is automatically handled.
"""
raise NotImplementedError
def buttons(self):
"""
Buttons that will be rendered and added to the existing list of buttons on the detail page view. Content
should be returned as an HTML string. Note that content does not need to be marked as safe because this is
automatically handled.
"""
raise NotImplementedError
def register_template_extensions(class_list):
"""
Register a list of PluginTemplateExtension classes
"""
# Validation
for template_extension in class_list:
if not inspect.isclass(template_extension):
raise TypeError(f"PluginTemplateExtension class {template_extension} was passes as an instance!")
if not issubclass(template_extension, PluginTemplateExtension):
raise TypeError(f"{template_extension} is not a subclass of extras.plugins.PluginTemplateExtension!")
if template_extension.model is None:
raise TypeError(f"PluginTemplateExtension class {template_extension} does not define a valid model!")
registry['plugin_template_extensions'][template_extension.model].append(template_extension)
#
# Navigation menu links
#
class PluginMenuItem:
"""
This class represents a navigation menu item. This constitutes primary link and its text, but also allows for
specifying additional link buttons that appear to the right of the item in the van menu.
Links are specified as Django reverse URL strings.
Buttons are each specified as a list of PluginMenuButton instances.
"""
permissions = []
buttons = []
def __init__(self, link, link_text, permissions=None, buttons=None):
self.link = link
self.link_text = link_text
if permissions is not None:
if type(permissions) not in (list, tuple):
raise TypeError("Permissions must be passed as a tuple or list.")
self.permissions = permissions
if buttons is not None:
if type(buttons) not in (list, tuple):
raise TypeError("Buttons must be passed as a tuple or list.")
self.buttons = buttons
class PluginMenuButton:
"""
This class represents a button within a PluginMenuItem. Note that button colors should come from
ButtonColorChoices.
"""
color = ButtonColorChoices.DEFAULT
permissions = []
def __init__(self, link, title, icon_class, color=None, permissions=None):
self.link = link
self.title = title
self.icon_class = icon_class
if permissions is not None:
if type(permissions) not in (list, tuple):
raise TypeError("Permissions must be passed as a tuple or list.")
self.permissions = permissions
if color is not None:
if color not in ButtonColorChoices.values():
raise ValueError("Button color must be a choice within ButtonColorChoices.")
self.color = color
def register_menu_items(section_name, class_list):
"""
Register a list of PluginMenuItem instances for a given menu section (e.g. plugin name)
"""
# Validation
for menu_link in class_list:
if not isinstance(menu_link, PluginMenuItem):
raise TypeError(f"{menu_link} must be an instance of extras.plugins.PluginMenuItem")
for button in menu_link.buttons:
if not isinstance(button, PluginMenuButton):
raise TypeError(f"{button} must be an instance of extras.plugins.PluginMenuButton")
registry['plugin_menu_items'][section_name] = class_list

View File

@ -0,0 +1,41 @@
from django.apps import apps
from django.conf import settings
from django.conf.urls import include
from django.contrib.admin.views.decorators import staff_member_required
from django.urls import path
from django.utils.module_loading import import_string
from . import views
# Initialize URL base, API, and admin URL patterns for plugins
plugin_patterns = []
plugin_api_patterns = [
path('', views.PluginsAPIRootView.as_view(), name='api-root'),
path('installed-plugins/', views.InstalledPluginsAPIView.as_view(), name='plugins-list')
]
plugin_admin_patterns = [
path('installed-plugins/', staff_member_required(views.InstalledPluginsAdminView.as_view()), name='plugins_list')
]
# Register base/API URL patterns for each plugin
for plugin in settings.PLUGINS:
app = apps.get_app_config(plugin)
base_url = getattr(app, 'base_url') or app.label
# Check if the plugin specifies any base URLs
try:
urlpatterns = import_string(f"{plugin}.urls.urlpatterns")
plugin_patterns.append(
path(f"{base_url}/", include((urlpatterns, app.label)))
)
except ImportError:
pass
# Check if the plugin specifies any API URLs
try:
urlpatterns = import_string(f"{plugin}.api.urls.urlpatterns")
plugin_api_patterns.append(
path(f"{base_url}/", include((urlpatterns, f"{app.label}-api")))
)
except ImportError:
pass

View File

@ -0,0 +1,93 @@
from collections import OrderedDict
from django.apps import apps
from django.conf import settings
from django.shortcuts import render
from django.urls.exceptions import NoReverseMatch
from django.utils.module_loading import import_string
from django.views.generic import View
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView
class InstalledPluginsAdminView(View):
"""
Admin view for listing all installed plugins
"""
def get(self, request):
plugins = [apps.get_app_config(plugin) for plugin in settings.PLUGINS]
return render(request, 'extras/admin/plugins_list.html', {
'plugins': plugins,
})
class InstalledPluginsAPIView(APIView):
"""
API view for listing all installed plugins
"""
permission_classes = [permissions.IsAdminUser]
_ignore_model_permissions = True
exclude_from_schema = True
swagger_schema = None
def get_view_name(self):
return "Installed Plugins"
@staticmethod
def _get_plugin_data(plugin_app_config):
return {
'name': plugin_app_config.verbose_name,
'package': plugin_app_config.name,
'author': plugin_app_config.author,
'author_email': plugin_app_config.author_email,
'description': plugin_app_config.description,
'verison': plugin_app_config.version
}
def get(self, request, format=None):
return Response([self._get_plugin_data(apps.get_app_config(plugin)) for plugin in settings.PLUGINS])
class PluginsAPIRootView(APIView):
_ignore_model_permissions = True
exclude_from_schema = True
swagger_schema = None
def get_view_name(self):
return "Plugins"
@staticmethod
def _get_plugin_entry(plugin, app_config, request, format):
try:
api_app_name = import_string(f"{plugin}.api.urls.app_name")
except (ImportError, ModuleNotFoundError):
# Plugin does not expose an API
return None
try:
entry = (getattr(app_config, 'base_url', app_config.label), reverse(
f"plugins-api:{api_app_name}:api-root",
request=request,
format=format
))
except NoReverseMatch:
# The plugin does not include an api-root
entry = None
return entry
def get(self, request, format=None):
entries = []
for plugin in settings.PLUGINS:
app_config = apps.get_app_config(plugin)
entry = self._get_plugin_entry(plugin, app_config, request, format)
if entry is not None:
entries.append(entry)
return Response(OrderedDict((
('installed-plugins', reverse('plugins-api:plugins-list', request=request, format=format)),
*entries
)))

View File

@ -0,0 +1,73 @@
from django import template as template_
from django.conf import settings
from django.utils.safestring import mark_safe
from extras.plugins import PluginTemplateExtension
from extras.registry import registry
register = template_.Library()
def _get_registered_content(obj, method, template_context):
"""
Given an object and a PluginTemplateExtension method name and the template context, return all the
registered content for the object's model.
"""
html = ''
context = {
'object': obj,
'request': template_context['request'],
'settings': template_context['settings'],
}
model_name = obj._meta.label_lower
template_extensions = registry['plugin_template_extensions'].get(model_name, [])
for template_extension in template_extensions:
# If the class has not overridden the specified method, we can skip it (because we know it
# will raise NotImplementedError).
if getattr(template_extension, method) == getattr(PluginTemplateExtension, method):
continue
# Update context with plugin-specific configuration parameters
plugin_name = template_extension.__module__.split('.')[0]
context['config'] = settings.PLUGINS_CONFIG.get(plugin_name, {})
# Call the method to render content
instance = template_extension(context)
content = getattr(instance, method)()
html += content
return mark_safe(html)
@register.simple_tag(takes_context=True)
def plugin_buttons(context, obj):
"""
Render all buttons registered by plugins
"""
return _get_registered_content(obj, 'buttons', context)
@register.simple_tag(takes_context=True)
def plugin_left_page(context, obj):
"""
Render all left page content registered by plugins
"""
return _get_registered_content(obj, 'left_page', context)
@register.simple_tag(takes_context=True)
def plugin_right_page(context, obj):
"""
Render all right page content registered by plugins
"""
return _get_registered_content(obj, 'right_page', context)
@register.simple_tag(takes_context=True)
def plugin_full_width_page(context, obj):
"""
Render all full width page content registered by plugins
"""
return _get_registered_content(obj, 'full_width_page', context)

View File

@ -11,6 +11,7 @@ class NetBoxAdminSite(AdminSite):
site_header = 'NetBox Administration'
site_title = 'NetBox'
site_url = '/{}'.format(settings.BASE_PATH)
index_template = 'admin/index.html'
admin_site = NetBoxAdminSite(name='admin')

View File

@ -203,6 +203,18 @@ RELEASE_CHECK_URL = None
# this setting is derived from the installed location.
# SCRIPTS_ROOT = '/opt/netbox/netbox/scripts'
# Enable plugin support in netbox. This setting must be enabled for any installed plugins to function.
PLUGINS_ENABLED = False
# Plugins configuration settings. These settings are used by various plugins that the user may have installed.
# Each key in the dictionary is the name of an installed plugin and its value is a dictionary of settings.
# PLUGINS_CONFIG = {
# 'my_plugin': {
# 'foo': 'bar',
# 'buzz': 'bazz'
# }
# }
# By default, NetBox will store session data in the database. Alternatively, a file path can be specified here to use
# local file storage instead. (This can be useful for enabling authentication on a standby instance with read-only
# database access.) Note that the user as which NetBox runs must have read and write permissions to this path.

View File

@ -1,3 +1,4 @@
import importlib
import logging
import os
import platform
@ -9,6 +10,7 @@ from urllib.parse import urlsplit
from django.contrib.messages import constants as messages
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.validators import URLValidator
from pkg_resources import iter_entry_points, parse_version
#
@ -90,6 +92,8 @@ NAPALM_PASSWORD = getattr(configuration, 'NAPALM_PASSWORD', '')
NAPALM_TIMEOUT = getattr(configuration, 'NAPALM_TIMEOUT', 30)
NAPALM_USERNAME = getattr(configuration, 'NAPALM_USERNAME', '')
PAGINATE_COUNT = getattr(configuration, 'PAGINATE_COUNT', 50)
PLUGINS_CONFIG = getattr(configuration, 'PLUGINS_CONFIG', {})
PLUGINS_ENABLED = getattr(configuration, 'PLUGINS_ENABLED', False)
PREFER_IPV4 = getattr(configuration, 'PREFER_IPV4', False)
REMOTE_AUTH_AUTO_CREATE_USER = getattr(configuration, 'REMOTE_AUTH_AUTO_CREATE_USER', False)
REMOTE_AUTH_BACKEND = getattr(configuration, 'REMOTE_AUTH_BACKEND', 'utilities.auth_backends.RemoteUserBackend')
@ -321,7 +325,7 @@ TEMPLATES = [
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'utilities.context_processors.settings',
'utilities.context_processors.settings_and_registry',
],
},
},
@ -627,3 +631,65 @@ PER_PAGE_DEFAULTS = [
if PAGINATE_COUNT not in PER_PAGE_DEFAULTS:
PER_PAGE_DEFAULTS.append(PAGINATE_COUNT)
PER_PAGE_DEFAULTS = sorted(PER_PAGE_DEFAULTS)
#
# Plugins
#
PLUGINS = set()
if PLUGINS_ENABLED:
for entry_point in iter_entry_points(group='netbox_plugins', name=None):
# Append plugin name to PLUGINS
plugin = entry_point.module_name
PLUGINS.add(plugin)
# Append plugin to INSTALLED_APPS. Specify the path to the PluginConfig so that we don't
# have to define default_app_config.
app_config = entry_point.load()
INSTALLED_APPS.append(f"{app_config.__module__}.{app_config.__name__}")
# Check version constraints
parsed_min_version = parse_version(app_config.min_version or VERSION)
parsed_max_version = parse_version(app_config.max_version or VERSION)
if app_config.min_version and app_config.max_version and parsed_min_version > parsed_max_version:
raise ImproperlyConfigured(f"Plugin {plugin} specifies invalid version constraints!")
if app_config.min_version and parsed_min_version > parse_version(VERSION):
raise ImproperlyConfigured(f"Plugin {plugin} requires NetBox minimum version {app_config.min_version}!")
if app_config.max_version and parsed_max_version < parse_version(VERSION):
raise ImproperlyConfigured(f"Plugin {plugin} requires NetBox maximum version {app_config.max_version}!")
# Add middleware
plugin_middleware = app_config.middleware
if plugin_middleware and type(plugin_middleware) in (list, tuple):
MIDDLEWARE.extend(plugin_middleware)
# Verify required configuration settings
if plugin not in PLUGINS_CONFIG:
PLUGINS_CONFIG[plugin] = {}
for setting in app_config.required_settings:
if setting not in PLUGINS_CONFIG[plugin]:
raise ImproperlyConfigured(
f"Plugin {plugin} requires '{setting}' to be present in the PLUGINS_CONFIG section of "
f"configuration.py."
)
# Apply default configuration values
for setting, value in app_config.default_settings.items():
if setting not in PLUGINS_CONFIG[plugin]:
PLUGINS_CONFIG[plugin][setting] = value
# Apply cacheops config
plugin_cacheops = app_config.caching_config
if plugin_cacheops:
if type(plugin_cacheops) is not dict:
raise ImproperlyConfigured(f"Plugin {plugin} caching_config must be a dictionary.")
for key in plugin_cacheops.keys():
# Validate config is only being set for the given plugin
app = key.split('.')[0]
if app != plugin:
raise ImproperlyConfigured(f"Plugin {plugin} may not modify caching config for another app: {app}")
else:
# Apply the default config like all other core apps
plugin_cacheops = {f"{plugin}.*": {'ops': 'all'}}
CACHEOPS.update(plugin_cacheops)

View File

@ -6,6 +6,7 @@ from django.views.static import serve
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from extras.plugins.urls import plugin_admin_patterns, plugin_patterns, plugin_api_patterns
from netbox.views import APIRootView, HomeView, StaticMediaFailureView, SearchView
from users.views import LoginView, LogoutView
from .admin import admin_site
@ -81,8 +82,13 @@ _patterns = [
# Errors
path('media-failure/', StaticMediaFailureView.as_view(), name='media_failure'),
# Plugins
path('plugins/', include((plugin_patterns, 'plugins'))),
path('api/plugins/', include((plugin_api_patterns, 'plugins-api'))),
path('admin/plugins/', include(plugin_admin_patterns))
]
if settings.DEBUG:
import debug_toolbar
_patterns += [

View File

@ -341,6 +341,7 @@ class APIRootView(APIView):
('dcim', reverse('dcim-api:api-root', request=request, format=format)),
('extras', reverse('extras-api:api-root', request=request, format=format)),
('ipam', reverse('ipam-api:api-root', request=request, format=format)),
('plugins', reverse('plugins-api:api-root', request=request, format=format)),
('secrets', reverse('secrets-api:api-root', request=request, format=format)),
('tenancy', reverse('tenancy-api:api-root', request=request, format=format)),
('virtualization', reverse('virtualization-api:api-root', request=request, format=format)),

View File

@ -6,13 +6,18 @@
{{ block.super }}
<div class="module">
<table style="width: 100%">
<caption>Utilities</caption>
<caption>System</caption>
<tbody>
<tr>
<th>
<a href="{% url 'rq_home' %}">Background Tasks</a>
</th>
</tr>
<tr>
<th>
<a href="{% url 'plugins_list' %}">Installed plugins</a>
</th>
</tr>
</tbody>
</table>
</div>

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block title %}{{ circuit }}{% endblock %}
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons circuit %}
{% if perms.circuits.add_circuit %}
{% clone_button circuit %}
{% endif %}
@ -125,10 +127,17 @@
{% endif %}
</div>
</div>
{% plugin_left_page circuit %}
</div>
<div class="col-md-6">
{% include 'circuits/inc/circuit_termination.html' with termination=termination_a side='A' %}
{% include 'circuits/inc/circuit_termination.html' with termination=termination_z side='Z' %}
{% plugin_right_page circuit %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page circuit %}
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,7 @@
{% load static %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block title %}{{ provider }}{% endblock %}
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons provider %}
{% if show_graphs %}
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#graphs_modal" data-obj="{{ provider.name }}" data-url="{% url 'circuits-api:provider-graphs' pk=provider.pk %}" title="Show graphs">
<i class="fa fa-signal" aria-hidden="true"></i> Graphs
@ -116,6 +118,7 @@
{% endif %}
</div>
</div>
{% plugin_left_page provider %}
</div>
<div class="col-md-8">
<div class="panel panel-default">
@ -132,9 +135,15 @@
{% endif %}
</div>
{% include 'inc/paginator.html' with paginator=circuits_table.paginator page=circuits_table.page %}
{% plugin_right_page provider %}
</div>
</div>
{% include 'inc/modal.html' with name='graphs' title='Graphs' %}
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page provider %}
</div>
</div>
{% endblock %}
{% block javascript %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -13,6 +14,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons cable %}
{% if perms.dcim.change_cable %}
{% edit_button cable %}
{% endif %}
@ -79,6 +81,7 @@
</tr>
</table>
</div>
{% plugin_left_page cable %}
</div>
<div class="col-md-6">
<div class="panel panel-default">
@ -93,6 +96,12 @@
</div>
{% include 'dcim/inc/cable_termination.html' with termination=cable.termination_b %}
</div>
{% plugin_right_page cable %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page cable %}
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,7 @@
{% load static %}
{% load helpers %}
{% load custom_links %}
{% load plugins %}
{% block title %}{{ device }}{% endblock %}
@ -36,6 +37,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons device %}
{% if show_graphs %}
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#graphs_modal" data-obj="{{ device.name }}" data-url="{% url 'dcim-api:device-graphs' pk=device.pk %}" title="Show graphs">
<i class="fa fa-signal" aria-hidden="true"></i>
@ -331,6 +333,7 @@
{% endif %}
</div>
</div>
{% plugin_left_page device %}
</div>
<div class="col-md-6">
{% if console_ports or power_ports %}
@ -497,6 +500,12 @@
<div class="panel-body text-muted">None found</div>
{% endif %}
</div>
{% plugin_right_page device %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page device %}
</div>
</div>
<div class="row">

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block title %}{{ devicetype.manufacturer }} {{ devicetype.model }}{% endblock %}
@ -16,6 +17,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons devicetype %}
{% if perms.dcim.change_devicetype %}
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@ -139,6 +141,7 @@
</tr>
</table>
</div>
{% plugin_left_page devicetype %}
</div>
<div class="col-md-6">
{% include 'inc/custom_fields_panel.html' with obj=devicetype %}
@ -155,6 +158,7 @@
{% endif %}
</div>
</div>
{% plugin_right_page devicetype %}
</div>
</div>
{% if devicetype.consoleport_templates.exists or devicetype.powerport_templates.exists %}
@ -167,6 +171,11 @@
</div>
</div>
{% endif %}
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page devicetype %}
</div>
</div>
{% if devicetype.is_parent_device or devicebay_table.rows %}
<div class="row">
<div class="col-md-12">

View File

@ -3,6 +3,7 @@
{% load static %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -31,6 +32,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons powerfeed %}
{% if perms.dcim.add_powerfeed %}
{% clone_button powerfeed %}
{% endif %}
@ -123,6 +125,7 @@
</div>
{% include 'inc/custom_fields_panel.html' with obj=powerfeed %}
{% include 'extras/inc/tags_panel.html' with tags=powerfeed.tags.all url='dcim:powerfeed_list' %}
{% plugin_left_page powerfeed %}
</div>
<div class="col-md-6">
<div class="panel panel-default">
@ -164,6 +167,12 @@
{% endif %}
</div>
</div>
{% plugin_right_page powerfeed %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page powerfeed %}
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,7 @@
{% load custom_links %}
{% load helpers %}
{% load static %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -30,6 +31,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons powerpanel %}
{% if perms.dcim.change_powerpanel %}
{% edit_button powerpanel %}
{% endif %}
@ -80,9 +82,16 @@
</tr>
</table>
</div>
{% plugin_left_page powerpanel %}
</div>
<div class="col-md-9">
{% include 'panel_table.html' with table=powerfeed_table heading='Connected Feeds' %}
{% plugin_right_page powerpanel %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page powerpanel %}
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,7 @@
{% load custom_links %}
{% load helpers %}
{% load static %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -27,6 +28,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons rack %}
<a {% if prev_rack %}href="{% url 'dcim:rack' pk=prev_rack.pk %}"{% else %}disabled="disabled"{% endif %} class="btn btn-primary">
<span class="fa fa-chevron-left" aria-hidden="true"></span> Previous Rack
</a>
@ -312,6 +314,7 @@
</div>
{% endif %}
</div>
{% plugin_left_page rack %}
</div>
<div class="col-md-6">
<div class="row" style="margin-bottom: 20px">
@ -369,6 +372,12 @@
</div>
{% endif %}
</div>
{% plugin_right_page rack %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page rack %}
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,7 @@
{% load custom_links %}
{% load helpers %}
{% load static %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -27,6 +28,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons rackreservation %}
{% if perms.dcim.change_rackreservation %}
{% edit_button rackreservation %}
{% endif %}
@ -122,6 +124,7 @@
</tr>
</table>
</div>
{% plugin_left_page rackreservation %}
</div>
<div class="col-md-6">
{% with rack=rackreservation.rack %}
@ -140,6 +143,12 @@
</div>
</div>
{% endwith %}
{% plugin_right_page rackreservation %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page rackreservation %}
</div>
</div>
{% endblock %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% load static %}
{% load tz %}
@ -33,6 +34,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons site %}
{% if show_graphs %}
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#graphs_modal" data-obj="{{ site.name }}" data-url="{% url 'dcim-api:site-graphs' pk=site.pk %}" title="Show graphs">
<i class="fa fa-signal" aria-hidden="true"></i>
@ -212,6 +214,7 @@
{% endif %}
</div>
</div>
{% plugin_left_page site %}
</div>
<div class="col-md-5">
<div class="panel panel-default">
@ -286,9 +289,15 @@
</div>
{% endif %}
</div>
{% plugin_right_page site %}
</div>
</div>
{% include 'inc/modal.html' with name='graphs' title='Graphs' %}
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page site %}
</div>
</div>
{% endblock %}
{% block javascript %}

View File

@ -0,0 +1,57 @@
{% extends "admin/base_site.html" %}
{% block title %}Installed Plugins {{ block.super }}{% endblock %}
{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">Home</a> &rsaquo;
<a href="{% url 'plugins_list' %}">Installed Plugins</a>
</div>
{% endblock %}
{% block content_title %}<h1>Installed Plugins{{ queue.name }}</h1>{% endblock %}
{% block content %}
<div id="content-main">
<div class="module" id="changelist">
<div class="results">
<table id="result_list">
<thead>
<tr>
<th><div class="text"><span>Name</span></div></th>
<th><div class="text"><span>Package Name</span></div></th>
<th><div class="text"><span>Author</span></div></th>
<th><div class="text"><span>Author Email</span></div></th>
<th><div class="text"><span>Description</span></div></th>
<th><div class="text"><span>Version</span></div></th>
</tr>
</thead>
<tbody>
{% for plugin in plugins %}
<tr class="{% cycle 'row1' 'row2' %}">
<td>
{{ plugin.verbose_name }}
</td>
<td>
{{ plugin.name }}
</td>
<td>
{{ plugin.author }}
</td>
<td>
{{ plugin.author_email }}
</td>
<td>
{{ plugin.description }}
</td>
<td>
{{ plugin.version }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}

View File

@ -504,6 +504,9 @@
</li>
</ul>
</li>
{% if registry.plugin_menu_items %}
{% include 'inc/plugin_menu_items.html' %}
{% endif %}
</ul>
{% endif %}
<ul class="nav navbar-nav navbar-right">

View File

@ -0,0 +1,26 @@
{% load helpers %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Plugins <span class="caret"></span></a>
<ul class="dropdown-menu">
{% for section_name, menu_items in registry.plugin_menu_items.items %}
<li class="dropdown-header">{{ section_name }}</li>
{% for menu_item in menu_items %}
<li{% if menu_item.permissions and not request.user|has_perms:menu_item.permissions %} class="disabled"{% endif %}>
{% if menu_item.buttons %}
<div class="buttons pull-right">
{% for button in menu_item.buttons %}
{% if not button.permissions or request.user|has_perms:button.permissions %}
<a href="{% url button.link %}" class="btn btn-xs btn-{{ button.color }}" title="{{ button.title }}"><i class="fa {{ button.icon_class }}"></i></a>
{% endif %}
{% endfor %}
</div>
{% endif %}
<a href="{% url menu_item.link %}">{{ menu_item.link_text }}</a>
</li>
{% endfor %}
{% if not forloop.last %}
<li class="divider"></li>
{% endif %}
{% endfor %}
</ul>
</li>

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -26,6 +27,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons aggregate %}
{% if perms.ipam.add_aggregate %}
{% clone_button aggregate %}
{% endif %}
@ -88,10 +90,17 @@
</tr>
</table>
</div>
{% plugin_left_page aggregate %}
</div>
<div class="col-md-6">
{% include 'inc/custom_fields_panel.html' with obj=aggregate %}
{% include 'extras/inc/tags_panel.html' with tags=aggregate.tags.all url='ipam:aggregate_list' %}
{% plugin_right_page aggregate %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page aggregate %}
</div>
</div>
<div class="row">

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons ipaddress %}
{% if perms.ipam.add_ipaddress %}
{% clone_button ipaddress %}
{% endif %}
@ -152,6 +154,7 @@
</div>
{% include 'inc/custom_fields_panel.html' with obj=ipaddress %}
{% include 'extras/inc/tags_panel.html' with tags=ipaddress.tags.all url='ipam:ipaddress_list' %}
{% plugin_left_page ipaddress %}
</div>
<div class="col-md-8">
{% include 'panel_table.html' with table=parent_prefixes_table heading='Parent Prefixes' %}
@ -159,6 +162,12 @@
{% include 'panel_table.html' with table=duplicate_ips_table heading='Duplicate IP Addresses' panel_class='danger' %}
{% endif %}
{% include 'utilities/obj_table.html' with table=related_ips_table table_template='panel_table.html' heading='Related IP Addresses' panel_class='default noprint' %}
{% plugin_right_page ipaddress %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page ipaddress %}
</div>
</div>
{% endblock %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons prefix %}
{% if perms.ipam.add_prefix and active_tab == 'prefixes' and first_available_prefix %}
<a href="{% url 'ipam:prefix_add' %}?prefix={{ first_available_prefix }}&vrf={{ prefix.vrf.pk }}&site={{ prefix.site.pk }}&tenant_group={{ prefix.tenant.group.pk }}&tenant={{ prefix.tenant.pk }}" class="btn btn-success">
<i class="fa fa-plus" aria-hidden="true"></i> Add Child Prefix
@ -187,12 +189,19 @@
</div>
{% include 'inc/custom_fields_panel.html' with obj=prefix %}
{% include 'extras/inc/tags_panel.html' with tags=prefix.tags.all url='ipam:prefix_list' %}
{% plugin_left_page prefix %}
</div>
<div class="col-md-7">
{% if duplicate_prefix_table.rows %}
{% include 'panel_table.html' with table=duplicate_prefix_table heading='Duplicate Prefixes' panel_class='danger' %}
{% endif %}
{% include 'panel_table.html' with table=parent_prefix_table heading='Parent Prefixes' panel_class='default' %}
{% plugin_right_page prefix %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page prefix %}
</div>
</div>
{% endblock %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block content %}
<div class="row noprint">
@ -26,6 +27,7 @@
</div>
</div>
<div class="pull-right">
{% plugin_buttons service %}
{% if perms.dcim.change_service %}
{% edit_button service %}
{% endif %}
@ -81,6 +83,15 @@
</div>
{% include 'inc/custom_fields_panel.html' with obj=service %}
{% include 'extras/inc/tags_panel.html' with tags=service.tags.all url='ipam:service_list' %}
</div>
{% plugin_left_page service %}
</div>
<div class="col-md-6">
{% plugin_right_page service %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page service %}
</div>
</div>
{% endblock %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -31,6 +32,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons vlan %}
{% if perms.ipam.add_vlan %}
{% clone_button vlan %}
{% endif %}
@ -139,6 +141,7 @@
</div>
{% include 'inc/custom_fields_panel.html' with obj=vlan %}
{% include 'extras/inc/tags_panel.html' with tags=vlan.tags.all url='ipam:vlan_list' %}
{% plugin_left_page vlan %}
</div>
<div class="col-md-8">
<div class="panel panel-default">
@ -155,6 +158,12 @@
</div>
{% endif %}
</div>
{% plugin_right_page vlan %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page vlan %}
</div>
</div>
{% endblock %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -25,6 +26,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons vrf %}
{% if perms.ipam.add_vrf %}
{% clone_button vrf %}
{% endif %}
@ -97,9 +99,16 @@
</table>
</div>
{% include 'extras/inc/tags_panel.html' with tags=vrf.tags.all url='ipam:vrf_list' %}
{% plugin_left_page vrf %}
</div>
<div class="col-md-6">
{% include 'inc/custom_fields_panel.html' with obj=vrf %}
{% plugin_right_page vrf %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page vrf %}
</div>
</div>
{% endblock %}

View File

@ -4,6 +4,7 @@
{% load helpers %}
{% load secret_helpers %}
{% load static %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -16,6 +17,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons secret %}
{% if perms.secrets.change_secret %}
{% edit_button secret %}
{% endif %}
@ -65,6 +67,7 @@
</table>
</div>
{% include 'inc/custom_fields_panel.html' with obj=secret %}
{% plugin_left_page secret %}
</div>
<div class="col-md-6">
{% if secret|decryptable_by:request.user %}
@ -100,6 +103,12 @@
</div>
{% endif %}
{% include 'extras/inc/tags_panel.html' with tags=secret.tags.all url='secrets:secret_list' %}
{% plugin_right_page secret %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page secret %}
</div>
</div>

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons tenant %}
{% if perms.tenancy.add_tenant %}
{% clone_button tenant %}
{% endif %}
@ -93,6 +95,7 @@
{% endif %}
</div>
</div>
{% plugin_left_page tenant %}
</div>
<div class="col-md-5">
<div class="panel panel-default">
@ -146,6 +149,12 @@
</div>
</div>
</div>
{% plugin_right_page tenant %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page tenant %}
</div>
</div>
{% endblock %}

View File

@ -2,6 +2,7 @@
{% load buttons %}
{% load custom_links %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint" xmlns="http://www.w3.org/1999/html">
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons cluster %}
{% if perms.virtualization.add_cluster %}
{% clone_button cluster %}
{% endif %}
@ -121,6 +123,7 @@
{% endif %}
</div>
</div>
{% plugin_left_page cluster %}
</div>
<div class="col-md-7">
<div class="panel panel-default">
@ -148,6 +151,12 @@
</form>
{% endif %}
</div>
{% plugin_right_page cluster %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page cluster %}
</div>
</div>
{% endblock %}

View File

@ -3,6 +3,7 @@
{% load custom_links %}
{% load static %}
{% load helpers %}
{% load plugins %}
{% block header %}
<div class="row noprint">
@ -28,6 +29,7 @@
</div>
</div>
<div class="pull-right noprint">
{% plugin_buttons virtualmachine %}
{% if perms.virtualization.add_virtualmachine %}
{% clone_button virtualmachine %}
{% endif %}
@ -158,6 +160,7 @@
{% endif %}
</div>
</div>
{% plugin_left_page virtualmachine %}
</div>
<div class="col-md-6">
<div class="panel panel-default">
@ -235,6 +238,12 @@
</div>
{% endif %}
</div>
{% plugin_right_page virtualmachine %}
</div>
</div>
<div class="row">
<div class="col-md-12">
{% plugin_full_width_page virtualmachine %}
</div>
</div>
<div class="row">

View File

@ -78,3 +78,30 @@ def unpack_grouped_choices(choices):
else:
unpacked_choices.append((key, value))
return unpacked_choices
#
# Button color choices
#
class ButtonColorChoices(ChoiceSet):
"""
Map standard button color choices to Bootstrap color classes
"""
DEFAULT = 'default'
BLUE = 'primary'
GREY = 'secondary'
GREEN = 'success'
RED = 'danger'
YELLOW = 'warning'
BLACK = 'dark'
CHOICES = (
(DEFAULT, 'Default'),
(BLUE, 'Blue'),
(GREY, 'Grey'),
(GREEN, 'Green'),
(RED, 'Red'),
(YELLOW, 'Yellow'),
(BLACK, 'Black')
)

View File

@ -1,10 +1,13 @@
from django.conf import settings as django_settings
from extras.registry import registry
def settings(request):
def settings_and_registry(request):
"""
Expose Django settings in the template context. Example: {{ settings.DEBUG }}
Expose Django settings and NetBox registry stores in the template context. Example: {{ settings.DEBUG }}
"""
return {
'settings': django_settings,
'registry': registry,
}

View File

@ -201,6 +201,14 @@ def get_docs(model):
return mark_safe(content)
@register.filter()
def has_perms(user, permissions_list):
"""
Return True if the user has *all* permissions in the list.
"""
return user.has_perms(permissions_list)
#
# Tags
#