mirror of
https://github.com/netbox-community/netbox.git
synced 2026-01-28 12:48:15 +01:00
Compare commits
269 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d79ed76d80 | ||
|
|
488129d7ad | ||
|
|
dc9f991e5f | ||
|
|
c691ec843d | ||
|
|
67f2cdc921 | ||
|
|
ee51dae73f | ||
|
|
0316063ba9 | ||
|
|
8939d4de92 | ||
|
|
5de085d83d | ||
|
|
19a10cee82 | ||
|
|
db70f04447 | ||
|
|
d5dbd5ccf1 | ||
|
|
b5aff1575d | ||
|
|
884d648cc2 | ||
|
|
ed05198c45 | ||
|
|
c593eca936 | ||
|
|
cfc09bfcc8 | ||
|
|
2daf1e2004 | ||
|
|
5266bf93a3 | ||
|
|
e04a5dc81f | ||
|
|
ccf8059452 | ||
|
|
b86c61dcdb | ||
|
|
eb2e960af4 | ||
|
|
2357928e72 | ||
|
|
ae58af4bb7 | ||
|
|
902b1b2c32 | ||
|
|
225ba4cc35 | ||
|
|
fe088dba7a | ||
|
|
46b896b2cf | ||
|
|
52ef488208 | ||
|
|
34c33549b8 | ||
|
|
76230cad53 | ||
|
|
9ffc404027 | ||
|
|
58442b1af6 | ||
|
|
5f6b63e978 | ||
|
|
ad08935c57 | ||
|
|
af405a8ab2 | ||
|
|
1ffbeba181 | ||
|
|
630788731e | ||
|
|
721368ea8d | ||
|
|
1f3a21ba20 | ||
|
|
6cfd68d9fb | ||
|
|
6413d47fb2 | ||
|
|
9e0aa0d11e | ||
|
|
ee4c5ef64a | ||
|
|
4ab3854d66 | ||
|
|
354f87c888 | ||
|
|
92fc28aa09 | ||
|
|
30e330c887 | ||
|
|
093181c186 | ||
|
|
f316958943 | ||
|
|
0432b1a6f9 | ||
|
|
b2f4ef06c7 | ||
|
|
f469c794ce | ||
|
|
221e014a25 | ||
|
|
fb2868f8bb | ||
|
|
aa38dcf490 | ||
|
|
06116cdde7 | ||
|
|
5f1329c71c | ||
|
|
613e37837b | ||
|
|
a914a7c438 | ||
|
|
8c7b3a1f9b | ||
|
|
9c16d5a747 | ||
|
|
0d9d0b0446 | ||
|
|
cb344a3792 | ||
|
|
dd9fc4173d | ||
|
|
fd6739f0cc | ||
|
|
fa83750e72 | ||
|
|
a72d5c899e | ||
|
|
5cf872d000 | ||
|
|
3d3d1bc623 | ||
|
|
59e6386361 | ||
|
|
9c1eda0d9a | ||
|
|
785119f5bb | ||
|
|
8a3ebf64bc | ||
|
|
af302d8368 | ||
|
|
f03cc96050 | ||
|
|
e7f7b14214 | ||
|
|
84d2db0d35 | ||
|
|
74e56a890c | ||
|
|
b94ef39a51 | ||
|
|
877417d68f | ||
|
|
62f14f0473 | ||
|
|
66a99e13bb | ||
|
|
d316d8ac61 | ||
|
|
40574b65af | ||
|
|
81c9177c09 | ||
|
|
68ef5dd2a4 | ||
|
|
59815ea53d | ||
|
|
5540079e81 | ||
|
|
68a0e76ca6 | ||
|
|
1d9fbeed81 | ||
|
|
d0edd9d5c1 | ||
|
|
9ea30c057f | ||
|
|
c1f2ad90ef | ||
|
|
2a47bb8b54 | ||
|
|
b6686a5fcb | ||
|
|
16b8a45ed6 | ||
|
|
579c365808 | ||
|
|
745ac294a5 | ||
|
|
eedda6e648 | ||
|
|
5ec1b31804 | ||
|
|
8e661c34e9 | ||
|
|
ce0b1733fe | ||
|
|
0a8b09a11a | ||
|
|
0b77702626 | ||
|
|
a4382f0b27 | ||
|
|
2732e7c3d9 | ||
|
|
2188b0982c | ||
|
|
eeb9633854 | ||
|
|
60b6c48775 | ||
|
|
4e84e8048f | ||
|
|
e220c38b97 | ||
|
|
ad1522f428 | ||
|
|
bc50c2aa55 | ||
|
|
28b5e88c50 | ||
|
|
33ca352fd9 | ||
|
|
058c78d8be | ||
|
|
05fdf5e9a0 | ||
|
|
533521b29d | ||
|
|
2dff093305 | ||
|
|
ba6ce07759 | ||
|
|
33eb5e11de | ||
|
|
8d3801896f | ||
|
|
f1236e9bf7 | ||
|
|
fa1548f3ce | ||
|
|
0995e10d87 | ||
|
|
e143158f12 | ||
|
|
40bfb55370 | ||
|
|
dab313897e | ||
|
|
c7fb2ff894 | ||
|
|
ced6fe313a | ||
|
|
7f5571200c | ||
|
|
fd879c7cf5 | ||
|
|
a9d04547d1 | ||
|
|
09e09e43ba | ||
|
|
87f0b19dc0 | ||
|
|
eab79faaeb | ||
|
|
dbbb2cdaba | ||
|
|
7246fd667e | ||
|
|
fe4f4bddc8 | ||
|
|
f7ba766de3 | ||
|
|
70c29051b3 | ||
|
|
043b1c28d2 | ||
|
|
022653f446 | ||
|
|
1706db38df | ||
|
|
81287833ee | ||
|
|
2f12d09663 | ||
|
|
3ace83c5aa | ||
|
|
356de985d2 | ||
|
|
ab93606e4a | ||
|
|
ec2dc8d7a4 | ||
|
|
a2eb2e7da6 | ||
|
|
3590ed378d | ||
|
|
2f37357a1b | ||
|
|
981c982237 | ||
|
|
457354c244 | ||
|
|
00afe7aa94 | ||
|
|
450615e0bb | ||
|
|
73881ad1e0 | ||
|
|
2522b88fc6 | ||
|
|
0068108c57 | ||
|
|
400f6fc5fb | ||
|
|
901143b72a | ||
|
|
9a38586e13 | ||
|
|
62ad7734b2 | ||
|
|
7ef9a6c0a7 | ||
|
|
8364694fb4 | ||
|
|
683c5a22db | ||
|
|
0574ac7530 | ||
|
|
a955f90a7e | ||
|
|
2dc31c0edd | ||
|
|
6ea15cec6f | ||
|
|
9df238c5f2 | ||
|
|
9466802a95 | ||
|
|
36130965f2 | ||
|
|
d4f6909859 | ||
|
|
1a8554fd32 | ||
|
|
9f5b138b0f | ||
|
|
cebe580484 | ||
|
|
3b4ec5926d | ||
|
|
c5776d9da4 | ||
|
|
9e45cafac4 | ||
|
|
2033d15b2f | ||
|
|
e2123f4a9e | ||
|
|
f6dfd2fa43 | ||
|
|
1f382f9252 | ||
|
|
459bcd88a9 | ||
|
|
1487b5004d | ||
|
|
a28509019a | ||
|
|
c189895f6c | ||
|
|
5e971994ff | ||
|
|
f108049142 | ||
|
|
9fc1e88d9f | ||
|
|
2cd44d0234 | ||
|
|
16bc262a4f | ||
|
|
ef5c20dc6f | ||
|
|
a53f854187 | ||
|
|
ea9de37dd1 | ||
|
|
235d99021b | ||
|
|
8af4cf87b5 | ||
|
|
997247ee77 | ||
|
|
b92e518370 | ||
|
|
b5d57262f9 | ||
|
|
45f6ea211d | ||
|
|
a4a276083a | ||
|
|
c42613cf4d | ||
|
|
84de0458aa | ||
|
|
2b33e91e2c | ||
|
|
71c363ebc8 | ||
|
|
7ffc00159e | ||
|
|
79aba5edf2 | ||
|
|
a504f5f309 | ||
|
|
90144ccd9a | ||
|
|
8c6d35645d | ||
|
|
0706c65ce6 | ||
|
|
0dc3a72912 | ||
|
|
0de857bf7a | ||
|
|
55558cb272 | ||
|
|
803287a514 | ||
|
|
1a89e35729 | ||
|
|
bc954bc7be | ||
|
|
2bd3f1fcc3 | ||
|
|
7454efe648 | ||
|
|
9df2769383 | ||
|
|
36cbbac870 | ||
|
|
406b88777c | ||
|
|
113313e000 | ||
|
|
c85bcbcf31 | ||
|
|
c983dac771 | ||
|
|
7a10748355 | ||
|
|
ca1186dca1 | ||
|
|
5f5edbc10e | ||
|
|
71a8a13644 | ||
|
|
a17c22746d | ||
|
|
5dc956fbe1 | ||
|
|
fcf3b14712 | ||
|
|
28473fa3e0 | ||
|
|
8ce106cb4b | ||
|
|
22ac9f63a1 | ||
|
|
0de7f4712f | ||
|
|
8d92089487 | ||
|
|
3a0849699f | ||
|
|
008fc5623e | ||
|
|
9d66ac4a6a | ||
|
|
405d93c6f2 | ||
|
|
2fcdc90d3f | ||
|
|
27e3b6f377 | ||
|
|
8ed0d0400f | ||
|
|
a5853427d4 | ||
|
|
d0bd1ad25b | ||
|
|
28e3b7af18 | ||
|
|
38ff01e874 | ||
|
|
be23230938 | ||
|
|
7b93155b06 | ||
|
|
b7d41bc42c | ||
|
|
e17597a0a9 | ||
|
|
f1b0421805 | ||
|
|
01b9d1a493 | ||
|
|
d6ccf13167 | ||
|
|
f6cbce65fa | ||
|
|
f0ced98dc6 | ||
|
|
fcdb05238c | ||
|
|
8687226cc7 | ||
|
|
047f13ac5d | ||
|
|
b475a575e4 | ||
|
|
8cb6aed8fa | ||
|
|
926b1fadf2 | ||
|
|
8274903985 |
19
.github/ISSUE_TEMPLATE/bug_report.md
vendored
19
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -15,22 +15,23 @@ about: Report a reproducible bug in the current release of NetBox
|
||||
|
||||
Please describe the environment in which you are running NetBox. Be sure
|
||||
that you are running an unmodified instance of the latest stable release
|
||||
before submitting a bug report.
|
||||
before submitting a bug report, and that any plugins have been disabled.
|
||||
-->
|
||||
### Environment
|
||||
* Python version: <!-- Example: 3.6.9 -->
|
||||
* NetBox version: <!-- Example: 2.7.3 -->
|
||||
* Python version:
|
||||
* NetBox version:
|
||||
|
||||
<!--
|
||||
Describe in detail the exact steps that someone else can take to reproduce
|
||||
this bug using the current stable release of NetBox (or the current beta
|
||||
release where applicable). Begin with the creation of any necessary
|
||||
database objects and call out every operation being performed explicitly.
|
||||
If reporting a bug in the REST API, be sure to reconstruct the raw HTTP
|
||||
request(s) being made: Don't rely on a wrapper like pynetbox.
|
||||
this bug using the current stable release of NetBox. Begin with the
|
||||
creation of any necessary database objects and call out every operation
|
||||
being performed explicitly. If reporting a bug in the REST API, be sure to
|
||||
reconstruct the raw HTTP request(s) being made: Don't rely on a client
|
||||
library such as pynetbox.
|
||||
-->
|
||||
### Steps to Reproduce
|
||||
1.
|
||||
1. Disable any installed plugins by commenting out the `PLUGINS` setting in
|
||||
`configuration.py`.
|
||||
2.
|
||||
3.
|
||||
|
||||
|
||||
@@ -3,10 +3,9 @@ services:
|
||||
- postgresql
|
||||
- redis-server
|
||||
addons:
|
||||
postgresql: "9.4"
|
||||
postgresql: "9.6"
|
||||
language: python
|
||||
python:
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
- "3.7"
|
||||
install:
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||

