fix(dal): raise on a failed request instead of reading it as empty
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 4m10s
driver / test (3.13) (pull_request) Successful in 4m6s
driver / lowest (pull_request) Successful in 3m43s
driver / build (pull_request) Successful in 31s
driver / security (pull_request) Successful in 1m17s
CI / driver (pull_request) Successful in 5m59s
driver / publish (pull_request) Skipped

_dal_query and _fetch_page returned None for any failure, and the
getters turned that into empty data, so a timeout or an expired session
read as a gateway with no hosts, port forwards, SSIDs or Wi-Fi clients.
Both now raise: ConnectionException when the gateway does not answer or
refuses the session, RuntimeError naming the request otherwise. A getter
whose DAL request fails still reads the HTML page and raises when that
fails too; get_facts no longer swallows a failed get_interfaces.

Closes #15
This commit is contained in:
Christian Manivong committed 2026-11-02 09:18:50 +01:00
1 parent da9e303e45
commit ded19238c0
4 files changed
+257 -94

No files matched your search

+96 -92
View File
@@ -8,10 +8,12 @@ from __future__ import annotations
import base64
import json
import logging
import os
import re
import socket
from typing import Any
from collections.abc import Callable
from typing import Any, TypeVar
from urllib.parse import urljoin
import requests
@@ -33,6 +35,13 @@ from napalm_device_types.models import (
WirelessClientDict,
)
logger = logging.getLogger(__name__)
#: Answers that mean the session is not (or no longer) accepted.
_SESSION_REFUSED = (401, 403)
_T = TypeVar("_T")
_PING_UNSUPPORTED = "Not supported on Zyxel VMG: the DAL does not report ping replies"
@@ -238,7 +247,8 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
except (requests.RequestException, json.JSONDecodeError, TypeError):
return None
def _dal_query(self, oid: str, data: dict | None = None) -> dict | None:
def _dal_query(self, oid: str, data: dict | None = None) -> dict:
"""The gateway's decrypted answer to DAL *oid*; a failed request raises (#15)."""
if self._session is None or self._sessionkey is None or self._crypto is None:
raise ConnectionClosedException("Not connected")
if data is None:
@@ -253,10 +263,11 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
)
resp.raise_for_status()
return self._crypto.decrypt_response(resp.json())
except Exception:
return None
except (requests.RequestException, ValueError, TypeError, KeyError) as exc:
raise self._request_failed(f"DAL {oid}", exc) from exc
def _fetch_page(self, path: str) -> str | None:
def _fetch_page(self, path: str) -> str:
"""The text of *path*; a failed request raises (#15)."""
if self._session is None or self._sessionkey is None:
raise ConnectionClosedException("Not connected")
try:
@@ -267,16 +278,34 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
)
resp.raise_for_status()
return resp.text
except requests.RequestException:
return None
except requests.RequestException as exc:
raise self._request_failed(f"GET {path}", exc) from exc
def _request_failed(self, what: str, exc: Exception) -> Exception:
"""``ConnectionException`` when the gateway did not answer or refused the session,
``RuntimeError`` naming *what* for any other failure."""
detail = f"{what} on {self._base_url} failed: {exc}"
if isinstance(exc, ValueError | TypeError | KeyError): # an answer, but not one we read
return RuntimeError(detail)
status = exc.response.status_code if getattr(exc, "response", None) is not None else None
if status is None or status in _SESSION_REFUSED:
return ConnectionException(detail)
return RuntimeError(detail)
def _read_dal_or_page(
self, oid: str, page: str, parse_dal: Callable[[Any], _T], parse_page: Callable[[str], _T]
) -> _T:
"""The DAL's answer to *oid*, else the HTML *page*; raises when neither can be read."""
try:
return parse_dal(json.loads(self._fetch_page(f"cgi-bin/DAL?oid={oid}")))
except (ConnectionException, RuntimeError, ValueError, TypeError) as exc:
logger.debug("DAL %s not read (%s), reading %s", oid, exc, page)
return parse_page(self._fetch_page(page))
def get_facts(self) -> dict[str, Any]:
"""Return device facts such as model, serial, OS version, and uptime."""
info = self._device_info or {}
try:
iface_list = list(self.get_interfaces().keys())
except Exception:
iface_list = []
iface_list = list(self.get_interfaces().keys())
return {
"vendor": self.VENDOR,
"model": info.get("ModelName", ""),
@@ -520,17 +549,12 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
def get_port_forwards(self) -> list[PortForwardDict]:
"""Return port forwarding rules from DAL or HTML fallback."""
html = self._fetch_page("cgi-bin/DAL?oid=NAT_PORTMAP")
if html is not None:
try:
data = json.loads(html)
return self._parse_port_forwards_dal(data)
except (json.JSONDecodeError, TypeError):
pass
html = self._fetch_page("Status.htm")
if html is not None:
return self._parse_port_forwards_html(html)
return []
return self._read_dal_or_page(
"NAT_PORTMAP",
"Status.htm",
self._parse_port_forwards_dal,
self._parse_port_forwards_html,
)
def _parse_port_forwards_dal(self, data: dict) -> list[PortForwardDict]:
forwards: list[PortForwardDict] = []
@@ -577,17 +601,9 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
def get_hosts(self) -> list[HostDict]:
"""Return DHCP host entries from DAL or HTML fallback."""
html = self._fetch_page("cgi-bin/DAL?oid=LAN_HOSTS")
if html is not None:
try:
data = json.loads(html)
return self._parse_hosts_dal(data)
except (json.JSONDecodeError, TypeError):
pass
html = self._fetch_page("dhcp.htm")
if html is not None:
return self._parse_hosts_html(html)
return []
return self._read_dal_or_page(
"LAN_HOSTS", "dhcp.htm", self._parse_hosts_dal, self._parse_hosts_html
)
def _parse_hosts_dal(self, data: dict) -> list[HostDict]:
hosts: list[HostDict] = []
@@ -659,17 +675,12 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
def get_wireless_clients(self) -> list[WirelessClientDict]:
"""Return connected wireless clients from DAL or HTML fallback."""
html = self._fetch_page("cgi-bin/DAL?oid=WIFI_CLIENTS")
if html is not None:
try:
data = json.loads(html)
return self._parse_wireless_clients_dal(data)
except (json.JSONDecodeError, TypeError):
pass
html = self._fetch_page("wireless.htm")
if html is not None:
return self._parse_wireless_clients_html(html)
return []
return self._read_dal_or_page(
"WIFI_CLIENTS",
"wireless.htm",
self._parse_wireless_clients_dal,
self._parse_wireless_clients_html,
)
def _parse_wireless_clients_dal(self, data: dict) -> list[WirelessClientDict]:
clients: list[WirelessClientDict] = []
@@ -725,17 +736,9 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
def get_ssids(self) -> dict[str, SSIDDict]:
"""Return WiFi SSID configurations from DAL or HTML fallback."""
html = self._fetch_page("cgi-bin/DAL?oid=WIFI_SSIDS")
if html is not None:
try:
data = json.loads(html)
return self._parse_ssids_dal(data)
except (json.JSONDecodeError, TypeError):
pass
html = self._fetch_page("wireless.htm")
if html is not None:
return self._parse_ssids_html(html)
return {}
return self._read_dal_or_page(
"WIFI_SSIDS", "wireless.htm", self._parse_ssids_dal, self._parse_ssids_html
)
def _parse_ssids_dal(self, data: dict) -> dict[str, SSIDDict]:
ssids: dict[str, SSIDDict] = {}
@@ -778,54 +781,55 @@ class ZyxelVMGDriver(ResidentialGatewayDriver):
def get_radio_status(self) -> dict[str, RadioStatusDict]:
"""Return WiFi radio status from DAL or HTML fallback."""
return self._read_dal_or_page(
"WIFI_RADIO",
"wireless.htm",
self._parse_radio_status_dal,
self._parse_radio_status_html,
)
def _parse_radio_status_dal(self, data: dict) -> dict[str, RadioStatusDict]:
radios: dict[str, RadioStatusDict] = {}
html = self._fetch_page("cgi-bin/DAL?oid=WIFI_RADIO")
if html is not None:
try:
data = json.loads(html)
entries = data.get("radios", data.get("entries", []))
if isinstance(entries, dict):
entries = [entries]
for entry in entries if isinstance(entries, list) else []:
name = entry.get("Name", entry.get("name", ""))
channel = int(entry.get("Channel", entry.get("channel", 0)) or 0)
radios[name] = {
"enabled": bool(entry.get("Enabled", entry.get("enabled", True))),
"band": "2.4GHz" if channel <= 14 else "5GHz",
"channel": channel,
"channel_width": int(
entry.get("ChannelWidth", entry.get("channel_width", 0)) or 0
),
"tx_power": int(entry.get("TxPower", entry.get("tx_power", 0)) or 0),
"frequency": float(entry.get("Frequency", entry.get("frequency", 0)) or 0),
}
return radios
except (json.JSONDecodeError, TypeError, ValueError):
pass
html = self._fetch_page("wireless.htm")
if html is not None:
for band, pat in [("2.4GHz", r"2\.4[Gg]"), ("5GHz", r"5[Gg]")]:
if re.search(pat, html):
radios[band] = {
"enabled": True,
"band": band,
"channel": 0,
"channel_width": 0,
"tx_power": 0,
"frequency": 0.0,
}
entries = data.get("radios", data.get("entries", []))
if isinstance(entries, dict):
entries = [entries]
for entry in entries if isinstance(entries, list) else []:
name = entry.get("Name", entry.get("name", ""))
channel = int(entry.get("Channel", entry.get("channel", 0)) or 0)
radios[name] = {
"enabled": bool(entry.get("Enabled", entry.get("enabled", True))),
"band": "2.4GHz" if channel <= 14 else "5GHz",
"channel": channel,
"channel_width": int(entry.get("ChannelWidth", entry.get("channel_width", 0)) or 0),
"tx_power": int(entry.get("TxPower", entry.get("tx_power", 0)) or 0),
"frequency": float(entry.get("Frequency", entry.get("frequency", 0)) or 0),
}
return radios
def _parse_radio_status_html(self, html: str) -> dict[str, RadioStatusDict]:
radios: dict[str, RadioStatusDict] = {}
for band, pat in [("2.4GHz", r"2\.4[Gg]"), ("5GHz", r"5[Gg]")]:
if re.search(pat, html):
radios[band] = {
"enabled": True,
"band": band,
"channel": 0,
"channel_width": 0,
"tx_power": 0,
"frequency": 0.0,
}
return radios
def reboot_host(self) -> None:
"""Restart the gateway (``HostRebootMixin``); raises when it refuses."""
result = self._dal_query("REBOOT", {"Command": "reboot"})
if result is None or result.get("result") != "ZCFG_SUCCESS":
if result.get("result") != "ZCFG_SUCCESS":
raise RuntimeError(f"the gateway refused to reboot: {result}")
def restart_wifi(self, band: str = "both") -> None:
"""Restart the radios of *band* (``2.4G``, ``5G`` or ``both``); raises when refused."""
result = self._dal_query("WIFI_RESTART", {"Band": band})
if result is None or result.get("result") != "ZCFG_SUCCESS":
if result.get("result") != "ZCFG_SUCCESS":
raise RuntimeError(f"the gateway refused to restart Wi-Fi ({band}): {result}")
def get_diagnostics(self) -> dict: