fix: the SNMP agent setup sends only what os-net-snmp 26.x knows (#36) #37

Merged
christianmanivong merged 2 commits from fix/snmp-agent-26x into main 2026-11-01 06:29:29 +00:00
4 changed files with 63 additions and 25 deletions

No files matched your search

+6
View File
@@ -13,6 +13,12 @@ All notable changes to this driver. The format follows
3.12 venv no longer has. 3.12 venv no longer has.
### Fixed ### Fixed
- `configure_snmp_agent()` works on OPNsense 26.x again. The configure step sent
fields the os-net-snmp model does not have (`contact`, `location`, `sysobjid`,
`bindip`) and `listen` in the shape `get` returns rather than as a string, which
26.x refuses with HTTP 500. It now sends `syscontact`/`syslocation`, and only when
the caller gives them, so an operator's sysContact and sysLocation are no longer
blanked (#36).
- `get_arp_table()` and `get_ipv6_neighbors_table()` report an unknown age as `-1.0` - `get_arp_table()` and `get_ipv6_neighbors_table()` report an unknown age as `-1.0`
(napalm-device-types' `ARP_AGE_UNKNOWN`). They reported `expires`, the seconds (napalm-device-types' `ARP_AGE_UNKNOWN`). They reported `expires`, the seconds
left until the entry expires, which is no age: an entry refreshed a second ago left until the entry expires, which is no age: an entry refreshed a second ago
+21 -20
View File
@@ -2438,6 +2438,8 @@ class OPNsenseDriver(
#: old any-source rule is recognised by its older description. #: old any-source rule is recognised by its older description.
_SNMP_RULE_PREFIX = "napalm-opnsense: SNMP from " _SNMP_RULE_PREFIX = "napalm-opnsense: SNMP from "
_SNMP_RULE_OLD = "[netork] Allow SNMP" _SNMP_RULE_OLD = "[netork] Allow SNMP"
#: The caller's system values and the os-net-snmp fields they go to.
_SNMP_SYSTEM_FIELDS = {"contact": "syscontact", "location": "syslocation"}
def _install_snmp_agent(self) -> FixStepOutcomeDict: def _install_snmp_agent(self) -> FixStepOutcomeDict:
# Installing over an installed os-net-snmp starts an async reinstall that # Installing over an installed os-net-snmp starts an async reinstall that
@@ -2452,34 +2454,33 @@ class OPNsenseDriver(
time.sleep(5) # the install settles before its API answers time.sleep(5) # the install settles before its API answers
return {"ok": result.get("status") == "ok", "output": f"os-net-snmp install: {result}"} return {"ok": result.get("status") == "ok", "output": f"os-net-snmp install: {result}"}
def _write_snmp_agent_config(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict: @staticmethod
community = settings["community"] def _check_snmp_community(community: str) -> None:
if not community or any(c.isspace() or c in '"#' for c in community): if not community or any(c.isspace() or c in '"#' for c in community):
raise ValueError("the community must be one word without quotes or #") raise ValueError("the community must be one word without quotes or #")
listen = settings.get("listen") or self.hostname
def _snmp_listen_address(self, settings: SnmpAgentSettingsDict) -> str:
try: try:
listen_val = {str(ipaddress.ip_address(listen)): {"selected": 1}} return str(ipaddress.ip_address(settings.get("listen") or self.hostname))
except ValueError: except ValueError:
listen_val = {} # a DNS name binds nothing; snmpd then listens everywhere return "" # a DNS name binds nothing; snmpd then listens everywhere
result = self._post(
"/api/netsnmp/general/set", def _write_snmp_agent_config(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
{ community = settings["community"]
"general": { self._check_snmp_community(community)
"enabled": "1", listen_val = self._snmp_listen_address(settings)
"community": community, general = {"enabled": "1", "community": community, "listen": listen_val}
"contact": settings.get("contact", ""), # Only what the caller gives: an empty one would blank the operator's.
"location": settings.get("location", ""), for key, field in self._SNMP_SYSTEM_FIELDS.items():
"sysobjid": "", if settings.get(key):
"bindip": "", general[field] = settings[key]
"listen": listen_val, # The plugin's model refuses any field it does not have, with a 500 (#36).
} result = self._post("/api/netsnmp/general/set", {"general": general})
},
)
if result.get("result") != "saved": if result.get("result") != "saved":
return {"ok": False, "output": f"configuration refused: {result}"} return {"ok": False, "output": f"configuration refused: {result}"}
return { return {
"ok": True, "ok": True,
"output": f"community set, listen {list(listen_val) or 'all addresses'}", "output": f"community set, listen {listen_val or 'all addresses'}",
} }
def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict: def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
+1 -1
View File
@@ -57,7 +57,7 @@
"napalm_opnsense.resolver_mixin" "napalm_opnsense.resolver_mixin"
], ],
"python_file_lines": { "python_file_lines": {
"napalm_opnsense/opnsense.py": 3082 "napalm_opnsense/opnsense.py": 3083
}, },
"untyped_public": [ "untyped_public": [
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config" "napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config"
+35 -4
View File
@@ -12,9 +12,25 @@ from __future__ import annotations
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
import requests
from napalm_opnsense.opnsense import OPNsenseDriver from napalm_opnsense.opnsense import OPNsenseDriver
#: The plugin's settings as OPNsense 26.7 serves them (gw-01, 2026-10-31). Its
#: model knows exactly these fields, and a set naming any other one, or giving a
#: field anything but a string, is a 500 (#36).
MODEL = {
"enabled": "0",
"community": "public",
"syslocation": "Home",
"syscontact": "admin@example.org",
"l3visibility": "1",
"versionoid": "1",
"enableagentx": "1",
"enableobservium": "1",
"listen": {"10.0.0.1": {"value": "10.0.0.1", "selected": 1}},
}
SETTINGS = { SETTINGS = {
"community": "c0mm", "community": "c0mm",
"allowed_sources": ["10.7.224.20", "10.7.225.0/24"], "allowed_sources": ["10.7.224.20", "10.7.225.0/24"],
@@ -34,12 +50,15 @@ class _Api:
def get(self, path): def get(self, path):
if path == "/api/netsnmp/general/get": if path == "/api/netsnmp/general/get":
return {"general": {"enabled": "0"}} if self.installed else {} return {"general": dict(MODEL)} if self.installed else {}
raise AssertionError(path) raise AssertionError(path)
def post(self, path, body=None): def post(self, path, body=None):
self.posts.append((path, body)) self.posts.append((path, body))
if path == "/api/netsnmp/general/set": if path == "/api/netsnmp/general/set":
general = (body or {}).get("general", {})
if any(k not in MODEL or not isinstance(v, str) for k, v in general.items()):
raise requests.HTTPError(f"500 Server Error: Internal Server Error for url: {path}")
return {"result": self.saved} return {"result": self.saved}
if path == "/api/firewall/filter/searchRule": if path == "/api/firewall/filter/searchRule":
return {"rows": self.rules} return {"rows": self.rules}
@@ -83,12 +102,24 @@ class TestTheCallersValues:
assert result["success"] is True assert result["success"] is True
general = _body(api, "/api/netsnmp/general/set")["general"] general = _body(api, "/api/netsnmp/general/set")["general"]
assert general["enabled"] == "1" assert general["enabled"] == "1"
assert (general["community"], general["contact"], general["location"]) == ( assert (general["community"], general["syscontact"], general["syslocation"]) == (
"c0mm", "c0mm",
"ops", "ops",
"rack 1", "rack 1",
) )
assert general["listen"] == {"10.0.0.1": {"selected": 1}} assert general["listen"] == "10.0.0.1"
def test_only_fields_the_plugins_model_has_are_sent(self, driver, api):
result = driver.configure_snmp_agent({**SETTINGS, "listen": "10.0.0.1"})
assert result["success"] is True
assert set(_body(api, "/api/netsnmp/general/set")["general"]) <= set(MODEL)
def test_contact_and_location_the_caller_leaves_out_stay_as_they_are(self, driver, api):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
general = _body(api, "/api/netsnmp/general/set")["general"]
assert "syscontact" not in general and "syslocation" not in general
def test_nothing_of_an_application_is_built_in(self, driver, api): def test_nothing_of_an_application_is_built_in(self, driver, api):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []}) driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
@@ -103,7 +134,7 @@ class TestTheCallersValues:
d.configure_snmp_agent({"community": "c0mm", "allowed_sources": []}) d.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
assert _body(api, "/api/netsnmp/general/set")["general"]["listen"] == {} assert _body(api, "/api/netsnmp/general/set")["general"]["listen"] == ""
def test_a_rejected_configuration_fails_the_fix(self, driver, api): def test_a_rejected_configuration_fails_the_fix(self, driver, api):
api.saved = "failed" api.saved = "failed"