Compare commits

..
22 Commits
Author SHA1 Message Date
Sven Luethi a5d163b4af modified: netbox_dns_bridge/catalog_zone_manager.py
modified:   netbox_dns_bridge/notify_handler.py
2026-07-11 01:44:21 +02:00
Sven Luethi f5791e94d5 modified: ../README.md
modified:   __init__.py
modified:   catalog_zone_manager.py
modified:   dns_server.py
modified:   notify_handler.py
Adding serial to notify messages to allow client to determine state.
2026-07-11 00:04:45 +02:00
Sven Luethi 3eb17187b4 modified: netbox_dns_bridge/__init__.py
modified:   netbox_dns_bridge/catalog_zone_manager.py
modified:   netbox_dns_bridge/notify_handler.py
2026-07-10 22:05:51 +02:00
Sven Luethi 5747b044b6 modified: catalog_zone_manager.py
modified:   management/commands/dns-export-zone.py
modified:   management/commands/dns-export-zones.py
modified:   management/commands/dns-transfer-endpoint.py
modified:   notify_handler.py
modified:   request_handler.py
Guard all db requests against broken database connections.
2026-07-10 17:10:19 +02:00
Sven Luthi d18e0fc262 Update README 2026-07-08 16:21:55 +02:00
Sven Luethi 2a89f4ae75 modified: netbox_dns_bridge/request_handler.py
modified:   netbox_dns_bridge/signals/netbox_dns_zones.py

1. On zone deletion the catalog zone serial was not incremented, causing clients
   not to delete the zone until another zone is created/modified. Fixed using
   post_delete signal.

2. Even with the notify_clients feature disabled, the client IPs were still
   being tracked. This disables the unnecessary behavior.

3. _track_seen_client function in DNSBaseRequestHandler did not have the 'self'
   reference parameter, causing calls to fail. Fixed.
2026-06-13 00:19:45 +02:00
Sven Luethi b78ae930e7 modified: README.md 2026-06-12 18:30:12 +02:00
Sven Luethi e89a6dfbd6 modified: README.md 2026-06-11 17:24:57 +02:00
Sven Luethi 73544a4335 modified: README.md
modified:   netbox_dns_bridge/notify_handler.py
modified:   netbox_dns_bridge/request_handler.py
modified:   netbox_dns_bridge/signals/netbox_dns_zones.py
Disable NOTIFY feature by default and add setting to enable it.
2026-06-11 16:33:47 +02:00
Sven Luethi cb4886f032 new file: .flake8
deleted:    pylint.conf
Switch to flake8 for code checking
2026-06-11 16:33:47 +02:00
Sven Luethi e5808b4a57 Merge branch 'main' into dev 2026-06-11 14:07:44 +02:00
Sven Luethi 547fe92b8b Merge pull request #23 from peteeckel/fix/active-record-zone-check
Replace explicit checks for STATUS_ACTIVE with the annotated "active" value
2026-06-11 10:39:13 +02:00
Peter Eckel 3f3426886e Replace explicit checks for STATUS_ACTIVE with the annotated "active" value 2026-06-11 10:11:19 +02:00
Sven Luethi 3eef3b4d7b modified: netbox_dns_bridge/__init__.py
modified:   netbox_dns_bridge/catalog_zone_manager.py
modified:   netbox_dns_bridge/dns_server.py
modified:   netbox_dns_bridge/logger.py
new file:   netbox_dns_bridge/migrations/0002_alter_integerkeyvaluesetting_options_and_more.py
modified:   netbox_dns_bridge/models.py
new file:   netbox_dns_bridge/notify_handler.py
modified:   netbox_dns_bridge/request_handler.py
modified:   netbox_dns_bridge/signals/__init__.py
new file:   netbox_dns_bridge/signals/netbox_dns_zones.py
deleted:    netbox_dns_bridge/signals/transfer_endpoint.py
modified:   netbox_dns_bridge/utils.py

Implement notify mechanism
2026-06-11 00:32:26 +02:00
Sven Luethi a4036c285c modified: netbox_dns_bridge/catalog_zone_manager.py
Move state to DB
2026-05-23 14:58:24 +02:00
Sven Luethi 1426ef2f70 modified: .gitignore
Update gitignore
2026-05-22 12:02:43 +02:00
sven ea1b5ee2b4 renamed: signals.py -> signals/transfer_endpoint.py
new file:   signals/__init__.py
2026-04-10 15:31:19 +02:00
sven 67ccf83b1c modified: netbox_dns_bridge/__init__.py
modified:   netbox_dns_bridge/catalog_zone_manager.py
modified:   netbox_dns_bridge/dns_server.py
new file:   netbox_dns_bridge/logger.py
modified:   netbox_dns_bridge/management/commands/dns-transfer-endpoint.py
modified:   netbox_dns_bridge/request_handler.py
Clean up logging
2026-04-10 15:08:10 +02:00
sven da6a5e09a5 modified: netbox_dns_bridge/__init__.py
Remove unneeded definition.

modified:   MANIFEST.in
Correct path

new file:   netbox_dns_bridge/migrations/__init__.py
Fixes missing migration.

