fix(rest): raise on a failed REST read instead of returning {}
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m14s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 2m49s
driver / publish (pull_request) Skipped

ProcurveApiClient.get() answered {} for a timeout, a refused session or
any HTTP error, so every REST getter reported a failed read as a switch
with no hostname, ports, VLANs or neighbours. get() now raises
ConnectionException (no answer, 401/403) or RuntimeError (other
non-2xx, a body that is not JSON); the getters that expect a resource
to be missing on some firmware pass missing_ok for its 404.

get_config no longer returns an empty configuration when both the REST
read and the SSH fallback failed, and cli() over REST raises instead of
returning "Error: HTTP <status>" as the command's output.

Closes #22
This commit is contained in:
Christian Manivong committed 2026-11-02 08:39:04 +01:00
1 parent 1105c47a3d
commit 628a827cbe
6 files changed
+340 -73

No files matched your search

+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}