fix(rest): raise on a failed REST read instead of returning {} #24

Merged
christianmanivong merged 1 commits from fix/bugs-2026-11-02 into main 2026-11-02 08:12:16 +00:00
6 changed files with 340 additions and 73 deletions

No files matched your search

+13
View File
@@ -49,6 +49,19 @@ All notable changes to this driver. The format follows
- `get_snmp_config` reads the switch's communities over the REST API too. It returned
`None` there, so a switch managed over REST always read as having no SNMP. A read that
fails now raises instead of reading as "no SNMP" (REST transport).
- A failed read over the REST API raises instead of reading as an empty switch (#22).
A timeout, a refused session or an HTTP error made `get_facts`, `get_interfaces`,
`get_interfaces_ip`, `get_vlans`, `get_arp_table`, `get_mac_address_table`,
`get_lldp_neighbors(_detail)`, `get_ntp_servers` and `get_poe_status` answer with no
hostname, ports, VLANs or neighbours. They now raise `ConnectionException` when the
switch does not answer or refuses the session (HTTP 401/403) and `RuntimeError` for
any other HTTP error. A resource that some firmware or configurations do not have
(HTTP 404) is left out as before: the DNS domain, port speeds, a VLAN's IPv4 address,
PoE on a switch without it.
- `get_config` raises when neither the REST API nor the SSH fallback could read the
configuration. It returned an empty running configuration.
- `cli()` over the REST API raises when the request fails. It returned
`"Error: HTTP <status>"` as if that were the command's output.
## [0.6.0] - 2026-10-23
+82 -49
View File
@@ -23,6 +23,24 @@ logger = logging.getLogger("napalm_procurve.api")
#: The port the REST API listens on over HTTPS; its URLs name no other.
HTTPS_PORT = 443
#: Answers that mean the session is not (or no longer) accepted.
HTTP_SESSION_REFUSED = (401, 403)
HTTP_NOT_FOUND = 404
def raise_for_answer(resp: requests.Response, what: str, hostname: str) -> None:
"""Raise unless *resp* is a 2xx answer (#22).
401/403 raise ``ConnectionException``: the session is gone, not the data.
Every other non-2xx answer raises ``RuntimeError`` with the status.
"""
if resp.ok:
return
detail = f"{what} on {hostname}: HTTP {resp.status_code}: {resp.text[:200]}"
if resp.status_code in HTTP_SESSION_REFUSED:
raise ConnectionException(detail)
raise RuntimeError(detail)
class ProcurveApiClient:
"""Thin wrapper around ArubaOS REST API sessions.
@@ -211,22 +229,44 @@ class ProcurveApiClient:
# HTTP helpers
# ------------------------------------------------------------------
def get(self, endpoint: str) -> dict[str, Any]:
"""GET ``{base_url}{endpoint}`` and return parsed JSON (or empty dict)."""
url = self._base_url + endpoint
def get(self, endpoint: str, *, missing_ok: bool = False) -> dict[str, Any]:
"""GET ``{base_url}{endpoint}`` and return the parsed JSON.
A failed read raises (#22): ``ConnectionException`` when the switch does not
answer or refuses the session (401/403), ``RuntimeError`` for any other
non-2xx answer or one that is not JSON. With *missing_ok* a 404 (a resource
this firmware or configuration does not have) is an empty answer instead.
"""
resp = self._send("GET", endpoint)
if missing_ok and resp.status_code == HTTP_NOT_FOUND:
logger.debug("GET %s: HTTP 404, read as empty", endpoint)
return {}
raise_for_answer(resp, f"GET {endpoint}", self.hostname)
try:
resp = self._session.get(url, timeout=self.timeout)
if resp.ok:
return resp.json()
if resp.status_code == 404:
logger.debug("GET %s returned HTTP 404", url)
else:
logger.warning(
"GET %s returned HTTP %s: %s", url, resp.status_code, resp.text[:200]
)
except Exception as exc:
logger.warning("GET %s error: %s", url, exc)
return {}
data: dict[str, Any] = resp.json()
except ValueError as exc:
raise RuntimeError(
f"GET {endpoint} on {self.hostname}: the answer is not JSON"
) from exc
return data
def run_cli(self, command: str) -> dict[str, Any]:
"""POST *command* to the ``/cli`` endpoint and return its answer; raises as get() does."""
resp = self._send("POST", "cli", json={"cmd": command})
raise_for_answer(resp, f"CLI {command!r}", self.hostname)
answer: dict[str, Any] = resp.json()
return answer
def _send(self, method: str, endpoint: str, **kwargs: Any) -> requests.Response:
"""One request; a switch that does not answer raises ``ConnectionException``."""
try:
return self._session.request(
method, self._base_url + endpoint, timeout=self.timeout, **kwargs
)
except requests.exceptions.RequestException as exc:
raise ConnectionException(
f"{method} {endpoint} on {self.hostname} failed: {exc}"
) from exc
def post(self, endpoint: str, **kwargs: Any) -> requests.Response:
"""POST ``{base_url}{endpoint}``."""
@@ -246,12 +286,12 @@ class ProcurveApiClient:
def get_facts(self) -> dict:
"""Return NAPALM facts from the REST API."""
system = self.get("system/status")
system = self.get("system/status", missing_ok=True)
if not system:
# Fallback endpoint for stacked switches
system = self.get("system/status/global_info")
dns = self.get("dns")
dns = self.get("dns", missing_ok=True)
domain = ""
if dns:
domains = dns.get("dns_domain_names", [])
@@ -262,7 +302,7 @@ class ProcurveApiClient:
# Interface list from blades
iface_list = []
sw_status = self.get("system/status/switch")
sw_status = self.get("system/status/switch", missing_ok=True)
for blade in sw_status.get("blades", []):
for port in blade.get("data_ports", []):
iface_list.append(port.get("port_name", ""))
@@ -297,7 +337,7 @@ class ProcurveApiClient:
def get_interfaces(self) -> dict[str, dict]:
"""Return NAPALM interfaces from the REST API."""
ports_data = self.get("ports")
stats_data = self.get("port-statistics")
stats_data = self.get("port-statistics", missing_ok=True)
output: dict[str, dict] = {}
trunk_groups: dict[str, list] = {}
@@ -309,24 +349,21 @@ class ProcurveApiClient:
# count (observed: a 2530-48G reports 51 of its 52 ports). Fill in
# any ports known to system/status/switch but missing from /ports.
seen_ids = {p.get("id") for p in port_elements}
try:
sw_status = self.get("system/status/switch")
for blade in sw_status.get("blades", []):
for p in blade.get("data_ports", []):
pid = p.get("port_name", "")
if pid and pid not in seen_ids:
port_elements.append(
{
"id": pid,
"name": "",
"is_port_up": p.get("operStatus") == "OPER_UP",
"is_port_enabled": p.get("adminStatus") == "ADMIN_UP",
"trunk_group": "",
}
)
seen_ids.add(pid)
except Exception:
logger.debug("system/status/switch for missing ports: ignored", exc_info=True)
sw_status = self.get("system/status/switch", missing_ok=True)
for blade in sw_status.get("blades", []):
for p in blade.get("data_ports", []):
pid = p.get("port_name", "")
if pid and pid not in seen_ids:
port_elements.append(
{
"id": pid,
"name": "",
"is_port_up": p.get("operStatus") == "OPER_UP",
"is_port_enabled": p.get("adminStatus") == "ADMIN_UP",
"trunk_group": "",
}
)
seen_ids.add(pid)
for port in port_elements:
pid = port.get("id", "")
@@ -369,7 +406,7 @@ class ProcurveApiClient:
vlan_id = str(vlan.get("vlan_id", ""))
vlan_name = f"VLAN{vlan_id}"
# IPv4 from /vlans/{id}/ipv4
ipv4_data = self.get(f"vlans/{vlan_id}/ipv4")
ipv4_data = self.get(f"vlans/{vlan_id}/ipv4", missing_ok=True)
for entry in ipv4_data.get("ipv4_element", []):
addr = entry.get("address", "")
mask = entry.get("mask", "")
@@ -393,7 +430,7 @@ class ProcurveApiClient:
def get_poe_ports(self) -> dict[str, dict]:
"""Return PoE configuration for all ports, keyed by port id."""
data = self.get("poe/ports")
data = self.get("poe/ports", missing_ok=True)
return {p["port_id"]: p for p in data.get("port_poe", []) if p.get("port_id")}
def set_port_poe(self, port_id: str, payload: dict[str, Any]) -> requests.Response:
@@ -484,16 +521,12 @@ class ProcurveApiClient:
}
def _get_text(self, endpoint: str) -> str:
"""GET *endpoint* and return the response body as plain text."""
url = self._base_url + endpoint
try:
resp = self._session.get(url, timeout=self.timeout)
if resp.ok:
return resp.text
logger.warning("GET %s returned HTTP %s: %s", url, resp.status_code, resp.text[:200])
except Exception as exc:
logger.warning("GET %s error: %s", url, exc)
return ""
"""GET *endpoint* as plain text; ``""`` when this firmware does not have it (404)."""
resp = self._send("GET", endpoint)
if resp.status_code == HTTP_NOT_FOUND:
return ""
raise_for_answer(resp, f"GET {endpoint}", self.hostname)
return resp.text
def get_ntp_servers(self) -> dict[str, dict]:
"""Return NTP servers from REST API."""
+11 -13
View File
@@ -631,7 +631,11 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
) -> dict[str, str]:
"""Return device configuration."""
if self._transport == "api":
result = self._api.get_config()
try:
result = self._api.get_config()
except (ConnectionException, RuntimeError) as exc: # SSH reads it, or raises
logger.info("REST config read failed for %s: %s", self.hostname, exc)
result = {}
if result.get("running"):
return result
# REST endpoint not available on this firmware (e.g. HP 2530 / YA series).
@@ -668,9 +672,10 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
return conn.send_command("show running-config")
finally:
conn.disconnect()
except Exception as exc:
logger.warning("SSH config fallback failed for %s: %s", self.hostname, exc)
return ""
except ConnectionException: # a changed host key, say: as it is
raise
except Exception as exc: # a failed read raises (#22)
raise ConnectionException(f"SSH config read failed for {self.hostname}: {exc}") from exc
# ------------------------------------------------------------------
# NAPALM: get_environment
@@ -1137,15 +1142,8 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
"""Execute raw CLI commands and return output dict."""
if self._transport == "api":
# ArubaOS REST API supports CLI via POST /rest/<ver>/cli
results: dict[str, str] = {}
for cmd in commands:
resp = self._api.post("cli", json={"cmd": cmd})
if resp.ok:
results[cmd] = parsers.parse_cli_answer(resp.json())
else:
results[cmd] = f"Error: HTTP {resp.status_code}"
return results
# POST /rest/<ver>/cli; a failed request raises, it is not the command's output
return {cmd: parsers.parse_cli_answer(self._api.run_cli(cmd)) for cmd in commands}
return {cmd: self._send_command(cmd) for cmd in commands}
+3 -3
View File
@@ -1,7 +1,7 @@
{
"coverage_floor": 54.0,
"function_complexity": {
"napalm_procurve/api_client.py::ProcurveApiClient.get_interfaces": 15,
"napalm_procurve/api_client.py::ProcurveApiClient.get_interfaces": 14,
"napalm_procurve/api_client.py::ProcurveApiClient.get_vlans": 15,
"napalm_procurve/parsers.py::_parse_procurve_uptime": 11,
"napalm_procurve/parsers.py::parse_ip_interfaces": 14,
@@ -13,7 +13,7 @@
"napalm_procurve/procurve.py::ProcurveDriver.set_lag_members": 12
},
"function_lines": {
"napalm_procurve/api_client.py::ProcurveApiClient.get_interfaces": 65,
"napalm_procurve/api_client.py::ProcurveApiClient.get_interfaces": 62,
"napalm_procurve/api_client.py::ProcurveApiClient.get_vlans": 101,
"napalm_procurve/parsers.py::parse_ip_interfaces": 58,
"napalm_procurve/parsers.py::parse_lldp_neighbors_detail": 59,
@@ -27,7 +27,7 @@
"napalm_procurve.procurve"
],
"python_file_lines": {
"napalm_procurve/procurve.py": 1387
"napalm_procurve/procurve.py": 1385
},
"untyped_public": []
}
+5 -8
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
from pathlib import Path
from unittest.mock import MagicMock
from napalm_procurve.api_client import ProcurveApiClient
from napalm_procurve.procurve import ProcurveDriver
FIXTURES = Path(__file__).parent.parent / "fixtures"
@@ -20,8 +21,10 @@ SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").re
def _rest_driver(resp: MagicMock) -> ProcurveDriver:
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
driver._transport = "api"
driver._api = MagicMock()
driver._api.post.return_value = resp
driver._api = ProcurveApiClient("10.0.0.40", "manager", "s3cret")
driver._api.setup("v7", "https")
driver._api._session = MagicMock()
driver._api._session.request.return_value = resp
return driver
@@ -36,9 +39,3 @@ def test_over_rest_cli_returns_the_decoded_output():
out = _rest_driver(resp).cli(["show snmp-server"])
assert out == {"show snmp-server": SHOW_SNMP_SERVER}
def test_over_rest_cli_names_a_failed_request():
resp = MagicMock(ok=False, status_code=401)
assert _rest_driver(resp).cli(["show version"]) == {"show version": "Error: HTTP 401"}
+226
View File
@@ -0,0 +1,226 @@
"""A failed REST read raises; it is not reported as an empty switch (#22).
``ProcurveApiClient.get()`` answered ``{}`` for a timeout, an expired session or an
HTTP 500, and every REST getter built its answer from that: a switch with no
hostname, no ports, no VLANs and no neighbours. A 404 is an empty answer only
where the getter expects the resource to be missing on some firmware.
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import MagicMock
import pytest
import requests
from napalm.base.exceptions import ConnectionException
from napalm_procurve.api_client import ProcurveApiClient
from napalm_procurve.procurve import ProcurveDriver
BASE = "https://10.0.0.40/rest/v7/"
def _response(status: int, body: Any = None, *, text: str | None = None) -> requests.Response:
resp = requests.Response()
resp.status_code = status
if text is not None:
resp._content = text.encode()
resp.headers["Content-Type"] = "text/html"
else:
resp._content = json.dumps({} if body is None else body).encode()
resp.headers["Content-Type"] = "application/json"
return resp
class FakeSession:
"""A REST session that answers each endpoint as told; 200 ``{}`` otherwise."""
def __init__(self, answers: dict[str, requests.Response | Exception]) -> None:
self.answers = answers
def _answer(self, url: str) -> requests.Response:
answer = self.answers.get(url.removeprefix(BASE), _response(200))
if isinstance(answer, Exception):
raise answer
return answer
def request(self, method: str, url: str, timeout: float, **kwargs: Any) -> requests.Response:
return self._answer(url)
def _client(answers: dict[str, requests.Response | Exception]) -> ProcurveApiClient:
client = ProcurveApiClient("10.0.0.40", "manager", "s3cret")
client.setup("v7", "https")
client._session = FakeSession(answers) # type: ignore[assignment]
return client
def _rest_driver(answers: dict[str, requests.Response | Exception]) -> ProcurveDriver:
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
driver._transport = "api"
driver._api = _client(answers)
return driver
PORTS = {"port_element": [{"id": "1", "name": "uplink", "is_port_up": True}]}
# --- get() -------------------------------------------------------------------
def test_get_returns_the_parsed_answer():
assert _client({"ports": _response(200, PORTS)}).get("ports") == PORTS
def test_get_raises_on_a_server_error():
with pytest.raises(RuntimeError, match="HTTP 500"):
_client({"ports": _response(500)}).get("ports")
@pytest.mark.parametrize("status", [401, 403])
def test_get_raises_connection_exception_for_a_refused_session(status):
with pytest.raises(ConnectionException, match=f"HTTP {status}"):
_client({"ports": _response(status)}).get("ports")
def test_get_raises_connection_exception_when_the_switch_does_not_answer():
timeout = requests.exceptions.ReadTimeout("read timed out")
with pytest.raises(ConnectionException, match="read timed out"):
_client({"ports": timeout}).get("ports")
def test_get_raises_on_a_404_unless_the_caller_expects_one():
client = _client({"dns": _response(404)})
with pytest.raises(RuntimeError, match="HTTP 404"):
client.get("dns")
assert client.get("dns", missing_ok=True) == {}
def test_get_raises_on_an_answer_that_is_not_json():
with pytest.raises(RuntimeError, match="not JSON"):
_client({"ports": _response(200, text="<html>session timed out</html>")}).get("ports")
# --- the getters ---------------------------------------------------------------
def test_get_interfaces_raises_when_ports_answers_500():
with pytest.raises(RuntimeError, match="ports"):
_rest_driver({"ports": _response(500)}).get_interfaces()
@pytest.mark.parametrize(
("getter", "endpoint"),
[
("get_facts", "system/status"),
("get_interfaces", "port-statistics"),
("get_interfaces", "system/status/switch"),
("get_interfaces_ip", "vlans"),
("get_arp_table", "arp"),
("get_mac_address_table", "mac-table"),
("get_lldp_neighbors", "lldp/remote-device"),
("get_lldp_neighbors_detail", "lldp/remote-device"),
("get_ntp_servers", "ntp/server"),
("get_vlans", "vlans"),
("get_vlans", "vlans-ports"),
("get_poe_status", "poe/ports"),
],
)
def test_a_getter_raises_when_its_read_fails(getter, endpoint):
with pytest.raises(RuntimeError, match="HTTP 500"):
getattr(_rest_driver({endpoint: _response(500)}), getter)()
def test_get_facts_falls_back_to_global_info_when_system_status_is_missing():
driver = _rest_driver(
{
"system/status": _response(404),
"system/status/global_info": _response(200, {"name": "stack-1"}),
}
)
assert driver.get_facts()["hostname"] == "stack-1"
def test_get_facts_without_a_dns_resource_has_no_domain():
driver = _rest_driver({"system/status": _response(200, {"name": "sw1"}), "dns": _response(404)})
facts = driver.get_facts()
assert (facts["hostname"], facts["fqdn"]) == ("sw1", "sw1")
def test_get_interfaces_without_port_statistics_reports_the_ports():
driver = _rest_driver({"ports": _response(200, PORTS), "port-statistics": _response(404)})
assert driver.get_interfaces()["1"]["speed"] == 0.0
def test_get_interfaces_ip_skips_a_vlan_without_an_ipv4_resource():
driver = _rest_driver(
{
"vlans": _response(200, {"vlan_element": [{"vlan_id": 1}, {"vlan_id": 10}]}),
"vlans/1/ipv4": _response(404),
"vlans/10/ipv4": _response(
200, {"ipv4_element": [{"address": "10.0.10.2", "mask": "255.255.255.0"}]}
),
}
)
assert driver.get_interfaces_ip() == {
"VLAN10": {"ipv4": {"10.0.10.2": {"prefix_length": 24}}, "ipv6": {}}
}
def test_get_poe_status_of_a_switch_without_poe_is_empty():
assert _rest_driver({"poe/ports": _response(404)}).get_poe_status() == {}
# --- get_config ----------------------------------------------------------------
def test_get_config_raises_when_neither_rest_nor_ssh_reads_it():
driver = _rest_driver({"running-config": _response(500)})
driver._ssh_connect = MagicMock(side_effect=OSError("connection refused"))
with pytest.raises(ConnectionException, match="connection refused"):
driver.get_config()
def test_get_config_reads_over_ssh_when_the_firmware_has_no_config_resource():
driver = _rest_driver({"running-config": _response(404)})
ssh = MagicMock()
ssh.send_command.return_value = "hostname sw1"
driver._ssh_connect = MagicMock(return_value=ssh)
assert driver.get_config()["running"] == "hostname sw1"
def test_get_config_over_rest_reads_running_and_startup():
running = requests.Response()
running.status_code, running._content = 200, b"hostname sw1"
startup = requests.Response()
startup.status_code, startup._content = 200, b"hostname sw0"
driver = _rest_driver({"running-config": running, "startup-config": startup})
assert driver.get_config() == {
"running": "hostname sw1",
"startup": "hostname sw0",
"candidate": "",
}
# --- cli() -----------------------------------------------------------------------
def test_cli_over_rest_raises_on_a_server_error():
with pytest.raises(RuntimeError, match="HTTP 500"):
_rest_driver({"cli": _response(500)}).cli(["show version"])
def test_cli_over_rest_raises_connection_exception_for_a_refused_session():
with pytest.raises(ConnectionException, match="HTTP 401"):
_rest_driver({"cli": _response(401)}).cli(["show version"])
def test_cli_over_rest_raises_connection_exception_when_the_switch_does_not_answer():
refused = requests.exceptions.ConnectionError("connection refused")
with pytest.raises(ConnectionException, match="connection refused"):
_rest_driver({"cli": refused}).cli(["show version"])