new file:   netbox_dns_bridge/management/__init__.py
new file:   netbox_dns_bridge/management/commands/__init__.py
Just in case
2026-04-10 13:23:37 +02:00
Sven Luthi 3eb58f9b29 modified: docs/install-systemd-service.md
Correct naming in service unit
2026-04-10 11:16:58 +02:00
Sven Luthi ad52457c48 modified: README.md
Fix link alt text
2026-04-10 10:59:49 +02:00
Sven Luthi 9c3d7cce7e modified: README.md 2026-04-09 19:18:35 +02:00
24 changed files with 590 additions and 1011 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[flake8]
max-line-length = 100
+3 -1
View File
@@ -1,4 +1,6 @@
netbox_dns_bridge.egg-info
dist/ dist/
build/ build/
__pycache__ __pycache__
venv/
.venv/
netbox_plugin_dns_bridge.egg-info/
+1 -1
View File
@@ -1 +1 @@
recursive-include netbox_bind_provisioner *.py recursive-include netbox_dns_bridge *.py
+71 -58
View File
@@ -1,28 +1,22 @@
# Netbox DNS Bridge # NetBox DNS Bridge
(Formerly Netbox Bind Provisioner)
The NetBox DNS Bridge plugin extends [NetBox DNS](https://github.com/sys4/netbox-plugin-dns) by The NetBox DNS Bridge plugin extends [NetBox DNS](https://github.com/sys4/netbox-plugin-dns) by
embedding a lightweight DNS server directly within NetBox. It acts as a bridge between NetBox DNS embedding a lightweight DNS server directly within NetBox. It acts as a bridge between NetBox DNS
and your existing DNS infrastructure, leveraging native DNS mechanisms for seamless integration. and your existing DNS infrastructure, leveraging native DNS mechanisms for seamless integration.
These include zone transfers (RFC 5936), catalog zones (RFC 9432), and dynamic updates (RFC 2136). These include zone transfers (RFC 5936), catalog zones (RFC 9432), and notifying clients about zone
changes (RFC 1996).
<a href="https://pypi.org/project/netbox-plugin-dns-bridge/"><img src="https://img.shields.io/pypi/v/netbox-plugin-dns-bridge" alt="PyPi"></a> <a href="https://pypi.org/project/netbox-plugin-dns-bridge/"><img src="https://img.shields.io/pypi/v/netbox-plugin-dns-bridge" alt="PyPi"></a>
<a href="https://github.com/suraxius/netbox-plugin-bind-provisioner/stargazers"><img src="https://img.shields.io/github/stars/suraxius/netbox-plugin-bind-provisioner?style=flat" alt="Stars Badge"></a> <a href="https://github.com/suraxius/netbox-plugin-dns-bridge/stargazers"><img src="https://img.shields.io/github/stars/suraxius/netbox-plugin-dns-bridge?style=flat" alt="Stars Badge"></a>
<a href="https://github.com/suraxius/netbox-plugin-bind-provisioner/network/members"><img src="https://img.shields.io/github/forks/suraxius/netbox-plugin-bind-provisioner?style=flat" alt="Forks Badge"></a> <a href="https://github.com/suraxius/netbox-plugin-dns-bridge/network/members"><img src="https://img.shields.io/github/forks/suraxius/netbox-plugin-dns-bridge?style=flat" alt="Forks Badge"></a>
<a href="https://github.com/suraxius/netbox-plugin-bind-provisioner/issues"><img src="https://img.shields.io/github/issues/suraxius/netbox-plugin-bind-provisioner" alt="Issues Badge"></a> <a href="https://github.com/suraxius/netbox-plugin-dns-bridge/issues"><img src="https://img.shields.io/github/issues/suraxius/netbox-plugin-dns-bridge" alt="Issues Badge"></a>
<a href="https://github.com/suraxius/netbox-plugin-bind-provisioner/pulls"><img src="https://img.shields.io/github/issues-pr/suraxius/netbox-plugin-bind-provisioner" alt="Pull Requests Badge"></a> <a href="https://github.com/suraxius/netbox-plugin-dns-bridge/pulls"><img src="https://img.shields.io/github/issues-pr/suraxius/netbox-plugin-dns-bridge" alt="Pull Requests Badge"></a>
<a href="https://github.com/suraxius/netbox-plugin-bind-provisioner/graphs/contributors"><img src="https://img.shields.io/github/contributors/suraxius/netbox-plugin-bind-provisioner?color=2b9348" alt="GitHub contributors"></a> <a href="https://github.com/suraxius/netbox-plugin-dns-bridge/graphs/contributors"><img src="https://img.shields.io/github/contributors/suraxius/netbox-plugin-dns-bridge?color=2b9348" alt="GitHub contributors"></a>
<a href="https://github.com/suraxius/netbox-plugin-bind-provisioner/blob/master/LICENSE"><img src="https://img.shields.io/github/license/suraxius/netbox-plugin-bind-provisioner?color=2b9348" alt="License Badge"></a> <a href="https://github.com/suraxius/netbox-plugin-dns-bridge/blob/master/LICENSE"><img src="https://img.shields.io/github/license/suraxius/netbox-plugin-dns-bridge?color=2b9348" alt="License Badge"></a>
<a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code Style Black"></a> <a href="https://github.com/psf/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code Style Black"></a>
<a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=total&left_color=BLACK&right_color=BLUE&left_text=Downloads" alt="Downloads"></a> <a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=total&left_color=BLACK&right_color=BLUE&left_text=Downloads" alt="Downloads"></a>
<a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=monthly&left_color=BLACK&right_color=BLUE&left_text=Downloads%2fMonth" alt="Downloads/Week"></a> <a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=monthly&left_color=BLACK&right_color=BLUE&left_text=Downloads%2fMonth" alt="Downloads/Month"></a>
<a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=weekly&left_color=BLACK&right_color=BLUE&left_text=Downloads%2fWeek" alt="Downloads/Month"></a> <a href="https://pepy.tech/project/netbox-plugin-dns-bridge"><img src="https://static.pepy.tech/personalized-badge/netbox-plugin-dns-bridge?period=weekly&left_color=BLACK&right_color=BLUE&left_text=Downloads%2fWeek" alt="Downloads/Week"></a>
![Architecture Overview](docs/architecture-overview.svg)
DISCLAIMER: The dynamic update endpoint isn't here yet. Its planned - without a deadline.
## Plugin configuration ## Plugin configuration
While providing Zone transfers via AXFR, the Server also exposes specialized catalog zones that BIND While providing Zone transfers via AXFR, the Server also exposes specialized catalog zones that BIND
@@ -52,44 +46,61 @@ Parameter | Description
--address | IP of interface to bind to (defaults to 0.0.0.0) --address | IP of interface to bind to (defaults to 0.0.0.0)
### Plugin settings ### Plugin settings
Setting | Description Plugin settings should be configured under `PLUGINS_CONFIG` in `netbox_dns_bridge`:
--------------------| --------------------------------------------------------- ```
tsig_keys | Maps a TSIG Key to be used for each view. PLUGINS_CONFIG = {
'netbox_dns_bridge': {
...
...
}
}
```
#### TSIG Authentication
Following sets the TSIG key that allows clients to query the transfer endpoint and also they key to
be used to sign NOTIFY messages to clients on zone changes. Each view should have its own unique
key to allow the plugin to identify the view the client is trying to access. Re-using the key for
multiple views yields unpredicted behavior.
```
'tsig_keys': {
'the-view-name-here': {
'keyname': 'the-tsig-key-name-here',
'algorithm': 'hmac-sha256',
'secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
}
```
#### NOTIFY
Clients may be notified of zone changes using the NOTIFY mechanism defined in RFC 1996.
When enabled, the zone transfer endpoint keeps track of any client that successfully queried the
endpoint and when a zone changes. Once a zone has changed, NetBox informs each client of change.
Note that this feature uses NetBox's background job system to schedule the messages asynchronously.
In order to work, you need at least one `rq-worker` service running in the background to handle
the queried jobs.
To enable the NOTIFY feature, set following:
```
'notify_clients': True
```
##### NOTIFY Settings
```
notify_client_alive_threshold_hours: 24
```
This sets how long a client is considred "alive" after it last queried the transfer endpoint.
Once the client has failed to check in for this amout of time, it is automatically removed from the
list of clients to be notified on zone changes. Default is 24 hours.
```
notify_over_tcp: True
```
Switch to using TCP instead of UDP. Default: False
## Plugin compatibility ## Plugin compatibility
This plugin is an extension to the netbox-plugin-dns plugin. As such the versioning of this plugin This plugin extends the netbox-plugin-dns plugin. As such the versioning was changed to match the
was changed to match the one of the netbox-plugin-dns plugin closely. To guarantee compatability, one of netbox-plugin-dns more closely. To guarantee compatability, ensure that the major and minor
ensure that the major and minor version match between both plugins. version match between both plugins. For example, when using netbox-plugin-dns `v1.5.5` install
For example, when using netbox-plugin-dns `v1.5.5` install netbox-plugin-dns-bridge `v1.5.x`. netbox-plugin-dns-bridge `v1.5.x`.
## Post 1.0.7 Upgrade Guide
Applies only if you have a <= 1.0.7 installation. If you are freshly installing this plugin,
go on to [Installation Guide](#installation-guide).
After version 1.0.7, the project was restructured and renamed. Until that point version updates
happened more or less automatically. However, this shift is more of a move from one plugin to
another as the package name has changed.
This should not be an issue since the slave DNS Servers connected to Netbox can operate
independently while this plugin is being upgraded.
Make sure to note down the catalog zone serial number before going further.
1. Remove Netbox Bind Provisioner package
- Remove `netbox-plugin-bind-provisioner` from **local_dependencies.txt**
- Uninstall the package: `pip uninstall netbox-plugin-bind-provisioner`
2. Install Netbox DNS Bridge package
- Install the package `pip install netbox-plugin-dns-bridge`
- Put `netbox-plugin-dns-bridge` in your **local_dependencies.txt** so it will be installed on
next upgrade.
3. Adjust your `configuration.py`
- Change the plugin name from `netbox-plugin-bind-provisioner` to `netbox-plugin-dns-bridge`
- Change the key in `PLUGIN_CONFIG` from `netbox_plugin_bind_provisioner` to `netbox_dns_bridge`
4. Run migrations: `manage.py migrate`
5. Restore the catalog zone serial you noted down previously so that your slave dns servers continue
to pull the changes: `manage.py dns-settings set catalog-zone-soa-serial yourserialnumber`
6. Start the `dns-transfer-endpoint` service.
7. Mission accomplished.
## Installation guide ## Installation guide
This setup provisions a BIND9 server directly with DNS data from NetBox. BIND9 can optionally run on This setup provisions a BIND9 server directly with DNS data from NetBox. BIND9 can optionally run on
@@ -98,10 +109,10 @@ of the NetBox host. TCP and UDP traffic from the BIND9 server to the NetBox host
port 5354 (or the port you have configured). port 5354 (or the port you have configured).
This guide assumes: This guide assumes:
- Netbox has been installed under /opt/netbox - NetBox has been installed under /opt/netbox
- Bind9 is installed on the same host as Netbox - Bind9 is installed on the same host as NetBox
- The Netbox DNS Plugin netbox-plugin-dns is installed - The NetBox DNS Plugin netbox-plugin-dns is installed
- The following dns views exist in Netbox DNS: - The following dns views exist in NetBox DNS:
- `public` (the default) - `public` (the default)
- `private` - `private`
@@ -176,7 +187,7 @@ This guide assumes:
manage.py dns-transfer-endpoint --port 5354 manage.py dns-transfer-endpoint --port 5354
``` ```
6. Configuring a Bind9 to interact with Netbox via the dns-transfer-endpoint endpoint. Note that its 6. Configuring a Bind9 to interact with NetBox via the dns-transfer-endpoint endpoint. Note that its
not possible to give all the correct details of the `options` block as it is heavily dependent not possible to give all the correct details of the `options` block as it is heavily dependent
on the Operating System used. Please dont forget to adjust as required. on the Operating System used. Please dont forget to adjust as required.
@@ -222,6 +233,7 @@ This guide assumes:
########## ZONES ########## ########## ZONES ##########
view "public" { view "public" {
match-clients { public; }; match-clients { public; };
allow-notify { key "public_view_key"; };
catalog-zones { catalog-zones {
zone "catz" zone "catz"
@@ -240,6 +252,7 @@ This guide assumes:
view "private" { view "private" {
match-clients { private; }; match-clients { private; };
allow-notify { key "private_view_key"; };
catalog-zones { catalog-zones {
zone "catz" zone "catz"
+7 -7
View File
@@ -1,9 +1,9 @@
1. Create System Unit file 1. Create System Unit file
``` ```
cat <<EOF > /etc/systemd/system/netbox-bind-endpoint.service cat <<EOF > /etc/systemd/system/netbox-dns-endpoint.service
[Unit] [Unit]
Description=Netbox BIND Catalog Endpoing Description=Netbox DNS transfer endpoint
Documentation=https://github.com/Suraxius/netbox-plugin-bind-provisioner Documentation=https://github.com/Suraxius/netbox-plugin-dns-bridge
After=network-online.target After=network-online.target
Wants=network-online.target Wants=network-online.target
@@ -15,7 +15,7 @@
PIDFile=/var/tmp/netbox.pid PIDFile=/var/tmp/netbox.pid
WorkingDirectory=/opt/netbox WorkingDirectory=/opt/netbox
ExecStart=/opt/netbox/venv/bin/python3 /opt/netbox/netbox/manage.py dns-transfer-endpoint --port 5354 ExecStart=/opt/netbox/venv/bin/python3 /opt/netbox/netbox/manage.py dns-transfer-endpoint --address 0.0.0.0 --port 5354
Restart=on-failure Restart=on-failure
RestartSec=30 RestartSec=30
@@ -28,7 +28,7 @@
2. Enable and start the service 2. Enable and start the service
``` ```
systemctl enable netbox-bind-endpoint systemctl enable netbox-dns-endpoint
systemctl start netbox-bind-endpoint systemctl start netbox-dns-endpoint
systemctl status netbox-bind-endpoint systemctl status netbox-dns-endpoint
``` ```
+4 -11
View File
@@ -1,16 +1,10 @@
import logging
from netbox.plugins import PluginConfig from netbox.plugins import PluginConfig
from django.conf import settings from django.conf import settings
from .logger import get_logger
__version__ = "1.5.2" __version__ = "1.5.4"
logger = logging.getLogger(__name__) LOGGER = get_logger(__name__)
logging.basicConfig(
level=logging.DEBUG, # Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", # Log format
datefmt="%Y-%m-%d %H:%M:%S", # Date format for timestamps
)
class DNSBridgeConfig(PluginConfig): class DNSBridgeConfig(PluginConfig):
@@ -29,8 +23,7 @@ class DNSBridgeConfig(PluginConfig):
f"{self.name}: Plugin {self.verbose_name} failed to initialize due to missing settings. Terminating Netbox." f"{self.name}: Plugin {self.verbose_name} failed to initialize due to missing settings. Terminating Netbox."
) )
from . import signals as signals from . import signals
config = DNSBridgeConfig config = DNSBridgeConfig
default_app_config = ".apps.NetboxDNSBridgeConfig"
+150 -167
View File
@@ -1,75 +1,149 @@
import logging
import threading
import dns.query
import dns.message
import dns.tsigkeyring
import dns.name import dns.name
import dns.zone import dns.zone
import dns.rdatatype import dns.rdatatype
import dns.rdataclass import dns.rdataclass
import dns.rdtypes from .logger import get_logger
import dns.exception
import dns.renderer
from netbox_dns.models import Zone from netbox_dns.models import Zone
from netbox_dns.choices import ZoneStatusChoices
from netbox_dns_bridge.models import IntegerKeyValueSetting, CatalogZoneMemberIdentifier from netbox_dns_bridge.models import IntegerKeyValueSetting, CatalogZoneMemberIdentifier
from uuid import uuid4 from uuid import uuid4
from base64 import b32encode from base64 import b32encode
from django.db import transaction, close_old_connections, OperationalError
logger = logging.getLogger(__name__) LOGGER = get_logger(__name__)
_LOCK = threading.Lock()
_SERIAL_MAX = 0xFFFFFFFF
_SERIAL_OBJ = None
_PREVIOUS_LAST_ZONE_UPDATE = None
def init() -> None: def init() -> None:
_init_serial() _init_soa_serial()
_create_missing_member_identifiers() _create_missing_member_identifiers()
# Following function loads the last serial from the DB. No return value def increment_soa_serial() -> int:
# but it sets the setting "catalog_serial" or terminates the plugin on failure. with transaction.atomic():
def _init_serial() -> None: try:
global _SERIAL_OBJ soa_serial = IntegerKeyValueSetting.objects.select_for_update().get(
key="catalog-zone-soa-serial"
)
new_soa_serial = soa_serial.value + 1
if new_soa_serial > 0xFFFFFFFF:
LOGGER.warning(
f"Catalog serial {soa_serial.value} reached max — wrapping back to 1"
)
new_soa_serial = 1
soa_serial.value = new_soa_serial
soa_serial.save()
soa_serial.refresh_from_db()
LOGGER.debug(f"Catalog zone SOA serial number is now {soa_serial.value}")
return soa_serial.value
except OperationalError as e:
LOGGER.error(
f"ERROR: Failed to increment the Catalog Zone's SOA serial: {e}"
)
close_old_connections()
def create_zone(name, view_name) -> dns.zone.Zone:
# Zone origin
origin = dns.name.from_text(name, dns.name.root)
# Create a new empty zone
zone = dns.zone.Zone(origin)
zone.rdclass = dns.rdataclass.IN
try: try:
_SERIAL_OBJ = IntegerKeyValueSetting.objects.get(key="catalog-zone-soa-serial") # get zones from netbox
logger.debug( nb_zones = Zone.objects.filter(
f"Catalog zone SOA serial number {_SERIAL_OBJ.value} loaded from database" view__name=view_name, active=True
).select_related("catz_identifier")
ptr_base = dns.name.from_text("zones", origin)
for nb_zone in nb_zones:
ttl = 0
qname = dns.name.from_text(nb_zone.name, dns.name.root)
# Create PTR record
p_name = nb_zone.catz_identifier.name
ptr_name = dns.name.from_text(p_name, ptr_base)
if not ptr_name.is_subdomain(origin):
raise ValueError(
f"Catalog zone member identifier {ptr_name.to_text()} not a subdomain"
) )
rdata = dns.rdata.from_text(
dns.rdataclass.IN, dns.rdatatype.PTR, qname.to_text()
)
rdataset = zone.find_rdataset(ptr_name, dns.rdatatype.PTR, create=True)
rdataset.add(rdata, ttl)
# Configure DNSSec Policy for member Zone if DNSSec is enabled
if nb_zone.dnssec_policy:
rid = dns.name.from_text("group", ptr_name)
policy_name = nb_zone.dnssec_policy.name.rstrip(" ")
group_name = f"dnssec-policy-{policy_name}"
rdata = dns.rdata.from_text(
dns.rdataclass.IN, dns.rdatatype.TXT, group_name
)
rdataset = zone.find_rdataset(rid, dns.rdatatype.TXT, create=True)
rdataset.add(rdata, ttl)
zone_root_node = zone.find_node(origin, create=True)
# SOA record
soa_rdataset = _create_soa_rdataset()
zone_root_node.rdatasets.append(soa_rdataset)
# NS record
ns_rdataset = _create_ns_rdataset()
zone_root_node.rdatasets.append(ns_rdataset)
# version.catz. record
version_rdataset = _create_version_rdataset()
zone_version_node = zone.find_node(
dns.name.from_text("version", origin), create=True
)
zone_version_node.rdatasets.append(version_rdataset)
return zone
except OperationalError as e:
LOGGER.error(f"ERROR: Failed to create Catalog Zone: {e}")
close_old_connections()
return None
def _init_soa_serial() -> None:
try:
IntegerKeyValueSetting.objects.get(key="catalog-zone-soa-serial")
LOGGER.info("Catalog zone SOA serial number loaded from database")
except IntegerKeyValueSetting.DoesNotExist: except IntegerKeyValueSetting.DoesNotExist:
_SERIAL_OBJ = IntegerKeyValueSetting.objects.create( IntegerKeyValueSetting.objects.create(key="catalog-zone-soa-serial", value=1)
key="catalog-zone-soa-serial", value=1 LOGGER.debug(
"Catalog zone SOA serial number was not set in the database. Set to 1"
) )
logger.debug( except OperationalError as e:
f"Catalog zone SOA serial number was not set in the database. Set to {_SERIAL_OBJ.value}" LOGGER.error(f"ERROR: Failed to initialize the Catalog Zone's SOA serial: {e}")
close_old_connections()
def _generate_member_identifier() -> str:
return b32encode(uuid4().bytes)[0:26].lower().decode("UTF-8")
def update_member_identifier(zone: Zone) -> None:
try:
CatalogZoneMemberIdentifier.objects.update_or_create(
zone=zone,
defaults={"name": _generate_member_identifier()},
) )
except OperationalError as e:
LOGGER.error(f"ERROR: Failed to update Catalog Zone member identifier: {e}")
close_old_connections()
def _set_serial(new_serial: int) -> bool:
global _SERIAL_OBJ
if 0 < new_serial < _SERIAL_MAX:
_SERIAL_OBJ.value = new_serial
_SERIAL_OBJ.save()
return True
else:
return False
def _increment_serial() -> None:
if not _set_serial(_SERIAL_OBJ.value + 1):
logger.warning(
f"Catalog serial {_SERIAL_OBJ.value} reached max — wrapping back to 1"
)
_set_serial(1)
logger.debug(f"Catalog zone SOA serial number is now {_SERIAL_OBJ.value}")
# If a zone has no catz identifier yet, create it:
def _create_missing_member_identifiers() -> None: def _create_missing_member_identifiers() -> None:
try:
existing_zone_ids = CatalogZoneMemberIdentifier.objects.values_list( existing_zone_ids = CatalogZoneMemberIdentifier.objects.values_list(
"zone_id", flat=True "zone_id", flat=True
) )
@@ -85,8 +159,8 @@ def _create_missing_member_identifiers() -> None:
] ]
for identifier in new_objects: for identifier in new_objects:
logger.debug( LOGGER.debug(
f"Zone {identifier.zone} has no catz member identifier. Creating..." f"Zone {identifier.zone} missing catz member identifier. Creating..."
) )
CatalogZoneMemberIdentifier.objects.bulk_create( CatalogZoneMemberIdentifier.objects.bulk_create(
@@ -94,139 +168,48 @@ def _create_missing_member_identifiers() -> None:
ignore_conflicts=False, ignore_conflicts=False,
) )
except OperationalError as e:
LOGGER.error(f"ERROR: Could not create catz member identifier: {e}")
close_old_connections()
def create_zone(name, view_name) -> dns.zone.Zone:
global _PREVIOUS_LAST_ZONE_UPDATE
# Synchronize following across threads as TCP and UDP listener both use it.
with _LOCK:
latest_zone = (
Zone.objects.filter(status=ZoneStatusChoices.STATUS_ACTIVE)
.order_by("-last_updated")
.first()
)
last_zone_update = getattr(latest_zone, "last_updated", None) def _create_soa_rdataset() -> dns.rdataset:
try:
# Check if there was a zone updated since last call serial = IntegerKeyValueSetting.objects.get(key="catalog-zone-soa-serial").value
# If no zone was found previously then this will be false since (None != None) = False
if _PREVIOUS_LAST_ZONE_UPDATE != last_zone_update:
if last_zone_update is not None:
logger.debug(
f"Zone {latest_zone.name} was updated in view {latest_zone.view.name}"
)
# Setting previous last zone update for next iteration:
_PREVIOUS_LAST_ZONE_UPDATE = last_zone_update
_increment_serial()
# Zone origin
origin = dns.name.from_text(name, dns.name.root)
# Create a new empty zone
zone = dns.zone.Zone(origin)
zone.rdclass = dns.rdataclass.IN
# get zones from netbox
nb_zones = Zone.objects.filter(
view__name=view_name, status=ZoneStatusChoices.STATUS_ACTIVE
).select_related("catz_identifier")
ptr_base = dns.name.from_text("zones", origin)
for nb_zone in nb_zones:
ttl = 0
qname = dns.name.from_text(nb_zone.name, dns.name.root)
# Create PTR record
# p_name = f"zid-{nb_zone.id:09d}"
p_name = nb_zone.catz_identifier.name
ptr_name = dns.name.from_text(p_name, ptr_base)
if not ptr_name.is_subdomain(origin):
raise ValueError(
"Catalog zone member identifier {ptr_name.to_text()} not a subdomain"
)
rdata = dns.rdata.from_text(
dns.rdataclass.IN, dns.rdatatype.PTR, qname.to_text()
)
rdataset = zone.find_rdataset(ptr_name, dns.rdatatype.PTR, create=True)
rdataset.add(rdata, ttl)
# Configure DNSSec Policy for member Zone if DNSSec is enabled
if nb_zone.dnssec_policy:
# Configure policy
rid = dns.name.from_text("group", ptr_name)
policy_name = nb_zone.dnssec_policy.name.rstrip(" ")
group_name = f"dnssec-policy-{policy_name}"
rdata = dns.rdata.from_text(
dns.rdataclass.IN, dns.rdatatype.TXT, group_name
)
rdataset = zone.find_rdataset(rid, dns.rdatatype.TXT, create=True)
rdataset.add(rdata, ttl)
## Configure dnssec status for member zone
# status = str(1 if nb_zone.dnssec_policy else 0)
# rid = dns.name.from_text("enabled.dnssec.ext", ptr_name)
# rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT, status)
# rdataset = zone.find_rdataset(rid, dns.rdatatype.TXT, create=True)
# rdataset.add(rdata, ttl)
# SOA Record components # SOA Record components
ttl = 0 ttl = 0
rclass = dns.rdataclass.IN rclass = dns.rdataclass.IN
rtype = dns.rdatatype.SOA rtype = dns.rdatatype.SOA
mname = dns.name.from_text("invalid", dns.name.root)
rname = dns.name.from_text("invalid", dns.name.root)
serial = _SERIAL_OBJ.value
refresh = 60
retry = 10
expire = 1209600
minimum = 0
# Create SOA rdata object # Create SOA rdata object
soa_rdata = dns.rdata.from_text( rdata = dns.rdata.from_text(
rclass, rclass,
rtype, rtype,
f"{mname} {rname} {serial} {refresh} {retry} {expire} {minimum}", f"invalid. invalid. {serial} 60 10 1209600 0",
) )
# Create Rdataset and add the RDATA to it # Create Rdataset and add the RDATA to it
soa_rdataset = dns.rdataset.Rdataset(rclass, rtype) rdataset = dns.rdataset.Rdataset(rclass, rtype)
soa_rdataset.add(soa_rdata, ttl) rdataset.add(rdata, ttl)
return rdataset
# Add to the origin node in the zone except OperationalError as e:
node = zone.find_node(origin, create=True) LOGGER.error(f"ERROR: Failed to access catz SOA record in database: {e}")
node.rdatasets.append(soa_rdataset) close_old_connections()
def _create_ns_rdataset() -> dns.rdataset:
# NS record for catz. # NS record for catz.
ns_name = dns.name.from_text("invalid", dns.name.root) name = dns.name.from_text("invalid", dns.name.root)
ns_rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.NS, str(ns_name)) rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.NS, str(name))
ns_rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.NS) rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.NS)
ns_rdataset.add(ns_rdata, 0) rdataset.add(rdata, 0)
return rdataset
# Add to node (catz. is the origin)
ns_node = zone.find_node(origin, create=True)
ns_node.rdatasets.append(ns_rdataset)
# TXT record for version.catz.
version_name = dns.name.from_text("version", origin) # relative to origin "catz."
txt_rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT, '"2"')
txt_rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.TXT)
txt_rdataset.add(txt_rdata, 0)
# Add to node version.catz.
txt_node = zone.find_node(version_name, create=True)
txt_node.rdatasets.append(txt_rdataset)
return zone
def _generate_member_identifier() -> None: def _create_version_rdataset() -> dns.rdataset:
return b32encode(uuid4().bytes)[0:26].lower().decode("UTF-8") rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT, '"2"')
rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN, dns.rdatatype.TXT)
rdataset.add(rdata, 0)
def update_member_identifier(zone: Zone) -> None: return rdataset
CatalogZoneMemberIdentifier.objects.update_or_create(
zone=zone,
defaults={"name": _generate_member_identifier()},
)
+2 -2
View File
@@ -1,8 +1,8 @@
import logging
import socketserver import socketserver
import socket import socket
from .logger import get_logger
logger = logging.getLogger(__name__) LOGGER = get_logger(__name__)
class DNSAddressMixin: class DNSAddressMixin:
+12
View File
@@ -0,0 +1,12 @@
import logging
PLUGIN_NAME = "dns-bridge"
def get_logger(name: str) -> logging.Logger:
# name = name.replace("_","-").rsplit(".", 1)[-1]
#
# if name.startswith(PLUGIN_NAME):
# return logging.getLogger(name)
# return logging.getLogger(f"{PLUGIN_NAME}.{name}")
return logging.getLogger(f"{PLUGIN_NAME}")
Whitespace-only changes.
Whitespace-only changes.
@@ -1,8 +1,3 @@
import os
import dns.zone
import dns.rdatatype
import dns.rdataclass
import dns.exception
import netbox_dns.models import netbox_dns.models
from netbox_dns_bridge.utils import export_bind_zone_file from netbox_dns_bridge.utils import export_bind_zone_file
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
@@ -24,10 +19,6 @@ class Command(BaseCommand):
) )
def handle(self, *args, **options): def handle(self, *args, **options):
# if len(options) < 2:
# print("export-zone <zone name> <file path>")
# sys.exit(1)
# Load parameters # Load parameters
view_name = options["view"] view_name = options["view"]
zone_name = options["zone"] zone_name = options["zone"]
@@ -48,13 +39,11 @@ class Command(BaseCommand):
if nb_zone: if nb_zone:
export_bind_zone_file(nb_zone, file_path=file_path) export_bind_zone_file(nb_zone, file_path=file_path)
else:
print("Zone not found in Netbox. Aborting")
sys.exit(1)
except Exception as e:
raise CommandError(f"Failed to export zone: {e}")
self.stdout.write( self.stdout.write(
self.style.SUCCESS(f"Zone '{zone_name}' exported to '{file_path}'") self.style.SUCCESS(f"Zone '{zone_name}' exported to '{file_path}'")
) )
else:
self.stderr.write("Zone not found in Netbox. Aborting")
except Exception as e:
raise CommandError(f"Failed to export zone: {e}")
@@ -1,8 +1,4 @@
import os import os
import dns.zone
import dns.rdatatype
import dns.rdataclass
import dns.exception
import netbox_dns.models import netbox_dns.models
from netbox_dns_bridge.utils import export_bind_zone_file from netbox_dns_bridge.utils import export_bind_zone_file
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
@@ -1,4 +1,3 @@
import logging
import threading import threading
import dns.query import dns.query
import dns.message import dns.message
@@ -13,31 +12,21 @@ import dns.renderer
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.conf import settings from django.conf import settings
from django.db import close_old_connections, OperationalError
from netbox_dns.models import View from netbox_dns.models import View
from netbox_dns_bridge import catalog_zone_manager as catzm
from netbox_dns_bridge.request_handler import UDPRequestHandler, TCPRequestHandler from netbox_dns_bridge.request_handler import UDPRequestHandler, TCPRequestHandler
from netbox_dns_bridge.dns_server import UDPDNSServer, TCPDNSServer from netbox_dns_bridge.dns_server import UDPDNSServer, TCPDNSServer
from netbox_dns_bridge import catalog_zone_manager as catzm from netbox_dns_bridge.logger import get_logger
from netbox_dns_bridge.models import IntegerKeyValueSetting
logger = logging.getLogger(__name__) LOGGER = get_logger(__name__)
SETTINGS = settings.PLUGINS_CONFIG.get("netbox_dns_bridge", {})
class Command(BaseCommand): class Command(BaseCommand):
help = "Run a minimal AXFR DNS server using data from NetBox DNS plugin" help = "Run a minimal AXFR DNS server using data from NetBox DNS plugin"
def load_settings(self): def _load_tsig_key_settings(self):
self.settings = settings.PLUGINS_CONFIG.get("netbox_dns_bridge", None)
if not self.settings:
raise RuntimeError(
"Command failed to initialize due to missing settings. Terminating Netbox."
)
self.tsig_keys = self.settings.get("tsig_keys", None)
if not self.tsig_keys:
raise RuntimeError("tsig_keys variable not set in plugin settings.")
# Load TSIG keys and map them to views
def load_tsig_key_settings(self):
self.keyring = {} self.keyring = {}
self.tsig_view_map = {} self.tsig_view_map = {}
@@ -47,7 +36,7 @@ class Command(BaseCommand):
algorithm_str = data.get("algorithm", "hmac-sha256") algorithm_str = data.get("algorithm", "hmac-sha256")
if not raw_key_name or not secret: if not raw_key_name or not secret:
logger.error( LOGGER.error(
f"Skipping TSIG key for view {view_name}: missing keyname or secret." f"Skipping TSIG key for view {view_name}: missing keyname or secret."
) )
continue continue
@@ -55,10 +44,12 @@ class Command(BaseCommand):
try: try:
nb_view = View.objects.get(name=view_name) nb_view = View.objects.get(name=view_name)
except View.DoesNotExist: except View.DoesNotExist:
logger.error( LOGGER.error(
f"Skipping TSIG key {raw_key_name}: view '{view_name}' not found." f"Skipping TSIG key {raw_key_name}: view '{view_name}' not found."
) )
continue continue
except OperationalError:
close_old_connections()
# Normalize key name to absolute DNS name # Normalize key name to absolute DNS name
key_name_obj = dns.name.from_text(raw_key_name, origin=None).canonicalize() key_name_obj = dns.name.from_text(raw_key_name, origin=None).canonicalize()
@@ -70,11 +61,11 @@ class Command(BaseCommand):
name=key_name_obj, secret=secret, algorithm=algorithm_str name=key_name_obj, secret=secret, algorithm=algorithm_str
) )
self.tsig_view_map[key_name_str] = nb_view self.tsig_view_map[key_name_str] = nb_view
logger.debug(f"Loaded TSIG key: {key_name_str} view: {nb_view.name}") LOGGER.info(f"Loaded TSIG key {key_name_str} for view {nb_view.name}")
if not self.keyring: if not self.keyring:
msg = "No TSIG keys found in database." msg = "No TSIG keys found in database."
logger.critical(msg) LOGGER.critical(msg)
raise RuntimeError(msg) raise RuntimeError(msg)
def add_arguments(self, parser): def add_arguments(self, parser):
@@ -91,9 +82,11 @@ class Command(BaseCommand):
address = options["address"] address = options["address"]
catzm.init() catzm.init()
# Initialize settings self.tsig_keys = SETTINGS.get("tsig_keys", None)
self.load_settings() if not self.tsig_keys:
self.load_tsig_key_settings() raise RuntimeError("tsig_keys variable not set in plugin settings.")
self._load_tsig_key_settings()
udp_server = UDPDNSServer( udp_server = UDPDNSServer(
(address, port), UDPRequestHandler, self.keyring, self.tsig_view_map (address, port), UDPRequestHandler, self.keyring, self.tsig_view_map
@@ -103,15 +96,15 @@ class Command(BaseCommand):
(address, port), TCPRequestHandler, self.keyring, self.tsig_view_map (address, port), TCPRequestHandler, self.keyring, self.tsig_view_map
) )
def run_udp_server(server): def _run_udp_server(server):
logger.debug(f"Query endpoint listening on {address} udp/{port}") LOGGER.info(f"Query endpoint listening on {address} udp/{port}")
server.serve_forever() server.serve_forever()
udp_thread = threading.Thread( udp_thread = threading.Thread(
target=run_udp_server, args=(udp_server,), daemon=True target=_run_udp_server, args=(udp_server,), daemon=True
) )
udp_thread.start() udp_thread.start()
logger.debug(f"Query endpoint listening on {address} tcp/{port}") LOGGER.info(f"Query endpoint listening on {address} tcp/{port}")
tcp_server.serve_forever() tcp_server.serve_forever()
@@ -0,0 +1,32 @@
# Generated by Django 5.2.9 on 2026-06-09 21:56
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('netbox_dns', '0030_dnsseckeytemplate_comments_dnsseckeytemplate_owner_and_more'),
('netbox_dns_bridge', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='integerkeyvaluesetting',
options={},
),
migrations.CreateModel(
name='SeenTransferClients',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
('source_ip', models.GenericIPAddressField()),
('last_seen', models.DateTimeField()),
('view', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='seen_transfer_clients', to='netbox_dns.view')),
],
options={
'ordering': ('source_ip',),
'constraints': [models.UniqueConstraint(fields=('source_ip', 'view'), name='unique_ip_view_seen_client')],
},
),
]
Whitespace-only changes.
+30 -4
View File
@@ -1,20 +1,22 @@
from django.db import models from django.db import models
import netbox.models
# import netbox.models
import netbox_dns.models import netbox_dns.models
class IntegerKeyValueSetting(models.Model): class IntegerKeyValueSetting(models.Model):
_netbox_private = True
key = models.CharField(max_length=64) key = models.CharField(max_length=64)
value = models.IntegerField() value = models.IntegerField()
def __str__(self): def __str__(self):
return f"{self.key}: {str(self.value)}" return f"{self.key}: {str(self.value)}"
class Meta:
default_permissions = ()
class CatalogZoneMemberIdentifier(models.Model): class CatalogZoneMemberIdentifier(models.Model):
_netbox_private = True
name = models.CharField( name = models.CharField(
max_length=26, max_length=26,
unique=True, unique=True,
@@ -31,3 +33,27 @@ class CatalogZoneMemberIdentifier(models.Model):
def __str__(self): def __str__(self):
return self.name return self.name
class SeenTransferClients(models.Model):
_netbox_private = True
source_ip = models.GenericIPAddressField()
last_seen = models.DateTimeField()
view = models.ForeignKey(
to=netbox_dns.models.View,
on_delete=models.PROTECT,
related_name="seen_transfer_clients",
)
def __str__(self):
return f"{self.source_ip} ({self.view.name})"
class Meta:
ordering = ("source_ip",)
constraints = [
models.UniqueConstraint(
fields=["source_ip", "view"],
name="unique_ip_view_seen_client",
),
]
+142
View File
@@ -0,0 +1,142 @@
import dns.message
import dns.name
import dns.opcode
import dns.query
import dns.rdatatype
import dns.rdataclass
import dns.rrset
import dns.tsig
from django.conf import settings
from django.utils import timezone
from django.db import close_old_connections, OperationalError
from netbox.jobs import JobRunner
from netbox_dns.models import View, Zone, Record
from .logger import get_logger
from .models import SeenTransferClients, IntegerKeyValueSetting
LOGGER = get_logger(__name__)
SETTINGS = settings.PLUGINS_CONFIG["netbox_dns_bridge"]
class SendDNSNotify(JobRunner):
class Meta:
name = "Send DNS NOTIFY"
def _load_tsig_key(self, view_name: str) -> dns.tsig.Key:
tsig_keys = SETTINGS.get("tsig_keys", {})
if view_name not in tsig_keys:
raise RuntimeError(f"No TSIG key configured for view '{view_name}'")
key_data = tsig_keys[view_name]
raw_key_name = key_data.get("keyname")
secret = key_data.get("secret")
algorithm = key_data.get("algorithm")
if not algorithm:
raise RuntimeError(
f"Missing 'algorithm' in TSIG key configuration for view '{view_name}'"
)
if not raw_key_name or not secret:
raise RuntimeError(
f"Incomplete TSIG key configuration for view '{view_name}'"
)
key_name = dns.name.from_text(raw_key_name, origin=None).canonicalize()
if not key_name.is_absolute():
key_name = key_name.concatenate(dns.name.root)
return dns.tsig.Key(name=key_name, secret=secret, algorithm=algorithm)
def run(self, *args, **kwargs):
notify_over_tcp = SETTINGS.get("notify_over_tcp", False)
view_name = kwargs["view_name"]
try:
catz_serial = IntegerKeyValueSetting.objects.get(key="catalog-zone-soa-serial").value
zones = [
(kwargs["zone_name"], kwargs["soa_serial"]),
("catz", catz_serial),
(f"{view_name}.catz", catz_serial)
]
view = View.objects.get(name=view_name)
tsig_key = self._load_tsig_key(view_name)
cutoff_hours = SETTINGS.get("notify_client_alive_threshold_hours", 24)
seen_cutoff = timezone.now() - timezone.timedelta(hours=cutoff_hours)
clients = SeenTransferClients.objects.filter(
view=view, last_seen__gte=seen_cutoff
)
for zone_name, soa_serial in zones:
zone_name = dns.name.from_text(zone_name, dns.name.root).to_text()
msg = dns.message.make_query(zone_name, dns.rdatatype.SOA)
msg.flags = 0
msg.set_opcode(dns.opcode.NOTIFY)
soa_rdata = dns.rdata.from_text(
dns.rdataclass.IN,
dns.rdatatype.SOA,
f"invalid. invalid. {soa_serial} 60 10 1209600 0",
)
soa_rrset = dns.rrset.from_rdata(
zone_name, 0, soa_rdata
)
msg.authority.append(soa_rrset)
msg.use_tsig(keyring={tsig_key.name: tsig_key}, keyname=tsig_key.name)
for client in clients:
try:
if notify_over_tcp:
LOGGER.debug("Sending NOTIFY over TCP")
dns.query.tcp(msg, client.source_ip, port=5355, timeout=2)
else:
LOGGER.debug("Sending NOTIFY over UDP")
dns.query.udp(msg, client.source_ip, port=5355, timeout=2)
LOGGER.info(
f"NOTIFY sent: {client.source_ip} {view_name}/{zone_name} {soa_serial}"
)
except Exception as e:
LOGGER.error(
f"NOTIFY failed: {client.source_ip}"
f" {view_name}/{zone_name} {soa_serial}: {e}"
)
except IntegerKeyValueSetting.DoesNotExist as e:
LOGGER.error(f"Failed to get catalog zone serial: {e}")
except OperationalError as e:
LOGGER.error(f"NOTIFY failed due to unexpected error: {e}")
close_old_connections()
def schedule(zone: Zone):
try:
soa_record = Record.objects.filter(
zone=zone, type="SOA", active=True
).first()
if soa_record is None:
LOGGER.error(
f"Zone {zone.name} has no active SOA record — skipping NOTIFY"
)
return
soa_serial = int(soa_record.value.split()[2])
except OperationalError as e:
LOGGER.error(f"DB ERROR while fetching SOA for zone {zone.name}: {e}")
close_old_connections()
return
except (ValueError, IndexError) as e:
LOGGER.error(
f"Failed to parse SOA serial for zone {zone.name}: {e}"
)
return
SendDNSNotify.enqueue(
zone_name=zone.name,
view_name=zone.view.name,
soa_serial=soa_serial,
)
+49 -29
View File
@@ -1,4 +1,3 @@
import logging
import socketserver import socketserver
import socket import socket
import dns.query import dns.query
@@ -11,11 +10,16 @@ import dns.rdataclass
import dns.rdtypes import dns.rdtypes
import dns.exception import dns.exception
import dns.renderer import dns.renderer
from netbox_dns.models import Zone, Record from .logger import get_logger
from netbox_dns.choices import ZoneStatusChoices, RecordStatusChoices from django.utils import timezone
from django.db import close_old_connections, OperationalError
from django.conf import settings
from netbox_dns.models import Zone, Record, View
from netbox_dns_bridge import catalog_zone_manager as catzm from netbox_dns_bridge import catalog_zone_manager as catzm
from .models import SeenTransferClients
logger = logging.getLogger(__name__) LOGGER = get_logger(__name__)
SETTINGS = settings.PLUGINS_CONFIG["netbox_dns_bridge"]
class DNSBaseRequestHandler(socketserver.BaseRequestHandler): class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
@@ -31,18 +35,13 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
nb_zone = Zone.objects.get( nb_zone = Zone.objects.get(
name=zone_name, name=zone_name,
view__name=view_name, view__name=view_name,
status=ZoneStatusChoices.STATUS_ACTIVE, active=True,
) )
except Zone.DoesNotExist:
return None
# Build DNS zone # Build DNS zone
zone = dns.zone.Zone(zone_name, dns.name.root) zone = dns.zone.Zone(zone_name, dns.name.root)
zone.rdclass = dns.rdataclass.IN zone.rdclass = dns.rdataclass.IN
nb_records = Record.objects.filter( nb_records = Record.objects.filter(zone=nb_zone, active=True)
zone=nb_zone, status=RecordStatusChoices.STATUS_ACTIVE
)
rdatasets_dict = {} rdatasets_dict = {}
@@ -102,18 +101,25 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
# Ensure rdataset has the same rdclass as the zone # Ensure rdataset has the same rdclass as the zone
if rdataset.rdclass != zone.rdclass: if rdataset.rdclass != zone.rdclass:
raise ValueError( raise ValueError(
f"rdataset rdclass {rdataset.rdclass} does not match zone rdclass {zone.rdclass}" f"rdataset rdclass {rdataset.rdclass} does not match "
f"zone rdclass {zone.rdclass}"
) )
# Check if the rdataset has any rdata before creating an RRset # Check if the rdataset has any rdata before creating an RRset
if not rdataset: if not rdataset:
logger.debug(f"Skipping empty rdataset for {name} {rdtype}") LOGGER.debug(f"Skipping empty rdataset for {name} {rdtype}")
continue # Skip empty rdataset continue # Skip empty rdataset
# Replace the rdataset for the given name and type # Replace the rdataset for the given name and type
zone.replace_rdataset(name, rdataset) zone.replace_rdataset(name, rdataset)
return zone return zone
except Zone.DoesNotExist:
return None
except OperationalError as e:
LOGGER.error(f"DB ERROR: {e}")
close_old_connections()
def _deny_request_bad_tsig(self, wire, tsig_error: dns.rcode) -> None: def _deny_request_bad_tsig(self, wire, tsig_error: dns.rcode) -> None:
# Use empty keyring to parse TSIG without validating # Use empty keyring to parse TSIG without validating
query = dns.message.from_wire( query = dns.message.from_wire(
@@ -142,6 +148,19 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
wire = response.to_wire(multi=False) wire = response.to_wire(multi=False)
self._send_response(wire) self._send_response(wire)
def _track_seen_client(self, source_ip: str, view: View) -> None:
if SETTINGS.get("notify_clients", False):
try:
SeenTransferClients.objects.update_or_create(
source_ip=source_ip,
view=view,
defaults={"last_seen": timezone.now()},
)
except OperationalError as e:
LOGGER.error(f"DB ERROR: {e}")
close_old_connections()
def _handle_soa_request(self, query, soa_rrset, zone, peer, nb_view, dname) -> None: def _handle_soa_request(self, query, soa_rrset, zone, peer, nb_view, dname) -> None:
# We assume that the SOA rdataset has at least one record (it usually does). # We assume that the SOA rdataset has at least one record (it usually does).
soa_rdata = soa_rrset[0] # Get the first SOA record soa_rdata = soa_rrset[0] # Get the first SOA record
@@ -175,11 +194,11 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
data = response.to_wire(max_size=512) data = response.to_wire(max_size=512)
self._send_response(data) self._send_response(data)
logger.info(f"{peer} SOA {nb_view.name}/{dname}") LOGGER.info(f"{peer} SOA {nb_view.name}/{dname}")
def _handle_axfr_request(self, query, zone, peer, nb_view, dname) -> None: def _handle_axfr_request(self, query, zone, peer, nb_view, dname) -> None:
if query.keyname not in self.server.keyring: if query.keyname not in self.server.keyring:
logger.error(f"AXFR aborted: keyname {query.keyname} not in keyring") LOGGER.error(f"AXFR aborted: keyname {query.keyname} not in keyring")
self._deny_request(query) self._deny_request(query)
return return
@@ -252,7 +271,7 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
try: try:
r.add_rrset(dns.renderer.ANSWER, rrset) r.add_rrset(dns.renderer.ANSWER, rrset)
except dns.exception.TooBig: except dns.exception.TooBig:
logger.error( LOGGER.error(
f"RRset {rrset.name}/{dns.rdatatype.to_text(rrset.rdtype)} " f"RRset {rrset.name}/{dns.rdatatype.to_text(rrset.rdtype)} "
f"exceeds MAX_WIRE ({self.MAX_WIRE}) and cannot be sent; " f"exceeds MAX_WIRE ({self.MAX_WIRE}) and cannot be sent; "
f"skipping." f"skipping."
@@ -273,8 +292,7 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
) )
wire = r.get_wire() wire = r.get_wire()
self._send_response(wire) self._send_response(wire)
LOGGER.info(f"{peer} AXFR {nb_view.name}/{dname}")
logger.info(f"{peer} AXFR {nb_view.name}/{dname}")
def _handle_dns_query(self, wire) -> None: def _handle_dns_query(self, wire) -> None:
peer = self.client_address[0] peer = self.client_address[0]
@@ -287,17 +305,17 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
) )
except dns.tsig.BadSignature as e: except dns.tsig.BadSignature as e:
logger.warning(f"Request denied from {peer} failed TSIG verification: {e}") LOGGER.warning(f"Request denied from {peer} failed TSIG verification: {e}")
self._deny_request_bad_tsig(wire, dns.rcode.BADSIG) self._deny_request_bad_tsig(wire, dns.rcode.BADSIG)
return return
except (dns.message.UnknownTSIGKey, dns.tsig.BadAlgorithm) as e: except (dns.message.UnknownTSIGKey, dns.tsig.BadAlgorithm) as e:
logger.warning(f"Request denied from {peer} with bad TSIG key: {e}") LOGGER.warning(f"Request denied from {peer} with bad TSIG key: {e}")
self._deny_request_bad_tsig(wire, dns.rcode.BADKEY) self._deny_request_bad_tsig(wire, dns.rcode.BADKEY)
return return
except Exception as e: except Exception as e:
logger.error("Error parsing query: ", e) LOGGER.error("Error parsing query: ", e)
return return
# If there was no question in the query, refuse # If there was no question in the query, refuse
@@ -312,7 +330,7 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
# Only process AXFR/SOA queris # Only process AXFR/SOA queris
if qtype not in (dns.rdatatype.AXFR, dns.rdatatype.SOA): if qtype not in (dns.rdatatype.AXFR, dns.rdatatype.SOA):
logger.warning( LOGGER.warning(
f"Request denied from {peer}: Request was not AXFR or SOA (Type: {qtype})" f"Request denied from {peer}: Request was not AXFR or SOA (Type: {qtype})"
) )
self._deny_request(query) self._deny_request(query)
@@ -320,7 +338,7 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
# Identify TSIG key used # Identify TSIG key used
if not query.had_tsig: if not query.had_tsig:
logger.warning(f"Request denied from {peer}: No TSIG key used") LOGGER.warning(f"Request denied from {peer}: No TSIG key used")
self._deny_request(query) self._deny_request(query)
return return
@@ -329,7 +347,7 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
# Check if the key matches a view # Check if the key matches a view
nb_view = self.server.tsig_view_map.get(key_name) nb_view = self.server.tsig_view_map.get(key_name)
if not nb_view: if not nb_view:
logger.warning( LOGGER.warning(
f"Request denied from {peer}: {key_name} does not match a view" f"Request denied from {peer}: {key_name} does not match a view"
) )
self._deny_request(query) self._deny_request(query)
@@ -342,20 +360,22 @@ class DNSBaseRequestHandler(socketserver.BaseRequestHandler):
zone = self._getZoneFromNB(dname, nb_view.name) zone = self._getZoneFromNB(dname, nb_view.name)
# When zone was not found, let client know # When zone was not found, let client know
if not zone: if not zone:
logger.warning(f"Zone {dname} not found in view {nb_view.name}") LOGGER.warning(f"Zone {dname} not found in view {nb_view.name}")
self._deny_request(query) self._deny_request(query)
return return
# Retrieve the existing SOA record from the Zone # Retrieve the existing SOA record from the Zone
soa_rrset = zone.get_rdataset(zone.origin, dns.rdatatype.SOA) soa_rrset = zone.get_rdataset(zone.origin, dns.rdatatype.SOA)
if soa_rrset is None: if soa_rrset is None:
logger.error(f"Zone {dname} has no SOA — aborting") LOGGER.error(f"Zone {dname} has no SOA — aborting")
return return
if qtype == dns.rdatatype.SOA: if qtype == dns.rdatatype.SOA:
self._handle_soa_request(query, soa_rrset, zone, peer, nb_view, dname) self._handle_soa_request(query, soa_rrset, zone, peer, nb_view, dname)
self._track_seen_client(peer, nb_view)
elif qtype == dns.rdatatype.AXFR: elif qtype == dns.rdatatype.AXFR:
self._handle_axfr_request(query, zone, peer, nb_view, dname) self._handle_axfr_request(query, zone, peer, nb_view, dname)
self._track_seen_client(peer, nb_view)
class UDPRequestHandler(DNSBaseRequestHandler): class UDPRequestHandler(DNSBaseRequestHandler):
@@ -372,7 +392,7 @@ class UDPRequestHandler(DNSBaseRequestHandler):
try: try:
self._handle_dns_query(data) self._handle_dns_query(data)
except Exception as e: except Exception as e:
logger.error(f"Error handling request from {peer}: {e}") LOGGER.error(f"Error handling request from {peer}: {e}")
import traceback import traceback
traceback.print_exc() traceback.print_exc()
@@ -414,9 +434,9 @@ class TCPRequestHandler(DNSBaseRequestHandler):
self._handle_dns_query(wire) self._handle_dns_query(wire)
except socket.timeout: except socket.timeout:
logger.debug(f"Connection from {peer} timed out") LOGGER.debug(f"Connection from {peer} timed out")
except Exception as e: except Exception as e:
logger.error(f"Error handling request from {peer}: {e}") LOGGER.error(f"Error handling request from {peer}: {e}")
import traceback import traceback
traceback.print_exc() traceback.print_exc()
-37
View File
@@ -1,37 +0,0 @@
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from netbox_dns.models import Zone
from . import catalog_zone_manager as catzm
@receiver(pre_save, sender=Zone)
def zone_pre_save(sender, instance, **kwargs):
"""
Cache the old name so post_save can see if it changed.
"""
if instance.pk:
try:
instance._old_name = sender.objects.only("name").get(pk=instance.pk).name
except sender.DoesNotExist:
instance._old_name = None
else:
instance._old_name = None
@receiver(post_save, sender=Zone)
def sync_catalog_zone_identifier(sender, instance, created, **kwargs):
"""
Ensure CatalogZoneMemberIdentifier exists for each Zone
and keep its identifier in sync.
"""
if created:
# Create the related object on Zone creation
catzm.update_member_identifier(instance)
else:
old_name = getattr(instance, "_old_name", None)
# If the name did not change, do nothing
if old_name == instance.name:
return
catzm.update_member_identifier(instance)
+1
View File
@@ -0,0 +1 @@
from . import netbox_dns_zones
@@ -0,0 +1,58 @@
from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver
from django.db import transaction
from django.conf import settings
from netbox.context import current_request
from netbox_dns.models import Zone
from netbox_dns_bridge import catalog_zone_manager as catzm
from netbox_dns_bridge import notify_handler
SETTINGS = settings.PLUGINS_CONFIG["netbox_dns_bridge"]
@receiver(pre_save, sender=Zone)
def zone_pre_save(sender, instance, **kwargs):
zone = instance
if zone.pk:
try:
zone._old_name = sender.objects.only("name").get(pk=zone.pk).name
except sender.DoesNotExist:
zone._old_name = None
else:
zone._old_name = None
@receiver(post_save, sender=Zone)
def zone_post_save(sender, instance, created, **kwargs):
zone = instance
# Quit if this is not the first signal in this session for this zone.
request = current_request.get()
if request is not None:
handled_zones = getattr(request, "_handled_zones", set())
if zone.pk in handled_zones:
return
handled_zones.add(zone.pk)
request._handled_zones = handled_zones
# On commit, increment soa serial and if notify is enabled, schedule bg job.
def _on_commit():
catzm.increment_soa_serial()
if SETTINGS.get("notify_clients", False):
notify_handler.schedule(zone)
transaction.on_commit(_on_commit)
if created:
# If zone was created, create catz member identifier record for this zone.
catzm.update_member_identifier(zone)
else:
# Check if zone name has changed and change the catz member identifier if so.
old_name = getattr(zone, "_old_name", None)
if old_name and zone.name != old_name:
catzm.update_member_identifier(zone)
@receiver(post_delete, sender=Zone)
def zone_post_delete(sender, instance, **kwargs):
catzm.increment_soa_serial()
-1
View File
@@ -1,4 +1,3 @@
import os
import dns.zone import dns.zone
import dns.rdatatype import dns.rdatatype
import dns.rdataclass import dns.rdataclass
-645
View File
@@ -1,645 +0,0 @@
[MAIN]
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
# in a server-like mode.
clear-cache-post-run=no
# Load and enable all available extensions. Use --list-extensions to see a list
# all available extensions.
#enable-all-extensions=
# In error mode, messages with a category besides ERROR or FATAL are
# suppressed, and no reports are done by default. Error mode is compatible with
# disabling specific errors.
#errors-only=
# Always return a 0 (non-error) status code, even if lint errors are found.
# This is primarily useful in continuous integration scripts.
#exit-zero=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
# for backward compatibility.)
extension-pkg-whitelist=
# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=
# Specify a score threshold under which the program will exit with error.
fail-under=10
# Interpret the stdin as a python script, whose filename needs to be passed as
# the module_or_package argument.
#from-stdin=
# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS
# Add files or directories matching the regular expressions patterns to the
# ignore-list. The regex matches against paths and can be in Posix or Windows
# format. Because '\\' represents the directory delimiter on Windows systems,
# it can't be used as an escape character.
ignore-paths=
# Files or directories matching the regular expression patterns are skipped.
# The regex matches against base names, not paths. The default value ignores
# Emacs file locks
ignore-patterns=^\.#
# List of module names for which member attributes should not be checked and
# will not be imported (useful for modules/projects where namespaces are
# manipulated during runtime and thus existing member attributes cannot be
# deduced by static analysis). It supports qualified module names, as well as
# Unix pattern matching.
ignored-modules=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use, and will cap the count on Windows to
# avoid hangs.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Resolve imports to .pyi stubs if available. May reduce no-member messages and
# increase not-an-iterable messages.
prefer-stubs=no
# Minimum Python version to use for version dependent checks. Will default to
# the version used to run pylint.
py-version=3.13
# Discover python modules and packages in the file system subtree.
recursive=no
# Add paths to the list of the source roots. Supports globbing patterns. The
# source root is an absolute path or a path relative to the current working
# directory used to determine a package namespace for modules located under the
# source root.
source-roots=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# In verbose mode, extra non-checker-related info will be displayed.
#verbose=
[BASIC]
# Naming style matching correct argument names.
#argument-naming-style=snake_case
argument-naming-style=camelCase
# Regular expression matching correct argument names. Overrides argument-
# naming-style. If left empty, argument names will be checked with the set
# naming style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style. If left empty, attribute names will be checked with the set naming
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style. If left empty, class attribute names will be checked
# with the set naming style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style. If left empty, class constant names will be checked with
# the set naming style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style. If left empty, class names will be checked with the set naming style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style. If left empty, constant names will be checked with the set naming
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=camelCase
# Regular expression matching correct function names. Overrides function-
# naming-style. If left empty, function names will be checked with the set
# naming style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style. If left empty, inline iteration names will be checked
# with the set naming style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=camelCase
# Regular expression matching correct method names. Overrides method-naming-
# style. If left empty, method names will be checked with the set naming style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style. If left empty, module names will be checked with the set naming style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Regular expression matching correct type alias names. If left empty, type
# alias names will be checked with the set naming style.
#typealias-rgx=
# Regular expression matching correct type variable names. If left empty, type
# variable names will be checked with the set naming style.
#typevar-rgx=
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
asyncSetUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
[DESIGN]
# List of regular expressions of class ancestor names to ignore when counting
# public methods (see R0903)
exclude-too-few-public-methods=
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[EXCEPTIONS]
# Exceptions that will emit a warning when caught.
overgeneral-exceptions=builtins.BaseException,builtins.Exception
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=120
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow explicit reexports by alias from a package __init__.
allow-reexport-from-package=no
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
# UNDEFINED.
confidence=HIGH,
CONTROL_FLOW,
INFERENCE,
INFERENCE_FAILURE,
UNDEFINED
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
use-implicit-booleaness-not-comparison-to-string,
use-implicit-booleaness-not-comparison-to-zero
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=
[METHOD_ARGS]
# List of qualified names (i.e., library.method) which require a timeout
# parameter e.g. 'requests.api.get,requests.api.post'
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
notes-rgx=
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit,argparse.parse_error
# Let 'consider-using-join' be raised when the separator to join on would be
# non-empty (resulting in expected fixes of the type: ``"- " + " -
# ".join(items)``)
suggest-join-with-non-empty-separator=yes
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
# 'convention', and 'info' which contain the number of messages in each
# category, as well as 'statement' which is the total number of statements
# analyzed. This score is used by the global evaluation report (RP0004).
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
msg-template=
# Set the output format. Available formats are: text, parseable, colorized,
# json2 (improved json format), json (old json format) and msvs (visual
# studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
#output-format=
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=yes
# Signatures are removed from the similarity computation
ignore-signatures=yes
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. No available dictionaries : You need to install
# both the python package and the system dependency for enchant to work.
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear at the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of symbolic message names to ignore for Mixin members.
ignored-checks-for-mixins=no-member,
not-async-context-manager,
not-context-manager,
attribute-defined-outside-init
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# Regex pattern to define which classes are considered mixins.
mixin-class-rgx=.*[Mm]ixin
# List of decorators that change the signature of a decorated function.
signature-mutators=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io