refactor(snmp): the SNMP agent's helpers in a module of their own
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m7s
driver / test (3.13) (pull_request) Failing after 1m2s
driver / test (3.12) (pull_request) Failing after 1m16s
driver / lowest (pull_request) Failing after 29s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Failing after 2m20s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m7s
driver / test (3.13) (pull_request) Failing after 1m2s
driver / test (3.12) (pull_request) Failing after 1m16s
driver / lowest (pull_request) Failing after 29s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Failing after 2m20s
driver / publish (pull_request) Skipped
linux.py had grown past its recorded size with the firewalld rule. The snmpd.conf rendering, the install commands and the firewalld rule now live in _snmp_agent.py; linux.py shrinks to 2014 lines and the baseline records that.
This commit is contained in:
1 parent
aab25fb049
commit
3683c85f21
4 files changed
+90
-71
No files matched your search
@@ -0,0 +1,80 @@
|
|||||||
|
"""The SNMP agent a fix sets up: net-snmp's configuration and the firewall rule for it."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import re
|
||||||
|
from shlex import quote as _shlex_quote
|
||||||
|
|
||||||
|
from napalm_device_types.models import SnmpAgentSettingsDict
|
||||||
|
|
||||||
|
#: Where net-snmp reads its configuration, and how each package manager installs it.
|
||||||
|
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
|
||||||
|
_SNMP_INSTALL = {
|
||||||
|
"apt": (
|
||||||
|
"apt-get update -y >/dev/null 2>&1; "
|
||||||
|
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1"
|
||||||
|
),
|
||||||
|
"dnf": "dnf install -y net-snmp net-snmp-utils 2>&1",
|
||||||
|
"yum": "yum install -y net-snmp net-snmp-utils 2>&1",
|
||||||
|
"apk": "apk add --no-cache net-snmp net-snmp-tools 2>&1",
|
||||||
|
"pacman": "pacman -Sy --noconfirm net-snmp 2>&1",
|
||||||
|
}
|
||||||
|
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
||||||
|
_SNMP_WORD = re.compile(r"^[^\s\"#]+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _source(value: str) -> str:
|
||||||
|
"""An allowed source as an address or network, or ValueError."""
|
||||||
|
return str(ipaddress.ip_network(value.strip(), strict=False))
|
||||||
|
|
||||||
|
|
||||||
|
#: The zones a firewalld rule must reach: the default one, which takes every interface
|
||||||
|
#: in no zone (a WireGuard ``wg0``), and each zone holding an interface or a source.
|
||||||
|
_FIREWALLD_ZONES = (
|
||||||
|
"$( { firewall-cmd --get-default-zone;"
|
||||||
|
" firewall-cmd --get-active-zones | grep -v '^[[:space:]]'; } | sort -u )"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def firewalld_allow_snmp(sources: list[str]) -> str:
|
||||||
|
"""The shell that opens udp/161 for *sources* (already normalised) in firewalld.
|
||||||
|
|
||||||
|
A rich rule per source in every zone of ``_FIREWALLD_ZONES``, at runtime and
|
||||||
|
permanently, each only when the zone lacks it -- no ``--reload``, which would drop
|
||||||
|
the runtime rules others (Docker) put there.
|
||||||
|
"""
|
||||||
|
steps = []
|
||||||
|
for source in sources:
|
||||||
|
family = f"ipv{ipaddress.ip_network(source).version}"
|
||||||
|
rule = _shlex_quote(
|
||||||
|
f'rule family="{family}" source address="{source}"'
|
||||||
|
' port port="161" protocol="udp" accept'
|
||||||
|
)
|
||||||
|
for scope in ("", "--permanent "):
|
||||||
|
zone = f'firewall-cmd {scope}--zone="$z"'
|
||||||
|
steps.append(
|
||||||
|
f"{{ {zone} --query-rich-rule={rule} >/dev/null 2>&1"
|
||||||
|
f" || {zone} --add-rich-rule={rule}; }}"
|
||||||
|
)
|
||||||
|
return f"for z in {_FIREWALLD_ZONES}; do {' && '.join(steps)} || exit 1; done"
|
||||||
|
|
||||||
|
|
||||||
|
def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
||||||
|
"""net-snmp's configuration for *settings*: read-only v2c, per allowed source."""
|
||||||
|
community = settings["community"]
|
||||||
|
if not _SNMP_WORD.match(community):
|
||||||
|
raise ValueError("the community must be one word without quotes or #")
|
||||||
|
listen = settings.get("listen")
|
||||||
|
lines = [f"agentAddress udp:{listen + ':' if listen else ''}161"]
|
||||||
|
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
||||||
|
lines += [f"rocommunity {community} {s}" for s in sources] or [f"rocommunity {community}"]
|
||||||
|
for key, directive, value in (
|
||||||
|
("location", "sysLocation", settings.get("location", "")),
|
||||||
|
("contact", "sysContact", settings.get("contact", "")),
|
||||||
|
):
|
||||||
|
if value:
|
||||||
|
if "\n" in value:
|
||||||
|
raise ValueError(f"{key} must be one line")
|
||||||
|
lines.append(f"{directive} {value}")
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
+7
-68
@@ -81,6 +81,13 @@ from napalm_linux._posix import LinuxPosixMixin
|
|||||||
from napalm_linux._readings import LinuxProcessReadingsMixin
|
from napalm_linux._readings import LinuxProcessReadingsMixin
|
||||||
from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length
|
from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length
|
||||||
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
|
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
|
||||||
|
from napalm_linux._snmp_agent import (
|
||||||
|
_SNMP_INSTALL,
|
||||||
|
_SNMPD_CONF,
|
||||||
|
_source,
|
||||||
|
firewalld_allow_snmp,
|
||||||
|
render_snmpd_conf,
|
||||||
|
)
|
||||||
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
|
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
|
||||||
|
|
||||||
logger = logging.getLogger("napalm_linux")
|
logger = logging.getLogger("napalm_linux")
|
||||||
@@ -255,75 +262,7 @@ def _arm_vendor_from_model(model: str) -> str:
|
|||||||
return " ".join(brand)
|
return " ".join(brand)
|
||||||
|
|
||||||
|
|
||||||
#: Where net-snmp reads its configuration, and how each package manager installs it.
|
|
||||||
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
|
|
||||||
_SNMP_INSTALL = {
|
|
||||||
"apt": (
|
|
||||||
"apt-get update -y >/dev/null 2>&1; "
|
|
||||||
"DEBIAN_FRONTEND=noninteractive apt-get install -y snmpd snmp 2>&1"
|
|
||||||
),
|
|
||||||
"dnf": "dnf install -y net-snmp net-snmp-utils 2>&1",
|
|
||||||
"yum": "yum install -y net-snmp net-snmp-utils 2>&1",
|
|
||||||
"apk": "apk add --no-cache net-snmp net-snmp-tools 2>&1",
|
|
||||||
"pacman": "pacman -Sy --noconfirm net-snmp 2>&1",
|
|
||||||
}
|
|
||||||
_USER_NAME = re.compile(r"^[a-z_][a-z0-9_.\-]{0,31}$")
|
_USER_NAME = re.compile(r"^[a-z_][a-z0-9_.\-]{0,31}$")
|
||||||
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
|
|
||||||
_SNMP_WORD = re.compile(r"^[^\s\"#]+$")
|
|
||||||
|
|
||||||
|
|
||||||
def _source(value: str) -> str:
|
|
||||||
"""An allowed source as an address or network, or ValueError."""
|
|
||||||
return str(ipaddress.ip_network(value.strip(), strict=False))
|
|
||||||
|
|
||||||
|
|
||||||
#: The zones a firewalld rule must reach: the default one, which takes every interface
|
|
||||||
#: in no zone (a WireGuard ``wg0``), and each zone holding an interface or a source.
|
|
||||||
_FIREWALLD_ZONES = (
|
|
||||||
"$( { firewall-cmd --get-default-zone;"
|
|
||||||
" firewall-cmd --get-active-zones | grep -v '^[[:space:]]'; } | sort -u )"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def firewalld_allow_snmp(sources: list[str]) -> str:
|
|
||||||
"""The shell that opens udp/161 for *sources* (already normalised) in firewalld.
|
|
||||||
|
|
||||||
A rich rule per source in every zone of ``_FIREWALLD_ZONES``, at runtime and
|
|
||||||
permanently, each only when the zone lacks it -- no ``--reload``, which would drop
|
|
||||||
the runtime rules others (Docker) put there.
|
|
||||||
"""
|
|
||||||
steps = []
|
|
||||||
for source in sources:
|
|
||||||
family = f"ipv{ipaddress.ip_network(source).version}"
|
|
||||||
rule = _shlex_quote(
|
|
||||||
f'rule family="{family}" source address="{source}"'
|
|
||||||
' port port="161" protocol="udp" accept'
|
|
||||||
)
|
|
||||||
for scope in ("", "--permanent "):
|
|
||||||
zone = f'firewall-cmd {scope}--zone="$z"'
|
|
||||||
steps.append(
|
|
||||||
f"{{ {zone} --query-rich-rule={rule} >/dev/null 2>&1"
|
|
||||||
f" || {zone} --add-rich-rule={rule}; }}"
|
|
||||||
)
|
|
||||||
return f"for z in {_FIREWALLD_ZONES}; do {' && '.join(steps)} || exit 1; done"
|
|
||||||
|
|
||||||
|
|
||||||
def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
|
||||||
"""net-snmp's configuration for *settings*: read-only v2c, per allowed source."""
|
|
||||||
community = settings["community"]
|
|
||||||
if not _SNMP_WORD.match(community):
|
|
||||||
raise ValueError("the community must be one word without quotes or #")
|
|
||||||
listen = settings.get("listen")
|
|
||||||
lines = [f"agentAddress udp:{listen + ':' if listen else ''}161"]
|
|
||||||
sources = [_source(s) for s in settings.get("allowed_sources", [])]
|
|
||||||
lines += [f"rocommunity {community} {s}" for s in sources] or [f"rocommunity {community}"]
|
|
||||||
for key, directive in (("location", "sysLocation"), ("contact", "sysContact")):
|
|
||||||
value = settings.get(key, "")
|
|
||||||
if value:
|
|
||||||
if "\n" in value:
|
|
||||||
raise ValueError(f"{key} must be one line")
|
|
||||||
lines.append(f"{directive} {value}")
|
|
||||||
return "\n".join(lines) + "\n"
|
|
||||||
|
|
||||||
|
|
||||||
class LinuxDriver(
|
class LinuxDriver(
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
"napalm_linux.linux"
|
"napalm_linux.linux"
|
||||||
],
|
],
|
||||||
"python_file_lines": {
|
"python_file_lines": {
|
||||||
"napalm_linux/linux.py": 2039
|
"napalm_linux/linux.py": 2014
|
||||||
},
|
},
|
||||||
"untyped_public": []
|
"untyped_public": []
|
||||||
}
|
}
|
||||||
@@ -128,7 +128,7 @@ class TestSnmpAgentSteps:
|
|||||||
def test_the_firewalld_rule_goes_to_the_default_and_every_active_zone(self, tmp_path):
|
def test_the_firewalld_rule_goes_to_the_default_and_every_active_zone(self, tmp_path):
|
||||||
"""An interface in no zone (a WireGuard wg0) is the default zone's; one in a
|
"""An interface in no zone (a WireGuard wg0) is the default zone's; one in a
|
||||||
zone of its own is that zone's. The rule goes in now and stays after a reload."""
|
zone of its own is that zone's. The rule goes in now and stays after a reload."""
|
||||||
from napalm_linux.linux import firewalld_allow_snmp
|
from napalm_linux._snmp_agent import firewalld_allow_snmp
|
||||||
|
|
||||||
log = tmp_path / "calls"
|
log = tmp_path / "calls"
|
||||||
fake = tmp_path / "firewall-cmd"
|
fake = tmp_path / "firewall-cmd"
|
||||||
@@ -165,7 +165,7 @@ class TestSnmpAgentSteps:
|
|||||||
assert len(adds) == 8
|
assert len(adds) == 8
|
||||||
|
|
||||||
def test_a_rule_firewalld_holds_already_is_not_added_twice(self, tmp_path):
|
def test_a_rule_firewalld_holds_already_is_not_added_twice(self, tmp_path):
|
||||||
from napalm_linux.linux import firewalld_allow_snmp
|
from napalm_linux._snmp_agent import firewalld_allow_snmp
|
||||||
|
|
||||||
log = tmp_path / "calls"
|
log = tmp_path / "calls"
|
||||||
fake = tmp_path / "firewall-cmd"
|
fake = tmp_path / "firewall-cmd"
|
||||||
|
|||||||
Reference in new issue
Block a user