|
||||
|
||||
**The [2020 NetBox user survey](https://docs.google.com/forms/d/1OVZuC4kQ-6kJbVf0bDB6vgkL9H96xF6phvYzby23elk/edit) is open!** Your feedback helps guide the project's long-term development.
|
||||
|
||||
NetBox is an IP address management (IPAM) and data center infrastructure
|
||||
management (DCIM) tool. Initially conceived by the network engineering team at
|
||||
[DigitalOcean](https://www.digitalocean.com/), NetBox was developed specifically
|
||||
|
||||
@@ -68,8 +68,7 @@ Jinja2
|
||||
|
||||
# Simple markup language for rendering HTML
|
||||
# https://github.com/Python-Markdown/markdown
|
||||
# py-gfm requires Markdown<3.0
|
||||
Markdown<3.0
|
||||
Markdown
|
||||
|
||||
# Library for manipulating IP prefixes and addresses
|
||||
# https://github.com/drkjam/netaddr
|
||||
|
||||
26
contrib/apache.conf
Normal file
26
contrib/apache.conf
Normal file
@@ -0,0 +1,26 @@
|
||||
<VirtualHost *:443>
|
||||
ProxyPreserveHost On
|
||||
|
||||
# CHANGE THIS TO YOUR SERVER'S NAME
|
||||
ServerName netbox.example.com
|
||||
|
||||
SSLEngine on
|
||||
SSLCertificateFile /etc/ssl/certs/netbox.crt
|
||||
SSLCertificateKeyFile /etc/ssl/private/netbox.key
|
||||
|
||||
Alias /static /opt/netbox/netbox/static
|
||||
|
||||
<Directory /opt/netbox/netbox/static>
|
||||
Options Indexes FollowSymLinks MultiViews
|
||||
AllowOverride None
|
||||
Require all granted
|
||||
</Directory>
|
||||
|
||||
<Location /static>
|
||||
ProxyPass !
|
||||
</Location>
|
||||
|
||||
RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
|
||||
ProxyPass / http://127.0.0.1:8001/
|
||||
ProxyPassReverse / http://127.0.0.1:8001/
|
||||
</VirtualHost>
|
||||
29
contrib/nginx.conf
Normal file
29
contrib/nginx.conf
Normal file
@@ -0,0 +1,29 @@
|
||||
server {
|
||||
listen 443 ssl;
|
||||
|
||||
# CHANGE THIS TO YOUR SERVER'S NAME
|
||||
server_name netbox.example.com;
|
||||
|
||||
ssl_certificate /etc/ssl/certs/netbox.crt;
|
||||
ssl_certificate_key /etc/ssl/private/netbox.key;
|
||||
|
||||
client_max_body_size 25m;
|
||||
|
||||
location /static/ {
|
||||
alias /opt/netbox/netbox/static/;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8001;
|
||||
proxy_set_header X-Forwarded-Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
# Redirect HTTP traffic to HTTPS
|
||||
listen 80;
|
||||
server_name _;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
@@ -63,7 +63,7 @@ A human-friendly description of what your script does.
|
||||
|
||||
### `field_order`
|
||||
|
||||
A list of field names indicating the order in which the form fields should appear. This is optional, however on Python 3.5 and earlier the fields will appear in random order. (Declarative ordering is preserved on Python 3.6 and above.) For example:
|
||||
A list of field names indicating the order in which the form fields should appear. This is optional, and should not be required on Python 3.6 and above. For example:
|
||||
|
||||
```
|
||||
field_order = ['var1', 'var2', 'var3']
|
||||
|
||||
@@ -71,3 +71,36 @@ If no body template is specified, the request body will be populated with a JSON
|
||||
When a change is detected, any resulting webhooks are placed into a Redis queue for processing. This allows the user's request to complete without needing to wait for the outgoing webhook(s) to be processed. The webhooks are then extracted from the queue by the `rqworker` process and HTTP requests are sent to their respective destinations. The current webhook queue and any failed webhooks can be inspected in the admin UI under Django RQ > Queues.
|
||||
|
||||
A request is considered successful if the response has a 2XX status code; otherwise, the request is marked as having failed. Failed requests may be retried manually via the admin UI.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
To assist with verifying that the content of outgoing webhooks is rendered correctly, NetBox provides a simple HTTP listener that can be run locally to receive and display webhook requests. First, modify the target URL of the desired webhook to `http://localhost:9000/`. This will instruct NetBox to send the request to the local server on TCP port 9000. Then, start the webhook receiver service from the NetBox root directory:
|
||||
|
||||
```no-highlight
|
||||
$ python netbox/manage.py webhook_receiver
|
||||
Listening on port http://localhost:9000. Stop with CONTROL-C.
|
||||
```
|
||||
|
||||
You can test the receiver itself by sending any HTTP request to it. For example:
|
||||
|
||||
```no-highlight
|
||||
$ curl -X POST http://localhost:9000 --data '{"foo": "bar"}'
|
||||
```
|
||||
|
||||
The server will print output similar to the following:
|
||||
|
||||
```no-highlight
|
||||
[1] Tue, 07 Apr 2020 17:44:02 GMT 127.0.0.1 "POST / HTTP/1.1" 200 -
|
||||
Host: localhost:9000
|
||||
User-Agent: curl/7.58.0
|
||||
Accept: */*
|
||||
Content-Length: 14
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
{"foo": "bar"}
|
||||
------------
|
||||
```
|
||||
|
||||
Note that `webhook_receiver` does not actually _do_ anything with the information received: It merely prints the request headers and body for inspection.
|
||||
|
||||
Now, when the NetBox webhook is triggered and processed, you should see its headers and content appear in the terminal where the webhook receiver is listening. If you don't, check that the `rqworker` process is running and that webhook events are being placed into the queue (visible under the NetBox admin UI).
|
||||
|
||||
@@ -10,8 +10,8 @@ This will launch a customized version of [the built-in Django shell](https://doc
|
||||
|
||||
```
|
||||
$ ./manage.py nbshell
|
||||
### NetBox interactive shell (jstretch-laptop)
|
||||
### Python 3.5.2 | Django 2.0.8 | NetBox 2.4.3
|
||||
### NetBox interactive shell (localhost)
|
||||
### Python 3.6.9 | Django 2.2.11 | NetBox 2.7.10
|
||||
### lsmodels() will show available models. Use help(<model>) for more info.
|
||||
```
|
||||
|
||||
|
||||
@@ -187,37 +187,6 @@ GET /api/ipam/prefixes/13980/?brief=1
|
||||
|
||||
The brief format is supported for both lists and individual objects.
|
||||
|
||||
### Static Choice Fields
|
||||
|
||||
Some model fields, such as the `status` field in the above example, utilize static integers corresponding to static choices. The available choices can be retrieved from the read-only `_choices` endpoint within each app. A specific `model:field` tuple may optionally be specified in the URL.
|
||||
|
||||
Each choice includes a human-friendly label and its corresponding numeric value. For example, `GET /api/ipam/_choices/prefix:status/` will return:
|
||||
|
||||
```
|
||||
[
|
||||
{
|
||||
"value": 0,
|
||||
"label": "Container"
|
||||
},
|
||||
{
|
||||
"value": 1,
|
||||
"label": "Active"
|
||||
},
|
||||
{
|
||||
"value": 2,
|
||||
"label": "Reserved"
|
||||
},
|
||||
{
|
||||
"value": 3,
|
||||
"label": "Deprecated"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Thus, to set a prefix's status to "Reserved," it would be assigned the integer `2`.
|
||||
|
||||
A request for `GET /api/ipam/_choices/` will return choices for _all_ fields belonging to models within the IPAM app.
|
||||
|
||||
## Pagination
|
||||
|
||||
API responses which contain a list of objects (for example, a request to `/api/dcim/devices/`) will be paginated to avoid unnecessary overhead. The root JSON object will contain the following attributes:
|
||||
@@ -280,27 +249,32 @@ A list of objects retrieved via the API can be filtered by passing one or more q
|
||||
GET /api/ipam/prefixes/?status=1
|
||||
```
|
||||
|
||||
The choices available for fixed choice fields such as `status` are exposed in the API under a special `_choices` endpoint for each NetBox app. For example, the available choices for `Prefix.status` are listed at `/api/ipam/_choices/` under the key `prefix:status`:
|
||||
The choices available for fixed choice fields such as `status` can be retrieved by sending an `OPTIONS` API request for the desired endpoint:
|
||||
|
||||
```no-highlight
|
||||
$ curl -s -X OPTIONS \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json; indent=4" \
|
||||
http://localhost:8000/api/ipam/prefixes/ | jq ".actions.POST.status.choices"
|
||||
[
|
||||
{
|
||||
"value": "container",
|
||||
"display_name": "Container"
|
||||
},
|
||||
{
|
||||
"value": "active",
|
||||
"display_name": "Active"
|
||||
},
|
||||
{
|
||||
"value": "reserved",
|
||||
"display_name": "Reserved"
|
||||
},
|
||||
{
|
||||
"value": "deprecated",
|
||||
"display_name": "Deprecated"
|
||||
}
|
||||
]
|
||||
|
||||
```
|
||||
"prefix:status": [
|
||||
{
|
||||
"label": "Container",
|
||||
"value": 0
|
||||
},
|
||||
{
|
||||
"label": "Active",
|
||||
"value": 1
|
||||
},
|
||||
{
|
||||
"label": "Reserved",
|
||||
"value": 2
|
||||
},
|
||||
{
|
||||
"label": "Deprecated",
|
||||
"value": 3
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
For most fields, when a filter is passed multiple times, objects matching _any_ of the provided values will be returned. For example, `GET /api/dcim/sites/?name=Foo&name=Bar` will return all sites named "Foo" _or_ "Bar". The exception to this rule is ManyToManyFields which may have multiple values assigned. Tags are the most common example of a ManyToManyField. For example, `GET /api/dcim/sites/?tag=foo&tag=bar` will return only sites tagged with both "foo" _and_ "bar".
|
||||
|
||||
@@ -191,6 +191,14 @@ LOGGING = {
|
||||
}
|
||||
```
|
||||
|
||||
### Available Loggers
|
||||
|
||||
* `netbox.auth.*` - Authentication events
|
||||
* `netbox.api.views.*` - Views which handle business logic for the REST API
|
||||
* `netbox.reports.*` - Report execution (`module.name`)
|
||||
* `netbox.scripts.*` - Custom script execution (`module.name`)
|
||||
* `netbox.views.*` - Views which handle business logic for the web UI
|
||||
|
||||
---
|
||||
|
||||
## LOGIN_REQUIRED
|
||||
@@ -291,6 +299,39 @@ Determine how many objects to display per page within each list of objects.
|
||||
|
||||
---
|
||||
|
||||
## PLUGINS
|
||||
|
||||
Default: Empty
|
||||
|
||||
A list of installed [NetBox plugins](../../plugins/) to enable. Plugins will not take effect unless they are listed here.
|
||||
|
||||
!!! 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.
|
||||
|
||||
---
|
||||
|
||||
## 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 a plugin must be listed in `PLUGINS` for its configuration to take effect.
|
||||
|
||||
---
|
||||
|
||||
## PREFER_IPV4
|
||||
|
||||
Default: False
|
||||
@@ -299,6 +340,72 @@ When determining the primary IP address for a device, IPv6 is preferred over IPv
|
||||
|
||||
---
|
||||
|
||||
## REMOTE_AUTH_ENABLED
|
||||
|
||||
Default: `False`
|
||||
|
||||
NetBox can be configured to support remote user authentication by inferring user authentication from an HTTP header set by the HTTP reverse proxy (e.g. nginx or Apache). Set this to `True` to enable this functionality. (Local authenitcation will still take effect as a fallback.)
|
||||
|
||||
---
|
||||
|
||||
## REMOTE_AUTH_BACKEND
|
||||
|
||||
Default: `'utilities.auth_backends.RemoteUserBackend'`
|
||||
|
||||
Python path to the custom [Django authentication backend](https://docs.djangoproject.com/en/stable/topics/auth/customizing/) to use for external user authentication, if not using NetBox's built-in backend. (Requires `REMOTE_AUTH_ENABLED`.)
|
||||
|
||||
---
|
||||
|
||||
## REMOTE_AUTH_HEADER
|
||||
|
||||
Default: `'HTTP_REMOTE_USER'`
|
||||
|
||||
When remote user authentication is in use, this is the name of the HTTP header which informs NetBox of the currently authenticated user. (Requires `REMOTE_AUTH_ENABLED`.)
|
||||
|
||||
---
|
||||
|
||||
## REMOTE_AUTH_AUTO_CREATE_USER
|
||||
|
||||
Default: `True`
|
||||
|
||||
If true, NetBox will automatically create local accounts for users authenticated via a remote service. (Requires `REMOTE_AUTH_ENABLED`.)
|
||||
|
||||
---
|
||||
|
||||
## REMOTE_AUTH_DEFAULT_GROUPS
|
||||
|
||||
Default: `[]` (Empty list)
|
||||
|
||||
The list of groups to assign a new user account when created using remote authentication. (Requires `REMOTE_AUTH_ENABLED`.)
|
||||
|
||||
---
|
||||
|
||||
## REMOTE_AUTH_DEFAULT_PERMISSIONS
|
||||
|
||||
Default: `[]` (Empty list)
|
||||
|
||||
The list of permissions to assign a new user account when created using remote authentication. (Requires `REMOTE_AUTH_ENABLED`.)
|
||||
|
||||
---
|
||||
|
||||
## RELEASE_CHECK_TIMEOUT
|
||||
|
||||
Default: 86,400 (24 hours)
|
||||
|
||||
The number of seconds to retain the latest version that is fetched from the GitHub API before automatically invalidating it and fetching it from the API again. This must be set to at least one hour (3600 seconds).
|
||||
|
||||
---
|
||||
|
||||
## RELEASE_CHECK_URL
|
||||
|
||||
Default: None
|
||||
|
||||
The releases of this repository are checked to detect new releases, which are shown on the home page of the web interface. You can change this to your own fork of the NetBox repository, or set it to `None` to disable the check. The URL provided **must** be compatible with the GitHub API.
|
||||
|
||||
Use `'https://api.github.com/repos/netbox-community/netbox/releases'` to check for release in the official NetBox repository.
|
||||
|
||||
---
|
||||
|
||||
## REPORTS_ROOT
|
||||
|
||||
Default: $BASE_DIR/netbox/reports/
|
||||
|
||||
@@ -46,9 +46,9 @@ DATABASE = {
|
||||
[Redis](https://redis.io/) is an in-memory data store similar to memcached. While Redis has been an optional component of
|
||||
NetBox since the introduction of webhooks in version 2.4, it is required starting in 2.6 to support NetBox's caching
|
||||
functionality (as well as other planned features). In 2.7, the connection settings were broken down into two sections for
|
||||
webhooks and caching, allowing the user to connect to different Redis instances/databases per feature.
|
||||
task queuing and caching, allowing the user to connect to different Redis instances/databases per feature.
|
||||
|
||||
Redis is configured using a configuration setting similar to `DATABASE` and these settings are the same for both of the `webhooks` and `caching` subsections:
|
||||
Redis is configured using a configuration setting similar to `DATABASE` and these settings are the same for both of the `tasks` and `caching` subsections:
|
||||
|
||||
* `HOST` - Name or IP address of the Redis server (use `localhost` if running locally)
|
||||
* `PORT` - TCP port of the Redis service; leave blank for default port (6379)
|
||||
@@ -61,7 +61,7 @@ Example:
|
||||
|
||||
```python
|
||||
REDIS = {
|
||||
'webhooks': {
|
||||
'tasks': {
|
||||
'HOST': 'redis.example.com',
|
||||
'PORT': 1234,
|
||||
'PASSWORD': 'foobar',
|
||||
@@ -84,9 +84,9 @@ REDIS = {
|
||||
If you are upgrading from a version prior to v2.7, please note that the Redis connection configuration settings have
|
||||
changed. Manual modification to bring the `REDIS` section inline with the above specification is necessary
|
||||
|
||||
!!! note
|
||||
It is highly recommended to keep the webhook and cache databases separate. Using the same database number on the
|
||||
same Redis instance for both may result in webhook processing data being lost during cache flushing events.
|
||||
!!! warning
|
||||
It is highly recommended to keep the task and cache databases separate. Using the same database number on the
|
||||
same Redis instance for both may result in queued background tasks being lost during cache flushing events.
|
||||
|
||||
### Using Redis Sentinel
|
||||
|
||||
@@ -102,7 +102,7 @@ Example:
|
||||
|
||||
```python
|
||||
REDIS = {
|
||||
'webhooks': {
|
||||
'tasks': {
|
||||
'SENTINELS': [('mysentinel.redis.example.com', 6379)],
|
||||
'SENTINEL_SERVICE': 'netbox',
|
||||
'PASSWORD': '',
|
||||
@@ -126,7 +126,7 @@ REDIS = {
|
||||
|
||||
!!! note
|
||||
It is possible to have only one or the other Redis configurations to use Sentinel functionality. It is possible
|
||||
for example to have the webhook use sentinel via `HOST`/`PORT` and for caching to use Sentinel via
|
||||
for example to have the tasks database use sentinel via `HOST`/`PORT` and for caching to use Sentinel via
|
||||
`SENTINELS`/`SENTINEL_SERVICE`.
|
||||
|
||||
|
||||
|
||||
55
docs/development/application-registry.md
Normal file
55
docs/development/application-registry.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Application Registry
|
||||
|
||||
The registry is an in-memory data structure which houses various miscellaneous application-wide parameters, such as installed plugins. It is not exposed to the user and is not intended to be modified by any code outside of NetBox core.
|
||||
|
||||
The registry behaves essentially like a Python dictionary, with the notable exception that once a store (key) has been declared, it cannot be deleted or overwritten. The value of a store can, however, me modified; e.g. by appending a value to a list. Store values generally do not change once the application has been initialized.
|
||||
|
||||
## Stores
|
||||
|
||||
### `model_features`
|
||||
|
||||
A dictionary of particular features (e.g. custom fields) mapped to the NetBox models which support them, arranged by app. For example:
|
||||
|
||||
```python
|
||||
{
|
||||
'custom_fields': {
|
||||
'circuits': ['provider', 'circuit'],
|
||||
'dcim': ['site', 'rack', 'devicetype', ...],
|
||||
...
|
||||
},
|
||||
'webhooks': {
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### `plugin_menu_items`
|
||||
|
||||
Navigation menu items provided by NetBox plugins. Each plugin is registered as a key with the list of menu items it provides. An example:
|
||||
|
||||
```python
|
||||
{
|
||||
'Plugin A': (
|
||||
<MenuItem>, <MenuItem>, <MenuItem>,
|
||||
),
|
||||
'Plugin B': (
|
||||
<MenuItem>, <MenuItem>, <MenuItem>,
|
||||
),
|
||||
}
|
||||
```
|
||||
|
||||
### `plugin_template_extensions`
|
||||
|
||||
Plugin content that gets embedded into core NetBox templates. The store comprises NetBox models registered as dictionary keys, each pointing to a list of applicable template extension classes that exist. An example:
|
||||
|
||||
```python
|
||||
{
|
||||
'dcim.site': [
|
||||
<TemplateExtension>, <TemplateExtension>, <TemplateExtension>,
|
||||
],
|
||||
'dcim.rack': [
|
||||
<TemplateExtension>, <TemplateExtension>,
|
||||
],
|
||||
}
|
||||
```
|
||||
19
docs/extra.css
Normal file
19
docs/extra.css
Normal file
@@ -0,0 +1,19 @@
|
||||
/* Images */
|
||||
img {
|
||||
display: block;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
/* Tables */
|
||||
table {
|
||||
margin-bottom: 24px;
|
||||
width: 100%;
|
||||
}
|
||||
th {
|
||||
background-color: #f0f0f0;
|
||||
padding: 6px;
|
||||
}
|
||||
td {
|
||||
padding: 6px;
|
||||
}
|
||||
@@ -55,7 +55,7 @@ NetBox is built on the [Django](https://djangoproject.com/) Python framework and
|
||||
|
||||
## Supported Python Versions
|
||||
|
||||
NetBox supports Python 3.5, 3.6, and 3.7 environments currently. Python 3.5 is scheduled to be unsupported in NetBox v2.8.
|
||||
NetBox supports Python 3.6 and 3.7 environments currently. (Support for Python 3.5 was removed in NetBox v2.8.)
|
||||
|
||||
## Getting Started
|
||||
|
||||
|
||||
@@ -172,7 +172,7 @@ Redis is a in-memory key-value store required as part of the NetBox installation
|
||||
|
||||
```python
|
||||
REDIS = {
|
||||
'webhooks': {
|
||||
'tasks': {
|
||||
'HOST': 'redis.example.com',
|
||||
'PORT': 1234,
|
||||
'PASSWORD': 'foobar',
|
||||
|
||||
@@ -5,6 +5,18 @@ We'll set up a simple WSGI front end using [gunicorn](http://gunicorn.org/) for
|
||||
!!! info
|
||||
For the sake of brevity, only Ubuntu 18.04 instructions are provided here, but this sort of web server and WSGI configuration is not unique to NetBox. Please consult your distribution's documentation for assistance if needed.
|
||||
|
||||
## Obtain an SSL Certificate
|
||||
|
||||
To enable HTTPS access to NetBox, you'll need a valid SSL certificate. You can purchase one from a trusted commercial provider, obtain one for free from [Let's Encrypt](https://letsencrypt.org/getting-started/), or generate your own (although self-signed certificates are generally untrusted). Both the public certificate and private key files need to be installed on your NetBox server in a location that is readable by the `netbox` user.
|
||||
|
||||
The command below can be used to generate a self-signed certificate for testing purposes, however it is strongly recommended to use a certificate from a trusted authority in production. Two files will be created: the public certificate (`netbox.crt`) and the private key (`netbox.key`). The certificate is published to the world, whereas the private key must be kept secret at all times.
|
||||
|
||||
```no-highlight
|
||||
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
|
||||
-keyout /etc/ssl/private/netbox.key \
|
||||
-out /etc/ssl/certs/netbox.crt
|
||||
```
|
||||
|
||||
## HTTP Daemon Installation
|
||||
|
||||
### Option A: nginx
|
||||
@@ -15,27 +27,10 @@ The following will serve as a minimal nginx configuration. Be sure to modify you
|
||||
# apt-get install -y nginx
|
||||
```
|
||||
|
||||
Once nginx is installed, save the following configuration to `/etc/nginx/sites-available/netbox`. Be sure to replace `netbox.example.com` with the domain name or IP address of your installation. (This should match the value configured for `ALLOWED_HOSTS` in `configuration.py`.)
|
||||
Once nginx is installed, copy the default nginx configuration file to `/etc/nginx/sites-available/netbox`. Be sure to replace `netbox.example.com` with the domain name or IP address of your installation. (This should match the value configured for `ALLOWED_HOSTS` in `configuration.py`.)
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
server_name netbox.example.com;
|
||||
|
||||
client_max_body_size 25m;
|
||||
|
||||
location /static/ {
|
||||
alias /opt/netbox/netbox/static/;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8001;
|
||||
proxy_set_header X-Forwarded-Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```no-highlight
|
||||
# cp /opt/netbox/contrib/nginx.conf /etc/nginx/sites-available/netbox
|
||||
```
|
||||
|
||||
Then, delete `/etc/nginx/sites-enabled/default` and create a symlink in the `sites-enabled` directory to the configuration file you just created.
|
||||
@@ -46,65 +41,38 @@ Then, delete `/etc/nginx/sites-enabled/default` and create a symlink in the `sit
|
||||
# ln -s /etc/nginx/sites-available/netbox
|
||||
```
|
||||
|
||||
Restart the nginx service to use the new configuration.
|
||||
Finally, restart the `nginx` service to use the new configuration.
|
||||
|
||||
```no-highlight
|
||||
# service nginx restart
|
||||
```
|
||||
|
||||
To enable SSL, consider this guide on [securing nginx with Let's Encrypt](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04).
|
||||
|
||||
### Option B: Apache
|
||||
|
||||
```no-highlight
|
||||
# apt-get install -y apache2 libapache2-mod-wsgi-py3
|
||||
```
|
||||
|
||||
Once Apache is installed, proceed with the following configuration (Be sure to modify the `ServerName` appropriately):
|
||||
|
||||
```apache
|
||||
<VirtualHost *:80>
|
||||
ProxyPreserveHost On
|
||||
|
||||
ServerName netbox.example.com
|
||||
|
||||
Alias /static /opt/netbox/netbox/static
|
||||
|
||||
# Needed to allow token-based API authentication
|
||||
WSGIPassAuthorization on
|
||||
|
||||
<Directory /opt/netbox/netbox/static>
|
||||
Options Indexes FollowSymLinks MultiViews
|
||||
AllowOverride None
|
||||
Require all granted
|
||||
</Directory>
|
||||
|
||||
<Location /static>
|
||||
ProxyPass !
|
||||
</Location>
|
||||
|
||||
RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
|
||||
ProxyPass / http://127.0.0.1:8001/
|
||||
ProxyPassReverse / http://127.0.0.1:8001/
|
||||
</VirtualHost>
|
||||
```
|
||||
|
||||
Save the contents of the above example in `/etc/apache2/sites-available/netbox.conf`, enable the `proxy` and `proxy_http` modules, and reload Apache:
|
||||
Begin by installing Apache:
|
||||
|
||||
```no-highlight
|
||||
# a2enmod proxy
|
||||
# a2enmod proxy_http
|
||||
# a2enmod headers
|
||||
# apt-get install -y apache2
|
||||
```
|
||||
|
||||
Next, copy the default configuration file to `/etc/apache2/sites-available/`. Be sure to modify the `ServerName` parameter appropriately.
|
||||
|
||||
```no-highlight
|
||||
# cp /opt/netbox/contrib/apache.conf /etc/apache2/sites-available/netbox.conf
|
||||
```
|
||||
|
||||
Finally, ensure that the required Apache modules are enabled, enable the `netbox` site, and reload Apache:
|
||||
|
||||
```no-highlight
|
||||
# a2enmod ssl proxy proxy_http headers
|
||||
# a2ensite netbox
|
||||
# service apache2 restart
|
||||
```
|
||||
|
||||
To enable SSL, consider this guide on [securing Apache with Let's Encrypt](https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04).
|
||||
|
||||
!!! note
|
||||
Certain components of NetBox (such as the display of rack elevation diagrams) rely on the use of embedded objects. Ensure that your HTTP server configuration does not override the `X-Frame-Options` response header set by NetBox.
|
||||
|
||||
## gunicorn Configuration
|
||||
## Gunicorn Configuration
|
||||
|
||||
Copy `/opt/netbox/contrib/gunicorn.py` to `/opt/netbox/gunicorn.py`. (We make a copy of this file to ensure that any changes to it do not get overwritten by a future upgrade.)
|
||||
|
||||
@@ -113,7 +81,7 @@ Copy `/opt/netbox/contrib/gunicorn.py` to `/opt/netbox/gunicorn.py`. (We make a
|
||||
# cp contrib/gunicorn.py /opt/netbox/gunicorn.py
|
||||
```
|
||||
|
||||
You may wish to edit this file to change the bound IP address or port number, or to make performance-related adjustments.
|
||||
You may wish to edit this file to change the bound IP address or port number, or to make performance-related adjustments. See [the Gunicorn documentation](https://docs.gunicorn.org/en/stable/configure.html) for the available configuration parameters.
|
||||
|
||||
## systemd Configuration
|
||||
|
||||
@@ -133,7 +101,7 @@ Then, start the `netbox` and `netbox-rq` services and enable them to initiate at
|
||||
|
||||
You can use the command `systemctl status netbox` to verify that the WSGI service is running:
|
||||
|
||||
```
|
||||
```no-highlight
|
||||
# systemctl status netbox.service
|
||||
● netbox.service - NetBox WSGI Service
|
||||
Loaded: loaded (/etc/systemd/system/netbox.service; enabled; vendor preset: enabled)
|
||||
|
||||
@@ -8,6 +8,10 @@ The following sections detail how to set up a new instance of NetBox:
|
||||
4. [HTTP daemon](4-http-daemon.md)
|
||||
5. [LDAP authentication](5-ldap.md) (optional)
|
||||
|
||||
Below is a simplified overview of the NetBox application stack for reference:
|
||||
|
||||

|
||||
|
||||
## Upgrading
|
||||
|
||||
If you are upgrading from an existing installation, please consult the [upgrading guide](upgrading.md).
|
||||
|
||||
@@ -7,7 +7,7 @@ This document contains instructions for migrating from a legacy NetBox deploymen
|
||||
### Uninstall supervisord
|
||||
|
||||
```no-highlight
|
||||
# apt-get remove -y supervisord
|
||||
# apt-get remove -y supervisor
|
||||
```
|
||||
|
||||
### Configure systemd
|
||||
|
||||
BIN
docs/media/installation/netbox_application_stack.png
Normal file
BIN
docs/media/installation/netbox_application_stack.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/media/plugins/plugin_admin_ui.png
Normal file
BIN
docs/media/plugins/plugin_admin_ui.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
docs/media/plugins/plugin_rest_api_endpoint.png
Normal file
BIN
docs/media/plugins/plugin_rest_api_endpoint.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
392
docs/plugins/development.md
Normal file
392
docs/plugins/development.md
Normal file
@@ -0,0 +1,392 @@
|
||||
# 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='An example NetBox plugin',
|
||||
url='https://github.com/netbox-community/netbox-animal-sounds',
|
||||
author='Jeremy Stretch',
|
||||
license='Apache 2.0',
|
||||
install_requires=[],
|
||||
packages=find_packages(),
|
||||
include_package_data=True,
|
||||
)
|
||||
```
|
||||
|
||||
Many of these are self-explanatory, but for more information, see the [setuptools documentation](https://setuptools.readthedocs.io/en/latest/setuptools.html).
|
||||
|
||||
### 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'
|
||||
description = 'An example plugin for development purposes'
|
||||
version = '0.1'
|
||||
author = 'Jeremy Stretch'
|
||||
author_email = 'author@example.com'
|
||||
base_url = 'animal-sounds'
|
||||
required_settings = []
|
||||
default_settings = {
|
||||
'loud': False
|
||||
}
|
||||
|
||||
config = AnimalSoundsConfig
|
||||
```
|
||||
|
||||
NetBox looks for the `config` variable within a plugin's `__init__.py` to load its configuration. Typically, this will be set to the PluginConfig subclass, but you may wish to dynamically generate a PluginConfig class based on environment variables or other factors.
|
||||
|
||||
#### 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 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 using Django's `admin.register()` function. An example `admin.py` file for the above model is shown below:
|
||||
|
||||
```python
|
||||
from django.contrib import admin
|
||||
from .models import Animal
|
||||
|
||||
@admin.register(Animal)
|
||||
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.
|
||||
|
||||

|
||||
|
||||
## 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 RandomAnimalView(View):
|
||||
"""
|
||||
Display a randomly-selected animal.
|
||||
"""
|
||||
def get(self, request):
|
||||
animal = Animal.objects.order_by('?').first()
|
||||
return render(request, 'netbox_animal_sounds/animal.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.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.html`:
|
||||
|
||||
```jinja2
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block content %}
|
||||
{% with config=settings.PLUGINS_CONFIG.netbox_animal_sounds %}
|
||||
<h2 class="text-center" style="margin-top: 200px">
|
||||
{% if animal %}
|
||||
The {{ animal.name|lower }} says
|
||||
{% if config.loud %}
|
||||
{{ animal.sound|upper }}!
|
||||
{% else %}
|
||||
{{ animal.sound }}
|
||||
{% endif %}
|
||||
{% else %}
|
||||
No animals have been created yet!
|
||||
{% endif %}
|
||||
</h2>
|
||||
{% endwith %}
|
||||
{% 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 . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('random/', views.RandomAnimalView.as_view(), name='random_animal'),
|
||||
]
|
||||
```
|
||||
|
||||
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/`. (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 view set 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.
|
||||
|
||||

|
||||
|
||||
!!! warning
|
||||
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_animal',
|
||||
link_text='Random sound',
|
||||
buttons=(
|
||||
PluginMenuButton('home', 'Button A', 'fa fa-info', ButtonColorChoices.BLUE),
|
||||
PluginMenuButton('home', 'Button B', 'fa 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 (NetBox currently supports [Font Awesome 4.7](https://fontawesome.com/v4.7.0/icons/))
|
||||
* `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
|
||||
from .models import Animal
|
||||
|
||||
class SiteAnimalCount(PluginTemplateExtension):
|
||||
model = 'dcim.site'
|
||||
|
||||
def right_page(self):
|
||||
return self.render('netbox_animal_sounds/inc/animal_count.html', extra_context={
|
||||
'animal_count': Animal.objects.count(),
|
||||
})
|
||||
|
||||
template_extensions = [SiteAnimalCount]
|
||||
```
|
||||
|
||||
## 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. All configuration keys will be applied within the context of the plugin; there is no need to include the plugin name. An example configuration is below:
|
||||
|
||||
```python
|
||||
class MyPluginConfig(PluginConfig):
|
||||
...
|
||||
caching_config = {
|
||||
'foo': {
|
||||
'ops': 'get',
|
||||
'timeout': 60 * 15,
|
||||
},
|
||||
'*': {
|
||||
'ops': 'all',
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
To disable caching for your plugin entirely, set:
|
||||
|
||||
```python
|
||||
caching_config = {
|
||||
'*': None
|
||||
}
|
||||
```
|
||||
|
||||
See the [django-cacheops](https://github.com/Suor/django-cacheops) documentation for more detail on configuring caching.
|
||||
82
docs/plugins/index.md
Normal file
82
docs/plugins/index.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# 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 the Plugin
|
||||
|
||||
In `configuration.py`, add the plugin's name to the `PLUGINS` list:
|
||||
|
||||
```python
|
||||
PLUGINS = [
|
||||
'plugin_name',
|
||||
]
|
||||
```
|
||||
|
||||
### 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'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Collect Static Files
|
||||
|
||||
Plugins may package static files to be served directly by the HTTP front end. Ensure that these are copied to the static root directory with the `collectstatic` management command:
|
||||
|
||||
```no-highlight
|
||||
(venv) $ cd /opt/netbox/netbox/
|
||||
(venv) $ python3 manage.py collectstatic
|
||||
```
|
||||
|
||||
### Restart WSGI Service
|
||||
|
||||
Restart the WSGI service to load the new plugin:
|
||||
|
||||
```no-highlight
|
||||
# sudo systemctl restart netbox
|
||||
```
|
||||
@@ -1,5 +1,50 @@
|
||||
# NetBox v2.7 Release Notes
|
||||
|
||||
## v2.7.12 (2020-04-08)
|
||||
|
||||
### Enhancements
|
||||
|
||||
* [#3676](https://github.com/netbox-community/netbox/issues/3676) - Reference VRF by name rather than RD during IP/prefix import
|
||||
* [#4147](https://github.com/netbox-community/netbox/issues/4147) - Use absolute URLs in rack elevation SVG renderings
|
||||
* [#4448](https://github.com/netbox-community/netbox/issues/4448) - Allow connecting cables between two circuit terminations
|
||||
* [#4460](https://github.com/netbox-community/netbox/issues/4460) - Add the `webhook_receiver` management command to assist in troubleshooting outgoing webhooks
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#4395](https://github.com/netbox-community/netbox/issues/4395) - Fix typing of count_ipaddresses on interface serializer
|
||||
* [#4418](https://github.com/netbox-community/netbox/issues/4418) - Fail cleanly when trying to import multiple device types simultaneously
|
||||
* [#4438](https://github.com/netbox-community/netbox/issues/4438) - Fix exception when disconnecting a cable from a power feed
|
||||
* [#4439](https://github.com/netbox-community/netbox/issues/4439) - Tweak display of unset custom integer fields
|
||||
* [#4449](https://github.com/netbox-community/netbox/issues/4449) - Fix reservation edit/delete button URLs on rack view
|
||||
|
||||
---
|
||||
|
||||
## v2.7.11 (2020-03-27)
|
||||
|
||||
### Enhancements
|
||||
|
||||
* [#738](https://github.com/netbox-community/netbox/issues/738) - Add ability to automatically check for new releases (must be enabled by setting `RELEASE_CHECK_URL`)
|
||||
* [#4255](https://github.com/netbox-community/netbox/issues/4255) - Custom script object variables now utilize dynamic form widgets
|
||||
* [#4309](https://github.com/netbox-community/netbox/issues/4309) - Add descriptive tooltip to custom fields on object views
|
||||
* [#4369](https://github.com/netbox-community/netbox/issues/4369) - Add a dedicated view for rack reservations
|
||||
* [#4380](https://github.com/netbox-community/netbox/issues/4380) - Enable webhooks for rack reservations
|
||||
* [#4381](https://github.com/netbox-community/netbox/issues/4381) - Enable export templates for rack reservations
|
||||
* [#4382](https://github.com/netbox-community/netbox/issues/4382) - Enable custom links for rack reservations
|
||||
* [#4386](https://github.com/netbox-community/netbox/issues/4386) - Update admin links for Django RQ to reflect multiple queues
|
||||
* [#4389](https://github.com/netbox-community/netbox/issues/4389) - Add a bulk edit view for device bays
|
||||
* [#4404](https://github.com/netbox-community/netbox/issues/4404) - Add cable trace button for circuit terminations
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#2769](https://github.com/netbox-community/netbox/issues/2769) - Improve `prefix_length` validation on available-prefixes API
|
||||
* [#3193](https://github.com/netbox-community/netbox/issues/3193) - Fix cable tracing across multiple rear ports
|
||||
* [#4340](https://github.com/netbox-community/netbox/issues/4340) - Enforce unique constraints for device and virtual machine names in the API
|
||||
* [#4343](https://github.com/netbox-community/netbox/issues/4343) - Fix Markdown support for tables
|
||||
* [#4365](https://github.com/netbox-community/netbox/issues/4365) - Fix exception raised on IP address bulk add view
|
||||
* [#4415](https://github.com/netbox-community/netbox/issues/4415) - Fix duplicate name validation on device model
|
||||
|
||||
---
|
||||
|
||||
## v2.7.10 (2020-03-10)
|
||||
|
||||
**Note:** If your deployment requires any non-core Python packages (such as `napalm`, `django-storages`, or `django-auth-ldap`), list them in a file named `local_requirements.txt` in the NetBox root directory (alongside `requirements.txt`). This will ensure they are detected and re-installed by the upgrade script when the Python virtual environment is rebuilt.
|
||||
|
||||
63
docs/release-notes/version-2.8.md
Normal file
63
docs/release-notes/version-2.8.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# NetBox v2.8
|
||||
|
||||
## v2.8.0 (2020-04-13)
|
||||
|
||||
### New Features (Beta)
|
||||
|
||||
This releases introduces two new features in beta status. While they are expected to be functional, their precise implementation is subject to change during the v2.8 release cycle. It is recommended to wait until NetBox v2.9 to deploy them in production.
|
||||
|
||||
#### Remote Authentication Support ([#2328](https://github.com/netbox-community/netbox/issues/2328))
|
||||
|
||||
Several new configuration parameters provide support for authenticating an incoming request based on the value of a specific HTTP header. This can be leveraged to employ remote authentication via an nginx or Apache plugin, directing NetBox to create and configure a local user account as needed. The configuration parameters are:
|
||||
|
||||
* `REMOTE_AUTH_ENABLED` - Enables remote authentication (disabled by default)
|
||||
* `REMOTE_AUTH_HEADER` - The name of the HTTP header which conveys the username
|
||||
* `REMOTE_AUTH_AUTO_CREATE_USER` - Enables the automatic creation of new users (disabled by default)
|
||||
* `REMOTE_AUTH_DEFAULT_GROUPS` - A list of groups to assign newly created users
|
||||
* `REMOTE_AUTH_DEFAULT_PERMISSIONS` - A list of permissions to assign newly created users
|
||||
|
||||
If further customization of remote authentication is desired (for instance, if you want to pass group/permission information via HTTP headers as well), NetBox allows you to inject a custom [Django authentication backend](https://docs.djangoproject.com/en/stable/topics/auth/customizing/) to retain full control over the authentication and configuration of remote users.
|
||||
|
||||
#### Plugins ([#3351](https://github.com/netbox-community/netbox/issues/3351))
|
||||
|
||||
This release introduces support for custom plugins, which can be used to extend NetBox's functionality beyond what the core product provides. For example, plugins can be used to:
|
||||
|
||||
* Add new Django models
|
||||
* Provide new views with custom templates
|
||||
* Inject custom template into object views
|
||||
* Introduce new API endpoints
|
||||
* Add custom request/response middleware
|
||||
|
||||
For NetBox plugins to be recognized, they must be installed and added by name to the `PLUGINS` configuration parameter. (Plugin support is disabled by default.) Plugins can be configured under the `PLUGINS_CONFIG` parameter. More information can be found the in the [plugins documentation](https://netbox.readthedocs.io/en/stable/plugins/).
|
||||
|
||||
### Enhancements
|
||||
|
||||
* [#1754](https://github.com/netbox-community/netbox/issues/1754) - Added support for nested rack groups
|
||||
* [#3939](https://github.com/netbox-community/netbox/issues/3939) - Added support for nested tenant groups
|
||||
* [#4078](https://github.com/netbox-community/netbox/issues/4078) - Standardized description fields across all models
|
||||
* [#4195](https://github.com/netbox-community/netbox/issues/4195) - Enabled application logging (see [logging configuration](../configuration/optional-settings.md#logging))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#4474](https://github.com/netbox-community/netbox/issues/4474) - Fix population of device types when bulk editing devices
|
||||
* [#4476](https://github.com/netbox-community/netbox/issues/4476) - Correct typo in slugs for Infiniband interface types
|
||||
|
||||
### API Changes
|
||||
|
||||
* The `_choices` API endpoints have been removed. Instead, use an `OPTIONS` request to a model's endpoint to view the available values for all fields. ([#3416](https://github.com/netbox-community/netbox/issues/3416))
|
||||
* The `id__in` filter has been removed from all models ([#4313](https://github.com/netbox-community/netbox/issues/4313)). Use the format `?id=1&id=2` instead.
|
||||
* dcim.Manufacturer: Added a `description` field
|
||||
* dcim.Platform: Added a `description` field
|
||||
* dcim.Rack: The `/api/dcim/racks/<pk>/units/` endpoint has been replaced with `/api/dcim/racks/<pk>/elevation/`.
|
||||
* dcim.RackGroup: Added a `description` field
|
||||
* dcim.Region: Added a `description` field
|
||||
* extras.Tag: Renamed `comments` to `description`; truncated length to 200 characters; removed Markdown rendering
|
||||
* ipam.RIR: Added a `description` field
|
||||
* ipam.VLANGroup: Added a `description` field
|
||||
* tenancy.TenantGroup: Added a `description` field
|
||||
* virtualization.ClusterGroup: Added a `description` field
|
||||
* virtualization.ClusterType: Added a `description` field
|
||||
|
||||
### Other Changes
|
||||
|
||||
* [#4081](https://github.com/netbox-community/netbox/issues/4081) - The `family` field has been removed from the Aggregate, Prefix, and IPAddress models. The field remains available in the API representations of these models, however the column has been removed from the database table.
|
||||
@@ -7,11 +7,12 @@ python:
|
||||
theme:
|
||||
name: readthedocs
|
||||
navigation_depth: 3
|
||||
extra_css:
|
||||
- extra.css
|
||||
markdown_extensions:
|
||||
- admonition:
|
||||
- markdown_include.include:
|
||||
headingOffset: 1
|
||||
|
||||
nav:
|
||||
- Introduction: 'index.md'
|
||||
- Installation:
|
||||
@@ -53,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'
|
||||
@@ -67,9 +71,11 @@ nav:
|
||||
- Style Guide: 'development/style-guide.md'
|
||||
- Utility Views: 'development/utility-views.md'
|
||||
- Extending Models: 'development/extending-models.md'
|
||||
- Application Registry: 'development/application-registry.md'
|
||||
- Release Checklist: 'development/release-checklist.md'
|
||||
- Squashing Migrations: 'development/squashing-migrations.md'
|
||||
- Release Notes:
|
||||
- Version 2.8: 'release-notes/version-2.8.md'
|
||||
- Version 2.7: 'release-notes/version-2.7.md'
|
||||
- Version 2.6: 'release-notes/version-2.6.md'
|
||||
- Version 2.5: 'release-notes/version-2.5.md'
|
||||
|
||||
@@ -14,9 +14,6 @@ class CircuitsRootView(routers.APIRootView):
|
||||
router = routers.DefaultRouter()
|
||||
router.APIRootView = CircuitsRootView
|
||||
|
||||
# Field choices
|
||||
router.register('_choices', views.CircuitsFieldChoicesViewSet, basename='field-choice')
|
||||
|
||||
# Providers
|
||||
router.register('providers', views.ProviderViewSet)
|
||||
|
||||
|
||||
@@ -8,21 +8,10 @@ from circuits.models import Provider, CircuitTermination, CircuitType, Circuit
|
||||
from extras.api.serializers import RenderedGraphSerializer
|
||||
from extras.api.views import CustomFieldModelViewSet
|
||||
from extras.models import Graph
|
||||
from utilities.api import FieldChoicesViewSet, ModelViewSet
|
||||
from utilities.api import ModelViewSet
|
||||
from . import serializers
|
||||
|
||||
|
||||
#
|
||||
# Field choices
|
||||
#
|
||||
|
||||
class CircuitsFieldChoicesViewSet(FieldChoicesViewSet):
|
||||
fields = (
|
||||
(serializers.CircuitSerializer, ['status']),
|
||||
(serializers.CircuitTerminationSerializer, ['term_side']),
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Providers
|
||||
#
|
||||
|
||||
@@ -5,7 +5,7 @@ from dcim.models import Region, Site
|
||||
from extras.filters import CustomFieldFilterSet, CreatedUpdatedFilterSet
|
||||
from tenancy.filters import TenancyFilterSet
|
||||
from utilities.filters import (
|
||||
BaseFilterSet, NameSlugSearchFilterSet, NumericInFilter, TagFilter, TreeNodeMultipleChoiceFilter
|
||||
BaseFilterSet, NameSlugSearchFilterSet, TagFilter, TreeNodeMultipleChoiceFilter
|
||||
)
|
||||
from .choices import *
|
||||
from .models import Circuit, CircuitTermination, CircuitType, Provider
|
||||
@@ -19,10 +19,6 @@ __all__ = (
|
||||
|
||||
|
||||
class ProviderFilterSet(BaseFilterSet, CustomFieldFilterSet, CreatedUpdatedFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -77,10 +73,6 @@ class CircuitTypeFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
|
||||
|
||||
class CircuitFilterSet(BaseFilterSet, CustomFieldFilterSet, TenancyFilterSet, CreatedUpdatedFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
|
||||
@@ -113,7 +113,6 @@ class ProviderFilterForm(BootstrapMixin, CustomFieldFilterForm):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/regions/",
|
||||
value_field="slug",
|
||||
filter_for={
|
||||
'site': 'region'
|
||||
@@ -125,7 +124,6 @@ class ProviderFilterForm(BootstrapMixin, CustomFieldFilterForm):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/sites/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -167,16 +165,10 @@ class CircuitTypeCSVForm(forms.ModelForm):
|
||||
|
||||
class CircuitForm(BootstrapMixin, TenancyForm, CustomFieldModelForm):
|
||||
provider = DynamicModelChoiceField(
|
||||
queryset=Provider.objects.all(),
|
||||
widget=APISelect(
|
||||
api_url="/api/circuits/providers/"
|
||||
)
|
||||
queryset=Provider.objects.all()
|
||||
)
|
||||
type = DynamicModelChoiceField(
|
||||
queryset=CircuitType.objects.all(),
|
||||
widget=APISelect(
|
||||
api_url="/api/circuits/circuit-types/"
|
||||
)
|
||||
queryset=CircuitType.objects.all()
|
||||
)
|
||||
comments = CommentField()
|
||||
tags = TagField(
|
||||
@@ -245,17 +237,11 @@ class CircuitBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEdit
|
||||
)
|
||||
type = DynamicModelChoiceField(
|
||||
queryset=CircuitType.objects.all(),
|
||||
required=False,
|
||||
widget=APISelect(
|
||||
api_url="/api/circuits/circuit-types/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
provider = DynamicModelChoiceField(
|
||||
queryset=Provider.objects.all(),
|
||||
required=False,
|
||||
widget=APISelect(
|
||||
api_url="/api/circuits/providers/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
status = forms.ChoiceField(
|
||||
choices=add_blank_choice(CircuitStatusChoices),
|
||||
@@ -265,10 +251,7 @@ class CircuitBulkEditForm(BootstrapMixin, AddRemoveTagsForm, CustomFieldBulkEdit
|
||||
)
|
||||
tenant = DynamicModelChoiceField(
|
||||
queryset=Tenant.objects.all(),
|
||||
required=False,
|
||||
widget=APISelect(
|
||||
api_url="/api/tenancy/tenants/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
commit_rate = forms.IntegerField(
|
||||
required=False,
|
||||
@@ -303,7 +286,6 @@ class CircuitFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/circuits/circuit-types/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -312,7 +294,6 @@ class CircuitFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/circuits/providers/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -326,7 +307,6 @@ class CircuitFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/regions/",
|
||||
value_field="slug",
|
||||
filter_for={
|
||||
'site': 'region'
|
||||
@@ -338,7 +318,6 @@ class CircuitFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/sites/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -355,6 +334,9 @@ class CircuitFilterForm(BootstrapMixin, TenancyFilterForm, CustomFieldFilterForm
|
||||
#
|
||||
|
||||
class CircuitTerminationForm(BootstrapMixin, forms.ModelForm):
|
||||
site = DynamicModelChoiceField(
|
||||
queryset=Site.objects.all()
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = CircuitTermination
|
||||
@@ -368,7 +350,4 @@ class CircuitTerminationForm(BootstrapMixin, forms.ModelForm):
|
||||
}
|
||||
widgets = {
|
||||
'term_side': forms.HiddenInput(),
|
||||
'site': APISelect(
|
||||
api_url="/api/dcim/sites/"
|
||||
)
|
||||
}
|
||||
|
||||
28
netbox/circuits/migrations/0008_standardize_description.py
Normal file
28
netbox/circuits/migrations/0008_standardize_description.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 3.0.3 on 2020-03-13 20:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('circuits', '0007_circuit_add_description_squashed_0017_circuittype_description'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='circuit',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='circuittermination',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='circuittype',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
]
|
||||
@@ -7,6 +7,7 @@ from dcim.constants import CONNECTION_STATUS_CHOICES
|
||||
from dcim.fields import ASNField
|
||||
from dcim.models import CableTermination
|
||||
from extras.models import CustomFieldModel, ObjectChange, TaggedItem
|
||||
from extras.utils import extras_features
|
||||
from utilities.models import ChangeLoggedModel
|
||||
from utilities.utils import serialize_object
|
||||
from .choices import *
|
||||
@@ -21,6 +22,7 @@ __all__ = (
|
||||
)
|
||||
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'graphs', 'export_templates', 'webhooks')
|
||||
class Provider(ChangeLoggedModel, CustomFieldModel):
|
||||
"""
|
||||
Each Circuit belongs to a Provider. This is usually a telecommunications company or similar organization. This model
|
||||
@@ -108,7 +110,7 @@ class CircuitType(ChangeLoggedModel):
|
||||
unique=True
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True,
|
||||
)
|
||||
|
||||
@@ -131,6 +133,7 @@ class CircuitType(ChangeLoggedModel):
|
||||
)
|
||||
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
|
||||
class Circuit(ChangeLoggedModel, CustomFieldModel):
|
||||
"""
|
||||
A communications circuit connects two points. Each Circuit belongs to a Provider; Providers may have multiple
|
||||
@@ -173,7 +176,7 @@ class Circuit(ChangeLoggedModel, CustomFieldModel):
|
||||
null=True,
|
||||
verbose_name='Commit rate (Kbps)')
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
comments = models.TextField(
|
||||
@@ -292,7 +295,7 @@ class CircuitTermination(CableTermination):
|
||||
verbose_name='Patch panel/port(s)'
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from circuits.choices import *
|
||||
from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
|
||||
from dcim.models import Site
|
||||
from extras.models import Graph
|
||||
from utilities.testing import APITestCase, choices_to_dict
|
||||
from utilities.testing import APITestCase
|
||||
|
||||
|
||||
class AppTest(APITestCase):
|
||||
@@ -18,19 +18,6 @@ class AppTest(APITestCase):
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_choices(self):
|
||||
|
||||
url = reverse('circuits-api:field-choice-list')
|
||||
response = self.client.get(url, **self.header)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Circuit
|
||||
self.assertEqual(choices_to_dict(response.data.get('circuit:status')), CircuitStatusChoices.as_dict())
|
||||
|
||||
# CircuitTermination
|
||||
self.assertEqual(choices_to_dict(response.data.get('circuit-termination:term_side')), CircuitTerminationSideChoices.as_dict())
|
||||
|
||||
|
||||
class ProviderTest(APITestCase):
|
||||
|
||||
|
||||
@@ -70,11 +70,6 @@ class ProviderTestCase(TestCase):
|
||||
params = {'account': ['1234', '2345']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:3]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
|
||||
|
||||
def test_site(self):
|
||||
sites = Site.objects.all()[:2]
|
||||
params = {'site_id': [sites[0].pk, sites[1].pk]}
|
||||
@@ -144,7 +139,8 @@ class CircuitTestCase(TestCase):
|
||||
TenantGroup(name='Tenant group 2', slug='tenant-group-2'),
|
||||
TenantGroup(name='Tenant group 3', slug='tenant-group-3'),
|
||||
)
|
||||
TenantGroup.objects.bulk_create(tenant_groups)
|
||||
for tenantgroup in tenant_groups:
|
||||
tenantgroup.save()
|
||||
|
||||
tenants = (
|
||||
Tenant(name='Tenant 1', slug='tenant-1', group=tenant_groups[0]),
|
||||
@@ -194,11 +190,6 @@ class CircuitTestCase(TestCase):
|
||||
params = {'commit_rate': ['1000', '2000']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:3]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
|
||||
|
||||
def test_provider(self):
|
||||
provider = Provider.objects.first()
|
||||
params = {'provider_id': [provider.pk]}
|
||||
|
||||
@@ -64,7 +64,7 @@ class RegionSerializer(serializers.ModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = Region
|
||||
fields = ['id', 'name', 'slug', 'parent', 'site_count']
|
||||
fields = ['id', 'name', 'slug', 'parent', 'description', 'site_count']
|
||||
|
||||
|
||||
class SiteSerializer(TaggitSerializer, CustomFieldModelSerializer):
|
||||
@@ -96,11 +96,12 @@ class SiteSerializer(TaggitSerializer, CustomFieldModelSerializer):
|
||||
|
||||
class RackGroupSerializer(ValidatedModelSerializer):
|
||||
site = NestedSiteSerializer()
|
||||
parent = NestedRackGroupSerializer(required=False, allow_null=True)
|
||||
rack_count = serializers.IntegerField(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = RackGroup
|
||||
fields = ['id', 'name', 'slug', 'site', 'rack_count']
|
||||
fields = ['id', 'name', 'slug', 'site', 'parent', 'description', 'rack_count']
|
||||
|
||||
|
||||
class RackRoleSerializer(ValidatedModelSerializer):
|
||||
@@ -218,7 +219,9 @@ class ManufacturerSerializer(ValidatedModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = Manufacturer
|
||||
fields = ['id', 'name', 'slug', 'devicetype_count', 'inventoryitem_count', 'platform_count']
|
||||
fields = [
|
||||
'id', 'name', 'slug', 'description', 'devicetype_count', 'inventoryitem_count', 'platform_count',
|
||||
]
|
||||
|
||||
|
||||
class DeviceTypeSerializer(TaggitSerializer, CustomFieldModelSerializer):
|
||||
@@ -355,7 +358,7 @@ class PlatformSerializer(ValidatedModelSerializer):
|
||||
class Meta:
|
||||
model = Platform
|
||||
fields = [
|
||||
'id', 'name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args', 'device_count',
|
||||
'id', 'name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args', 'description', 'device_count',
|
||||
'virtualmachine_count',
|
||||
]
|
||||
|
||||
@@ -530,6 +533,7 @@ class InterfaceSerializer(TaggitSerializer, ConnectedEndpointSerializer):
|
||||
)
|
||||
cable = NestedCableSerializer(read_only=True)
|
||||
tags = TagListSerializerField(required=False)
|
||||
count_ipaddresses = serializers.IntegerField(read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Interface
|
||||
|
||||
@@ -14,9 +14,6 @@ class DCIMRootView(routers.APIRootView):
|
||||
router = routers.DefaultRouter()
|
||||
router.APIRootView = DCIMRootView
|
||||
|
||||
# Field choices
|
||||
router.register('_choices', views.DCIMFieldChoicesViewSet, basename='field-choice')
|
||||
|
||||
# Sites
|
||||
router.register('regions', views.RegionViewSet)
|
||||
router.register('sites', views.SiteViewSet)
|
||||
|
||||
@@ -26,7 +26,7 @@ from extras.api.views import CustomFieldModelViewSet
|
||||
from extras.models import Graph
|
||||
from ipam.models import Prefix, VLAN
|
||||
from utilities.api import (
|
||||
get_serializer_for_model, IsAuthenticatedOrLoginNotRequired, FieldChoicesViewSet, ModelViewSet, ServiceUnavailable,
|
||||
get_serializer_for_model, IsAuthenticatedOrLoginNotRequired, ModelViewSet, ServiceUnavailable,
|
||||
)
|
||||
from utilities.utils import get_subquery
|
||||
from virtualization.models import VirtualMachine
|
||||
@@ -34,35 +34,6 @@ from . import serializers
|
||||
from .exceptions import MissingFilterException
|
||||
|
||||
|
||||
#
|
||||
# Field choices
|
||||
#
|
||||
|
||||
class DCIMFieldChoicesViewSet(FieldChoicesViewSet):
|
||||
fields = (
|
||||
(serializers.CableSerializer, ['length_unit', 'status', 'termination_a_type', 'termination_b_type', 'type']),
|
||||
(serializers.ConsolePortSerializer, ['type', 'connection_status']),
|
||||
(serializers.ConsolePortTemplateSerializer, ['type']),
|
||||
(serializers.ConsoleServerPortSerializer, ['type']),
|
||||
(serializers.ConsoleServerPortTemplateSerializer, ['type']),
|
||||
(serializers.DeviceSerializer, ['face', 'status']),
|
||||
(serializers.DeviceTypeSerializer, ['subdevice_role']),
|
||||
(serializers.FrontPortSerializer, ['type']),
|
||||
(serializers.FrontPortTemplateSerializer, ['type']),
|
||||
(serializers.InterfaceSerializer, ['type', 'mode']),
|
||||
(serializers.InterfaceTemplateSerializer, ['type']),
|
||||
(serializers.PowerFeedSerializer, ['phase', 'status', 'supply', 'type']),
|
||||
(serializers.PowerOutletSerializer, ['type', 'feed_leg']),
|
||||
(serializers.PowerOutletTemplateSerializer, ['type', 'feed_leg']),
|
||||
(serializers.PowerPortSerializer, ['type', 'connection_status']),
|
||||
(serializers.PowerPortTemplateSerializer, ['type']),
|
||||
(serializers.RackSerializer, ['outer_unit', 'status', 'type', 'width']),
|
||||
(serializers.RearPortSerializer, ['type']),
|
||||
(serializers.RearPortTemplateSerializer, ['type']),
|
||||
(serializers.SiteSerializer, ['status']),
|
||||
)
|
||||
|
||||
|
||||
# Mixins
|
||||
|
||||
class CableTraceMixin(object):
|
||||
@@ -77,7 +48,7 @@ class CableTraceMixin(object):
|
||||
# Initialize the path array
|
||||
path = []
|
||||
|
||||
for near_end, cable, far_end in obj.trace(follow_circuits=True):
|
||||
for near_end, cable, far_end in obj.trace():
|
||||
|
||||
# Serialize each object
|
||||
serializer_a = get_serializer_for_model(near_end, prefix='Nested')
|
||||
@@ -176,33 +147,6 @@ class RackViewSet(CustomFieldModelViewSet):
|
||||
serializer_class = serializers.RackSerializer
|
||||
filterset_class = filters.RackFilterSet
|
||||
|
||||
@swagger_auto_schema(deprecated=True)
|
||||
@action(detail=True)
|
||||
def units(self, request, pk=None):
|
||||
"""
|
||||
List rack units (by rack)
|
||||
"""
|
||||
# TODO: Remove this action detail route in v2.8
|
||||
rack = get_object_or_404(Rack, pk=pk)
|
||||
face = request.GET.get('face', 'front')
|
||||
exclude_pk = request.GET.get('exclude', None)
|
||||
if exclude_pk is not None:
|
||||
try:
|
||||
exclude_pk = int(exclude_pk)
|
||||
except ValueError:
|
||||
exclude_pk = None
|
||||
elevation = rack.get_rack_units(face, exclude_pk)
|
||||
|
||||
# Enable filtering rack units by ID
|
||||
q = request.GET.get('q', None)
|
||||
if q:
|
||||
elevation = [u for u in elevation if q in str(u['id'])]
|
||||
|
||||
page = self.paginate_queryset(elevation)
|
||||
if page is not None:
|
||||
rack_units = serializers.RackUnitSerializer(page, many=True, context={'request': request})
|
||||
return self.get_paginated_response(rack_units.data)
|
||||
|
||||
@swagger_auto_schema(
|
||||
responses={200: serializers.RackUnitSerializer(many=True)},
|
||||
query_serializer=serializers.RackElevationDetailFilterSerializer
|
||||
@@ -225,7 +169,8 @@ class RackViewSet(CustomFieldModelViewSet):
|
||||
unit_width=data['unit_width'],
|
||||
unit_height=data['unit_height'],
|
||||
legend_width=data['legend_width'],
|
||||
include_images=data['include_images']
|
||||
include_images=data['include_images'],
|
||||
base_url=request.build_absolute_uri('/')
|
||||
)
|
||||
return HttpResponse(drawing.tostring(), content_type='image/svg+xml')
|
||||
|
||||
|
||||
@@ -575,15 +575,15 @@ class InterfaceTypeChoices(ChoiceSet):
|
||||
TYPE_128GFC_QSFP28 = '128gfc-sfp28'
|
||||
|
||||
# InfiniBand
|
||||
TYPE_INFINIBAND_SDR = 'inifiband-sdr'
|
||||
TYPE_INFINIBAND_DDR = 'inifiband-ddr'
|
||||
TYPE_INFINIBAND_QDR = 'inifiband-qdr'
|
||||
TYPE_INFINIBAND_FDR10 = 'inifiband-fdr10'
|
||||
TYPE_INFINIBAND_FDR = 'inifiband-fdr'
|
||||
TYPE_INFINIBAND_EDR = 'inifiband-edr'
|
||||
TYPE_INFINIBAND_HDR = 'inifiband-hdr'
|
||||
TYPE_INFINIBAND_NDR = 'inifiband-ndr'
|
||||
TYPE_INFINIBAND_XDR = 'inifiband-xdr'
|
||||
TYPE_INFINIBAND_SDR = 'infiniband-sdr'
|
||||
TYPE_INFINIBAND_DDR = 'infiniband-ddr'
|
||||
TYPE_INFINIBAND_QDR = 'infiniband-qdr'
|
||||
TYPE_INFINIBAND_FDR10 = 'infiniband-fdr10'
|
||||
TYPE_INFINIBAND_FDR = 'infiniband-fdr'
|
||||
TYPE_INFINIBAND_EDR = 'infiniband-edr'
|
||||
TYPE_INFINIBAND_HDR = 'infiniband-hdr'
|
||||
TYPE_INFINIBAND_NDR = 'infiniband-ndr'
|
||||
TYPE_INFINIBAND_XDR = 'infiniband-xdr'
|
||||
|
||||
# Serial
|
||||
TYPE_T1 = 't1'
|
||||
|
||||
@@ -92,5 +92,5 @@ COMPATIBLE_TERMINATION_TYPES = {
|
||||
'interface': ['interface', 'circuittermination', 'frontport', 'rearport'],
|
||||
'frontport': ['consoleport', 'consoleserverport', 'interface', 'frontport', 'rearport', 'circuittermination'],
|
||||
'rearport': ['consoleport', 'consoleserverport', 'interface', 'frontport', 'rearport', 'circuittermination'],
|
||||
'circuittermination': ['interface', 'frontport', 'rearport'],
|
||||
'circuittermination': ['interface', 'frontport', 'rearport', 'circuittermination'],
|
||||
}
|
||||
|
||||
@@ -15,10 +15,15 @@ class RackElevationSVG:
|
||||
|
||||
:param rack: A NetBox Rack instance
|
||||
:param include_images: If true, the SVG document will embed front/rear device face images, where available
|
||||
:param base_url: Base URL for links within the SVG document. If none, links will be relative.
|
||||
"""
|
||||
def __init__(self, rack, include_images=True):
|
||||
def __init__(self, rack, include_images=True, base_url=None):
|
||||
self.rack = rack
|
||||
self.include_images = include_images
|
||||
if base_url is not None:
|
||||
self.base_url = base_url.rstrip('/')
|
||||
else:
|
||||
self.base_url = ''
|
||||
|
||||
def _get_device_description(self, device):
|
||||
return '{} ({}) — {} ({}U) {} {}'.format(
|
||||
@@ -69,7 +74,7 @@ class RackElevationSVG:
|
||||
color = device.device_role.color
|
||||
link = drawing.add(
|
||||
drawing.a(
|
||||
href=reverse('dcim:device', kwargs={'pk': device.pk}),
|
||||
href='{}{}'.format(self.base_url, reverse('dcim:device', kwargs={'pk': device.pk})),
|
||||
target='_top',
|
||||
fill='black'
|
||||
)
|
||||
@@ -81,7 +86,7 @@ class RackElevationSVG:
|
||||
|
||||
# Embed front device type image if one exists
|
||||
if self.include_images and device.device_type.front_image:
|
||||
url = device.device_type.front_image.url
|
||||
url = '{}{}'.format(self.base_url, device.device_type.front_image.url)
|
||||
image = drawing.image(href=url, insert=start, size=end, class_='device-image')
|
||||
image.fit(scale='slice')
|
||||
link.add(image)
|
||||
|
||||
@@ -7,7 +7,7 @@ from tenancy.models import Tenant
|
||||
from utilities.constants import COLOR_CHOICES
|
||||
from utilities.filters import (
|
||||
BaseFilterSet, MultiValueCharFilter, MultiValueMACAddressFilter, MultiValueNumberFilter,
|
||||
NameSlugSearchFilterSet, NumericInFilter, TagFilter, TreeNodeMultipleChoiceFilter,
|
||||
NameSlugSearchFilterSet, TagFilter, TreeNodeMultipleChoiceFilter,
|
||||
)
|
||||
from virtualization.models import Cluster
|
||||
from .choices import *
|
||||
@@ -74,14 +74,10 @@ class RegionFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
|
||||
class Meta:
|
||||
model = Region
|
||||
fields = ['id', 'name', 'slug']
|
||||
fields = ['id', 'name', 'slug', 'description']
|
||||
|
||||
|
||||
class SiteFilterSet(BaseFilterSet, TenancyFilterSet, CustomFieldFilterSet, CreatedUpdatedFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -157,10 +153,20 @@ class RackGroupFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
to_field_name='slug',
|
||||
label='Site (slug)',
|
||||
)
|
||||
parent_id = django_filters.ModelMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
label='Rack group (ID)',
|
||||
)
|
||||
parent = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name='parent__slug',
|
||||
queryset=RackGroup.objects.all(),
|
||||
to_field_name='slug',
|
||||
label='Rack group (slug)',
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = RackGroup
|
||||
fields = ['id', 'name', 'slug']
|
||||
fields = ['id', 'name', 'slug', 'description']
|
||||
|
||||
|
||||
class RackRoleFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
@@ -171,10 +177,6 @@ class RackRoleFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
|
||||
|
||||
class RackFilterSet(BaseFilterSet, TenancyFilterSet, CustomFieldFilterSet, CreatedUpdatedFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -202,15 +204,18 @@ class RackFilterSet(BaseFilterSet, TenancyFilterSet, CustomFieldFilterSet, Creat
|
||||
to_field_name='slug',
|
||||
label='Site (slug)',
|
||||
)
|
||||
group_id = django_filters.ModelMultipleChoiceFilter(
|
||||
group_id = TreeNodeMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
label='Group (ID)',
|
||||
field_name='group',
|
||||
lookup_expr='in',
|
||||
label='Rack group (ID)',
|
||||
)
|
||||
group = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name='group__slug',
|
||||
group = TreeNodeMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
field_name='group',
|
||||
lookup_expr='in',
|
||||
to_field_name='slug',
|
||||
label='Group',
|
||||
label='Rack group (slug)',
|
||||
)
|
||||
status = django_filters.MultipleChoiceFilter(
|
||||
choices=RackStatusChoices,
|
||||
@@ -251,10 +256,6 @@ class RackFilterSet(BaseFilterSet, TenancyFilterSet, CustomFieldFilterSet, Creat
|
||||
|
||||
|
||||
class RackReservationFilterSet(BaseFilterSet, TenancyFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -274,16 +275,18 @@ class RackReservationFilterSet(BaseFilterSet, TenancyFilterSet):
|
||||
to_field_name='slug',
|
||||
label='Site (slug)',
|
||||
)
|
||||
group_id = django_filters.ModelMultipleChoiceFilter(
|
||||
group_id = TreeNodeMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
field_name='rack__group',
|
||||
queryset=RackGroup.objects.all(),
|
||||
label='Group (ID)',
|
||||
lookup_expr='in',
|
||||
label='Rack group (ID)',
|
||||
)
|
||||
group = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name='rack__group__slug',
|
||||
group = TreeNodeMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
field_name='rack__group',
|
||||
lookup_expr='in',
|
||||
to_field_name='slug',
|
||||
label='Group',
|
||||
label='Rack group (slug)',
|
||||
)
|
||||
user_id = django_filters.ModelMultipleChoiceFilter(
|
||||
queryset=User.objects.all(),
|
||||
@@ -315,14 +318,10 @@ class ManufacturerFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
|
||||
class Meta:
|
||||
model = Manufacturer
|
||||
fields = ['id', 'name', 'slug']
|
||||
fields = ['id', 'name', 'slug', 'description']
|
||||
|
||||
|
||||
class DeviceTypeFilterSet(BaseFilterSet, CustomFieldFilterSet, CreatedUpdatedFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -494,7 +493,7 @@ class PlatformFilterSet(BaseFilterSet, NameSlugSearchFilterSet):
|
||||
|
||||
class Meta:
|
||||
model = Platform
|
||||
fields = ['id', 'name', 'slug', 'napalm_driver']
|
||||
fields = ['id', 'name', 'slug', 'napalm_driver', 'description']
|
||||
|
||||
|
||||
class DeviceFilterSet(
|
||||
@@ -504,10 +503,6 @@ class DeviceFilterSet(
|
||||
CustomFieldFilterSet,
|
||||
CreatedUpdatedFilterSet
|
||||
):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -571,9 +566,10 @@ class DeviceFilterSet(
|
||||
to_field_name='slug',
|
||||
label='Site name (slug)',
|
||||
)
|
||||
rack_group_id = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name='rack__group',
|
||||
rack_group_id = TreeNodeMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
field_name='rack__group',
|
||||
lookup_expr='in',
|
||||
label='Rack group (ID)',
|
||||
)
|
||||
rack_id = django_filters.ModelMultipleChoiceFilter(
|
||||
@@ -1236,10 +1232,6 @@ class InterfaceConnectionFilterSet(BaseFilterSet):
|
||||
|
||||
|
||||
class PowerPanelFilterSet(BaseFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
@@ -1267,9 +1259,10 @@ class PowerPanelFilterSet(BaseFilterSet):
|
||||
to_field_name='slug',
|
||||
label='Site name (slug)',
|
||||
)
|
||||
rack_group_id = django_filters.ModelMultipleChoiceFilter(
|
||||
field_name='rack_group',
|
||||
rack_group_id = TreeNodeMultipleChoiceFilter(
|
||||
queryset=RackGroup.objects.all(),
|
||||
field_name='rack_group',
|
||||
lookup_expr='in',
|
||||
label='Rack group (ID)',
|
||||
)
|
||||
|
||||
@@ -1287,10 +1280,6 @@ class PowerPanelFilterSet(BaseFilterSet):
|
||||
|
||||
|
||||
class PowerFeedFilterSet(BaseFilterSet, CustomFieldFilterSet, CreatedUpdatedFilterSet):
|
||||
id__in = NumericInFilter(
|
||||
field_name='id',
|
||||
lookup_expr='in'
|
||||
)
|
||||
q = django_filters.CharFilter(
|
||||
method='search',
|
||||
label='Search',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
28
netbox/dcim/migrations/0100_mptt_remove_indexes.py
Normal file
28
netbox/dcim/migrations/0100_mptt_remove_indexes.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 3.0.3 on 2020-02-18 21:02
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('dcim', '0099_powerfeed_negative_voltage'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='region',
|
||||
name='level',
|
||||
field=models.PositiveIntegerField(editable=False),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='region',
|
||||
name='lft',
|
||||
field=models.PositiveIntegerField(editable=False),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='region',
|
||||
name='rght',
|
||||
field=models.PositiveIntegerField(editable=False),
|
||||
),
|
||||
]
|
||||
43
netbox/dcim/migrations/0101_nested_rackgroups.py
Normal file
43
netbox/dcim/migrations/0101_nested_rackgroups.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import mptt.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('dcim', '0100_mptt_remove_indexes'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='rackgroup',
|
||||
name='parent',
|
||||
field=mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='dcim.RackGroup'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rackgroup',
|
||||
name='level',
|
||||
field=models.PositiveIntegerField(default=0, editable=False),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rackgroup',
|
||||
name='lft',
|
||||
field=models.PositiveIntegerField(default=1, editable=False),
|
||||
preserve_default=False,
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rackgroup',
|
||||
name='rght',
|
||||
field=models.PositiveIntegerField(default=2, editable=False),
|
||||
preserve_default=False,
|
||||
),
|
||||
# tree_id will be set to a valid value during the following migration (which needs to be a separate migration)
|
||||
migrations.AddField(
|
||||
model_name='rackgroup',
|
||||
name='tree_id',
|
||||
field=models.PositiveIntegerField(db_index=True, default=0, editable=False),
|
||||
preserve_default=False,
|
||||
),
|
||||
]
|
||||
21
netbox/dcim/migrations/0102_nested_rackgroups_rebuild.py
Normal file
21
netbox/dcim/migrations/0102_nested_rackgroups_rebuild.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def rebuild_mptt(apps, schema_editor):
|
||||
RackGroup = apps.get_model('dcim', 'RackGroup')
|
||||
for i, rackgroup in enumerate(RackGroup.objects.all(), start=1):
|
||||
RackGroup.objects.filter(pk=rackgroup.pk).update(tree_id=i)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('dcim', '0101_nested_rackgroups'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(
|
||||
code=rebuild_mptt,
|
||||
reverse_code=migrations.RunPython.noop
|
||||
),
|
||||
]
|
||||
98
netbox/dcim/migrations/0103_standardize_description.py
Normal file
98
netbox/dcim/migrations/0103_standardize_description.py
Normal file
@@ -0,0 +1,98 @@
|
||||
# Generated by Django 3.0.3 on 2020-03-13 20:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('dcim', '0102_nested_rackgroups_rebuild'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='manufacturer',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='platform',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='rackgroup',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='region',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='consoleport',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='consoleserverport',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='devicebay',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='devicerole',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='frontport',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='interface',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='inventoryitem',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='poweroutlet',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='powerport',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='rackreservation',
|
||||
name='description',
|
||||
field=models.CharField(max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='rackrole',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='rearport',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='site',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
]
|
||||
34
netbox/dcim/migrations/0104_correct_infiniband_types.py
Normal file
34
netbox/dcim/migrations/0104_correct_infiniband_types.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
INFINIBAND_SLUGS = (
|
||||
('inifiband-sdr', 'infiniband-sdr'),
|
||||
('inifiband-ddr', 'infiniband-ddr'),
|
||||
('inifiband-qdr', 'infiniband-qdr'),
|
||||
('inifiband-fdr10', 'infiniband-fdr10'),
|
||||
('inifiband-fdr', 'infiniband-fdr'),
|
||||
('inifiband-edr', 'infiniband-edr'),
|
||||
('inifiband-hdr', 'infiniband-hdr'),
|
||||
('inifiband-ndr', 'infiniband-ndr'),
|
||||
('inifiband-xdr', 'infiniband-xdr'),
|
||||
)
|
||||
|
||||
|
||||
def correct_infiniband_types(apps, schema_editor):
|
||||
Interface = apps.get_model('dcim', 'Interface')
|
||||
for old, new in INFINIBAND_SLUGS:
|
||||
Interface.objects.filter(type=old).update(type=new)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('dcim', '0103_standardize_description'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(
|
||||
code=correct_infiniband_types,
|
||||
reverse_code=migrations.RunPython.noop
|
||||
),
|
||||
]
|
||||
@@ -21,6 +21,7 @@ from dcim.constants import *
|
||||
from dcim.fields import ASNField
|
||||
from dcim.elevations import RackElevationSVG
|
||||
from extras.models import ConfigContextModel, CustomFieldModel, ObjectChange, TaggedItem
|
||||
from extras.utils import extras_features
|
||||
from utilities.fields import ColorField, NaturalOrderingField
|
||||
from utilities.models import ChangeLoggedModel
|
||||
from utilities.utils import serialize_object, to_meters
|
||||
@@ -75,6 +76,7 @@ __all__ = (
|
||||
# Regions
|
||||
#
|
||||
|
||||
@extras_features('export_templates', 'webhooks')
|
||||
class Region(MPTTModel, ChangeLoggedModel):
|
||||
"""
|
||||
Sites can be grouped within geographic Regions.
|
||||
@@ -94,8 +96,12 @@ class Region(MPTTModel, ChangeLoggedModel):
|
||||
slug = models.SlugField(
|
||||
unique=True
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
|
||||
csv_headers = ['name', 'slug', 'parent']
|
||||
csv_headers = ['name', 'slug', 'parent', 'description']
|
||||
|
||||
class MPTTMeta:
|
||||
order_insertion_by = ['name']
|
||||
@@ -111,6 +117,7 @@ class Region(MPTTModel, ChangeLoggedModel):
|
||||
self.name,
|
||||
self.slug,
|
||||
self.parent.name if self.parent else None,
|
||||
self.description,
|
||||
)
|
||||
|
||||
def get_site_count(self):
|
||||
@@ -133,6 +140,7 @@ class Region(MPTTModel, ChangeLoggedModel):
|
||||
# Sites
|
||||
#
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'graphs', 'export_templates', 'webhooks')
|
||||
class Site(ChangeLoggedModel, CustomFieldModel):
|
||||
"""
|
||||
A Site represents a geographic location within a network; typically a building or campus. The optional facility
|
||||
@@ -182,7 +190,7 @@ class Site(ChangeLoggedModel, CustomFieldModel):
|
||||
blank=True
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
physical_address = models.CharField(
|
||||
@@ -283,7 +291,8 @@ class Site(ChangeLoggedModel, CustomFieldModel):
|
||||
# Racks
|
||||
#
|
||||
|
||||
class RackGroup(ChangeLoggedModel):
|
||||
@extras_features('export_templates')
|
||||
class RackGroup(MPTTModel, ChangeLoggedModel):
|
||||
"""
|
||||
Racks can be grouped as subsets within a Site. The scope of a group will depend on how Sites are defined. For
|
||||
example, if a Site spans a corporate campus, a RackGroup might be defined to represent each building within that
|
||||
@@ -298,8 +307,20 @@ class RackGroup(ChangeLoggedModel):
|
||||
on_delete=models.CASCADE,
|
||||
related_name='rack_groups'
|
||||
)
|
||||
parent = TreeForeignKey(
|
||||
to='self',
|
||||
on_delete=models.CASCADE,
|
||||
related_name='children',
|
||||
blank=True,
|
||||
null=True,
|
||||
db_index=True
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
|
||||
csv_headers = ['site', 'name', 'slug']
|
||||
csv_headers = ['site', 'parent', 'name', 'slug', 'description']
|
||||
|
||||
class Meta:
|
||||
ordering = ['site', 'name']
|
||||
@@ -308,6 +329,9 @@ class RackGroup(ChangeLoggedModel):
|
||||
['site', 'slug'],
|
||||
]
|
||||
|
||||
class MPTTMeta:
|
||||
order_insertion_by = ['name']
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
@@ -317,10 +341,27 @@ class RackGroup(ChangeLoggedModel):
|
||||
def to_csv(self):
|
||||
return (
|
||||
self.site,
|
||||
self.parent.name if self.parent else '',
|
||||
self.name,
|
||||
self.slug,
|
||||
self.description,
|
||||
)
|
||||
|
||||
def to_objectchange(self, action):
|
||||
# Remove MPTT-internal fields
|
||||
return ObjectChange(
|
||||
changed_object=self,
|
||||
object_repr=str(self),
|
||||
action=action,
|
||||
object_data=serialize_object(self, exclude=['level', 'lft', 'rght', 'tree_id'])
|
||||
)
|
||||
|
||||
def clean(self):
|
||||
|
||||
# Parent RackGroup (if any) must belong to the same Site
|
||||
if self.parent and self.parent.site != self.site:
|
||||
raise ValidationError(f"Parent rack group ({self.parent}) must belong to the same site ({self.site})")
|
||||
|
||||
|
||||
class RackRole(ChangeLoggedModel):
|
||||
"""
|
||||
@@ -335,7 +376,7 @@ class RackRole(ChangeLoggedModel):
|
||||
)
|
||||
color = ColorField()
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True,
|
||||
)
|
||||
|
||||
@@ -359,6 +400,7 @@ class RackRole(ChangeLoggedModel):
|
||||
)
|
||||
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
|
||||
class Rack(ChangeLoggedModel, CustomFieldModel):
|
||||
"""
|
||||
Devices are housed within Racks. Each rack has a defined height measured in rack units, and a front and rear face.
|
||||
@@ -677,7 +719,8 @@ class Rack(ChangeLoggedModel, CustomFieldModel):
|
||||
unit_width=RACK_ELEVATION_UNIT_WIDTH_DEFAULT,
|
||||
unit_height=RACK_ELEVATION_UNIT_HEIGHT_DEFAULT,
|
||||
legend_width=RACK_ELEVATION_LEGEND_WIDTH_DEFAULT,
|
||||
include_images=True
|
||||
include_images=True,
|
||||
base_url=None
|
||||
):
|
||||
"""
|
||||
Return an SVG of the rack elevation
|
||||
@@ -688,8 +731,9 @@ class Rack(ChangeLoggedModel, CustomFieldModel):
|
||||
height of the elevation
|
||||
:param legend_width: Width of the unit legend, in pixels
|
||||
:param include_images: Embed front/rear device images where available
|
||||
:param base_url: Base URL for links and images. If none, URLs will be relative.
|
||||
"""
|
||||
elevation = RackElevationSVG(self, include_images=include_images)
|
||||
elevation = RackElevationSVG(self, include_images=include_images, base_url=base_url)
|
||||
|
||||
return elevation.render(face, unit_width, unit_height, legend_width)
|
||||
|
||||
@@ -734,6 +778,7 @@ class Rack(ChangeLoggedModel, CustomFieldModel):
|
||||
return 0
|
||||
|
||||
|
||||
@extras_features('custom_links', 'export_templates', 'webhooks')
|
||||
class RackReservation(ChangeLoggedModel):
|
||||
"""
|
||||
One or more reserved units within a Rack.
|
||||
@@ -758,7 +803,7 @@ class RackReservation(ChangeLoggedModel):
|
||||
on_delete=models.PROTECT
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100
|
||||
max_length=200
|
||||
)
|
||||
|
||||
csv_headers = ['site', 'rack_group', 'rack', 'units', 'tenant', 'user', 'description']
|
||||
@@ -769,6 +814,9 @@ class RackReservation(ChangeLoggedModel):
|
||||
def __str__(self):
|
||||
return "Reservation for rack {}".format(self.rack)
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse('dcim:rackreservation', args=[self.pk])
|
||||
|
||||
def clean(self):
|
||||
|
||||
if self.units:
|
||||
@@ -820,6 +868,7 @@ class RackReservation(ChangeLoggedModel):
|
||||
# Device Types
|
||||
#
|
||||
|
||||
@extras_features('export_templates', 'webhooks')
|
||||
class Manufacturer(ChangeLoggedModel):
|
||||
"""
|
||||
A Manufacturer represents a company which produces hardware devices; for example, Juniper or Dell.
|
||||
@@ -831,8 +880,12 @@ class Manufacturer(ChangeLoggedModel):
|
||||
slug = models.SlugField(
|
||||
unique=True
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
|
||||
csv_headers = ['name', 'slug']
|
||||
csv_headers = ['name', 'slug', 'description']
|
||||
|
||||
class Meta:
|
||||
ordering = ['name']
|
||||
@@ -847,9 +900,11 @@ class Manufacturer(ChangeLoggedModel):
|
||||
return (
|
||||
self.name,
|
||||
self.slug,
|
||||
self.description
|
||||
)
|
||||
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
|
||||
class DeviceType(ChangeLoggedModel, CustomFieldModel):
|
||||
"""
|
||||
A DeviceType represents a particular make (Manufacturer) and model of device. It specifies rack height and depth, as
|
||||
@@ -1115,7 +1170,7 @@ class DeviceRole(ChangeLoggedModel):
|
||||
help_text='Virtual machines may be assigned to this role'
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True,
|
||||
)
|
||||
|
||||
@@ -1171,8 +1226,12 @@ class Platform(ChangeLoggedModel):
|
||||
verbose_name='NAPALM arguments',
|
||||
help_text='Additional arguments to pass when initiating the NAPALM driver (JSON format)'
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
|
||||
csv_headers = ['name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args']
|
||||
csv_headers = ['name', 'slug', 'manufacturer', 'napalm_driver', 'napalm_args', 'description']
|
||||
|
||||
class Meta:
|
||||
ordering = ['name']
|
||||
@@ -1190,9 +1249,11 @@ class Platform(ChangeLoggedModel):
|
||||
self.manufacturer.name if self.manufacturer else None,
|
||||
self.napalm_driver,
|
||||
self.napalm_args,
|
||||
self.description,
|
||||
)
|
||||
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'graphs', 'export_templates', 'webhooks')
|
||||
class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):
|
||||
"""
|
||||
A Device represents a piece of physical hardware mounted within a Rack. Each Device is assigned a DeviceType,
|
||||
@@ -1378,7 +1439,7 @@ class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):
|
||||
# because Django does not consider two NULL fields to be equal, and thus will not trigger a violation
|
||||
# of the uniqueness constraint without manual intervention.
|
||||
if self.name and self.tenant is None:
|
||||
if Device.objects.exclude(pk=self.pk).filter(name=self.name, tenant__isnull=True):
|
||||
if Device.objects.exclude(pk=self.pk).filter(name=self.name, site=self.site, tenant__isnull=True):
|
||||
raise ValidationError({
|
||||
'name': 'A device with this name already exists.'
|
||||
})
|
||||
@@ -1628,6 +1689,7 @@ class Device(ChangeLoggedModel, ConfigContextModel, CustomFieldModel):
|
||||
# Virtual chassis
|
||||
#
|
||||
|
||||
@extras_features('export_templates', 'webhooks')
|
||||
class VirtualChassis(ChangeLoggedModel):
|
||||
"""
|
||||
A collection of Devices which operate with a shared control plane (e.g. a switch stack).
|
||||
@@ -1694,6 +1756,7 @@ class VirtualChassis(ChangeLoggedModel):
|
||||
# Power
|
||||
#
|
||||
|
||||
@extras_features('custom_links', 'export_templates', 'webhooks')
|
||||
class PowerPanel(ChangeLoggedModel):
|
||||
"""
|
||||
A distribution point for electrical power; e.g. a data center RPP.
|
||||
@@ -1740,6 +1803,7 @@ class PowerPanel(ChangeLoggedModel):
|
||||
))
|
||||
|
||||
|
||||
@extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
|
||||
class PowerFeed(ChangeLoggedModel, CableTermination, CustomFieldModel):
|
||||
"""
|
||||
An electrical circuit delivered from a PowerPanel.
|
||||
@@ -1890,6 +1954,10 @@ class PowerFeed(ChangeLoggedModel, CableTermination, CustomFieldModel):
|
||||
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def parent(self):
|
||||
return self.power_panel
|
||||
|
||||
def get_type_class(self):
|
||||
return self.TYPE_CLASS_MAP.get(self.type)
|
||||
|
||||
@@ -1901,6 +1969,7 @@ class PowerFeed(ChangeLoggedModel, CableTermination, CustomFieldModel):
|
||||
# Cables
|
||||
#
|
||||
|
||||
@extras_features('custom_links', 'export_templates', 'webhooks')
|
||||
class Cable(ChangeLoggedModel):
|
||||
"""
|
||||
A physical connection between two endpoints.
|
||||
@@ -2052,15 +2121,15 @@ class Cable(ChangeLoggedModel):
|
||||
self.termination_a_type, self.termination_b_type
|
||||
))
|
||||
|
||||
# A component with multiple positions must be connected to a component with an equal number of positions
|
||||
term_a_positions = getattr(self.termination_a, 'positions', 1)
|
||||
term_b_positions = getattr(self.termination_b, 'positions', 1)
|
||||
if term_a_positions != term_b_positions:
|
||||
raise ValidationError(
|
||||
"{} has {} positions and {} has {}. Both terminations must have the same number of positions.".format(
|
||||
self.termination_a, term_a_positions, self.termination_b, term_b_positions
|
||||
# A RearPort with multiple positions must be connected to a component with an equal number of positions
|
||||
if isinstance(self.termination_a, RearPort) and isinstance(self.termination_b, RearPort):
|
||||
if self.termination_a.positions != self.termination_b.positions:
|
||||
raise ValidationError(
|
||||
"{} has {} positions and {} has {}. Both terminations must have the same number of positions.".format(
|
||||
self.termination_a, self.termination_a.positions,
|
||||
self.termination_b, self.termination_b.positions
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# A termination point cannot be connected to itself
|
||||
if self.termination_a == self.termination_b:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import logging
|
||||
|
||||
from django.contrib.contenttypes.fields import GenericRelation
|
||||
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
@@ -8,9 +10,9 @@ from taggit.managers import TaggableManager
|
||||
|
||||
from dcim.choices import *
|
||||
from dcim.constants import *
|
||||
from dcim.exceptions import LoopDetected
|
||||
from dcim.fields import MACAddressField
|
||||
from extras.models import ObjectChange, TaggedItem
|
||||
from extras.utils import extras_features
|
||||
from utilities.fields import NaturalOrderingField
|
||||
from utilities.ordering import naturalize_interface
|
||||
from utilities.utils import serialize_object
|
||||
@@ -33,7 +35,7 @@ __all__ = (
|
||||
|
||||
class ComponentModel(models.Model):
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
|
||||
@@ -87,7 +89,7 @@ class CableTermination(models.Model):
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
def trace(self, position=1, follow_circuits=False, cable_history=None):
|
||||
def trace(self):
|
||||
"""
|
||||
Return a list representing a complete cable path, with each individual segment represented as a three-tuple:
|
||||
[
|
||||
@@ -96,65 +98,85 @@ class CableTermination(models.Model):
|
||||
(termination E, cable, termination F)
|
||||
]
|
||||
"""
|
||||
def get_peer_port(termination, position=1, follow_circuits=False):
|
||||
endpoint = self
|
||||
path = []
|
||||
position_stack = []
|
||||
|
||||
def get_peer_port(termination):
|
||||
from circuits.models import CircuitTermination
|
||||
|
||||
# Map a front port to its corresponding rear port
|
||||
if isinstance(termination, FrontPort):
|
||||
return termination.rear_port, termination.rear_port_position
|
||||
position_stack.append(termination.rear_port_position)
|
||||
# Retrieve the corresponding RearPort from database to ensure we have an up-to-date instance
|
||||
peer_port = RearPort.objects.get(pk=termination.rear_port.pk)
|
||||
return peer_port
|
||||
|
||||
# Map a rear port/position to its corresponding front port
|
||||
elif isinstance(termination, RearPort):
|
||||
|
||||
# Can't map to a FrontPort without a position
|
||||
if not position_stack:
|
||||
# TODO: This behavior is broken. We need a mechanism by which to return all FrontPorts mapped
|
||||
# to a given RearPort so that we can update end-to-end paths when a cable is created/deleted.
|
||||
# For now, we're maintaining the current behavior of tracing only to the first FrontPort.
|
||||
position_stack.append(1)
|
||||
|
||||
position = position_stack.pop()
|
||||
|
||||
# Validate the position
|
||||
if position not in range(1, termination.positions + 1):
|
||||
raise Exception("Invalid position for {} ({} positions): {})".format(
|
||||
termination, termination.positions, position
|
||||
))
|
||||
|
||||
try:
|
||||
peer_port = FrontPort.objects.get(
|
||||
rear_port=termination,
|
||||
rear_port_position=position,
|
||||
)
|
||||
return peer_port, 1
|
||||
return peer_port
|
||||
except ObjectDoesNotExist:
|
||||
return None, None
|
||||
return None
|
||||
|
||||
# Follow a circuit to its other termination
|
||||
elif isinstance(termination, CircuitTermination) and follow_circuits:
|
||||
elif isinstance(termination, CircuitTermination):
|
||||
peer_termination = termination.get_peer_termination()
|
||||
if peer_termination is None:
|
||||
return None, None
|
||||
return peer_termination, position
|
||||
return None
|
||||
return peer_termination
|
||||
|
||||
# Termination is not a pass-through port
|
||||
else:
|
||||
return None, None
|
||||
return None
|
||||
|
||||
if not self.cable:
|
||||
return [(self, None, None)]
|
||||
logger = logging.getLogger('netbox.dcim.cable.trace')
|
||||
logger.debug("Tracing cable from {} {}".format(self.parent, self))
|
||||
|
||||
# Record cable history to detect loops
|
||||
if cable_history is None:
|
||||
cable_history = []
|
||||
elif self.cable in cable_history:
|
||||
raise LoopDetected()
|
||||
cable_history.append(self.cable)
|
||||
while endpoint is not None:
|
||||
|
||||
far_end = self.cable.termination_b if self.cable.termination_a == self else self.cable.termination_a
|
||||
path = [(self, self.cable, far_end)]
|
||||
# No cable connected; nothing to trace
|
||||
if not endpoint.cable:
|
||||
path.append((endpoint, None, None))
|
||||
logger.debug("No cable connected")
|
||||
return path
|
||||
|
||||
peer_port, position = get_peer_port(far_end, position, follow_circuits)
|
||||
if peer_port is None:
|
||||
return path
|
||||
# Check for loops
|
||||
if endpoint.cable in [segment[1] for segment in path]:
|
||||
logger.debug("Loop detected!")
|
||||
return path
|
||||
|
||||
try:
|
||||
next_segment = peer_port.trace(position, follow_circuits, cable_history)
|
||||
except LoopDetected:
|
||||
return path
|
||||
# Record the current segment in the path
|
||||
far_end = endpoint.get_cable_peer()
|
||||
path.append((endpoint, endpoint.cable, far_end))
|
||||
logger.debug("{}[{}] --- Cable {} ---> {}[{}]".format(
|
||||
endpoint.parent, endpoint, endpoint.cable.pk, far_end.parent, far_end
|
||||
))
|
||||
|
||||
if next_segment is None:
|
||||
return path + [(peer_port, None, None)]
|
||||
|
||||
return path + next_segment
|
||||
# Get the peer port of the far end termination
|
||||
endpoint = get_peer_port(far_end)
|
||||
if endpoint is None:
|
||||
return path
|
||||
|
||||
def get_cable_peer(self):
|
||||
if self.cable is None:
|
||||
@@ -169,6 +191,7 @@ class CableTermination(models.Model):
|
||||
# Console ports
|
||||
#
|
||||
|
||||
@extras_features('export_templates', 'webhooks')
|
||||
class ConsolePort(CableTermination, ComponentModel):
|
||||
"""
|
||||
A physical console port within a Device. ConsolePorts connect to ConsoleServerPorts.
|
||||
@@ -229,6 +252,7 @@ class ConsolePort(CableTermination, ComponentModel):
|
||||
# Console server ports
|
||||
#
|
||||
|
||||
@extras_features('webhooks')
|
||||
class ConsoleServerPort(CableTermination, ComponentModel):
|
||||
"""
|
||||
A physical port within a Device (typically a designated console server) which provides access to ConsolePorts.
|
||||
@@ -282,6 +306,7 @@ class ConsoleServerPort(CableTermination, ComponentModel):
|
||||
# Power ports
|
||||
#
|
||||
|
||||
@extras_features('export_templates', 'webhooks')
|
||||
class PowerPort(CableTermination, ComponentModel):
|
||||
"""
|
||||
A physical power supply (intake) port within a Device. PowerPorts connect to PowerOutlets.
|
||||
@@ -443,6 +468,7 @@ class PowerPort(CableTermination, ComponentModel):
|
||||
# Power outlets
|
||||
#
|
||||
|
||||
@extras_features('webhooks')
|
||||
class PowerOutlet(CableTermination, ComponentModel):
|
||||
"""
|
||||
A physical power outlet (output) within a Device which provides power to a PowerPort.
|
||||
@@ -519,6 +545,7 @@ class PowerOutlet(CableTermination, ComponentModel):
|
||||
# Interfaces
|
||||
#
|
||||
|
||||
@extras_features('graphs', 'export_templates', 'webhooks')
|
||||
class Interface(CableTermination, ComponentModel):
|
||||
"""
|
||||
A network interface within a Device or VirtualMachine. A physical Interface can connect to exactly one other
|
||||
@@ -792,6 +819,7 @@ class Interface(CableTermination, ComponentModel):
|
||||
# Pass-through ports
|
||||
#
|
||||
|
||||
@extras_features('webhooks')
|
||||
class FrontPort(CableTermination, ComponentModel):
|
||||
"""
|
||||
A pass-through port on the front of a Device.
|
||||
@@ -864,6 +892,7 @@ class FrontPort(CableTermination, ComponentModel):
|
||||
)
|
||||
|
||||
|
||||
@extras_features('webhooks')
|
||||
class RearPort(CableTermination, ComponentModel):
|
||||
"""
|
||||
A pass-through port on the rear of a Device.
|
||||
@@ -915,6 +944,7 @@ class RearPort(CableTermination, ComponentModel):
|
||||
# Device bays
|
||||
#
|
||||
|
||||
@extras_features('webhooks')
|
||||
class DeviceBay(ComponentModel):
|
||||
"""
|
||||
An empty space within a Device which can house a child device
|
||||
@@ -989,6 +1019,7 @@ class DeviceBay(ComponentModel):
|
||||
# Inventory items
|
||||
#
|
||||
|
||||
@extras_features('export_templates', 'webhooks')
|
||||
class InventoryItem(ComponentModel):
|
||||
"""
|
||||
An InventoryItem represents a serialized piece of hardware within a Device, such as a line card or power supply.
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import logging
|
||||
|
||||
from django.db.models.signals import post_save, pre_delete
|
||||
from django.dispatch import receiver
|
||||
|
||||
@@ -34,18 +36,22 @@ def update_connected_endpoints(instance, **kwargs):
|
||||
"""
|
||||
When a Cable is saved, check for and update its two connected endpoints
|
||||
"""
|
||||
logger = logging.getLogger('netbox.dcim.cable')
|
||||
|
||||
# Cache the Cable on its two termination points
|
||||
if instance.termination_a.cable != instance:
|
||||
logger.debug("Updating termination A for cable {}".format(instance))
|
||||
instance.termination_a.cable = instance
|
||||
instance.termination_a.save()
|
||||
if instance.termination_b.cable != instance:
|
||||
logger.debug("Updating termination B for cable {}".format(instance))
|
||||
instance.termination_b.cable = instance
|
||||
instance.termination_b.save()
|
||||
|
||||
# Check if this Cable has formed a complete path. If so, update both endpoints.
|
||||
endpoint_a, endpoint_b, path_status = instance.get_path_endpoints()
|
||||
if getattr(endpoint_a, 'is_path_endpoint', False) and getattr(endpoint_b, 'is_path_endpoint', False):
|
||||
logger.debug("Updating path endpoints: {} <---> {}".format(endpoint_a, endpoint_b))
|
||||
endpoint_a.connected_endpoint = endpoint_b
|
||||
endpoint_a.connection_status = path_status
|
||||
endpoint_a.save()
|
||||
@@ -59,18 +65,23 @@ def nullify_connected_endpoints(instance, **kwargs):
|
||||
"""
|
||||
When a Cable is deleted, check for and update its two connected endpoints
|
||||
"""
|
||||
logger = logging.getLogger('netbox.dcim.cable')
|
||||
|
||||
endpoint_a, endpoint_b, _ = instance.get_path_endpoints()
|
||||
|
||||
# Disassociate the Cable from its termination points
|
||||
if instance.termination_a is not None:
|
||||
logger.debug("Nullifying termination A for cable {}".format(instance))
|
||||
instance.termination_a.cable = None
|
||||
instance.termination_a.save()
|
||||
if instance.termination_b is not None:
|
||||
logger.debug("Nullifying termination B for cable {}".format(instance))
|
||||
instance.termination_b.cable = None
|
||||
instance.termination_b.save()
|
||||
|
||||
# If this Cable was part of a complete path, tear it down
|
||||
if hasattr(endpoint_a, 'connected_endpoint') and hasattr(endpoint_b, 'connected_endpoint'):
|
||||
logger.debug("Tearing down path ({} <---> {})".format(endpoint_a, endpoint_b))
|
||||
endpoint_a.connected_endpoint = None
|
||||
endpoint_a.connection_status = None
|
||||
endpoint_a.save()
|
||||
|
||||
@@ -11,13 +11,13 @@ from .models import (
|
||||
VirtualChassis,
|
||||
)
|
||||
|
||||
REGION_LINK = """
|
||||
MPTT_LINK = """
|
||||
{% if record.get_children %}
|
||||
<span style="padding-left: {{ record.get_ancestors|length }}0px "><i class="fa fa-caret-right"></i>
|
||||
{% else %}
|
||||
<span style="padding-left: {{ record.get_ancestors|length }}9px">
|
||||
{% endif %}
|
||||
<a href="{% url 'dcim:site_list' %}?region={{ record.slug }}">{{ record.name }}</a>
|
||||
<a href="{{ record.get_absolute_url }}">{{ record.name }}</a>
|
||||
</span>
|
||||
"""
|
||||
|
||||
@@ -214,7 +214,7 @@ def get_component_template_actions(model_name):
|
||||
|
||||
class RegionTable(BaseTable):
|
||||
pk = ToggleColumn()
|
||||
name = tables.TemplateColumn(template_code=REGION_LINK, orderable=False)
|
||||
name = tables.TemplateColumn(template_code=MPTT_LINK, orderable=False)
|
||||
site_count = tables.Column(verbose_name='Sites')
|
||||
slug = tables.Column(verbose_name='Slug')
|
||||
actions = tables.TemplateColumn(
|
||||
@@ -225,7 +225,7 @@ class RegionTable(BaseTable):
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = Region
|
||||
fields = ('pk', 'name', 'site_count', 'slug', 'actions')
|
||||
fields = ('pk', 'name', 'site_count', 'description', 'slug', 'actions')
|
||||
|
||||
|
||||
#
|
||||
@@ -250,7 +250,10 @@ class SiteTable(BaseTable):
|
||||
|
||||
class RackGroupTable(BaseTable):
|
||||
pk = ToggleColumn()
|
||||
name = tables.LinkColumn()
|
||||
name = tables.TemplateColumn(
|
||||
template_code=MPTT_LINK,
|
||||
orderable=False
|
||||
)
|
||||
site = tables.LinkColumn(
|
||||
viewname='dcim:site',
|
||||
args=[Accessor('site.slug')],
|
||||
@@ -268,7 +271,7 @@ class RackGroupTable(BaseTable):
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = RackGroup
|
||||
fields = ('pk', 'name', 'site', 'rack_count', 'slug', 'actions')
|
||||
fields = ('pk', 'name', 'site', 'rack_count', 'description', 'slug', 'actions')
|
||||
|
||||
|
||||
#
|
||||
@@ -338,21 +341,38 @@ class RackDetailTable(RackTable):
|
||||
|
||||
class RackReservationTable(BaseTable):
|
||||
pk = ToggleColumn()
|
||||
reservation = tables.LinkColumn(
|
||||
viewname='dcim:rackreservation',
|
||||
args=[Accessor('pk')],
|
||||
accessor='pk'
|
||||
)
|
||||
site = tables.LinkColumn(
|
||||
viewname='dcim:site',
|
||||
accessor=Accessor('rack.site'),
|
||||
args=[Accessor('rack.site.slug')],
|
||||
)
|
||||
tenant = tables.TemplateColumn(template_code=COL_TENANT)
|
||||
rack = tables.LinkColumn('dcim:rack', args=[Accessor('rack.pk')])
|
||||
unit_list = tables.Column(orderable=False, verbose_name='Units')
|
||||
tenant = tables.TemplateColumn(
|
||||
template_code=COL_TENANT
|
||||
)
|
||||
rack = tables.LinkColumn(
|
||||
viewname='dcim:rack',
|
||||
args=[Accessor('rack.pk')]
|
||||
)
|
||||
unit_list = tables.Column(
|
||||
orderable=False,
|
||||
verbose_name='Units'
|
||||
)
|
||||
actions = tables.TemplateColumn(
|
||||
template_code=RACKRESERVATION_ACTIONS, attrs={'td': {'class': 'text-right noprint'}}, verbose_name=''
|
||||
template_code=RACKRESERVATION_ACTIONS,
|
||||
attrs={'td': {'class': 'text-right noprint'}},
|
||||
verbose_name=''
|
||||
)
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = RackReservation
|
||||
fields = ('pk', 'site', 'rack', 'unit_list', 'user', 'created', 'tenant', 'description', 'actions')
|
||||
fields = (
|
||||
'pk', 'reservation', 'site', 'rack', 'unit_list', 'user', 'created', 'tenant', 'description', 'actions',
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
@@ -380,7 +400,9 @@ class ManufacturerTable(BaseTable):
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = Manufacturer
|
||||
fields = ('pk', 'name', 'devicetype_count', 'inventoryitem_count', 'platform_count', 'slug', 'actions')
|
||||
fields = (
|
||||
'pk', 'name', 'devicetype_count', 'inventoryitem_count', 'platform_count', 'description', 'slug', 'actions',
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
@@ -656,7 +678,9 @@ class PlatformTable(BaseTable):
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = Platform
|
||||
fields = ('pk', 'name', 'manufacturer', 'device_count', 'vm_count', 'slug', 'napalm_driver', 'actions')
|
||||
fields = (
|
||||
'pk', 'name', 'manufacturer', 'device_count', 'vm_count', 'slug', 'napalm_driver', 'description', 'actions',
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
@@ -840,7 +864,7 @@ class DeviceBayTable(BaseTable):
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = DeviceBay
|
||||
fields = ('name',)
|
||||
fields = ('name', 'description')
|
||||
|
||||
|
||||
class DeviceBayDetailTable(DeviceComponentDetailTable):
|
||||
@@ -848,8 +872,8 @@ class DeviceBayDetailTable(DeviceComponentDetailTable):
|
||||
installed_device = tables.LinkColumn()
|
||||
|
||||
class Meta(DeviceBayTable.Meta):
|
||||
fields = ('pk', 'name', 'device', 'installed_device')
|
||||
sequence = ('pk', 'name', 'device', 'installed_device')
|
||||
fields = ('pk', 'name', 'device', 'installed_device', 'description')
|
||||
sequence = ('pk', 'name', 'device', 'installed_device', 'description')
|
||||
exclude = ('cable',)
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ from netaddr import IPNetwork
|
||||
from rest_framework import status
|
||||
|
||||
from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
|
||||
from dcim.api import serializers
|
||||
from dcim.choices import *
|
||||
from dcim.constants import *
|
||||
from dcim.models import (
|
||||
@@ -15,7 +14,7 @@ from dcim.models import (
|
||||
)
|
||||
from ipam.models import IPAddress, VLAN
|
||||
from extras.models import Graph
|
||||
from utilities.testing import APITestCase, choices_to_dict
|
||||
from utilities.testing import APITestCase
|
||||
from virtualization.models import Cluster, ClusterType
|
||||
|
||||
|
||||
@@ -28,79 +27,6 @@ class AppTest(APITestCase):
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_choices(self):
|
||||
|
||||
url = reverse('dcim-api:field-choice-list')
|
||||
response = self.client.get(url, **self.header)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Cable
|
||||
self.assertEqual(choices_to_dict(response.data.get('cable:length_unit')), CableLengthUnitChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('cable:status')), CableStatusChoices.as_dict())
|
||||
content_types = ContentType.objects.filter(CABLE_TERMINATION_MODELS)
|
||||
cable_termination_choices = {
|
||||
"{}.{}".format(ct.app_label, ct.model): ct.name for ct in content_types
|
||||
}
|
||||
self.assertEqual(choices_to_dict(response.data.get('cable:termination_a_type')), cable_termination_choices)
|
||||
self.assertEqual(choices_to_dict(response.data.get('cable:termination_b_type')), cable_termination_choices)
|
||||
self.assertEqual(choices_to_dict(response.data.get('cable:type')), CableTypeChoices.as_dict())
|
||||
|
||||
# Console ports
|
||||
self.assertEqual(choices_to_dict(response.data.get('console-port:type')), ConsolePortTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('console-port:connection_status')), dict(CONNECTION_STATUS_CHOICES))
|
||||
self.assertEqual(choices_to_dict(response.data.get('console-port-template:type')), ConsolePortTypeChoices.as_dict())
|
||||
|
||||
# Console server ports
|
||||
self.assertEqual(choices_to_dict(response.data.get('console-server-port:type')), ConsolePortTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('console-server-port-template:type')), ConsolePortTypeChoices.as_dict())
|
||||
|
||||
# Device
|
||||
self.assertEqual(choices_to_dict(response.data.get('device:face')), DeviceFaceChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('device:status')), DeviceStatusChoices.as_dict())
|
||||
|
||||
# Device type
|
||||
self.assertEqual(choices_to_dict(response.data.get('device-type:subdevice_role')), SubdeviceRoleChoices.as_dict())
|
||||
|
||||
# Front ports
|
||||
self.assertEqual(choices_to_dict(response.data.get('front-port:type')), PortTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('front-port-template:type')), PortTypeChoices.as_dict())
|
||||
|
||||
# Interfaces
|
||||
self.assertEqual(choices_to_dict(response.data.get('interface:type')), InterfaceTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('interface:mode')), InterfaceModeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('interface-template:type')), InterfaceTypeChoices.as_dict())
|
||||
|
||||
# Power feed
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-feed:phase')), PowerFeedPhaseChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-feed:status')), PowerFeedStatusChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-feed:supply')), PowerFeedSupplyChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-feed:type')), PowerFeedTypeChoices.as_dict())
|
||||
|
||||
# Power outlets
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-outlet:type')), PowerOutletTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-outlet:feed_leg')), PowerOutletFeedLegChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-outlet-template:type')), PowerOutletTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-outlet-template:feed_leg')), PowerOutletFeedLegChoices.as_dict())
|
||||
|
||||
# Power ports
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-port:type')), PowerPortTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-port:connection_status')), dict(CONNECTION_STATUS_CHOICES))
|
||||
self.assertEqual(choices_to_dict(response.data.get('power-port-template:type')), PowerPortTypeChoices.as_dict())
|
||||
|
||||
# Rack
|
||||
self.assertEqual(choices_to_dict(response.data.get('rack:type')), RackTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('rack:width')), RackWidthChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('rack:status')), RackStatusChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('rack:outer_unit')), RackDimensionUnitChoices.as_dict())
|
||||
|
||||
# Rear ports
|
||||
self.assertEqual(choices_to_dict(response.data.get('rear-port:type')), PortTypeChoices.as_dict())
|
||||
self.assertEqual(choices_to_dict(response.data.get('rear-port-template:type')), PortTypeChoices.as_dict())
|
||||
|
||||
# Site
|
||||
self.assertEqual(choices_to_dict(response.data.get('site:status')), SiteStatusChoices.as_dict())
|
||||
|
||||
|
||||
class RegionTest(APITestCase):
|
||||
|
||||
@@ -350,9 +276,11 @@ class RackGroupTest(APITestCase):
|
||||
|
||||
self.site1 = Site.objects.create(name='Test Site 1', slug='test-site-1')
|
||||
self.site2 = Site.objects.create(name='Test Site 2', slug='test-site-2')
|
||||
self.rackgroup1 = RackGroup.objects.create(site=self.site1, name='Test Rack Group 1', slug='test-rack-group-1')
|
||||
self.rackgroup2 = RackGroup.objects.create(site=self.site1, name='Test Rack Group 2', slug='test-rack-group-2')
|
||||
self.rackgroup3 = RackGroup.objects.create(site=self.site1, name='Test Rack Group 3', slug='test-rack-group-3')
|
||||
self.parent_rackgroup1 = RackGroup.objects.create(site=self.site1, name='Parent Rack Group 1', slug='parent-rack-group-1')
|
||||
self.parent_rackgroup2 = RackGroup.objects.create(site=self.site2, name='Parent Rack Group 2', slug='parent-rack-group-2')
|
||||
self.rackgroup1 = RackGroup.objects.create(site=self.site1, name='Rack Group 1', slug='rack-group-1', parent=self.parent_rackgroup1)
|
||||
self.rackgroup2 = RackGroup.objects.create(site=self.site1, name='Rack Group 2', slug='rack-group-2', parent=self.parent_rackgroup1)
|
||||
self.rackgroup3 = RackGroup.objects.create(site=self.site1, name='Rack Group 3', slug='rack-group-3', parent=self.parent_rackgroup1)
|
||||
|
||||
def test_get_rackgroup(self):
|
||||
|
||||
@@ -366,7 +294,7 @@ class RackGroupTest(APITestCase):
|
||||
url = reverse('dcim-api:rackgroup-list')
|
||||
response = self.client.get(url, **self.header)
|
||||
|
||||
self.assertEqual(response.data['count'], 3)
|
||||
self.assertEqual(response.data['count'], 5)
|
||||
|
||||
def test_list_rackgroups_brief(self):
|
||||
|
||||
@@ -381,20 +309,22 @@ class RackGroupTest(APITestCase):
|
||||
def test_create_rackgroup(self):
|
||||
|
||||
data = {
|
||||
'name': 'Test Rack Group 4',
|
||||
'slug': 'test-rack-group-4',
|
||||
'name': 'Rack Group 4',
|
||||
'slug': 'rack-group-4',
|
||||
'site': self.site1.pk,
|
||||
'parent': self.parent_rackgroup1.pk,
|
||||
}
|
||||
|
||||
url = reverse('dcim-api:rackgroup-list')
|
||||
response = self.client.post(url, data, format='json', **self.header)
|
||||
|
||||
self.assertHttpStatus(response, status.HTTP_201_CREATED)
|
||||
self.assertEqual(RackGroup.objects.count(), 4)
|
||||
self.assertEqual(RackGroup.objects.count(), 6)
|
||||
rackgroup4 = RackGroup.objects.get(pk=response.data['id'])
|
||||
self.assertEqual(rackgroup4.name, data['name'])
|
||||
self.assertEqual(rackgroup4.slug, data['slug'])
|
||||
self.assertEqual(rackgroup4.site_id, data['site'])
|
||||
self.assertEqual(rackgroup4.parent_id, data['parent'])
|
||||
|
||||
def test_create_rackgroup_bulk(self):
|
||||
|
||||
@@ -403,16 +333,19 @@ class RackGroupTest(APITestCase):
|
||||
'name': 'Test Rack Group 4',
|
||||
'slug': 'test-rack-group-4',
|
||||
'site': self.site1.pk,
|
||||
'parent': self.parent_rackgroup1.pk,
|
||||
},
|
||||
{
|
||||
'name': 'Test Rack Group 5',
|
||||
'slug': 'test-rack-group-5',
|
||||
'site': self.site1.pk,
|
||||
'parent': self.parent_rackgroup1.pk,
|
||||
},
|
||||
{
|
||||
'name': 'Test Rack Group 6',
|
||||
'slug': 'test-rack-group-6',
|
||||
'site': self.site1.pk,
|
||||
'parent': self.parent_rackgroup1.pk,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -420,7 +353,7 @@ class RackGroupTest(APITestCase):
|
||||
response = self.client.post(url, data, format='json', **self.header)
|
||||
|
||||
self.assertHttpStatus(response, status.HTTP_201_CREATED)
|
||||
self.assertEqual(RackGroup.objects.count(), 6)
|
||||
self.assertEqual(RackGroup.objects.count(), 8)
|
||||
self.assertEqual(response.data[0]['name'], data[0]['name'])
|
||||
self.assertEqual(response.data[1]['name'], data[1]['name'])
|
||||
self.assertEqual(response.data[2]['name'], data[2]['name'])
|
||||
@@ -431,17 +364,19 @@ class RackGroupTest(APITestCase):
|
||||
'name': 'Test Rack Group X',
|
||||
'slug': 'test-rack-group-x',
|
||||
'site': self.site2.pk,
|
||||
'parent': self.parent_rackgroup2.pk,
|
||||
}
|
||||
|
||||
url = reverse('dcim-api:rackgroup-detail', kwargs={'pk': self.rackgroup1.pk})
|
||||
response = self.client.put(url, data, format='json', **self.header)
|
||||
|
||||
self.assertHttpStatus(response, status.HTTP_200_OK)
|
||||
self.assertEqual(RackGroup.objects.count(), 3)
|
||||
self.assertEqual(RackGroup.objects.count(), 5)
|
||||
rackgroup1 = RackGroup.objects.get(pk=response.data['id'])
|
||||
self.assertEqual(rackgroup1.name, data['name'])
|
||||
self.assertEqual(rackgroup1.slug, data['slug'])
|
||||
self.assertEqual(rackgroup1.site_id, data['site'])
|
||||
self.assertEqual(rackgroup1.parent_id, data['parent'])
|
||||
|
||||
def test_delete_rackgroup(self):
|
||||
|
||||
@@ -449,7 +384,7 @@ class RackGroupTest(APITestCase):
|
||||
response = self.client.delete(url, **self.header)
|
||||
|
||||
self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT)
|
||||
self.assertEqual(RackGroup.objects.count(), 2)
|
||||
self.assertEqual(RackGroup.objects.count(), 4)
|
||||
|
||||
|
||||
class RackRoleTest(APITestCase):
|
||||
@@ -589,13 +524,6 @@ class RackTest(APITestCase):
|
||||
|
||||
self.assertEqual(response.data['name'], self.rack1.name)
|
||||
|
||||
def test_get_rack_units(self):
|
||||
|
||||
url = reverse('dcim-api:rack-units', kwargs={'pk': self.rack1.pk})
|
||||
response = self.client.get(url, **self.header)
|
||||
|
||||
self.assertEqual(response.data['count'], 42)
|
||||
|
||||
def test_get_elevation_rack_units(self):
|
||||
|
||||
url = '{}?q=3'.format(reverse('dcim-api:rack-elevation', kwargs={'pk': self.rack1.pk}))
|
||||
@@ -2089,6 +2017,20 @@ class DeviceTest(APITestCase):
|
||||
|
||||
self.assertFalse('config_context' in response.data['results'][0])
|
||||
|
||||
def test_unique_name_per_site_constraint(self):
|
||||
|
||||
data = {
|
||||
'device_type': self.devicetype1.pk,
|
||||
'device_role': self.devicerole1.pk,
|
||||
'name': 'Test Device 1',
|
||||
'site': self.site1.pk,
|
||||
}
|
||||
|
||||
url = reverse('dcim-api:device-list')
|
||||
response = self.client.post(url, data, format='json', **self.header)
|
||||
|
||||
self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class ConsolePortTest(APITestCase):
|
||||
|
||||
|
||||
@@ -17,14 +17,15 @@ from virtualization.models import Cluster, ClusterType
|
||||
|
||||
class RegionTestCase(TestCase):
|
||||
queryset = Region.objects.all()
|
||||
filterset = RegionFilterSet
|
||||
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
|
||||
regions = (
|
||||
Region(name='Region 1', slug='region-1'),
|
||||
Region(name='Region 2', slug='region-2'),
|
||||
Region(name='Region 3', slug='region-3'),
|
||||
Region(name='Region 1', slug='region-1', description='A'),
|
||||
Region(name='Region 2', slug='region-2', description='B'),
|
||||
Region(name='Region 3', slug='region-3', description='C'),
|
||||
)
|
||||
for region in regions:
|
||||
region.save()
|
||||
@@ -43,22 +44,26 @@ class RegionTestCase(TestCase):
|
||||
def test_id(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
params = {'id': [str(id) for id in id_list]}
|
||||
self.assertEqual(RegionFilterSet(params, self.queryset).qs.count(), 2)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_name(self):
|
||||
params = {'name': ['Region 1', 'Region 2']}
|
||||
self.assertEqual(RegionFilterSet(params, self.queryset).qs.count(), 2)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_slug(self):
|
||||
params = {'slug': ['region-1', 'region-2']}
|
||||
self.assertEqual(RegionFilterSet(params, self.queryset).qs.count(), 2)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_description(self):
|
||||
params = {'description': ['A', 'B']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_parent(self):
|
||||
parent_regions = Region.objects.filter(parent__isnull=True)[:2]
|
||||
params = {'parent_id': [parent_regions[0].pk, parent_regions[1].pk]}
|
||||
self.assertEqual(RegionFilterSet(params, self.queryset).qs.count(), 4)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
|
||||
params = {'parent': [parent_regions[0].slug, parent_regions[1].slug]}
|
||||
self.assertEqual(RegionFilterSet(params, self.queryset).qs.count(), 4)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
|
||||
|
||||
|
||||
class SiteTestCase(TestCase):
|
||||
@@ -81,7 +86,8 @@ class SiteTestCase(TestCase):
|
||||
TenantGroup(name='Tenant group 2', slug='tenant-group-2'),
|
||||
TenantGroup(name='Tenant group 3', slug='tenant-group-3'),
|
||||
)
|
||||
TenantGroup.objects.bulk_create(tenant_groups)
|
||||
for tenantgroup in tenant_groups:
|
||||
tenantgroup.save()
|
||||
|
||||
tenants = (
|
||||
Tenant(name='Tenant 1', slug='tenant-1', group=tenant_groups[0]),
|
||||
@@ -138,11 +144,6 @@ class SiteTestCase(TestCase):
|
||||
params = {'contact_email': ['contact1@example.com', 'contact2@example.com']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_status(self):
|
||||
params = {'status': [SiteStatusChoices.STATUS_ACTIVE, SiteStatusChoices.STATUS_PLANNED]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
@@ -191,12 +192,21 @@ class RackGroupTestCase(TestCase):
|
||||
)
|
||||
Site.objects.bulk_create(sites)
|
||||
|
||||
rack_groups = (
|
||||
RackGroup(name='Rack Group 1', slug='rack-group-1', site=sites[0]),
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1]),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=sites[2]),
|
||||
parent_rack_groups = (
|
||||
RackGroup(name='Parent Rack Group 1', slug='parent-rack-group-1', site=sites[0]),
|
||||
RackGroup(name='Parent Rack Group 2', slug='parent-rack-group-2', site=sites[1]),
|
||||
RackGroup(name='Parent Rack Group 3', slug='parent-rack-group-3', site=sites[2]),
|
||||
)
|
||||
RackGroup.objects.bulk_create(rack_groups)
|
||||
for rackgroup in parent_rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
rack_groups = (
|
||||
RackGroup(name='Rack Group 1', slug='rack-group-1', site=sites[0], parent=parent_rack_groups[0], description='A'),
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1], parent=parent_rack_groups[1], description='B'),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=sites[2], parent=parent_rack_groups[2], description='C'),
|
||||
)
|
||||
for rackgroup in rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
def test_id(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
@@ -211,18 +221,29 @@ class RackGroupTestCase(TestCase):
|
||||
params = {'slug': ['rack-group-1', 'rack-group-2']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_description(self):
|
||||
params = {'description': ['A', 'B']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_region(self):
|
||||
regions = Region.objects.all()[:2]
|
||||
params = {'region_id': [regions[0].pk, regions[1].pk]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
|
||||
params = {'region': [regions[0].slug, regions[1].slug]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
|
||||
|
||||
def test_site(self):
|
||||
sites = Site.objects.all()[:2]
|
||||
params = {'site_id': [sites[0].pk, sites[1].pk]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
|
||||
params = {'site': [sites[0].slug, sites[1].slug]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
|
||||
|
||||
def test_parent(self):
|
||||
parent_groups = RackGroup.objects.filter(name__startswith='Parent')[:2]
|
||||
params = {'parent_id': [parent_groups[0].pk, parent_groups[1].pk]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
params = {'parent': [parent_groups[0].slug, parent_groups[1].slug]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
|
||||
@@ -285,7 +306,8 @@ class RackTestCase(TestCase):
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1]),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=sites[2]),
|
||||
)
|
||||
RackGroup.objects.bulk_create(rack_groups)
|
||||
for rackgroup in rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
rack_roles = (
|
||||
RackRole(name='Rack Role 1', slug='rack-role-1'),
|
||||
@@ -299,7 +321,8 @@ class RackTestCase(TestCase):
|
||||
TenantGroup(name='Tenant group 2', slug='tenant-group-2'),
|
||||
TenantGroup(name='Tenant group 3', slug='tenant-group-3'),
|
||||
)
|
||||
TenantGroup.objects.bulk_create(tenant_groups)
|
||||
for tenantgroup in tenant_groups:
|
||||
tenantgroup.save()
|
||||
|
||||
tenants = (
|
||||
Tenant(name='Tenant 1', slug='tenant-1', group=tenant_groups[0]),
|
||||
@@ -365,11 +388,6 @@ class RackTestCase(TestCase):
|
||||
params = {'outer_unit': RackDimensionUnitChoices.UNIT_MILLIMETER}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_region(self):
|
||||
regions = Region.objects.all()[:2]
|
||||
params = {'region_id': [regions[0].pk, regions[1].pk]}
|
||||
@@ -442,7 +460,8 @@ class RackReservationTestCase(TestCase):
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1]),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=sites[2]),
|
||||
)
|
||||
RackGroup.objects.bulk_create(rack_groups)
|
||||
for rackgroup in rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
racks = (
|
||||
Rack(name='Rack 1', site=sites[0], group=rack_groups[0]),
|
||||
@@ -463,7 +482,8 @@ class RackReservationTestCase(TestCase):
|
||||
TenantGroup(name='Tenant group 2', slug='tenant-group-2'),
|
||||
TenantGroup(name='Tenant group 3', slug='tenant-group-3'),
|
||||
)
|
||||
TenantGroup.objects.bulk_create(tenant_groups)
|
||||
for tenantgroup in tenant_groups:
|
||||
tenantgroup.save()
|
||||
|
||||
tenants = (
|
||||
Tenant(name='Tenant 1', slug='tenant-1', group=tenant_groups[0]),
|
||||
@@ -479,11 +499,6 @@ class RackReservationTestCase(TestCase):
|
||||
)
|
||||
RackReservation.objects.bulk_create(reservations)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_site(self):
|
||||
sites = Site.objects.all()[:2]
|
||||
params = {'site_id': [sites[0].pk, sites[1].pk]}
|
||||
@@ -529,9 +544,9 @@ class ManufacturerTestCase(TestCase):
|
||||
def setUpTestData(cls):
|
||||
|
||||
manufacturers = (
|
||||
Manufacturer(name='Manufacturer 1', slug='manufacturer-1'),
|
||||
Manufacturer(name='Manufacturer 2', slug='manufacturer-2'),
|
||||
Manufacturer(name='Manufacturer 3', slug='manufacturer-3'),
|
||||
Manufacturer(name='Manufacturer 1', slug='manufacturer-1', description='A'),
|
||||
Manufacturer(name='Manufacturer 2', slug='manufacturer-2', description='B'),
|
||||
Manufacturer(name='Manufacturer 3', slug='manufacturer-3', description='C'),
|
||||
)
|
||||
Manufacturer.objects.bulk_create(manufacturers)
|
||||
|
||||
@@ -548,6 +563,10 @@ class ManufacturerTestCase(TestCase):
|
||||
params = {'slug': ['manufacturer-1', 'manufacturer-2']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_description(self):
|
||||
params = {'description': ['A', 'B']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
|
||||
class DeviceTypeTestCase(TestCase):
|
||||
queryset = DeviceType.objects.all()
|
||||
@@ -631,11 +650,6 @@ class DeviceTypeTestCase(TestCase):
|
||||
params = {'subdevice_role': SubdeviceRoleChoices.ROLE_PARENT}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_manufacturer(self):
|
||||
manufacturers = Manufacturer.objects.all()[:2]
|
||||
params = {'manufacturer_id': [manufacturers[0].pk, manufacturers[1].pk]}
|
||||
@@ -1080,9 +1094,9 @@ class PlatformTestCase(TestCase):
|
||||
Manufacturer.objects.bulk_create(manufacturers)
|
||||
|
||||
platforms = (
|
||||
Platform(name='Platform 1', slug='platform-1', manufacturer=manufacturers[0], napalm_driver='driver-1'),
|
||||
Platform(name='Platform 2', slug='platform-2', manufacturer=manufacturers[1], napalm_driver='driver-2'),
|
||||
Platform(name='Platform 3', slug='platform-3', manufacturer=manufacturers[2], napalm_driver='driver-3'),
|
||||
Platform(name='Platform 1', slug='platform-1', manufacturer=manufacturers[0], napalm_driver='driver-1', description='A'),
|
||||
Platform(name='Platform 2', slug='platform-2', manufacturer=manufacturers[1], napalm_driver='driver-2', description='B'),
|
||||
Platform(name='Platform 3', slug='platform-3', manufacturer=manufacturers[2], napalm_driver='driver-3', description='C'),
|
||||
)
|
||||
Platform.objects.bulk_create(platforms)
|
||||
|
||||
@@ -1099,6 +1113,10 @@ class PlatformTestCase(TestCase):
|
||||
params = {'slug': ['platform-1', 'platform-2']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_description(self):
|
||||
params = {'description': ['A', 'B']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_napalm_driver(self):
|
||||
params = {'napalm_driver': ['driver-1', 'driver-2']}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
@@ -1166,7 +1184,8 @@ class DeviceTestCase(TestCase):
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1]),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=sites[2]),
|
||||
)
|
||||
RackGroup.objects.bulk_create(rack_groups)
|
||||
for rackgroup in rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
racks = (
|
||||
Rack(name='Rack 1', site=sites[0], group=rack_groups[0]),
|
||||
@@ -1188,7 +1207,8 @@ class DeviceTestCase(TestCase):
|
||||
TenantGroup(name='Tenant group 2', slug='tenant-group-2'),
|
||||
TenantGroup(name='Tenant group 3', slug='tenant-group-3'),
|
||||
)
|
||||
TenantGroup.objects.bulk_create(tenant_groups)
|
||||
for tenantgroup in tenant_groups:
|
||||
tenantgroup.save()
|
||||
|
||||
tenants = (
|
||||
Tenant(name='Tenant 1', slug='tenant-1', group=tenant_groups[0]),
|
||||
@@ -1242,8 +1262,8 @@ class DeviceTestCase(TestCase):
|
||||
|
||||
# Assign primary IPs for filtering
|
||||
ipaddresses = (
|
||||
IPAddress(family=4, address='192.0.2.1/24', interface=interfaces[0]),
|
||||
IPAddress(family=4, address='192.0.2.2/24', interface=interfaces[1]),
|
||||
IPAddress(address='192.0.2.1/24', interface=interfaces[0]),
|
||||
IPAddress(address='192.0.2.2/24', interface=interfaces[1]),
|
||||
)
|
||||
IPAddress.objects.bulk_create(ipaddresses)
|
||||
Device.objects.filter(pk=devices[0].pk).update(primary_ip4=ipaddresses[0])
|
||||
@@ -1283,11 +1303,6 @@ class DeviceTestCase(TestCase):
|
||||
params = {'vc_priority': [1, 2]}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_id__in(self):
|
||||
id_list = self.queryset.values_list('id', flat=True)[:2]
|
||||
params = {'id__in': ','.join([str(id) for id in id_list])}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_manufacturer(self):
|
||||
manufacturers = Manufacturer.objects.all()[:2]
|
||||
params = {'manufacturer_id': [manufacturers[0].pk, manufacturers[1].pk]}
|
||||
@@ -2584,7 +2599,8 @@ class PowerPanelTestCase(TestCase):
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1]),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=sites[2]),
|
||||
)
|
||||
RackGroup.objects.bulk_create(rack_groups)
|
||||
for rackgroup in rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
power_panels = (
|
||||
PowerPanel(name='Power Panel 1', site=sites[0], rack_group=rack_groups[0]),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.test import TestCase
|
||||
|
||||
from circuits.models import *
|
||||
from dcim.choices import *
|
||||
from dcim.models import *
|
||||
from tenancy.models import Tenant
|
||||
@@ -459,95 +460,346 @@ class CableTestCase(TestCase):
|
||||
|
||||
class CablePathTestCase(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
|
||||
site = Site.objects.create(name='Test Site 1', slug='test-site-1')
|
||||
manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
|
||||
site = Site.objects.create(name='Site 1', slug='site-1')
|
||||
manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
|
||||
devicetype = DeviceType.objects.create(
|
||||
manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
|
||||
manufacturer=manufacturer, model='Device Type 1', slug='device-type-1'
|
||||
)
|
||||
devicerole = DeviceRole.objects.create(
|
||||
name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
|
||||
)
|
||||
self.device1 = Device.objects.create(
|
||||
device_type=devicetype, device_role=devicerole, name='Test Device 1', site=site
|
||||
)
|
||||
self.device2 = Device.objects.create(
|
||||
device_type=devicetype, device_role=devicerole, name='Test Device 2', site=site
|
||||
)
|
||||
self.interface1 = Interface.objects.create(device=self.device1, name='eth0')
|
||||
self.interface2 = Interface.objects.create(device=self.device2, name='eth0')
|
||||
self.panel1 = Device.objects.create(
|
||||
device_type=devicetype, device_role=devicerole, name='Test Panel 1', site=site
|
||||
)
|
||||
self.panel2 = Device.objects.create(
|
||||
device_type=devicetype, device_role=devicerole, name='Test Panel 2', site=site
|
||||
)
|
||||
self.rear_port1 = RearPort.objects.create(
|
||||
device=self.panel1, name='Rear Port 1', type=PortTypeChoices.TYPE_8P8C
|
||||
)
|
||||
self.front_port1 = FrontPort.objects.create(
|
||||
device=self.panel1, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C, rear_port=self.rear_port1
|
||||
)
|
||||
self.rear_port2 = RearPort.objects.create(
|
||||
device=self.panel2, name='Rear Port 2', type=PortTypeChoices.TYPE_8P8C
|
||||
)
|
||||
self.front_port2 = FrontPort.objects.create(
|
||||
device=self.panel2, name='Front Port 2', type=PortTypeChoices.TYPE_8P8C, rear_port=self.rear_port2
|
||||
name='Device Role 1', slug='device-role-1', color='ff0000'
|
||||
)
|
||||
provider = Provider.objects.create(name='Provider 1', slug='provider-1')
|
||||
circuittype = CircuitType.objects.create(name='Circuit Type 1', slug='circuit-type-1')
|
||||
circuit = Circuit.objects.create(provider=provider, type=circuittype, cid='1')
|
||||
CircuitTermination.objects.bulk_create((
|
||||
CircuitTermination(circuit=circuit, site=site, term_side='A', port_speed=1000),
|
||||
CircuitTermination(circuit=circuit, site=site, term_side='Z', port_speed=1000),
|
||||
))
|
||||
|
||||
def test_path_completion(self):
|
||||
# Create four network devices with four interfaces each
|
||||
devices = (
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Device 1', site=site),
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Device 2', site=site),
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Device 3', site=site),
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Device 4', site=site),
|
||||
)
|
||||
Device.objects.bulk_create(devices)
|
||||
for device in devices:
|
||||
Interface.objects.bulk_create((
|
||||
Interface(device=device, name='Interface 1', type=InterfaceTypeChoices.TYPE_1GE_FIXED),
|
||||
Interface(device=device, name='Interface 2', type=InterfaceTypeChoices.TYPE_1GE_FIXED),
|
||||
Interface(device=device, name='Interface 3', type=InterfaceTypeChoices.TYPE_1GE_FIXED),
|
||||
Interface(device=device, name='Interface 4', type=InterfaceTypeChoices.TYPE_1GE_FIXED),
|
||||
))
|
||||
|
||||
# First segment
|
||||
cable1 = Cable(termination_a=self.interface1, termination_b=self.front_port1)
|
||||
# Create four patch panels, each with one rear port and four front ports
|
||||
patch_panels = (
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Panel 1', site=site),
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Panel 2', site=site),
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Panel 3', site=site),
|
||||
Device(device_type=devicetype, device_role=devicerole, name='Panel 4', site=site),
|
||||
)
|
||||
Device.objects.bulk_create(patch_panels)
|
||||
for patch_panel in patch_panels:
|
||||
rearport = RearPort.objects.create(device=patch_panel, name='Rear Port 1', positions=4, type=PortTypeChoices.TYPE_8P8C)
|
||||
FrontPort.objects.bulk_create((
|
||||
FrontPort(device=patch_panel, name='Front Port 1', rear_port=rearport, rear_port_position=1, type=PortTypeChoices.TYPE_8P8C),
|
||||
FrontPort(device=patch_panel, name='Front Port 2', rear_port=rearport, rear_port_position=2, type=PortTypeChoices.TYPE_8P8C),
|
||||
FrontPort(device=patch_panel, name='Front Port 3', rear_port=rearport, rear_port_position=3, type=PortTypeChoices.TYPE_8P8C),
|
||||
FrontPort(device=patch_panel, name='Front Port 4', rear_port=rearport, rear_port_position=4, type=PortTypeChoices.TYPE_8P8C),
|
||||
))
|
||||
|
||||
def test_direct_connection(self):
|
||||
"""
|
||||
|
||||
[Device 1] ----- [Device 2]
|
||||
Iface1 Iface1
|
||||
|
||||
"""
|
||||
# Create cable
|
||||
cable = Cable(
|
||||
termination_a=Interface.objects.get(device__name='Device 1', name='Interface 1'),
|
||||
termination_b=Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
)
|
||||
cable.save()
|
||||
|
||||
# Retrieve endpoints
|
||||
endpoint_a = Interface.objects.get(device__name='Device 1', name='Interface 1')
|
||||
endpoint_b = Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
|
||||
# Validate connections
|
||||
self.assertEqual(endpoint_a.connected_endpoint, endpoint_b)
|
||||
self.assertEqual(endpoint_b.connected_endpoint, endpoint_a)
|
||||
self.assertTrue(endpoint_a.connection_status)
|
||||
self.assertTrue(endpoint_b.connection_status)
|
||||
|
||||
# Delete cable
|
||||
cable.delete()
|
||||
|
||||
# Refresh endpoints
|
||||
endpoint_a.refresh_from_db()
|
||||
endpoint_b.refresh_from_db()
|
||||
|
||||
# Check that connections have been nullified
|
||||
self.assertIsNone(endpoint_a.connected_endpoint)
|
||||
self.assertIsNone(endpoint_b.connected_endpoint)
|
||||
self.assertIsNone(endpoint_a.connection_status)
|
||||
self.assertIsNone(endpoint_b.connection_status)
|
||||
|
||||
def test_connection_via_patch(self):
|
||||
"""
|
||||
1 2 3
|
||||
[Device 1] ----- [Panel 1] ----- [Panel 2] ----- [Device 2]
|
||||
Iface1 FP1 RP1 RP1 FP1 Iface1
|
||||
|
||||
"""
|
||||
# Create cables
|
||||
cable1 = Cable(
|
||||
termination_a=Interface.objects.get(device__name='Device 1', name='Interface 1'),
|
||||
termination_b=FrontPort.objects.get(device__name='Panel 1', name='Front Port 1')
|
||||
)
|
||||
cable1.save()
|
||||
interface1 = Interface.objects.get(pk=self.interface1.pk)
|
||||
self.assertIsNone(interface1.connected_endpoint)
|
||||
self.assertIsNone(interface1.connection_status)
|
||||
|
||||
# Second segment
|
||||
cable2 = Cable(termination_a=self.rear_port1, termination_b=self.rear_port2)
|
||||
cable2 = Cable(
|
||||
termination_a=RearPort.objects.get(device__name='Panel 1', name='Rear Port 1'),
|
||||
termination_b=RearPort.objects.get(device__name='Panel 2', name='Rear Port 1')
|
||||
)
|
||||
cable2.save()
|
||||
interface1 = Interface.objects.get(pk=self.interface1.pk)
|
||||
self.assertIsNone(interface1.connected_endpoint)
|
||||
self.assertIsNone(interface1.connection_status)
|
||||
|
||||
# Third segment
|
||||
cable3 = Cable(
|
||||
termination_a=self.front_port2,
|
||||
termination_b=self.interface2,
|
||||
status=CableStatusChoices.STATUS_PLANNED
|
||||
termination_a=FrontPort.objects.get(device__name='Panel 2', name='Front Port 1'),
|
||||
termination_b=Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
)
|
||||
cable3.save()
|
||||
interface1 = Interface.objects.get(pk=self.interface1.pk)
|
||||
self.assertEqual(interface1.connected_endpoint, self.interface2)
|
||||
self.assertFalse(interface1.connection_status)
|
||||
|
||||
# Switch third segment from planned to connected
|
||||
cable3.status = CableStatusChoices.STATUS_CONNECTED
|
||||
cable3.save()
|
||||
interface1 = Interface.objects.get(pk=self.interface1.pk)
|
||||
self.assertEqual(interface1.connected_endpoint, self.interface2)
|
||||
self.assertTrue(interface1.connection_status)
|
||||
# Retrieve endpoints
|
||||
endpoint_a = Interface.objects.get(device__name='Device 1', name='Interface 1')
|
||||
endpoint_b = Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
|
||||
def test_path_teardown(self):
|
||||
# Validate connections
|
||||
self.assertEqual(endpoint_a.connected_endpoint, endpoint_b)
|
||||
self.assertEqual(endpoint_b.connected_endpoint, endpoint_a)
|
||||
self.assertTrue(endpoint_a.connection_status)
|
||||
self.assertTrue(endpoint_b.connection_status)
|
||||
|
||||
# Build the path
|
||||
cable1 = Cable(termination_a=self.interface1, termination_b=self.front_port1)
|
||||
cable1.save()
|
||||
cable2 = Cable(termination_a=self.rear_port1, termination_b=self.rear_port2)
|
||||
cable2.save()
|
||||
cable3 = Cable(termination_a=self.front_port2, termination_b=self.interface2)
|
||||
cable3.save()
|
||||
interface1 = Interface.objects.get(pk=self.interface1.pk)
|
||||
self.assertEqual(interface1.connected_endpoint, self.interface2)
|
||||
self.assertTrue(interface1.connection_status)
|
||||
|
||||
# Remove a cable
|
||||
# Delete cable 2
|
||||
cable2.delete()
|
||||
interface1 = Interface.objects.get(pk=self.interface1.pk)
|
||||
self.assertIsNone(interface1.connected_endpoint)
|
||||
self.assertIsNone(interface1.connection_status)
|
||||
interface2 = Interface.objects.get(pk=self.interface2.pk)
|
||||
self.assertIsNone(interface2.connected_endpoint)
|
||||
self.assertIsNone(interface2.connection_status)
|
||||
|
||||
# Refresh endpoints
|
||||
endpoint_a.refresh_from_db()
|
||||
endpoint_b.refresh_from_db()
|
||||
|
||||
# Check that connections have been nullified
|
||||
self.assertIsNone(endpoint_a.connected_endpoint)
|
||||
self.assertIsNone(endpoint_b.connected_endpoint)
|
||||
self.assertIsNone(endpoint_a.connection_status)
|
||||
self.assertIsNone(endpoint_b.connection_status)
|
||||
|
||||
def test_connection_via_multiple_patches(self):
|
||||
"""
|
||||
1 2 3 4 5
|
||||
[Device 1] ----- [Panel 1] ----- [Panel 2] ----- [Panel 3] ----- [Panel 4] ----- [Device 2]
|
||||
Iface1 FP1 RP1 RP1 FP1 FP1 RP1 RP1 FP1 Iface1
|
||||
|
||||
"""
|
||||
# Create cables
|
||||
cable1 = Cable(
|
||||
termination_a=Interface.objects.get(device__name='Device 1', name='Interface 1'),
|
||||
termination_b=FrontPort.objects.get(device__name='Panel 1', name='Front Port 1')
|
||||
)
|
||||
cable1.save()
|
||||
cable2 = Cable(
|
||||
termination_a=RearPort.objects.get(device__name='Panel 1', name='Rear Port 1'),
|
||||
termination_b=RearPort.objects.get(device__name='Panel 2', name='Rear Port 1')
|
||||
)
|
||||
cable2.save()
|
||||
cable3 = Cable(
|
||||
termination_a=FrontPort.objects.get(device__name='Panel 2', name='Front Port 1'),
|
||||
termination_b=FrontPort.objects.get(device__name='Panel 3', name='Front Port 1')
|
||||
)
|
||||
cable3.save()
|
||||
cable4 = Cable(
|
||||
termination_a=RearPort.objects.get(device__name='Panel 3', name='Rear Port 1'),
|
||||
termination_b=RearPort.objects.get(device__name='Panel 4', name='Rear Port 1')
|
||||
)
|
||||
cable4.save()
|
||||
cable5 = Cable(
|
||||
termination_a=FrontPort.objects.get(device__name='Panel 4', name='Front Port 1'),
|
||||
termination_b=Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
)
|
||||
cable5.save()
|
||||
|
||||
# Retrieve endpoints
|
||||
endpoint_a = Interface.objects.get(device__name='Device 1', name='Interface 1')
|
||||
endpoint_b = Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
|
||||
# Validate connections
|
||||
self.assertEqual(endpoint_a.connected_endpoint, endpoint_b)
|
||||
self.assertEqual(endpoint_b.connected_endpoint, endpoint_a)
|
||||
self.assertTrue(endpoint_a.connection_status)
|
||||
self.assertTrue(endpoint_b.connection_status)
|
||||
|
||||
# Delete cable 3
|
||||
cable3.delete()
|
||||
|
||||
# Refresh endpoints
|
||||
endpoint_a.refresh_from_db()
|
||||
endpoint_b.refresh_from_db()
|
||||
|
||||
# Check that connections have been nullified
|
||||
self.assertIsNone(endpoint_a.connected_endpoint)
|
||||
self.assertIsNone(endpoint_b.connected_endpoint)
|
||||
self.assertIsNone(endpoint_a.connection_status)
|
||||
self.assertIsNone(endpoint_b.connection_status)
|
||||
|
||||
def test_connection_via_stacked_rear_ports(self):
|
||||
"""
|
||||
1 2 3 4 5
|
||||
[Device 1] ----- [Panel 1] ----- [Panel 2] ----- [Panel 3] ----- [Panel 4] ----- [Device 2]
|
||||
Iface1 FP1 RP1 FP1 RP1 RP1 FP1 RP1 FP1 Iface1
|
||||
|
||||
"""
|
||||
# Create cables
|
||||
cable1 = Cable(
|
||||
termination_a=Interface.objects.get(device__name='Device 1', name='Interface 1'),
|
||||
termination_b=FrontPort.objects.get(device__name='Panel 1', name='Front Port 1')
|
||||
)
|
||||
cable1.save()
|
||||
cable2 = Cable(
|
||||
termination_a=RearPort.objects.get(device__name='Panel 1', name='Rear Port 1'),
|
||||
termination_b=FrontPort.objects.get(device__name='Panel 2', name='Front Port 1')
|
||||
)
|
||||
cable2.save()
|
||||
cable3 = Cable(
|
||||
termination_a=RearPort.objects.get(device__name='Panel 2', name='Rear Port 1'),
|
||||
termination_b=RearPort.objects.get(device__name='Panel 3', name='Rear Port 1')
|
||||
)
|
||||
cable3.save()
|
||||
cable4 = Cable(
|
||||
termination_a=FrontPort.objects.get(device__name='Panel 3', name='Front Port 1'),
|
||||
termination_b=RearPort.objects.get(device__name='Panel 4', name='Rear Port 1')
|
||||
)
|
||||
cable4.save()
|
||||
cable5 = Cable(
|
||||
termination_a=FrontPort.objects.get(device__name='Panel 4', name='Front Port 1'),
|
||||
termination_b=Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
)
|
||||
cable5.save()
|
||||
|
||||
# Retrieve endpoints
|
||||
endpoint_a = Interface.objects.get(device__name='Device 1', name='Interface 1')
|
||||
endpoint_b = Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
|
||||
# Validate connections
|
||||
self.assertEqual(endpoint_a.connected_endpoint, endpoint_b)
|
||||
self.assertEqual(endpoint_b.connected_endpoint, endpoint_a)
|
||||
self.assertTrue(endpoint_a.connection_status)
|
||||
self.assertTrue(endpoint_b.connection_status)
|
||||
|
||||
# Delete cable 3
|
||||
cable3.delete()
|
||||
|
||||
# Refresh endpoints
|
||||
endpoint_a.refresh_from_db()
|
||||
endpoint_b.refresh_from_db()
|
||||
|
||||
# Check that connections have been nullified
|
||||
self.assertIsNone(endpoint_a.connected_endpoint)
|
||||
self.assertIsNone(endpoint_b.connected_endpoint)
|
||||
self.assertIsNone(endpoint_a.connection_status)
|
||||
self.assertIsNone(endpoint_b.connection_status)
|
||||
|
||||
def test_connection_via_circuit(self):
|
||||
"""
|
||||
1 2
|
||||
[Device 1] ----- [Circuit] ----- [Device 2]
|
||||
Iface1 A Z Iface1
|
||||
|
||||
"""
|
||||
# Create cables
|
||||
cable1 = Cable(
|
||||
termination_a=Interface.objects.get(device__name='Device 1', name='Interface 1'),
|
||||
termination_b=CircuitTermination.objects.get(term_side='A')
|
||||
)
|
||||
cable1.save()
|
||||
cable2 = Cable(
|
||||
termination_a=CircuitTermination.objects.get(term_side='Z'),
|
||||
termination_b=Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
)
|
||||
cable2.save()
|
||||
|
||||
# Retrieve endpoints
|
||||
endpoint_a = Interface.objects.get(device__name='Device 1', name='Interface 1')
|
||||
endpoint_b = Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
|
||||
# Validate connections
|
||||
self.assertEqual(endpoint_a.connected_endpoint, endpoint_b)
|
||||
self.assertEqual(endpoint_b.connected_endpoint, endpoint_a)
|
||||
self.assertTrue(endpoint_a.connection_status)
|
||||
self.assertTrue(endpoint_b.connection_status)
|
||||
|
||||
# Delete circuit
|
||||
circuit = Circuit.objects.first().delete()
|
||||
|
||||
# Refresh endpoints
|
||||
endpoint_a.refresh_from_db()
|
||||
endpoint_b.refresh_from_db()
|
||||
|
||||
# Check that connections have been nullified
|
||||
self.assertIsNone(endpoint_a.connected_endpoint)
|
||||
self.assertIsNone(endpoint_b.connected_endpoint)
|
||||
self.assertIsNone(endpoint_a.connection_status)
|
||||
self.assertIsNone(endpoint_b.connection_status)
|
||||
|
||||
def test_connection_via_patched_circuit(self):
|
||||
"""
|
||||
1 2 3 4
|
||||
[Device 1] ----- [Panel 1] ----- [Circuit] ----- [Panel 2] ----- [Device 2]
|
||||
Iface1 FP1 RP1 A Z RP1 FP1 Iface1
|
||||
|
||||
"""
|
||||
# Create cables
|
||||
cable1 = Cable(
|
||||
termination_a=Interface.objects.get(device__name='Device 1', name='Interface 1'),
|
||||
termination_b=FrontPort.objects.get(device__name='Panel 1', name='Front Port 1')
|
||||
)
|
||||
cable1.save()
|
||||
cable2 = Cable(
|
||||
termination_a=RearPort.objects.get(device__name='Panel 1', name='Rear Port 1'),
|
||||
termination_b=CircuitTermination.objects.get(term_side='A')
|
||||
)
|
||||
cable2.save()
|
||||
cable3 = Cable(
|
||||
termination_a=CircuitTermination.objects.get(term_side='Z'),
|
||||
termination_b=RearPort.objects.get(device__name='Panel 2', name='Rear Port 1')
|
||||
)
|
||||
cable3.save()
|
||||
cable4 = Cable(
|
||||
termination_a=FrontPort.objects.get(device__name='Panel 2', name='Front Port 1'),
|
||||
termination_b=Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
)
|
||||
cable4.save()
|
||||
|
||||
# Retrieve endpoints
|
||||
endpoint_a = Interface.objects.get(device__name='Device 1', name='Interface 1')
|
||||
endpoint_b = Interface.objects.get(device__name='Device 2', name='Interface 1')
|
||||
|
||||
# Validate connections
|
||||
self.assertEqual(endpoint_a.connected_endpoint, endpoint_b)
|
||||
self.assertEqual(endpoint_b.connected_endpoint, endpoint_a)
|
||||
self.assertTrue(endpoint_a.connection_status)
|
||||
self.assertTrue(endpoint_b.connection_status)
|
||||
|
||||
# Delete circuit
|
||||
circuit = Circuit.objects.first().delete()
|
||||
|
||||
# Refresh endpoints
|
||||
endpoint_a.refresh_from_db()
|
||||
endpoint_b.refresh_from_db()
|
||||
|
||||
# Check that connections have been nullified
|
||||
self.assertIsNone(endpoint_a.connected_endpoint)
|
||||
self.assertIsNone(endpoint_b.connected_endpoint)
|
||||
self.assertIsNone(endpoint_a.connection_status)
|
||||
self.assertIsNone(endpoint_b.connection_status)
|
||||
|
||||
@@ -46,13 +46,14 @@ class RegionTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
|
||||
'name': 'Region X',
|
||||
'slug': 'region-x',
|
||||
'parent': regions[2].pk,
|
||||
'description': 'A new region',
|
||||
}
|
||||
|
||||
cls.csv_data = (
|
||||
"name,slug",
|
||||
"Region 4,region-4",
|
||||
"Region 5,region-5",
|
||||
"Region 6,region-6",
|
||||
"name,slug,description",
|
||||
"Region 4,region-4,Fourth region",
|
||||
"Region 5,region-5,Fifth region",
|
||||
"Region 6,region-6,Sixth region",
|
||||
)
|
||||
|
||||
|
||||
@@ -122,23 +123,26 @@ class RackGroupTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
|
||||
site = Site(name='Site 1', slug='site-1')
|
||||
site.save()
|
||||
|
||||
RackGroup.objects.bulk_create([
|
||||
rack_groups = (
|
||||
RackGroup(name='Rack Group 1', slug='rack-group-1', site=site),
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=site),
|
||||
RackGroup(name='Rack Group 3', slug='rack-group-3', site=site),
|
||||
])
|
||||
)
|
||||
for rackgroup in rack_groups:
|
||||
rackgroup.save()
|
||||
|
||||
cls.form_data = {
|
||||
'name': 'Rack Group X',
|
||||
'slug': 'rack-group-x',
|
||||
'site': site.pk,
|
||||
'description': 'A new rack group',
|
||||
}
|
||||
|
||||
cls.csv_data = (
|
||||
"site,name,slug",
|
||||
"Site 1,Rack Group 4,rack-group-4",
|
||||
"Site 1,Rack Group 5,rack-group-5",
|
||||
"Site 1,Rack Group 6,rack-group-6",
|
||||
"site,name,slug,description",
|
||||
"Site 1,Rack Group 4,rack-group-4,Fourth rack group",
|
||||
"Site 1,Rack Group 5,rack-group-5,Fifth rack group",
|
||||
"Site 1,Rack Group 6,rack-group-6,Sixth rack group",
|
||||
)
|
||||
|
||||
|
||||
@@ -172,10 +176,6 @@ class RackRoleTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
|
||||
class RackReservationTestCase(ViewTestCases.PrimaryObjectViewTestCase):
|
||||
model = RackReservation
|
||||
|
||||
# Disable inapplicable tests
|
||||
test_get_object = None
|
||||
test_create_object = None
|
||||
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
|
||||
@@ -231,7 +231,8 @@ class RackTestCase(ViewTestCases.PrimaryObjectViewTestCase):
|
||||
RackGroup(name='Rack Group 1', slug='rack-group-1', site=sites[0]),
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1])
|
||||
)
|
||||
RackGroup.objects.bulk_create(rackgroups)
|
||||
for rackgroup in rackgroups:
|
||||
rackgroup.save()
|
||||
|
||||
rackroles = (
|
||||
RackRole(name='Rack Role 1', slug='rack-role-1'),
|
||||
@@ -306,13 +307,14 @@ class ManufacturerTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
|
||||
cls.form_data = {
|
||||
'name': 'Manufacturer X',
|
||||
'slug': 'manufacturer-x',
|
||||
'description': 'A new manufacturer',
|
||||
}
|
||||
|
||||
cls.csv_data = (
|
||||
"name,slug",
|
||||
"Manufacturer 4,manufacturer-4",
|
||||
"Manufacturer 5,manufacturer-5",
|
||||
"Manufacturer 6,manufacturer-6",
|
||||
"name,slug,description",
|
||||
"Manufacturer 4,manufacturer-4,Fourth manufacturer",
|
||||
"Manufacturer 5,manufacturer-5,Fifth manufacturer",
|
||||
"Manufacturer 6,manufacturer-6,Sixth manufacturer",
|
||||
)
|
||||
|
||||
|
||||
@@ -865,13 +867,14 @@ class PlatformTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
|
||||
'manufacturer': manufacturer.pk,
|
||||
'napalm_driver': 'junos',
|
||||
'napalm_args': None,
|
||||
'description': 'A new platform',
|
||||
}
|
||||
|
||||
cls.csv_data = (
|
||||
"name,slug",
|
||||
"Platform 4,platform-4",
|
||||
"Platform 5,platform-5",
|
||||
"Platform 6,platform-6",
|
||||
"name,slug,description",
|
||||
"Platform 4,platform-4,Fourth platform",
|
||||
"Platform 5,platform-5,Fifth platform",
|
||||
"Platform 6,platform-6,Sixth platform",
|
||||
)
|
||||
|
||||
|
||||
@@ -1333,37 +1336,37 @@ class RearPortTestCase(ViewTestCases.DeviceComponentViewTestCase):
|
||||
class DeviceBayTestCase(ViewTestCases.DeviceComponentViewTestCase):
|
||||
model = DeviceBay
|
||||
|
||||
# Disable inapplicable views
|
||||
test_bulk_edit_objects = None
|
||||
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
device1 = create_test_device('Device 1')
|
||||
device2 = create_test_device('Device 2')
|
||||
device = create_test_device('Device 1')
|
||||
|
||||
# Update the DeviceType subdevice role to allow adding DeviceBays
|
||||
DeviceType.objects.update(subdevice_role=SubdeviceRoleChoices.ROLE_PARENT)
|
||||
|
||||
DeviceBay.objects.bulk_create([
|
||||
DeviceBay(device=device1, name='Device Bay 1'),
|
||||
DeviceBay(device=device1, name='Device Bay 2'),
|
||||
DeviceBay(device=device1, name='Device Bay 3'),
|
||||
DeviceBay(device=device, name='Device Bay 1'),
|
||||
DeviceBay(device=device, name='Device Bay 2'),
|
||||
DeviceBay(device=device, name='Device Bay 3'),
|
||||
])
|
||||
|
||||
cls.form_data = {
|
||||
'device': device2.pk,
|
||||
'device': device.pk,
|
||||
'name': 'Device Bay X',
|
||||
'description': 'A device bay',
|
||||
'tags': 'Alpha,Bravo,Charlie',
|
||||
}
|
||||
|
||||
cls.bulk_create_data = {
|
||||
'device': device2.pk,
|
||||
'device': device.pk,
|
||||
'name_pattern': 'Device Bay [4-6]',
|
||||
'description': 'A device bay',
|
||||
'tags': 'Alpha,Bravo,Charlie',
|
||||
}
|
||||
|
||||
cls.bulk_edit_data = {
|
||||
'description': 'New description',
|
||||
}
|
||||
|
||||
cls.csv_data = (
|
||||
"device,name",
|
||||
"Device 1,Device Bay 4",
|
||||
@@ -1570,7 +1573,8 @@ class PowerPanelTestCase(ViewTestCases.PrimaryObjectViewTestCase):
|
||||
RackGroup(name='Rack Group 1', slug='rack-group-1', site=sites[0]),
|
||||
RackGroup(name='Rack Group 2', slug='rack-group-2', site=sites[1]),
|
||||
)
|
||||
RackGroup.objects.bulk_create(rackgroups)
|
||||
for rackgroup in rackgroups:
|
||||
rackgroup.save()
|
||||
|
||||
PowerPanel.objects.bulk_create((
|
||||
PowerPanel(site=sites[0], rack_group=rackgroups[0], name='Power Panel 1'),
|
||||
|
||||
@@ -2,7 +2,6 @@ from django.urls import path
|
||||
|
||||
from extras.views import ObjectChangeLogView, ImageAttachmentEditView
|
||||
from ipam.views import ServiceCreateView
|
||||
from secrets.views import secret_add
|
||||
from . import views
|
||||
from .models import (
|
||||
Cable, ConsolePort, ConsoleServerPort, Device, DeviceRole, DeviceType, FrontPort, Interface, Manufacturer, Platform,
|
||||
@@ -51,9 +50,11 @@ urlpatterns = [
|
||||
|
||||
# Rack reservations
|
||||
path('rack-reservations/', views.RackReservationListView.as_view(), name='rackreservation_list'),
|
||||
path('rack-reservations/add/', views.RackReservationCreateView.as_view(), name='rackreservation_add'),
|
||||
path('rack-reservations/import/', views.RackReservationImportView.as_view(), name='rackreservation_import'),
|
||||
path('rack-reservations/edit/', views.RackReservationBulkEditView.as_view(), name='rackreservation_bulk_edit'),
|
||||
path('rack-reservations/delete/', views.RackReservationBulkDeleteView.as_view(), name='rackreservation_bulk_delete'),
|
||||
path('rack-reservations/<int:pk>/', views.RackReservationView.as_view(), name='rackreservation'),
|
||||
path('rack-reservations/<int:pk>/edit/', views.RackReservationEditView.as_view(), name='rackreservation_edit'),
|
||||
path('rack-reservations/<int:pk>/delete/', views.RackReservationDeleteView.as_view(), name='rackreservation_delete'),
|
||||
path('rack-reservations/<int:pk>/changelog/', ObjectChangeLogView.as_view(), name='rackreservation_changelog', kwargs={'model': RackReservation}),
|
||||
@@ -69,7 +70,6 @@ urlpatterns = [
|
||||
path('racks/<int:pk>/edit/', views.RackEditView.as_view(), name='rack_edit'),
|
||||
path('racks/<int:pk>/delete/', views.RackDeleteView.as_view(), name='rack_delete'),
|
||||
path('racks/<int:pk>/changelog/', ObjectChangeLogView.as_view(), name='rack_changelog', kwargs={'model': Rack}),
|
||||
path('racks/<int:rack>/reservations/add/', views.RackReservationCreateView.as_view(), name='rack_add_reservation'),
|
||||
path('racks/<int:object_id>/images/add/', ImageAttachmentEditView.as_view(), name='rack_add_image', kwargs={'model': Rack}),
|
||||
|
||||
# Manufacturers
|
||||
@@ -179,7 +179,6 @@ urlpatterns = [
|
||||
path('devices/<int:pk>/status/', views.DeviceStatusView.as_view(), name='device_status'),
|
||||
path('devices/<int:pk>/lldp-neighbors/', views.DeviceLLDPNeighborsView.as_view(), name='device_lldp_neighbors'),
|
||||
path('devices/<int:pk>/config/', views.DeviceConfigView.as_view(), name='device_config'),
|
||||
path('devices/<int:pk>/add-secret/', secret_add, name='device_addsecret'),
|
||||
path('devices/<int:device>/services/assign/', ServiceCreateView.as_view(), name='device_service_assign'),
|
||||
path('devices/<int:object_id>/images/add/', ImageAttachmentEditView.as_view(), name='device_add_image', kwargs={'model': Device}),
|
||||
|
||||
@@ -285,7 +284,7 @@ urlpatterns = [
|
||||
path('device-bays/', views.DeviceBayListView.as_view(), name='devicebay_list'),
|
||||
path('device-bays/add/', views.DeviceBayCreateView.as_view(), name='devicebay_add'),
|
||||
path('device-bays/import/', views.DeviceBayBulkImportView.as_view(), name='devicebay_import'),
|
||||
# TODO: Bulk edit view for DeviceBays
|
||||
path('device-bays/edit/', views.DeviceBayBulkEditView.as_view(), name='devicebay_bulk_edit'),
|
||||
path('device-bays/rename/', views.DeviceBayBulkRenameView.as_view(), name='devicebay_bulk_rename'),
|
||||
path('device-bays/delete/', views.DeviceBayBulkDeleteView.as_view(), name='devicebay_bulk_delete'),
|
||||
path('device-bays/<int:pk>/edit/', views.DeviceBayEditView.as_view(), name='devicebay_edit'),
|
||||
|
||||
@@ -266,7 +266,13 @@ class SiteBulkDeleteView(PermissionRequiredMixin, BulkDeleteView):
|
||||
|
||||
class RackGroupListView(PermissionRequiredMixin, ObjectListView):
|
||||
permission_required = 'dcim.view_rackgroup'
|
||||
queryset = RackGroup.objects.prefetch_related('site').annotate(rack_count=Count('racks'))
|
||||
queryset = RackGroup.objects.add_related_count(
|
||||
RackGroup.objects.all(),
|
||||
Rack,
|
||||
'group',
|
||||
'rack_count',
|
||||
cumulative=True
|
||||
).prefetch_related('site')
|
||||
filterset = filters.RackGroupFilterSet
|
||||
filterset_form = forms.RackGroupFilterForm
|
||||
table = tables.RackGroupTable
|
||||
@@ -473,20 +479,32 @@ class RackReservationListView(PermissionRequiredMixin, ObjectListView):
|
||||
action_buttons = ('export',)
|
||||
|
||||
|
||||
class RackReservationView(PermissionRequiredMixin, View):
|
||||
permission_required = 'dcim.view_rackreservation'
|
||||
|
||||
def get(self, request, pk):
|
||||
|
||||
rackreservation = get_object_or_404(RackReservation.objects.prefetch_related('rack'), pk=pk)
|
||||
|
||||
return render(request, 'dcim/rackreservation.html', {
|
||||
'rackreservation': rackreservation,
|
||||
})
|
||||
|
||||
|
||||
class RackReservationCreateView(PermissionRequiredMixin, ObjectEditView):
|
||||
permission_required = 'dcim.add_rackreservation'
|
||||
model = RackReservation
|
||||
model_form = forms.RackReservationForm
|
||||
template_name = 'dcim/rackreservation_edit.html'
|
||||
default_return_url = 'dcim:rackreservation_list'
|
||||
|
||||
def alter_obj(self, obj, request, args, kwargs):
|
||||
if not obj.pk:
|
||||
obj.rack = get_object_or_404(Rack, pk=kwargs['rack'])
|
||||
if 'rack' in request.GET:
|
||||
obj.rack = get_object_or_404(Rack, pk=request.GET.get('rack'))
|
||||
obj.user = request.user
|
||||
return obj
|
||||
|
||||
def get_return_url(self, request, obj):
|
||||
return obj.rack.get_absolute_url()
|
||||
|
||||
|
||||
class RackReservationEditView(RackReservationCreateView):
|
||||
permission_required = 'dcim.change_rackreservation'
|
||||
@@ -495,9 +513,7 @@ class RackReservationEditView(RackReservationCreateView):
|
||||
class RackReservationDeleteView(PermissionRequiredMixin, ObjectDeleteView):
|
||||
permission_required = 'dcim.delete_rackreservation'
|
||||
model = RackReservation
|
||||
|
||||
def get_return_url(self, request, obj):
|
||||
return obj.rack.get_absolute_url()
|
||||
default_return_url = 'dcim:rackreservation_list'
|
||||
|
||||
|
||||
class RackReservationImportView(PermissionRequiredMixin, BulkImportView):
|
||||
@@ -1883,6 +1899,14 @@ class DeviceBayBulkImportView(PermissionRequiredMixin, BulkImportView):
|
||||
default_return_url = 'dcim:devicebay_list'
|
||||
|
||||
|
||||
class DeviceBayBulkEditView(PermissionRequiredMixin, BulkEditView):
|
||||
permission_required = 'dcim.change_devicebay'
|
||||
queryset = DeviceBay.objects.all()
|
||||
filterset = filters.DeviceBayFilterSet
|
||||
table = tables.DeviceBayTable
|
||||
form = forms.DeviceBayBulkEditForm
|
||||
|
||||
|
||||
class DeviceBayBulkRenameView(PermissionRequiredMixin, BulkRenameView):
|
||||
permission_required = 'dcim.change_devicebay'
|
||||
queryset = DeviceBay.objects.all()
|
||||
@@ -2009,7 +2033,7 @@ class CableTraceView(PermissionRequiredMixin, View):
|
||||
def get(self, request, model, pk):
|
||||
|
||||
obj = get_object_or_404(model, pk=pk)
|
||||
trace = obj.trace(follow_circuits=True)
|
||||
trace = obj.trace()
|
||||
total_length = sum([entry[1]._abs_length for entry in trace if entry[1] and entry[1]._abs_length])
|
||||
|
||||
return render(request, 'dcim/cable_trace.html', {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from django import forms
|
||||
from django.contrib import admin
|
||||
|
||||
from netbox.admin import admin_site
|
||||
from utilities.forms import LaxURLField
|
||||
from .models import CustomField, CustomFieldChoice, CustomLink, Graph, ExportTemplate, ReportResult, Webhook
|
||||
from .reports import get_report
|
||||
@@ -35,7 +34,7 @@ class WebhookForm(forms.ModelForm):
|
||||
order_content_types(self.fields['obj_type'])
|
||||
|
||||
|
||||
@admin.register(Webhook, site=admin_site)
|
||||
@admin.register(Webhook)
|
||||
class WebhookAdmin(admin.ModelAdmin):
|
||||
list_display = [
|
||||
'name', 'models', 'payload_url', 'http_content_type', 'enabled', 'type_create', 'type_update', 'type_delete',
|
||||
@@ -93,7 +92,7 @@ class CustomFieldChoiceAdmin(admin.TabularInline):
|
||||
extra = 5
|
||||
|
||||
|
||||
@admin.register(CustomField, site=admin_site)
|
||||
@admin.register(CustomField)
|
||||
class CustomFieldAdmin(admin.ModelAdmin):
|
||||
inlines = [CustomFieldChoiceAdmin]
|
||||
list_display = [
|
||||
@@ -135,7 +134,7 @@ class CustomLinkForm(forms.ModelForm):
|
||||
self.fields['content_type'].choices.insert(0, ('', '---------'))
|
||||
|
||||
|
||||
@admin.register(CustomLink, site=admin_site)
|
||||
@admin.register(CustomLink)
|
||||
class CustomLinkAdmin(admin.ModelAdmin):
|
||||
list_display = [
|
||||
'name', 'content_type', 'group_name', 'weight',
|
||||
@@ -150,7 +149,7 @@ class CustomLinkAdmin(admin.ModelAdmin):
|
||||
# Graphs
|
||||
#
|
||||
|
||||
@admin.register(Graph, site=admin_site)
|
||||
@admin.register(Graph)
|
||||
class GraphAdmin(admin.ModelAdmin):
|
||||
list_display = [
|
||||
'name', 'type', 'weight', 'template_language', 'source',
|
||||
@@ -178,7 +177,7 @@ class ExportTemplateForm(forms.ModelForm):
|
||||
self.fields['content_type'].choices.insert(0, ('', '---------'))
|
||||
|
||||
|
||||
@admin.register(ExportTemplate, site=admin_site)
|
||||
@admin.register(ExportTemplate)
|
||||
class ExportTemplateAdmin(admin.ModelAdmin):
|
||||
list_display = [
|
||||
'name', 'content_type', 'description', 'mime_type', 'file_extension',
|
||||
@@ -193,7 +192,7 @@ class ExportTemplateAdmin(admin.ModelAdmin):
|
||||
# Reports
|
||||
#
|
||||
|
||||
@admin.register(ReportResult, site=admin_site)
|
||||
@admin.register(ReportResult)
|
||||
class ReportResultAdmin(admin.ModelAdmin):
|
||||
list_display = [
|
||||
'report', 'active', 'created', 'user', 'passing',
|
||||
|
||||
@@ -20,7 +20,10 @@ class CustomFieldDefaultValues:
|
||||
"""
|
||||
Return a dictionary of all CustomFields assigned to the parent model and their default values.
|
||||
"""
|
||||
def __call__(self):
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, serializer_field):
|
||||
self.model = serializer_field.parent.Meta.model
|
||||
|
||||
# Retrieve the CustomFields for the parent model
|
||||
content_type = ContentType.objects.get_for_model(self.model)
|
||||
@@ -49,9 +52,6 @@ class CustomFieldDefaultValues:
|
||||
|
||||
return value
|
||||
|
||||
def set_context(self, serializer_field):
|
||||
self.model = serializer_field.parent.Meta.model
|
||||
|
||||
|
||||
class CustomFieldsSerializer(serializers.BaseSerializer):
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from extras.constants import *
|
||||
from extras.models import (
|
||||
ConfigContext, ExportTemplate, Graph, ImageAttachment, ObjectChange, ReportResult, Tag,
|
||||
)
|
||||
from extras.utils import FeatureQuery
|
||||
from tenancy.api.nested_serializers import NestedTenantSerializer, NestedTenantGroupSerializer
|
||||
from tenancy.models import Tenant, TenantGroup
|
||||
from users.api.nested_serializers import NestedUserSerializer
|
||||
@@ -31,7 +32,7 @@ from .nested_serializers import *
|
||||
|
||||
class GraphSerializer(ValidatedModelSerializer):
|
||||
type = ContentTypeField(
|
||||
queryset=ContentType.objects.filter(GRAPH_MODELS),
|
||||
queryset=ContentType.objects.filter(FeatureQuery('graphs').get_query()),
|
||||
)
|
||||
|
||||
class Meta:
|
||||
@@ -67,7 +68,7 @@ class RenderedGraphSerializer(serializers.ModelSerializer):
|
||||
|
||||
class ExportTemplateSerializer(ValidatedModelSerializer):
|
||||
content_type = ContentTypeField(
|
||||
queryset=ContentType.objects.filter(EXPORTTEMPLATE_MODELS),
|
||||
queryset=ContentType.objects.filter(FeatureQuery('export_templates').get_query()),
|
||||
)
|
||||
template_language = ChoiceField(
|
||||
choices=TemplateLanguageChoices,
|
||||
@@ -91,7 +92,7 @@ class TagSerializer(ValidatedModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = Tag
|
||||
fields = ['id', 'name', 'slug', 'color', 'comments', 'tagged_items']
|
||||
fields = ['id', 'name', 'slug', 'color', 'description', 'tagged_items']
|
||||
|
||||
|
||||
#
|
||||
|
||||
@@ -14,9 +14,6 @@ class ExtrasRootView(routers.APIRootView):
|
||||
router = routers.DefaultRouter()
|
||||
router.APIRootView = ExtrasRootView
|
||||
|
||||
# Field choices
|
||||
router.register('_choices', views.ExtrasFieldChoicesViewSet, basename='field-choice')
|
||||
|
||||
# Custom field choices
|
||||
router.register('_custom_field_choices', views.CustomFieldChoicesViewSet, basename='custom-field-choice')
|
||||
|
||||
|
||||
@@ -15,22 +15,10 @@ from extras.models import (
|
||||
)
|
||||
from extras.reports import get_report, get_reports
|
||||
from extras.scripts import get_script, get_scripts, run_script
|
||||
from utilities.api import FieldChoicesViewSet, IsAuthenticatedOrLoginNotRequired, ModelViewSet
|
||||
from utilities.api import IsAuthenticatedOrLoginNotRequired, ModelViewSet
|
||||
from . import serializers
|
||||
|
||||
|
||||
#
|
||||
# Field choices
|
||||
#
|
||||
|
||||
class ExtrasFieldChoicesViewSet(FieldChoicesViewSet):
|
||||
fields = (
|
||||
(serializers.ExportTemplateSerializer, ['template_language']),
|
||||
(serializers.GraphSerializer, ['type', 'template_language']),
|
||||
(serializers.ObjectChangeSerializer, ['action']),
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Custom field choices
|
||||
#
|
||||
|
||||
@@ -1,129 +1,3 @@
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
# Models which support custom fields
|
||||
CUSTOMFIELD_MODELS = Q(
|
||||
Q(app_label='circuits', model__in=[
|
||||
'circuit',
|
||||
'provider',
|
||||
]) |
|
||||
Q(app_label='dcim', model__in=[
|
||||
'device',
|
||||
'devicetype',
|
||||
'powerfeed',
|
||||
'rack',
|
||||
'site',
|
||||
]) |
|
||||
Q(app_label='ipam', model__in=[
|
||||
'aggregate',
|
||||
'ipaddress',
|
||||
'prefix',
|
||||
'service',
|
||||
'vlan',
|
||||
'vrf',
|
||||
]) |
|
||||
Q(app_label='secrets', model__in=[
|
||||
'secret',
|
||||
]) |
|
||||
Q(app_label='tenancy', model__in=[
|
||||
'tenant',
|
||||
]) |
|
||||
Q(app_label='virtualization', model__in=[
|
||||
'cluster',
|
||||
'virtualmachine',
|
||||
])
|
||||
)
|
||||
|
||||
# Custom links
|
||||
CUSTOMLINK_MODELS = Q(
|
||||
Q(app_label='circuits', model__in=[
|
||||
'circuit',
|
||||
'provider',
|
||||
]) |
|
||||
Q(app_label='dcim', model__in=[
|
||||
'cable',
|
||||
'device',
|
||||
'devicetype',
|
||||
'powerpanel',
|
||||
'powerfeed',
|
||||
'rack',
|
||||
'site',
|
||||
]) |
|
||||
Q(app_label='ipam', model__in=[
|
||||
'aggregate',
|
||||
'ipaddress',
|
||||
'prefix',
|
||||
'service',
|
||||
'vlan',
|
||||
'vrf',
|
||||
]) |
|
||||
Q(app_label='secrets', model__in=[
|
||||
'secret',
|
||||
]) |
|
||||
Q(app_label='tenancy', model__in=[
|
||||
'tenant',
|
||||
]) |
|
||||
Q(app_label='virtualization', model__in=[
|
||||
'cluster',
|
||||
'virtualmachine',
|
||||
])
|
||||
)
|
||||
|
||||
# Models which can have Graphs associated with them
|
||||
GRAPH_MODELS = Q(
|
||||
Q(app_label='circuits', model__in=[
|
||||
'provider',
|
||||
]) |
|
||||
Q(app_label='dcim', model__in=[
|
||||
'device',
|
||||
'interface',
|
||||
'site',
|
||||
])
|
||||
)
|
||||
|
||||
# Models which support export templates
|
||||
EXPORTTEMPLATE_MODELS = Q(
|
||||
Q(app_label='circuits', model__in=[
|
||||
'circuit',
|
||||
'provider',
|
||||
]) |
|
||||
Q(app_label='dcim', model__in=[
|
||||
'cable',
|
||||
'consoleport',
|
||||
'device',
|
||||
'devicetype',
|
||||
'interface',
|
||||
'inventoryitem',
|
||||
'manufacturer',
|
||||
'powerpanel',
|
||||
'powerport',
|
||||
'powerfeed',
|
||||
'rack',
|
||||
'rackgroup',
|
||||
'region',
|
||||
'site',
|
||||
'virtualchassis',
|
||||
]) |
|
||||
Q(app_label='ipam', model__in=[
|
||||
'aggregate',
|
||||
'ipaddress',
|
||||
'prefix',
|
||||
'service',
|
||||
'vlan',
|
||||
'vrf',
|
||||
]) |
|
||||
Q(app_label='secrets', model__in=[
|
||||
'secret',
|
||||
]) |
|
||||
Q(app_label='tenancy', model__in=[
|
||||
'tenant',
|
||||
]) |
|
||||
Q(app_label='virtualization', model__in=[
|
||||
'cluster',
|
||||
'virtualmachine',
|
||||
])
|
||||
)
|
||||
|
||||
# Report logging levels
|
||||
LOG_DEFAULT = 0
|
||||
LOG_SUCCESS = 10
|
||||
@@ -138,51 +12,14 @@ LOG_LEVEL_CODES = {
|
||||
LOG_FAILURE: 'failure',
|
||||
}
|
||||
|
||||
# Webhook content types
|
||||
HTTP_CONTENT_TYPE_JSON = 'application/json'
|
||||
|
||||
# Models which support registered webhooks
|
||||
WEBHOOK_MODELS = Q(
|
||||
Q(app_label='circuits', model__in=[
|
||||
'circuit',
|
||||
'provider',
|
||||
]) |
|
||||
Q(app_label='dcim', model__in=[
|
||||
'cable',
|
||||
'consoleport',
|
||||
'consoleserverport',
|
||||
'device',
|
||||
'devicebay',
|
||||
'devicetype',
|
||||
'frontport',
|
||||
'interface',
|
||||
'inventoryitem',
|
||||
'manufacturer',
|
||||
'poweroutlet',
|
||||
'powerpanel',
|
||||
'powerport',
|
||||
'powerfeed',
|
||||
'rack',
|
||||
'rearport',
|
||||
'region',
|
||||
'site',
|
||||
'virtualchassis',
|
||||
]) |
|
||||
Q(app_label='ipam', model__in=[
|
||||
'aggregate',
|
||||
'ipaddress',
|
||||
'prefix',
|
||||
'service',
|
||||
'vlan',
|
||||
'vrf',
|
||||
]) |
|
||||
Q(app_label='secrets', model__in=[
|
||||
'secret',
|
||||
]) |
|
||||
Q(app_label='tenancy', model__in=[
|
||||
'tenant',
|
||||
]) |
|
||||
Q(app_label='virtualization', model__in=[
|
||||
'cluster',
|
||||
'virtualmachine',
|
||||
])
|
||||
)
|
||||
# Registerable extras features
|
||||
EXTRAS_FEATURES = [
|
||||
'custom_fields',
|
||||
'custom_links',
|
||||
'graphs',
|
||||
'export_templates',
|
||||
'webhooks'
|
||||
]
|
||||
|
||||
@@ -144,12 +144,11 @@ class CustomFieldFilterForm(forms.Form):
|
||||
|
||||
class TagForm(BootstrapMixin, forms.ModelForm):
|
||||
slug = SlugField()
|
||||
comments = CommentField()
|
||||
|
||||
class Meta:
|
||||
model = Tag
|
||||
fields = [
|
||||
'name', 'slug', 'color', 'comments'
|
||||
'name', 'slug', 'color', 'description'
|
||||
]
|
||||
|
||||
|
||||
@@ -181,9 +180,13 @@ class TagBulkEditForm(BootstrapMixin, BulkEditForm):
|
||||
required=False,
|
||||
widget=ColorSelect()
|
||||
)
|
||||
description = forms.CharField(
|
||||
max_length=200,
|
||||
required=False
|
||||
)
|
||||
|
||||
class Meta:
|
||||
nullable_fields = []
|
||||
nullable_fields = ['description']
|
||||
|
||||
|
||||
#
|
||||
@@ -198,60 +201,36 @@ class ConfigContextForm(BootstrapMixin, forms.ModelForm):
|
||||
)
|
||||
sites = DynamicModelMultipleChoiceField(
|
||||
queryset=Site.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/sites/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
roles = DynamicModelMultipleChoiceField(
|
||||
queryset=DeviceRole.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/device-roles/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
platforms = DynamicModelMultipleChoiceField(
|
||||
queryset=Platform.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/platforms/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
cluster_groups = DynamicModelMultipleChoiceField(
|
||||
queryset=ClusterGroup.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/virtualization/cluster-groups/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
clusters = DynamicModelMultipleChoiceField(
|
||||
queryset=Cluster.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/virtualization/clusters/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
tenant_groups = DynamicModelMultipleChoiceField(
|
||||
queryset=TenantGroup.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/tenancy/tenant-groups/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
tenants = DynamicModelMultipleChoiceField(
|
||||
queryset=Tenant.objects.all(),
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/tenancy/tenants/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
tags = DynamicModelMultipleChoiceField(
|
||||
queryset=Tag.objects.all(),
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/extras/tags/"
|
||||
)
|
||||
required=False
|
||||
)
|
||||
data = JSONField(
|
||||
label=''
|
||||
@@ -299,7 +278,6 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/regions/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -308,7 +286,6 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/sites/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -317,7 +294,6 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/device-roles/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -326,7 +302,6 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/dcim/platforms/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -335,24 +310,19 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/virtualization/cluster-groups/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
cluster_id = DynamicModelMultipleChoiceField(
|
||||
queryset=Cluster.objects.all(),
|
||||
required=False,
|
||||
label='Cluster',
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/virtualization/clusters/",
|
||||
)
|
||||
label='Cluster'
|
||||
)
|
||||
tenant_group = DynamicModelMultipleChoiceField(
|
||||
queryset=TenantGroup.objects.all(),
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/tenancy/tenant-groups/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -361,7 +331,6 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/tenancy/tenants/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -370,7 +339,6 @@ class ConfigContextFilterForm(BootstrapMixin, forms.Form):
|
||||
to_field_name='slug',
|
||||
required=False,
|
||||
widget=APISelectMultiple(
|
||||
api_url="/api/extras/tags/",
|
||||
value_field="slug",
|
||||
)
|
||||
)
|
||||
@@ -467,7 +435,8 @@ class ScriptForm(BootstrapMixin, forms.Form):
|
||||
self.fields['_commit'].initial = False
|
||||
|
||||
# Move _commit to the end of the form
|
||||
self.fields.move_to_end('_commit', True)
|
||||
commit = self.fields.pop('_commit')
|
||||
self.fields['_commit'] = commit
|
||||
|
||||
@property
|
||||
def requires_input(self):
|
||||
|
||||
16
netbox/extras/management/commands/rqworker.py
Normal file
16
netbox/extras/management/commands/rqworker.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from django.conf import settings
|
||||
from django_rq.management.commands.rqworker import Command as _Command
|
||||
|
||||
|
||||
class Command(_Command):
|
||||
"""
|
||||
Subclass django_rq's built-in rqworker to listen on all configured queues if none are specified (instead
|
||||
of only the 'default' queue).
|
||||
"""
|
||||
def handle(self, *args, **options):
|
||||
|
||||
# If no queues have been specified on the command line, listen on all configured queues.
|
||||
if len(args) < 1:
|
||||
args = settings.RQ_QUEUES
|
||||
|
||||
super().handle(*args, **options)
|
||||
85
netbox/extras/management/commands/webhook_receiver.py
Normal file
85
netbox/extras/management/commands/webhook_receiver.py
Normal file
@@ -0,0 +1,85 @@
|
||||
import sys
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
|
||||
request_counter = 1
|
||||
|
||||
|
||||
class WebhookHandler(BaseHTTPRequestHandler):
|
||||
show_headers = True
|
||||
|
||||
def __getattr__(self, item):
|
||||
|
||||
# Return the same method for any type of HTTP request (GET, POST, etc.)
|
||||
if item.startswith('do_'):
|
||||
return self.do_ANY
|
||||
|
||||
raise AttributeError
|
||||
|
||||
def log_message(self, format_str, *args):
|
||||
global request_counter
|
||||
|
||||
print("[{}] {} {} {}".format(
|
||||
request_counter,
|
||||
self.date_time_string(),
|
||||
self.address_string(),
|
||||
format_str % args
|
||||
))
|
||||
|
||||
def do_ANY(self):
|
||||
global request_counter
|
||||
|
||||
# Send a 200 response regardless of the request content
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b'Webhook received!\n')
|
||||
|
||||
request_counter += 1
|
||||
|
||||
# Print the request headers to stdout
|
||||
if self.show_headers:
|
||||
for k, v in self.headers.items():
|
||||
print('{}: {}'.format(k, v))
|
||||
print()
|
||||
|
||||
# Print the request body (if any)
|
||||
content_length = self.headers.get('Content-Length')
|
||||
if content_length is not None:
|
||||
body = self.rfile.read(int(content_length))
|
||||
print(body.decode('utf-8'))
|
||||
else:
|
||||
print('(No body)')
|
||||
|
||||
print('------------')
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Start a simple listener to display received HTTP requests"
|
||||
|
||||
default_port = 9000
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
'--port', type=int, default=self.default_port,
|
||||
help="Optional port number (default: {})".format(self.default_port)
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-headers", action='store_true', dest='no_headers',
|
||||
help="Hide HTTP request headers"
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
port = options['port']
|
||||
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
|
||||
|
||||
WebhookHandler.show_headers = not options['no_headers']
|
||||
|
||||
self.stdout.write('Listening on port http://localhost:{}. Stop with {}.'.format(port, quit_command))
|
||||
httpd = HTTPServer(('localhost', port), WebhookHandler)
|
||||
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
self.stdout.write("\nExiting...")
|
||||
@@ -0,0 +1,40 @@
|
||||
# Generated by Django 2.2.11 on 2020-03-14 06:50
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import extras.utils
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('extras', '0038_webhook_template_support'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='customfield',
|
||||
name='obj_type',
|
||||
field=models.ManyToManyField(limit_choices_to=extras.utils.FeatureQuery('custom_fields'), related_name='custom_fields', to='contenttypes.ContentType'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='customlink',
|
||||
name='content_type',
|
||||
field=models.ForeignKey(limit_choices_to=extras.utils.FeatureQuery('custom_links'), on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='exporttemplate',
|
||||
name='content_type',
|
||||
field=models.ForeignKey(limit_choices_to=extras.utils.FeatureQuery('export_templates'), on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='graph',
|
||||
name='type',
|
||||
field=models.ForeignKey(limit_choices_to=extras.utils.FeatureQuery('graphs'), on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='webhook',
|
||||
name='obj_type',
|
||||
field=models.ManyToManyField(limit_choices_to=extras.utils.FeatureQuery('webhooks'), related_name='webhooks', to='contenttypes.ContentType'),
|
||||
),
|
||||
]
|
||||
23
netbox/extras/migrations/0040_standardize_description.py
Normal file
23
netbox/extras/migrations/0040_standardize_description.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.0.3 on 2020-03-13 20:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('extras', '0039_update_features_content_types'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='configcontext',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='customfield',
|
||||
name='description',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
]
|
||||
23
netbox/extras/migrations/0041_tag_description.py
Normal file
23
netbox/extras/migrations/0041_tag_description.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 3.0.3 on 2020-03-13 20:46
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('extras', '0040_standardize_description'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='tag',
|
||||
name='comments',
|
||||
field=models.CharField(blank=True, max_length=200),
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='tag',
|
||||
old_name='comments',
|
||||
new_name='description',
|
||||
),
|
||||
]
|
||||
@@ -22,6 +22,7 @@ from utilities.utils import deepmerge, render_jinja2
|
||||
from .choices import *
|
||||
from .constants import *
|
||||
from .querysets import ConfigContextQuerySet
|
||||
from .utils import FeatureQuery
|
||||
|
||||
|
||||
__all__ = (
|
||||
@@ -58,7 +59,7 @@ class Webhook(models.Model):
|
||||
to=ContentType,
|
||||
related_name='webhooks',
|
||||
verbose_name='Object types',
|
||||
limit_choices_to=WEBHOOK_MODELS,
|
||||
limit_choices_to=FeatureQuery('webhooks'),
|
||||
help_text="The object(s) to which this Webhook applies."
|
||||
)
|
||||
name = models.CharField(
|
||||
@@ -223,7 +224,7 @@ class CustomField(models.Model):
|
||||
to=ContentType,
|
||||
related_name='custom_fields',
|
||||
verbose_name='Object(s)',
|
||||
limit_choices_to=CUSTOMFIELD_MODELS,
|
||||
limit_choices_to=FeatureQuery('custom_fields'),
|
||||
help_text='The object(s) to which this field applies.'
|
||||
)
|
||||
type = models.CharField(
|
||||
@@ -242,7 +243,7 @@ class CustomField(models.Model):
|
||||
'the field\'s name will be used)'
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
required = models.BooleanField(
|
||||
@@ -470,7 +471,7 @@ class CustomLink(models.Model):
|
||||
content_type = models.ForeignKey(
|
||||
to=ContentType,
|
||||
on_delete=models.CASCADE,
|
||||
limit_choices_to=CUSTOMLINK_MODELS
|
||||
limit_choices_to=FeatureQuery('custom_links')
|
||||
)
|
||||
name = models.CharField(
|
||||
max_length=100,
|
||||
@@ -518,7 +519,7 @@ class Graph(models.Model):
|
||||
type = models.ForeignKey(
|
||||
to=ContentType,
|
||||
on_delete=models.CASCADE,
|
||||
limit_choices_to=GRAPH_MODELS
|
||||
limit_choices_to=FeatureQuery('graphs')
|
||||
)
|
||||
weight = models.PositiveSmallIntegerField(
|
||||
default=1000
|
||||
@@ -550,7 +551,6 @@ class Graph(models.Model):
|
||||
def embed_url(self, obj):
|
||||
context = {'obj': obj}
|
||||
|
||||
# TODO: Remove in v2.8
|
||||
if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
|
||||
template = Template(self.source)
|
||||
return template.render(Context(context))
|
||||
@@ -564,7 +564,6 @@ class Graph(models.Model):
|
||||
|
||||
context = {'obj': obj}
|
||||
|
||||
# TODO: Remove in v2.8
|
||||
if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
|
||||
template = Template(self.link)
|
||||
return template.render(Context(context))
|
||||
@@ -581,7 +580,7 @@ class ExportTemplate(models.Model):
|
||||
content_type = models.ForeignKey(
|
||||
to=ContentType,
|
||||
on_delete=models.CASCADE,
|
||||
limit_choices_to=EXPORTTEMPLATE_MODELS
|
||||
limit_choices_to=FeatureQuery('export_templates')
|
||||
)
|
||||
name = models.CharField(
|
||||
max_length=100
|
||||
@@ -766,7 +765,7 @@ class ConfigContext(models.Model):
|
||||
default=1000
|
||||
)
|
||||
description = models.CharField(
|
||||
max_length=100,
|
||||
max_length=200,
|
||||
blank=True
|
||||
)
|
||||
is_active = models.BooleanField(
|
||||
@@ -1053,9 +1052,9 @@ class Tag(TagBase, ChangeLoggedModel):
|
||||
color = ColorField(
|
||||
default='9e9e9e'
|
||||
)
|
||||
comments = models.TextField(
|
||||
description = models.CharField(
|
||||
max_length=200,
|
||||
blank=True,
|
||||
default=''
|
||||
)
|
||||
|
||||
def get_absolute_url(self):
|
||||
|
||||
250
netbox/extras/plugins/__init__.py
Normal file
250
netbox/extras/plugins/__init__.py
Normal file
@@ -0,0 +1,250 @@
|
||||
import collections
|
||||
import inspect
|
||||
from packaging import version
|
||||
|
||||
from django.apps import AppConfig
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
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 = []
|
||||
|
||||
# Cacheops configuration. Cache all operations by default.
|
||||
caching_config = {
|
||||
'*': {'ops': 'all'},
|
||||
}
|
||||
|
||||
# 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
|
||||
|
||||
@classmethod
|
||||
def validate(cls, user_config):
|
||||
|
||||
# Enforce version constraints
|
||||
current_version = version.parse(settings.VERSION)
|
||||
if cls.min_version is not None:
|
||||
min_version = version.parse(cls.min_version)
|
||||
if current_version < min_version:
|
||||
raise ImproperlyConfigured(
|
||||
f"Plugin {cls.__module__} requires NetBox minimum version {cls.min_version}."
|
||||
)
|
||||
if cls.max_version is not None:
|
||||
max_version = version.parse(cls.max_version)
|
||||
if current_version > max_version:
|
||||
raise ImproperlyConfigured(
|
||||
f"Plugin {cls.__module__} requires NetBox maximum version {cls.max_version}."
|
||||
)
|
||||
|
||||
# Verify required configuration settings
|
||||
for setting in cls.required_settings:
|
||||
if setting not in user_config:
|
||||
raise ImproperlyConfigured(
|
||||
f"Plugin {cls.__module__} requires '{setting}' to be present in the PLUGINS_CONFIG section of "
|
||||
f"configuration.py."
|
||||
)
|
||||
|
||||
# Apply default configuration values
|
||||
for setting, value in cls.default_settings.items():
|
||||
if setting not in user_config:
|
||||
user_config[setting] = value
|
||||
|
||||
|
||||
#
|
||||
# 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
|
||||
42
netbox/extras/plugins/urls.py
Normal file
42
netbox/extras/plugins/urls.py
Normal file
@@ -0,0 +1,42 @@
|
||||
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_path in settings.PLUGINS:
|
||||
plugin_name = plugin_path.split('.')[-1]
|
||||
app = apps.get_app_config(plugin_name)
|
||||
base_url = getattr(app, 'base_url') or app.label
|
||||
|
||||
# Check if the plugin specifies any base URLs
|
||||
try:
|
||||
urlpatterns = import_string(f"{plugin_path}.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_path}.api.urls.urlpatterns")
|
||||
plugin_api_patterns.append(
|
||||
path(f"{base_url}/", include((urlpatterns, f"{app.label}-api")))
|
||||
)
|
||||
except ImportError:
|
||||
pass
|
||||
93
netbox/extras/plugins/views.py
Normal file
93
netbox/extras/plugins/views.py
Normal 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
|
||||
)))
|
||||
21
netbox/extras/registry.py
Normal file
21
netbox/extras/registry.py
Normal file
@@ -0,0 +1,21 @@
|
||||
class Registry(dict):
|
||||
"""
|
||||
Central registry for registration of functionality. Once a store (key) is defined, it cannot be overwritten or
|
||||
deleted (although its value may be manipulated).
|
||||
"""
|
||||
def __getitem__(self, key):
|
||||
try:
|
||||
return super().__getitem__(key)
|
||||
except KeyError:
|
||||
raise KeyError("Invalid store: {}".format(key))
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key in self:
|
||||
raise KeyError("Store already set: {}".format(key))
|
||||
super().__setitem__(key, value)
|
||||
|
||||
def __delitem__(self, key):
|
||||
raise TypeError("Cannot delete stores from registry")
|
||||
|
||||
|
||||
registry = Registry()
|
||||
@@ -1,5 +1,6 @@
|
||||
import importlib
|
||||
import inspect
|
||||
import logging
|
||||
import pkgutil
|
||||
from collections import OrderedDict
|
||||
|
||||
@@ -91,6 +92,8 @@ class Report(object):
|
||||
self.active_test = None
|
||||
self.failed = False
|
||||
|
||||
self.logger = logging.getLogger(f"netbox.reports.{self.module}.{self.name}")
|
||||
|
||||
# Compile test methods and initialize results skeleton
|
||||
test_methods = []
|
||||
for method in dir(self):
|
||||
@@ -138,6 +141,7 @@ class Report(object):
|
||||
Log a message which is not associated with a particular object.
|
||||
"""
|
||||
self._log(None, message, level=LOG_DEFAULT)
|
||||
self.logger.info(message)
|
||||
|
||||
def log_success(self, obj, message=None):
|
||||
"""
|
||||
@@ -146,6 +150,7 @@ class Report(object):
|
||||
if message:
|
||||
self._log(obj, message, level=LOG_SUCCESS)
|
||||
self._results[self.active_test]['success'] += 1
|
||||
self.logger.info(f"Success | {obj}: {message}")
|
||||
|
||||
def log_info(self, obj, message):
|
||||
"""
|
||||
@@ -153,6 +158,7 @@ class Report(object):
|
||||
"""
|
||||
self._log(obj, message, level=LOG_INFO)
|
||||
self._results[self.active_test]['info'] += 1
|
||||
self.logger.info(f"Info | {obj}: {message}")
|
||||
|
||||
def log_warning(self, obj, message):
|
||||
"""
|
||||
@@ -160,6 +166,7 @@ class Report(object):
|
||||
"""
|
||||
self._log(obj, message, level=LOG_WARNING)
|
||||
self._results[self.active_test]['warning'] += 1
|
||||
self.logger.info(f"Warning | {obj}: {message}")
|
||||
|
||||
def log_failure(self, obj, message):
|
||||
"""
|
||||
@@ -167,12 +174,15 @@ class Report(object):
|
||||
"""
|
||||
self._log(obj, message, level=LOG_FAILURE)
|
||||
self._results[self.active_test]['failure'] += 1
|
||||
self.logger.info(f"Failure | {obj}: {message}")
|
||||
self.failed = True
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Run the report and return its results. Each test method will be executed in order.
|
||||
"""
|
||||
self.logger.info(f"Running report")
|
||||
|
||||
for method_name in self.test_methods:
|
||||
self.active_test = method_name
|
||||
test_method = getattr(self, method_name)
|
||||
@@ -184,6 +194,11 @@ class Report(object):
|
||||
result.save()
|
||||
self.result = result
|
||||
|
||||
if self.failed:
|
||||
self.logger.warning("Report failed")
|
||||
else:
|
||||
self.logger.info("Report completed successfully")
|
||||
|
||||
# Perform any post-run tasks
|
||||
self.post_run()
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pkgutil
|
||||
import time
|
||||
@@ -18,6 +19,7 @@ from ipam.formfields import IPAddressFormField, IPNetworkFormField
|
||||
from ipam.validators import MaxPrefixLengthValidator, MinPrefixLengthValidator, prefix_validator
|
||||
from .constants import LOG_DEFAULT, LOG_FAILURE, LOG_INFO, LOG_SUCCESS, LOG_WARNING
|
||||
from utilities.exceptions import AbortTransaction
|
||||
from utilities.forms import DynamicModelChoiceField, DynamicModelMultipleChoiceField
|
||||
from .forms import ScriptForm
|
||||
from .signals import purge_changelog
|
||||
|
||||
@@ -167,7 +169,7 @@ class ObjectVar(ScriptVariable):
|
||||
"""
|
||||
NetBox object representation. The provided QuerySet will determine the choices available.
|
||||
"""
|
||||
form_field = forms.ModelChoiceField
|
||||
form_field = DynamicModelChoiceField
|
||||
|
||||
def __init__(self, queryset, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
@@ -184,7 +186,7 @@ class MultiObjectVar(ScriptVariable):
|
||||
"""
|
||||
Like ObjectVar, but can represent one or more objects.
|
||||
"""
|
||||
form_field = forms.ModelMultipleChoiceField
|
||||
form_field = DynamicModelMultipleChoiceField
|
||||
|
||||
def __init__(self, queryset, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
@@ -254,6 +256,7 @@ class BaseScript:
|
||||
def __init__(self):
|
||||
|
||||
# Initiate the log
|
||||
self.logger = logging.getLogger(f"netbox.scripts.{self.module()}.{self.__class__.__name__}")
|
||||
self.log = []
|
||||
|
||||
# Declare the placeholder for the current request
|
||||
@@ -301,18 +304,23 @@ class BaseScript:
|
||||
# Logging
|
||||
|
||||
def log_debug(self, message):
|
||||
self.logger.log(logging.DEBUG, message)
|
||||
self.log.append((LOG_DEFAULT, message))
|
||||
|
||||
def log_success(self, message):
|
||||
self.logger.log(logging.INFO, message) # No syslog equivalent for SUCCESS
|
||||
self.log.append((LOG_SUCCESS, message))
|
||||
|
||||
def log_info(self, message):
|
||||
self.logger.log(logging.INFO, message)
|
||||
self.log.append((LOG_INFO, message))
|
||||
|
||||
def log_warning(self, message):
|
||||
self.logger.log(logging.WARNING, message)
|
||||
self.log.append((LOG_WARNING, message))
|
||||
|
||||
def log_failure(self, message):
|
||||
self.logger.log(logging.ERROR, message)
|
||||
self.log.append((LOG_FAILURE, message))
|
||||
|
||||
# Convenience functions
|
||||
@@ -375,6 +383,10 @@ def run_script(script, data, request, commit=True):
|
||||
start_time = None
|
||||
end_time = None
|
||||
|
||||
script_name = script.__class__.__name__
|
||||
logger = logging.getLogger(f"netbox.scripts.{script.module()}.{script_name}")
|
||||
logger.info(f"Running script (commit={commit})")
|
||||
|
||||
# Add files to form data
|
||||
files = request.FILES
|
||||
for field_name, fileobj in files.items():
|
||||
@@ -404,6 +416,7 @@ def run_script(script, data, request, commit=True):
|
||||
script.log_failure(
|
||||
"An exception occurred: `{}: {}`\n```\n{}\n```".format(type(e).__name__, e, stacktrace)
|
||||
)
|
||||
logger.error(f"Exception raised during script execution: {e}")
|
||||
commit = False
|
||||
finally:
|
||||
if not commit:
|
||||
@@ -416,6 +429,7 @@ def run_script(script, data, request, commit=True):
|
||||
# Calculate execution time
|
||||
if end_time is not None:
|
||||
execution_time = end_time - start_time
|
||||
logger.info(f"Script completed in {execution_time:.4f} seconds")
|
||||
else:
|
||||
execution_time = None
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ class TagTable(BaseTable):
|
||||
|
||||
class Meta(BaseTable.Meta):
|
||||
model = Tag
|
||||
fields = ('pk', 'name', 'items', 'slug', 'color', 'actions')
|
||||
fields = ('pk', 'name', 'items', 'slug', 'color', 'description', 'actions')
|
||||
|
||||
|
||||
class TaggedItemTable(BaseTable):
|
||||
|
||||
73
netbox/extras/templatetags/plugins.py
Normal file
73
netbox/extras/templatetags/plugins.py
Normal 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)
|
||||
17
netbox/extras/tests/dummy_plugin/__init__.py
Normal file
17
netbox/extras/tests/dummy_plugin/__init__.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from extras.plugins import PluginConfig
|
||||
|
||||
|
||||
class DummyPluginConfig(PluginConfig):
|
||||
name = 'extras.tests.dummy_plugin'
|
||||
verbose_name = 'Dummy plugin'
|
||||
version = '0.0'
|
||||
description = 'For testing purposes only'
|
||||
base_url = 'dummy-plugin'
|
||||
min_version = '1.0'
|
||||
max_version = '9.0'
|
||||
middleware = [
|
||||
'extras.tests.dummy_plugin.middleware.DummyMiddleware'
|
||||
]
|
||||
|
||||
|
||||
config = DummyPluginConfig
|
||||
9
netbox/extras/tests/dummy_plugin/admin.py
Normal file
9
netbox/extras/tests/dummy_plugin/admin.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from netbox.admin import admin_site
|
||||
from .models import DummyModel
|
||||
|
||||
|
||||
@admin.register(DummyModel, site=admin_site)
|
||||
class DummyModelAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'number')
|
||||
9
netbox/extras/tests/dummy_plugin/api/serializers.py
Normal file
9
netbox/extras/tests/dummy_plugin/api/serializers.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from rest_framework.serializers import ModelSerializer
|
||||
from extras.tests.dummy_plugin.models import DummyModel
|
||||
|
||||
|
||||
class DummySerializer(ModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = DummyModel
|
||||
fields = ('id', 'name', 'number')
|
||||
6
netbox/extras/tests/dummy_plugin/api/urls.py
Normal file
6
netbox/extras/tests/dummy_plugin/api/urls.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from rest_framework import routers
|
||||
from .views import DummyViewSet
|
||||
|
||||
router = routers.DefaultRouter()
|
||||
router.register('dummy-models', DummyViewSet)
|
||||
urlpatterns = router.urls
|
||||
8
netbox/extras/tests/dummy_plugin/api/views.py
Normal file
8
netbox/extras/tests/dummy_plugin/api/views.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from rest_framework.viewsets import ModelViewSet
|
||||
from extras.tests.dummy_plugin.models import DummyModel
|
||||
from .serializers import DummySerializer
|
||||
|
||||
|
||||
class DummyViewSet(ModelViewSet):
|
||||
queryset = DummyModel.objects.all()
|
||||
serializer_class = DummySerializer
|
||||
7
netbox/extras/tests/dummy_plugin/middleware.py
Normal file
7
netbox/extras/tests/dummy_plugin/middleware.py
Normal file
@@ -0,0 +1,7 @@
|
||||
class DummyMiddleware:
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
return self.get_response(request)
|
||||
23
netbox/extras/tests/dummy_plugin/migrations/0001_initial.py
Normal file
23
netbox/extras/tests/dummy_plugin/migrations/0001_initial.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='DummyModel',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
|
||||
('name', models.CharField(max_length=20)),
|
||||
('number', models.IntegerField(default=100)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['name'],
|
||||
},
|
||||
),
|
||||
]
|
||||
13
netbox/extras/tests/dummy_plugin/models.py
Normal file
13
netbox/extras/tests/dummy_plugin/models.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class DummyModel(models.Model):
|
||||
name = models.CharField(
|
||||
max_length=20
|
||||
)
|
||||
number = models.IntegerField(
|
||||
default=100
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ['name']
|
||||
25
netbox/extras/tests/dummy_plugin/navigation.py
Normal file
25
netbox/extras/tests/dummy_plugin/navigation.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from extras.plugins import PluginMenuButton, PluginMenuItem
|
||||
|
||||
|
||||
menu_items = (
|
||||
PluginMenuItem(
|
||||
link='plugins:dummy_plugin:dummy_models',
|
||||
link_text='Item 1',
|
||||
buttons=(
|
||||
PluginMenuButton(
|
||||
link='admin:dummy_plugin_dummymodel_add',
|
||||
title='Add a new dummy model',
|
||||
icon_class='fa fa-plus',
|
||||
),
|
||||
PluginMenuButton(
|
||||
link='admin:dummy_plugin_dummymodel_add',
|
||||
title='Add a new dummy model',
|
||||
icon_class='fa fa-plus',
|
||||
),
|
||||
)
|
||||
),
|
||||
PluginMenuItem(
|
||||
link='plugins:dummy_plugin:dummy_models',
|
||||
link_text='Item 2',
|
||||
),
|
||||
)
|
||||
20
netbox/extras/tests/dummy_plugin/template_content.py
Normal file
20
netbox/extras/tests/dummy_plugin/template_content.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from extras.plugins import PluginTemplateExtension
|
||||
|
||||
|
||||
class SiteContent(PluginTemplateExtension):
|
||||
model = 'dcim.site'
|
||||
|
||||
def left_page(self):
|
||||
return "SITE CONTENT - LEFT PAGE"
|
||||
|
||||
def right_page(self):
|
||||
return "SITE CONTENT - RIGHT PAGE"
|
||||
|
||||
def full_width_page(self):
|
||||
return "SITE CONTENT - FULL WIDTH PAGE"
|
||||
|
||||
def full_buttons(self):
|
||||
return "SITE CONTENT - BUTTONS"
|
||||
|
||||
|
||||
template_extensions = [SiteContent]
|
||||
8
netbox/extras/tests/dummy_plugin/urls.py
Normal file
8
netbox/extras/tests/dummy_plugin/urls.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
|
||||
urlpatterns = (
|
||||
path('models/', views.DummyModelsView.as_view(), name='dummy_models'),
|
||||
)
|
||||
11
netbox/extras/tests/dummy_plugin/views.py
Normal file
11
netbox/extras/tests/dummy_plugin/views.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from django.http import HttpResponse
|
||||
from django.views.generic import View
|
||||
|
||||
from .models import DummyModel
|
||||
|
||||
|
||||
class DummyModelsView(View):
|
||||
|
||||
def get(self, request):
|
||||
instance_count = DummyModel.objects.count()
|
||||
return HttpResponse(f"Instances: {instance_count}")
|
||||
@@ -7,12 +7,11 @@ from rest_framework import status
|
||||
|
||||
from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Platform, Rack, RackGroup, RackRole, Region, Site
|
||||
from extras.api.views import ScriptViewSet
|
||||
from extras.choices import *
|
||||
from extras.constants import GRAPH_MODELS
|
||||
from extras.models import ConfigContext, Graph, ExportTemplate, Tag
|
||||
from extras.scripts import BooleanVar, IntegerVar, Script, StringVar
|
||||
from extras.utils import FeatureQuery
|
||||
from tenancy.models import Tenant, TenantGroup
|
||||
from utilities.testing import APITestCase, choices_to_dict
|
||||
from utilities.testing import APITestCase
|
||||
|
||||
|
||||
class AppTest(APITestCase):
|
||||
@@ -24,27 +23,6 @@ class AppTest(APITestCase):
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_choices(self):
|
||||
|
||||
url = reverse('extras-api:field-choice-list')
|
||||
response = self.client.get(url, **self.header)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# ExportTemplate
|
||||
self.assertEqual(choices_to_dict(response.data.get('export-template:template_language')), TemplateLanguageChoices.as_dict())
|
||||
|
||||
# Graph
|
||||
content_types = ContentType.objects.filter(GRAPH_MODELS)
|
||||
graph_type_choices = {
|
||||
"{}.{}".format(ct.app_label, ct.model): ct.name for ct in content_types
|
||||
}
|
||||
self.assertEqual(choices_to_dict(response.data.get('graph:type')), graph_type_choices)
|
||||
self.assertEqual(choices_to_dict(response.data.get('graph:template_language')), TemplateLanguageChoices.as_dict())
|
||||
|
||||
# ObjectChange
|
||||
self.assertEqual(choices_to_dict(response.data.get('object-change:action')), ObjectChangeActionChoices.as_dict())
|
||||
|
||||
|
||||
class GraphTest(APITestCase):
|
||||
|
||||
@@ -402,8 +380,10 @@ class ConfigContextTest(APITestCase):
|
||||
role2 = DeviceRole.objects.create(name='Test Role 2', slug='test-role-2')
|
||||
platform1 = Platform.objects.create(name='Test Platform 1', slug='test-platform-1')
|
||||
platform2 = Platform.objects.create(name='Test Platform 2', slug='test-platform-2')
|
||||
tenantgroup1 = TenantGroup.objects.create(name='Test Tenant Group 1', slug='test-tenant-group-1')
|
||||
tenantgroup2 = TenantGroup.objects.create(name='Test Tenant Group 2', slug='test-tenant-group-2')
|
||||
tenantgroup1 = TenantGroup(name='Test Tenant Group 1', slug='test-tenant-group-1')
|
||||
tenantgroup1.save()
|
||||
tenantgroup2 = TenantGroup(name='Test Tenant Group 2', slug='test-tenant-group-2')
|
||||
tenantgroup2.save()
|
||||
tenant1 = Tenant.objects.create(name='Test Tenant 1', slug='test-tenant-1')
|
||||
tenant2 = Tenant.objects.create(name='Test Tenant 2', slug='test-tenant-2')
|
||||
tag1 = Tag.objects.create(name='Test Tag 1', slug='test-tag-1')
|
||||
|
||||
@@ -3,8 +3,8 @@ from django.test import TestCase
|
||||
|
||||
from dcim.models import DeviceRole, Platform, Region, Site
|
||||
from extras.choices import *
|
||||
from extras.constants import GRAPH_MODELS
|
||||
from extras.filters import *
|
||||
from extras.utils import FeatureQuery
|
||||
from extras.models import ConfigContext, ExportTemplate, Graph
|
||||
from tenancy.models import Tenant, TenantGroup
|
||||
from virtualization.models import Cluster, ClusterGroup, ClusterType
|
||||
@@ -18,7 +18,7 @@ class GraphTestCase(TestCase):
|
||||
def setUpTestData(cls):
|
||||
|
||||
# Get the first three available types
|
||||
content_types = ContentType.objects.filter(GRAPH_MODELS)[:3]
|
||||
content_types = ContentType.objects.filter(FeatureQuery('graphs').get_query())[:3]
|
||||
|
||||
graphs = (
|
||||
Graph(name='Graph 1', type=content_types[0], template_language=TemplateLanguageChoices.LANGUAGE_DJANGO, source='http://example.com/1'),
|
||||
@@ -32,11 +32,10 @@ class GraphTestCase(TestCase):
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
|
||||
def test_type(self):
|
||||
content_type = ContentType.objects.filter(GRAPH_MODELS).first()
|
||||
content_type = ContentType.objects.filter(FeatureQuery('graphs').get_query()).first()
|
||||
params = {'type': content_type.pk}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
|
||||
|
||||
# TODO: Remove in v2.8
|
||||
def test_template_language(self):
|
||||
params = {'template_language': TemplateLanguageChoices.LANGUAGE_JINJA2}
|
||||
self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
|
||||
@@ -128,7 +127,8 @@ class ConfigContextTestCase(TestCase):
|
||||
TenantGroup(name='Tenant Group 2', slug='tenant-group-2'),
|
||||
TenantGroup(name='Tenant Group 3', slug='tenant-group-3'),
|
||||
)
|
||||
TenantGroup.objects.bulk_create(tenant_groups)
|
||||
for tenantgroup in tenant_groups:
|
||||
tenantgroup.save()
|
||||
|
||||
tenants = (
|
||||
Tenant(name='Tenant 1', slug='tenant-1'),
|
||||
|
||||
136
netbox/extras/tests/test_plugins.py
Normal file
136
netbox/extras/tests/test_plugins.py
Normal file
@@ -0,0 +1,136 @@
|
||||
from unittest import skipIf
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.test import Client, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
|
||||
from extras.registry import registry
|
||||
from extras.tests.dummy_plugin import config as dummy_config
|
||||
|
||||
|
||||
@skipIf('extras.tests.dummy_plugin' not in settings.PLUGINS, "dummy_plugin not in settings.PLUGINS")
|
||||
class PluginTest(TestCase):
|
||||
|
||||
def test_config(self):
|
||||
|
||||
self.assertIn('extras.tests.dummy_plugin.DummyPluginConfig', settings.INSTALLED_APPS)
|
||||
|
||||
def test_models(self):
|
||||
from extras.tests.dummy_plugin.models import DummyModel
|
||||
|
||||
# Test saving an instance
|
||||
instance = DummyModel(name='Instance 1', number=100)
|
||||
instance.save()
|
||||
self.assertIsNotNone(instance.pk)
|
||||
|
||||
# Test deleting an instance
|
||||
instance.delete()
|
||||
self.assertIsNone(instance.pk)
|
||||
|
||||
def test_admin(self):
|
||||
|
||||
# Test admin view URL resolution
|
||||
url = reverse('admin:dummy_plugin_dummymodel_add')
|
||||
self.assertEqual(url, '/admin/dummy_plugin/dummymodel/add/')
|
||||
|
||||
def test_views(self):
|
||||
|
||||
# Test URL resolution
|
||||
url = reverse('plugins:dummy_plugin:dummy_models')
|
||||
self.assertEqual(url, '/plugins/dummy-plugin/models/')
|
||||
|
||||
# Test GET request
|
||||
client = Client()
|
||||
response = client.get(url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
|
||||
def test_api_views(self):
|
||||
|
||||
# Test URL resolution
|
||||
url = reverse('plugins-api:dummy_plugin-api:dummymodel-list')
|
||||
self.assertEqual(url, '/api/plugins/dummy-plugin/dummy-models/')
|
||||
|
||||
# Test GET request
|
||||
client = Client()
|
||||
response = client.get(url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_menu_items(self):
|
||||
"""
|
||||
Check that plugin MenuItems and MenuButtons are registered.
|
||||
"""
|
||||
self.assertIn('Dummy plugin', registry['plugin_menu_items'])
|
||||
menu_items = registry['plugin_menu_items']['Dummy plugin']
|
||||
self.assertEqual(len(menu_items), 2)
|
||||
self.assertEqual(len(menu_items[0].buttons), 2)
|
||||
|
||||
def test_template_extensions(self):
|
||||
"""
|
||||
Check that plugin TemplateExtensions are registered.
|
||||
"""
|
||||
from extras.tests.dummy_plugin.template_content import SiteContent
|
||||
|
||||
self.assertIn(SiteContent, registry['plugin_template_extensions']['dcim.site'])
|
||||
|
||||
def test_middleware(self):
|
||||
"""
|
||||
Check that plugin middleware is registered.
|
||||
"""
|
||||
self.assertIn('extras.tests.dummy_plugin.middleware.DummyMiddleware', settings.MIDDLEWARE)
|
||||
|
||||
def test_caching_config(self):
|
||||
"""
|
||||
Check that plugin caching configuration is registered.
|
||||
"""
|
||||
self.assertIn('extras.tests.dummy_plugin.*', settings.CACHEOPS)
|
||||
|
||||
@override_settings(VERSION='0.9')
|
||||
def test_min_version(self):
|
||||
"""
|
||||
Check enforcement of minimum NetBox version.
|
||||
"""
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
dummy_config.validate({})
|
||||
|
||||
@override_settings(VERSION='10.0')
|
||||
def test_max_version(self):
|
||||
"""
|
||||
Check enforcement of maximum NetBox version.
|
||||
"""
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
dummy_config.validate({})
|
||||
|
||||
def test_required_settings(self):
|
||||
"""
|
||||
Validate enforcement of required settings.
|
||||
"""
|
||||
class DummyConfigWithRequiredSettings(dummy_config):
|
||||
required_settings = ['foo']
|
||||
|
||||
# Validation should pass when all required settings are present
|
||||
DummyConfigWithRequiredSettings.validate({'foo': True})
|
||||
|
||||
# Validation should fail when a required setting is missing
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
DummyConfigWithRequiredSettings.validate({})
|
||||
|
||||
def test_default_settings(self):
|
||||
"""
|
||||
Validate population of default config settings.
|
||||
"""
|
||||
class DummyConfigWithDefaultSettings(dummy_config):
|
||||
default_settings = {
|
||||
'bar': 123,
|
||||
}
|
||||
|
||||
# Populate the default value if setting has not been specified
|
||||
user_config = {}
|
||||
DummyConfigWithDefaultSettings.validate(user_config)
|
||||
self.assertEqual(user_config['bar'], 123)
|
||||
|
||||
# Don't overwrite specified values
|
||||
user_config = {'bar': 456}
|
||||
DummyConfigWithDefaultSettings.validate(user_config)
|
||||
self.assertEqual(user_config['bar'], 456)
|
||||
33
netbox/extras/tests/test_registry.py
Normal file
33
netbox/extras/tests/test_registry.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from django.test import TestCase
|
||||
|
||||
from extras.registry import Registry
|
||||
|
||||
|
||||
class RegistryTest(TestCase):
|
||||
|
||||
def test_add_store(self):
|
||||
reg = Registry()
|
||||
reg['foo'] = 123
|
||||
|
||||
self.assertEqual(reg['foo'], 123)
|
||||
|
||||
def test_manipulate_store(self):
|
||||
reg = Registry()
|
||||
reg['foo'] = [1, 2]
|
||||
reg['foo'].append(3)
|
||||
|
||||
self.assertListEqual(reg['foo'], [1, 2, 3])
|
||||
|
||||
def test_overwrite_store(self):
|
||||
reg = Registry()
|
||||
reg['foo'] = 123
|
||||
|
||||
with self.assertRaises(KeyError):
|
||||
reg['foo'] = 456
|
||||
|
||||
def test_delete_store(self):
|
||||
reg = Registry()
|
||||
reg['foo'] = 123
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
del(reg['foo'])
|
||||
@@ -1,6 +1,13 @@
|
||||
import collections
|
||||
|
||||
from django.db.models import Q
|
||||
from django.utils.deconstruct import deconstructible
|
||||
from taggit.managers import _TaggableManager
|
||||
from utilities.querysets import DummyQuerySet
|
||||
|
||||
from extras.constants import EXTRAS_FEATURES
|
||||
from extras.registry import registry
|
||||
|
||||
|
||||
def is_taggable(obj):
|
||||
"""
|
||||
@@ -13,3 +20,46 @@ def is_taggable(obj):
|
||||
if isinstance(obj.tags, DummyQuerySet):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@deconstructible
|
||||
class FeatureQuery:
|
||||
"""
|
||||
Helper class that delays evaluation of the registry contents for the functionality store
|
||||
until it has been populated.
|
||||
"""
|
||||
def __init__(self, feature):
|
||||
self.feature = feature
|
||||
|
||||
def __call__(self):
|
||||
return self.get_query()
|
||||
|
||||
def get_query(self):
|
||||
"""
|
||||
Given an extras feature, return a Q object for content type lookup
|
||||
"""
|
||||
query = Q()
|
||||
for app_label, models in registry['model_features'][self.feature].items():
|
||||
query |= Q(app_label=app_label, model__in=models)
|
||||
|
||||
return query
|
||||
|
||||
|
||||
def extras_features(*features):
|
||||
"""
|
||||
Decorator used to register extras provided features to a model
|
||||
"""
|
||||
def wrapper(model_class):
|
||||
# Initialize the model_features store if not already defined
|
||||
if 'model_features' not in registry:
|
||||
registry['model_features'] = {
|
||||
f: collections.defaultdict(list) for f in EXTRAS_FEATURES
|
||||
}
|
||||
for feature in features:
|
||||
if feature in EXTRAS_FEATURES:
|
||||
app_label, model_name = model_class._meta.label_lower.split('.')
|
||||
registry['model_features'][feature][app_label].append(model_name)
|
||||
else:
|
||||
raise ValueError('{} is not a valid extras feature!'.format(feature))
|
||||
return model_class
|
||||
return wrapper
|
||||
|
||||
@@ -274,7 +274,7 @@ class ObjectChangeLogView(View):
|
||||
template.loader.get_template(base_template)
|
||||
object_var = model._meta.model_name
|
||||
except template.TemplateDoesNotExist:
|
||||
base_template = '_base.html'
|
||||
base_template = 'base.html'
|
||||
object_var = 'obj'
|
||||
|
||||
return render(request, 'extras/object_changelog.html', {
|
||||
|
||||
@@ -8,6 +8,7 @@ from extras.models import Webhook
|
||||
from utilities.api import get_serializer_for_model
|
||||
from .choices import *
|
||||
from .constants import *
|
||||
from .utils import FeatureQuery
|
||||
|
||||
|
||||
def generate_signature(request_body, secret):
|
||||
@@ -29,7 +30,7 @@ def enqueue_webhooks(instance, user, request_id, action):
|
||||
"""
|
||||
obj_type = ContentType.objects.get_for_model(instance.__class__)
|
||||
|
||||
webhook_models = ContentType.objects.filter(WEBHOOK_MODELS)
|
||||
webhook_models = ContentType.objects.filter(FeatureQuery('webhooks').get_query())
|
||||
if obj_type not in webhook_models:
|
||||
return
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ class RIRSerializer(ValidatedModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = RIR
|
||||
fields = ['id', 'name', 'slug', 'is_private', 'aggregate_count']
|
||||
fields = ['id', 'name', 'slug', 'is_private', 'description', 'aggregate_count']
|
||||
|
||||
|
||||
class AggregateSerializer(TaggitSerializer, CustomFieldModelSerializer):
|
||||
@@ -81,7 +81,7 @@ class VLANGroupSerializer(ValidatedModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = VLANGroup
|
||||
fields = ['id', 'name', 'slug', 'site', 'vlan_count']
|
||||
fields = ['id', 'name', 'slug', 'site', 'description', 'vlan_count']
|
||||
validators = []
|
||||
|
||||
def validate(self, data):
|
||||
@@ -154,6 +154,33 @@ class PrefixSerializer(TaggitSerializer, CustomFieldModelSerializer):
|
||||
read_only_fields = ['family']
|
||||
|
||||
|
||||
class PrefixLengthSerializer(serializers.Serializer):
|
||||
|
||||
prefix_length = serializers.IntegerField()
|
||||
|
||||
def to_internal_value(self, data):
|
||||
requested_prefix = data.get('prefix_length')
|
||||
if requested_prefix is None:
|
||||
raise serializers.ValidationError({
|
||||
'prefix_length': 'this field can not be missing'
|
||||
})
|
||||
if not isinstance(requested_prefix, int):
|
||||
raise serializers.ValidationError({
|
||||
'prefix_length': 'this field must be int type'
|
||||
})
|
||||
|
||||
prefix = self.context.get('prefix')
|
||||
if prefix.family == 4 and requested_prefix > 32:
|
||||
raise serializers.ValidationError({
|
||||
'prefix_length': 'Invalid prefix length ({}) for IPv4'.format((requested_prefix))
|
||||
})
|
||||
elif prefix.family == 6 and requested_prefix > 128:
|
||||
raise serializers.ValidationError({
|
||||
'prefix_length': 'Invalid prefix length ({}) for IPv6'.format((requested_prefix))
|
||||
})
|
||||
return data
|
||||
|
||||
|
||||
class AvailablePrefixSerializer(serializers.Serializer):
|
||||
"""
|
||||
Representation of a prefix which does not exist in the database.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user