Files
napalm-zyxel/napalm_zyxel/parsers.py
T
Christian Manivong 3213dfaaaa fix(wan): read the uplink from the gateway's status page (#29)
get_wan_status built its answer from WanIp, WanAccessType,
SystemUpTime, MaxUpstream and MaxDownstream in getBasicInformation.
A VMG4005-B50A sends none of them there, so every gateway's uplink
read as down, with no address and no sync rate; get_nat_translations
built inside_global from the same WanIp and reported ":<port>".

Both now read the DAL's cardpage_status. A bridge has no WAN address
of its own, so it is connected when its DSL line is in sync (a
DslChannelInfo entry with Status "Up"); a router is connected when a
WAN interface that is not IP_Bridged is up with an address. The sync
rates are those of the channels in sync, added up for bonded lines;
a channel out of sync keeps its last rates, which are not reported.
A translation without a WAN address goes to 0.0.0.0, and without
enabled port forwards the status page is not read at all.

The tests read the recorded, anonymised status page of a
VMG4005-B50A bridge whose line was not in sync; the in-sync and
router states are derived from it.

Closes #29
2026-11-12 19:05:48 +01:00

150 lines
5.8 KiB
Python

"""Pure parsers: the gateway's decrypted DAL answers in, NAPALM's typed dicts out."""
from __future__ import annotations
from typing import Any
from napalm_device_types.models import HostDict, PortForwardDict, WANStatusDict
#: The name ``lanhosts`` gives a host the gateway has no name for.
_UNKNOWN_HOST = "Unknown"
#: ``Protocol`` of a ``nat`` rule, as the protocols it forwards.
_FORWARD_PROTOCOLS = {"TCP": ("TCP",), "UDP": ("UDP",), "ALL": ("TCP", "UDP")}
def _host(entry: dict[str, Any]) -> HostDict:
"""One host of the DAL's ``lanhosts`` answer."""
name = str(entry.get("HostName") or "")
connection = str(entry.get("X_ZYXEL_ConnectionType") or "")
host: HostDict = {
"mac": str(entry.get("PhysAddress") or "").lower(),
"ip": str(entry.get("IPAddress") or ""),
"hostname": "" if name == _UNKNOWN_HOST else name,
"interface_type": "WLAN" if "Wi-Fi" in connection else "LAN",
"is_active": bool(entry.get("Active")),
}
if entry.get("AddressSource") == "DHCP":
host["lease_time_remaining"] = int(entry.get("LeaseTimeRemaining") or 0)
return host
def hosts(objects: list[dict[str, Any]]) -> list[HostDict]:
"""The hosts of the DAL's ``lanhosts`` answer (``Object[].lanhosts[]``)."""
return [
_host(entry)
for obj in objects
for entry in obj.get("lanhosts") or []
if isinstance(entry, dict)
]
def port_forwards(objects: list[dict[str, Any]]) -> list[PortForwardDict]:
"""The rules of the DAL's ``nat`` answer, one per protocol they forward.
A port range is reported by its first port.
"""
forwards: list[PortForwardDict] = []
for rule in objects:
protocol = str(rule.get("Protocol") or "").upper()
for proto in _FORWARD_PROTOCOLS.get(protocol, (protocol,)):
forward: PortForwardDict = {
"name": str(rule.get("Description") or ""),
"protocol": proto,
"external_port": int(rule.get("ExternalPortStart") or 0),
"internal_ip": str(rule.get("InternalClient") or ""),
"internal_port": int(rule.get("InternalPortStart") or 0),
"enabled": bool(rule.get("Enable")),
}
if rule.get("SetOriginatingIP") and rule.get("OriginatingIpAddress"):
forward["remote_host"] = str(rule["OriginatingIpAddress"])
forwards.append(forward)
return forwards
def _channels_in_sync(page: dict[str, Any]) -> list[dict[str, Any]]:
"""The DSL channels of a ``cardpage_status`` page that are in sync."""
return [
channel
for channel in page.get("DslChannelInfo") or []
if isinstance(channel, dict) and channel.get("Status") == "Up"
]
def _routed_wans(page: dict[str, Any]) -> list[dict[str, Any]]:
"""The enabled WAN interfaces of a ``cardpage_status`` page that are not bridges."""
return [
entry
for entry in page.get("WanLanInfo") or []
if isinstance(entry, dict)
and entry.get("X_ZYXEL_Type") == "WAN"
and entry.get("Enable")
and entry.get("X_ZYXEL_ConnectionType") != "IP_Bridged"
]
def _address(entry: dict[str, Any]) -> str:
"""The first enabled IPv4 address of a ``WanLanInfo`` entry, else ``""``."""
for addr in entry.get("IPv4Address") or []:
if isinstance(addr, dict) and addr.get("Enable") and addr.get("IPAddress"):
return str(addr["IPAddress"])
return ""
def _connected_wan(page: dict[str, Any]) -> dict[str, Any] | None:
"""The routed WAN interface that is up with an address, if there is one."""
for entry in _routed_wans(page):
if entry.get("Status") == "Up" and _address(entry):
return entry
return None
def wan_address(page: dict[str, Any]) -> str:
"""The gateway's own WAN address on a ``cardpage_status`` page; ``""`` for a bridge
or a router whose WAN is not up."""
wan = _connected_wan(page)
return _address(wan) if wan is not None else ""
def _seconds(value: Any) -> int:
"""*value* as a number of seconds; ``0`` (unknown) when it is not a number."""
text = str(value if value is not None else "").strip()
return int(text) if text.isdigit() else 0
def _uplink(page: dict[str, Any], channels: list[dict[str, Any]]) -> tuple[bool, str, int]:
"""Whether the uplink is connected, its type and how long it has been up."""
routed = _routed_wans(page)
if not routed: # a bridge: the DSL line is the uplink
uptime = _seconds(channels[0].get("DSLUpTime")) if channels else 0
return bool(channels), "DSL", uptime
wan = _connected_wan(page)
connection_type = str(routed[0].get("Encapsulation") or "")
if wan is None:
return False, connection_type, 0
return True, connection_type, _seconds(wan.get("X_ZYXEL_UpTime"))
def wan_status(page: dict[str, Any]) -> WANStatusDict:
"""The uplink of a ``cardpage_status`` page.
A router (a WAN interface that is not ``IP_Bridged``) is connected when such an
interface is up with an address. A bridge has no WAN address of its own: it is
connected when its DSL line is in sync. The sync rates (kbit/s) are those of the
channels in sync, added up for bonded lines; a channel out of sync keeps the rates
of its last sync, which are not reported.
"""
channels = _channels_in_sync(page)
connected, connection_type, uptime = _uplink(page, channels)
return {
"connection_type": connection_type,
"is_connected": connected,
"external_ip": wan_address(page),
"uptime": uptime,
"bytes_sent": 0,
"bytes_received": 0,
"max_bitrate_up": sum(int(c.get("UpstreamCurrRate") or 0) for c in channels),
"max_bitrate_down": sum(int(c.get("DownstreamCurrRate") or 0) for c in channels),
"link_status": "Up" if channels else "Down",
}