From 6bd33729337e0b905eb54234e49ca63e79921d30 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 11 Nov 2026 15:25:06 +0100 Subject: [PATCH] feat(time-sync): the switch's NTP servers and zone through TimeSyncMixin netOrk aligns every device's NTP servers and time zone with its site's (NetOrk/netork#2360, #2366). A ProCurve keeps them as configuration lines: sntp server priority <1-3> (or ntp server lines when 16.x runs timesync ntp), time timezone and time daylight-time-rule. get_time_sync() reads those lines from show running-config, over REST through the /cli endpoint, and the zone as None: the switch keeps minutes and a rule, no name. configure_time_sync() writes the servers in the protocol the switch runs (SNTP unless it runs NTP, switching TimeP to sntp unicast), keeping those already in place from the first on; the zone as minutes and the switch's own US/EU rule, or user-defined dates for other Sunday rules, from the zone's POSIX rule. What the switch cannot take is refused before anything is sent: more than 3 SNTP or 8 NTP servers, host names, half an hour of summer time, a change on a weekday. A change is saved with write memory; values already in place are not sent again, so the alignment on every poll does not churn. Over REST the writes need the CLI, so the temporary SSH session configure_snmp_agent opened is now the _config_cli() context manager both use. get_ntp_servers() reads through get_time_sync() on every transport; it and get_ntp_stats() move to time_sync.py with the rest of the clock, so procurve.py shrinks (1383 -> 1339 lines). The unused parse_ntp_servers() and ProcurveApiClient.get_ntp_servers() are gone. --- CHANGELOG.md | 21 ++ README.md | 2 + napalm_procurve/api_client.py | 10 - napalm_procurve/parsers.py | 23 -- napalm_procurve/procurve.py | 80 ++--- napalm_procurve/time_sync.py | 305 ++++++++++++++++++ pyproject.toml | 2 +- tests/quality_baseline.json | 2 +- tests/unit/test_driver.py | 16 - tests/unit/test_rest_failed_reads.py | 1 - tests/unit/test_time_sync.py | 450 +++++++++++++++++++++++++++ 11 files changed, 801 insertions(+), 111 deletions(-) create mode 100644 napalm_procurve/time_sync.py create mode 100644 tests/unit/test_time_sync.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3baf034..49a15da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,28 @@ All notable changes to this driver. The format follows ## [Unreleased] +### Added +- `get_time_sync()` and `configure_time_sync()` through napalm-device-types' + `TimeSyncMixin` (4.35.0, NetOrk/netork#2366). The read takes the switch's time lines + from `show running-config` (over REST through the `/cli` endpoint): the SNTP servers + by priority, or the `ntp server` lines on a switch running `timesync ntp`; the zone + reads as `None`, since the switch keeps minutes and a summer-time rule, not a name. + A write puts the servers in the protocol the switch runs, at most 3 SNTP or 8 NTP + servers, IP addresses only, and turns a switch on TimeP or no protocol to `timesync + sntp` and `sntp unicast`. Servers already in place from the first one on are kept, + the rest replaced. An IANA zone is written as `time timezone ` and a + `time daylight-time-rule` from its POSIX rule: the US and EU dates as the switch's own + rules, other Sunday rules as `user-defined` dates; a zone the switch cannot keep (half + an hour of summer time, a change on a weekday other than Sunday) is refused before + anything is sent. A change is saved with `write memory`; what the switch already has + is not sent again. Over REST the writes run on a temporary SSH session, as + `configure_snmp_agent` does. + ### Changed +- Needs napalm-device-types 4.35.0. +- `get_ntp_servers()` lists the configured servers as `get_time_sync()` reads them, over + every transport. Over SSH it took every IPv4 address in `show ntp associations` (or + `show timesync`), over REST the `ntp/server` resource. `get_ntp_stats()` is unchanged. - The floor on napalm-device-types is 4.23.0, the first release with what this driver uses. - `ssl_verify` (`verify_ssl`, `verify`) no longer has any effect: the REST certificate is verified by its fingerprint instead. Callers that set it to `True` had their login diff --git a/README.md b/README.md index 4ba3c75..80089e2 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,8 @@ with Driver( | `get_lldp_neighbors_detail()` | ✅ | ✅ | | `get_config()` | ✅ | ✅ | | `get_ntp_servers()` | ✅ | ✅ | +| `get_time_sync()` | ✅ | ✅ | +| `configure_time_sync()` | ✅ (CLI over a temporary SSH session) | ✅ | | `get_environment()` | ❌ | ✅ | | `get_users()` | ❌ | ✅ | | `get_snmp_information()` | ❌ | ✅ | diff --git a/napalm_procurve/api_client.py b/napalm_procurve/api_client.py index 4453519..215d322 100644 --- a/napalm_procurve/api_client.py +++ b/napalm_procurve/api_client.py @@ -528,16 +528,6 @@ class ProcurveApiClient: 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.""" - data = self.get("ntp/server") - servers: dict[str, dict] = {} - for entry in data.get("ntp_server_element", []): - addr = entry.get("server_address", "") - if addr: - servers[addr] = {} - return servers - def get_vlans(self) -> dict[int, dict]: """Return VLAN information with proper tagged/untagged separation. diff --git a/napalm_procurve/parsers.py b/napalm_procurve/parsers.py index df42e47..dd5110b 100644 --- a/napalm_procurve/parsers.py +++ b/napalm_procurve/parsers.py @@ -563,29 +563,6 @@ def _parse_capabilities(cap_str: str) -> list[str]: return result -# --------------------------------------------------------------------------- -# show ntp associations / show timesync -# --------------------------------------------------------------------------- - - -def parse_ntp_servers(output: str) -> dict[str, dict]: - """Parse ``show ntp associations`` or ``show ntp status`` output. - - Returns dict of {server_ip: {}} as per NAPALM get_ntp_servers. - """ - servers: dict[str, dict] = {} - for line in output.splitlines(): - # " 10.0.0.1 sys.peer 2 ..." or "NTP server: 10.0.0.1" - m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", line) - if m: - ip = m.group(1) - # Skip gateway / default-gateway entries - if "gateway" in line.lower() or "default" in line.lower(): - continue - servers[ip] = {} - return servers - - # --------------------------------------------------------------------------- # show environment # --------------------------------------------------------------------------- diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 61ccf02..7c09dec 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -17,6 +17,8 @@ Netmiko device type: ``hp_procurve`` / ``hp_procurve_telnet`` import logging import re +from collections.abc import Iterator +from contextlib import contextmanager from typing import Any, ClassVar from napalm.base.exceptions import ( @@ -48,6 +50,7 @@ from netmiko.exceptions import NetmikoAuthenticationException from napalm_procurve import parsers from napalm_procurve.api_client import HTTPS_PORT, ProcurveApiClient from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason +from napalm_procurve.time_sync import ProcurveTimeSyncMixin logger = logging.getLogger("napalm_procurve") @@ -83,7 +86,7 @@ _SSH_PORT_BESIDE_API = 22 # SSH beside the REST API: ``port`` then is the API's _CLI_WORD = re.compile(r'^[^\s"#]+$') -class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): +class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver): """NAPALM driver for HPE/Aruba ProCurve switches. Auto-detects transport on ``open()``. See module docstring for details. @@ -689,52 +692,6 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): combined = sysinfo + "\n" + env_out return parsers.parse_environment(combined) - # ------------------------------------------------------------------ - # NAPALM: get_ntp_servers - # ------------------------------------------------------------------ - - def get_ntp_servers(self) -> dict[str, dict]: - """Return configured NTP servers.""" - if self._transport == "api": - return self._api.get_ntp_servers() - - out = self._send_command(["show ntp associations", "show ntp status", "show timesync"]) - return parsers.parse_ntp_servers(out) - - # ------------------------------------------------------------------ - # NAPALM: get_ntp_stats - # ------------------------------------------------------------------ - - def get_ntp_stats(self) -> list[dict]: - """Return NTP peer statistics.""" - out = self._send_command(["show ntp associations", "show ntp status"]) - stats = [] - for line in out.splitlines(): - m = re.match( - r"\s*([*+]?)\s*(\d{1,3}(?:\.\d{1,3}){3})" - r"\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)", - line, - ) - if not m: - continue - synced = m.group(1) == "*" - stats.append( - { - "remote": m.group(2), - "referenceid": m.group(3), - "synchronized": synced, - "stratum": int(m.group(4)), - "type": "-", - "when": m.group(5), - "hostpoll": int(m.group(6)) if m.group(6).isdigit() else -1, - "reachability": int(m.group(7), 8) if m.group(7).isdigit() else -1, - "delay": float(m.group(8)) if _is_float(m.group(8)) else 0.0, - "offset": float(m.group(9)) if _is_float(m.group(9)) else 0.0, - "jitter": 0.0, - } - ) - return stats - # ------------------------------------------------------------------ # NAPALM: get_users # ------------------------------------------------------------------ @@ -1248,8 +1205,22 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): ("firewall", lambda: self._snmp_sources_note(settings)), ("start", lambda: self._snmp_save_and_verify(settings)), ] + try: + with self._config_cli(): + return run_fix_steps(steps) + except ConnectionException as exc: + failed = {"ok": False, "output": str(exc)} + return run_fix_steps([("configure", lambda: failed)]) + + @contextmanager + def _config_cli(self) -> Iterator[None]: + """The config-mode CLI: this session, or over REST a temporary SSH session on port 22. + + :raises ConnectionException: when no SSH session opens. + """ if self._transport != "api": - return run_fix_steps(steps) + yield + return old_api, old_device, old_transport = self._api, self._device, self._transport self._api = self._device = self._transport = None ssh_error = "" @@ -1265,9 +1236,8 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): ssh_error = str(exc) try: if self._device is None: - failed = {"ok": False, "output": f"no SSH for the CLI: {ssh_error}"} - return run_fix_steps([("configure", lambda: failed)]) - return run_fix_steps(steps) + raise ConnectionException(f"no SSH for the CLI: {ssh_error}") + yield finally: if self._device is not None: try: @@ -1315,14 +1285,6 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): # --------------------------------------------------------------------------- -def _is_float(s: str) -> bool: - try: - float(s) - return True - except (ValueError, TypeError): - return False - - def _parse_ping_output(output: str, count: int) -> dict: """Parse ProCurve CLI ping output into NAPALM ping result dict. diff --git a/napalm_procurve/time_sync.py b/napalm_procurve/time_sync.py new file mode 100644 index 0000000..a3f26d6 --- /dev/null +++ b/napalm_procurve/time_sync.py @@ -0,0 +1,305 @@ +"""The switch's time sources and zone (napalm-device-types ``TimeSyncMixin``). + +A ProCurve keeps them as lines of its configuration (management and configuration +guide, "Time Protocols"):: + + time timezone + time daylight-time-rule + timesync sntp + sntp unicast + sntp server priority <1-3>
+ +ArubaOS-Switch 16.x can run NTP instead: ``timesync ntp`` with ``ntp server +
`` lines (up to 8). The driver writes servers in the protocol the switch +runs, SNTP unless it runs NTP, and switches a switch on TimeP or none to SNTP +unicast. Addresses only: the switch takes no host names here. + +The zone is minutes and one of the switch's summer-time rules; the switch keeps no +zone name, so ``timezone`` reads as None. An IANA name is written from its POSIX +rule: the US and EU dates as the switch's own rules, other Sunday rules as +``user-defined`` dates, the switch changing on the first Sunday on or after each. + +Every change is saved with ``write memory``; nothing is sent when the switch already +has what is asked. Over the REST API the configuration is read through its ``/cli`` +endpoint and written over a temporary SSH session. +""" + +from __future__ import annotations + +import calendar +import ipaddress +import re +from collections.abc import Sequence +from contextlib import AbstractContextManager +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple + +from napalm_device_types import TimeSyncDict, TimeSyncMixin +from napalm_device_types.models import FixStepOutcomeDict +from napalm_device_types.posix_tz import DstTransitionDict, parse_posix_tz, posix_tz + +#: How many servers each protocol takes. +MAX_SERVERS = {"sntp": 3, "ntp": 8} +#: ``time timezone`` takes -720 to 840 minutes. +_OFFSET_RANGE = range(-720, 841) +#: The switch puts the clock forward by one hour, no more, no less. +_SUMMER_SHIFT = 3600 + +#: The switch's own rules, by (start, end) as (month, week, weekday); 5 = last week. +_US = ((3, 2, 0), (11, 1, 0)) +_EU = ((3, 5, 0), (10, 5, 0)) +_SOUTH = ((10, 5, 0), (3, 5, 0)) +_EU_RULES = frozenset({"western-europe", "middle-europe-and-portugal"}) + +_SNTP_SERVER = re.compile(r"sntp server priority ([1-3]) (\S+)(?: .*)?") +_NTP_SERVER = re.compile(r"ntp server (\S+)(?: .*)?") +_TIMESYNC = re.compile(r"timesync (\S+)") +_TIMEZONE = re.compile(r"time timezone (-?\d+)") +_DST_RULE = re.compile(r"time daylight-time-rule (.+)") +_DATE = re.compile(r"(\d{1,2})/(\d{1,2})") +#: A row of ``show ntp associations``: mark, address, ref-clock, stratum, when, poll, +#: reach, delay, offset. +_ASSOCIATION = re.compile( + r"\s*([*+]?)\s*(\d{1,3}(?:\.\d{1,3}){3})" + r"\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)" +) + + +class TimeConfig(NamedTuple): + """The time lines of a running configuration.""" + + timesync: str | None # "sntp", "ntp", "timep"; None when not listed + sntp_unicast: bool + sntp: list[str] # by priority + ntp: list[str] # in their order + offset: int # minutes east of UTC; 0 when not listed + dst_rule: str # "none" when not listed + + @property + def protocol(self) -> str: + """The protocol the driver writes servers in.""" + return "ntp" if self.timesync == "ntp" else "sntp" + + @property + def servers(self) -> list[str]: + return self.ntp if self.protocol == "ntp" else self.sntp + + +def parse_time_config(running: str) -> TimeConfig: + """The time lines of *running*, ``show running-config``.""" + timesync, unicast, offset, rule = None, False, 0, "none" + sntp: dict[int, str] = {} + ntp: list[str] = [] + for raw in running.splitlines(): + line = " ".join(raw.split()) + if m := _SNTP_SERVER.fullmatch(line): + sntp[int(m.group(1))] = m.group(2) + elif m := _NTP_SERVER.fullmatch(line): + ntp.append(m.group(1)) + elif m := _TIMESYNC.fullmatch(line): + timesync = m.group(1).lower() + elif m := _TIMEZONE.fullmatch(line): + offset = int(m.group(1)) + elif m := _DST_RULE.fullmatch(line): + rule = m.group(1).lower() + elif line == "sntp unicast": + unicast = True + return TimeConfig(timesync, unicast, [sntp[p] for p in sorted(sntp)], ntp, offset, rule) + + +def _first_sunday_date(transition: DstTransitionDict) -> str: + """The date from which the switch's "first Sunday on or after" hits *transition*.""" + month, week = transition["month"], transition["week"] + day = calendar.monthrange(2001, month)[1] - 6 if week == 5 else 1 + 7 * (week - 1) + return f"{month:02d}/{day:02d}" + + +def _rule(utc_offset: int, start: DstTransitionDict, end: DstTransitionDict) -> str: + dates = tuple((t["month"], t["week"], t["weekday"]) for t in (start, end)) + if dates == _US: + return "canada-and-continental-us" + if dates == _EU: + return "western-europe" if utc_offset <= 0 else "middle-europe-and-portugal" + if dates == _SOUTH: + return "southern-hemisphere" + if start["weekday"] or end["weekday"]: + raise ValueError("the switch changes to and from summer time on a Sunday only") + return f"user-defined begin-date {_first_sunday_date(start)} end-date {_first_sunday_date(end)}" + + +def _minutes(utc_offset: int) -> int: + minutes, rest = divmod(utc_offset, 60) + if rest or minutes not in _OFFSET_RANGE: + raise ValueError(f"the switch does not take the UTC offset {utc_offset / 3600:+g} h") + return minutes + + +def zone_settings(zone: str) -> tuple[int, str]: + """*zone* as the switch keeps it: ``time timezone`` minutes and summer-time rule. + + A zone whose "summer" time is behind its standard time (Europe/Dublin) is + written the other way round: the switch only puts the clock forward. + + :raises ValueError: for a zone the switch cannot keep. + """ + rule = posix_tz(zone) + parts = parse_posix_tz(rule) if rule else None + if parts is None: + raise ValueError(f"no summer-time rule the switch can take for {zone}") + std, summer = parts["utc_offset"], parts["dst_offset"] + start, end = parts["dst_start"], parts["dst_end"] + if summer is not None and summer < std: + std, summer, start, end = summer, std, end, start + minutes = _minutes(std) + if summer is None: + return minutes, "none" + if summer - std != _SUMMER_SHIFT: + raise ValueError("the switch puts the clock forward by one hour for summer time only") + if start is None or end is None: + raise ValueError(f"{zone} has summer time without a rule for it") + return minutes, _rule(std, start, end) + + +def _same_rule(have: str, want: str) -> bool: + if have in _EU_RULES and want in _EU_RULES: + return True + if have.startswith("user-defined") and want.startswith("user-defined"): + dates = [[(int(m), int(d)) for m, d in _DATE.findall(r)] for r in (have, want)] + return dates[0] == dates[1] + return have == want + + +def _check_servers(servers: Sequence[str], protocol: str) -> None: + limit = MAX_SERVERS[protocol] + if len(servers) > limit: + raise ValueError( + f"the switch takes at most {limit} {protocol.upper()} servers, not {len(servers)}" + ) + for server in servers: + try: + ipaddress.ip_address(server) + except ValueError: + raise ValueError( + f"the switch takes {protocol.upper()} servers as IP addresses, not {server!r}" + ) from None + + +def _server_commands(config: TimeConfig, servers: Sequence[str]) -> list[str]: + """Remove what differs from *servers*, from the first difference on; add the rest.""" + have, ntp = config.servers, config.protocol == "ntp" + keep = 0 + while keep < min(len(have), len(servers)) and have[keep].lower() == servers[keep].lower(): + keep += 1 + commands = [ + f"no ntp server {s}" if ntp else f"no sntp server priority {i} {s}" + for i, s in enumerate(have[keep:], keep + 1) + ] + commands += [ + f"ntp server {s} iburst" if ntp else f"sntp server priority {i} {s}" + for i, s in enumerate(servers[keep:], keep + 1) + ] + return commands + + +def _float(value: str) -> float: + try: + return float(value) + except ValueError: + return 0.0 + + +def _association(m: re.Match[str]) -> dict[str, Any]: + poll, reach = m.group(6), m.group(7) + return { + "remote": m.group(2), + "referenceid": m.group(3), + "synchronized": m.group(1) == "*", + "stratum": int(m.group(4)), + "type": "-", + "when": m.group(5), + "hostpoll": int(poll) if poll.isdigit() else -1, + "reachability": int(reach, 8) if reach.isdigit() else -1, + "delay": _float(m.group(8)), + "offset": _float(m.group(9)), + "jitter": 0.0, + } + + +class ProcurveTimeSyncMixin(TimeSyncMixin): + """The NAPALM NTP getters, ``get_time_sync`` and ``configure_time_sync``'s steps.""" + + time_sync_writes: ClassVar[frozenset[str]] = frozenset({"ntp_servers", "timezone"}) + + if TYPE_CHECKING: # pragma: no cover - the driver's own helpers + _transport: str | None + + def _send_command(self, command: str | list[str]) -> str: ... + def _api_show(self, command: str) -> str: ... + def _config_cli(self) -> AbstractContextManager[None]: ... + def _enter_config_mode(self) -> None: ... + def _exit_config_mode(self) -> None: ... + def _apply_config_lines(self, config_text: str) -> list[str]: ... + def _save_config(self) -> None: ... + + def _time_config(self) -> TimeConfig: + if self._transport == "api": + return parse_time_config(self._api_show("show running-config")) + return parse_time_config(self._send_command("show running-config")) + + def get_time_sync(self) -> TimeSyncDict: + """The servers of the protocol the switch runs; no zone name, no sync state.""" + return { + "ntp_servers": self._time_config().servers, + "timezone": None, + "synchronized": None, + "daemon": None, + } + + def get_ntp_servers(self) -> dict[str, dict[str, Any]]: + """The configured servers, as ``get_time_sync`` reads them.""" + return {server: {} for server in self.get_time_sync()["ntp_servers"]} + + def get_ntp_stats(self) -> list[dict[str, Any]]: + """The NTP associations of ``show ntp associations`` (16.x, NTP mode).""" + out = self._send_command(["show ntp associations", "show ntp status"]) + return [_association(m) for line in out.splitlines() if (m := _ASSOCIATION.match(line))] + + def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict: + config = self._time_config() + _check_servers(servers, config.protocol) + commands = _server_commands(config, servers) + if config.protocol == "sntp": + commands += [] if config.sntp_unicast else ["sntp unicast"] + commands += [] if config.timesync == "sntp" else ["timesync sntp"] + if not commands: + return {"ok": True, "output": "the switch already has these servers"} + self._apply_time_commands(commands) + return { + "ok": True, + "output": f"{config.protocol.upper()} servers set: {', '.join(servers)}", + } + + def _write_time_zone(self, zone: str) -> FixStepOutcomeDict: + minutes, rule = zone_settings(zone) + config = self._time_config() + commands = [] if config.offset == minutes else [f"time timezone {minutes}"] + if not _same_rule(config.dst_rule, rule): + commands.append(f"time daylight-time-rule {rule}") + if not commands: + return {"ok": True, "output": f"the switch is already in {zone}"} + self._apply_time_commands(commands) + return {"ok": True, "output": f"time zone set: {minutes} minutes, summer time {rule}"} + + def _apply_time_commands(self, commands: list[str]) -> None: + """Send *commands* in ``configure`` and save them; raise on a refused one.""" + with self._config_cli(): + self._enter_config_mode() + try: + errors = self._apply_config_lines("\n".join(commands)) + finally: + self._exit_config_mode() + if errors: + raise RuntimeError("the switch refused:\n" + "\n".join(errors)) + self._save_config() + + +__all__ = ["ProcurveTimeSyncMixin", "TimeConfig", "parse_time_config", "zone_settings"] diff --git a/pyproject.toml b/pyproject.toml index 83457c2..91d716e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.23.0", + "napalm-device-types>=4.35.0", "netmiko>=4.3.0", # takes a SessionLog object as session_log "paramiko>=5.0.0", # CVE-2026-44405 "netaddr>=0.7.10", diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 0ab12d4..7f82314 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,7 +27,7 @@ "napalm_procurve.procurve" ], "python_file_lines": { - "napalm_procurve/procurve.py": 1383 + "napalm_procurve/procurve.py": 1345 }, "untyped_public": [] } diff --git a/tests/unit/test_driver.py b/tests/unit/test_driver.py index 95b0146..974054c 100644 --- a/tests/unit/test_driver.py +++ b/tests/unit/test_driver.py @@ -168,15 +168,6 @@ SHOW_IP = """\ Subnet Mask : 255.255.255.0 """ -SHOW_NTP = """\ - NTP associations - - Address Ref-clock St When Poll Reach Delay Offset Jitter - --------------- --------- -- ----- ---- ----- ------ ------ ------ - *10.0.0.10 10.0.0.1 2 64 1024 377 0.620 0.000 0.000 - 10.0.0.20 .INIT. 16 - 1024 0 0.000 0.000 0.000 -""" - SHOW_RUNNING_CONFIG = """\ ; J9565A Configuration Editor; Created on release #R.11.27 ; Ver #01:14.3f.f8 @@ -369,13 +360,6 @@ class TestParseIpInterfaces: assert result["VLAN1"]["ipv4"]["192.168.0.1"]["prefix_length"] == 24 -class TestParseNtpServers: - def test_two_servers(self): - servers = parsers.parse_ntp_servers(SHOW_NTP) - assert "10.0.0.10" in servers - assert "10.0.0.20" in servers - - class TestParsePingOutput: def test_success(self): result = _parse_ping_output(PING_OUTPUT_SUCCESS, 5) diff --git a/tests/unit/test_rest_failed_reads.py b/tests/unit/test_rest_failed_reads.py index d5263c4..d08cfdb 100644 --- a/tests/unit/test_rest_failed_reads.py +++ b/tests/unit/test_rest_failed_reads.py @@ -122,7 +122,6 @@ def test_get_interfaces_raises_when_ports_answers_500(): ("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"), diff --git a/tests/unit/test_time_sync.py b/tests/unit/test_time_sync.py new file mode 100644 index 0000000..ea43ff7 --- /dev/null +++ b/tests/unit/test_time_sync.py @@ -0,0 +1,450 @@ +"""The switch's time sources and zone through napalm-device-types' TimeSyncMixin (netOrk #2366). + +A ProCurve keeps them in its configuration as (management and configuration guide, +"Time Protocols"):: + + time timezone 60 + time daylight-time-rule middle-europe-and-portugal + timesync sntp + sntp unicast + sntp server priority 1 10.0.0.1 + +or, with ArubaOS-Switch 16.x in NTP mode, ``timesync ntp`` and ``ntp server`` lines. +The fake switch below keeps those lines the way ``show running-config`` lists them +and applies what the driver sends in ``configure``. +""" + +from __future__ import annotations + +import base64 +from unittest.mock import MagicMock + +import pytest +from napalm.base.exceptions import CommandErrorException, ConnectionException +from napalm_device_types import TimeSyncMixin + +from napalm_procurve.procurve import ProcurveDriver +from napalm_procurve.time_sync import parse_time_config, zone_settings + +HEADER = """\ +; J9774A Configuration Editor; Created on release #YA.16.10.0012 +; Ver #14:41.44.00.04.19.02.13.98.82.34.61.18.28.f3.84.9c.63.ff.37.27:05 +hostname "HP-2530-8G-PoEP" +""" + +SNTP_CONFIG = ( + HEADER + + """\ +time timezone 60 +time daylight-time-rule middle-europe-and-portugal +timesync sntp +sntp unicast +sntp server priority 1 10.0.0.1 +sntp server priority 2 10.0.0.2 4 +ip default-gateway 192.168.0.254 +""" +) + +NTP_CONFIG = ( + HEADER + + """\ +timesync ntp +ntp unicast +ntp server 10.0.0.1 iburst +ntp server 10.0.0.2 +ntp enable +""" +) + +#: Factory default: no time lines at all (TimeP, UTC, no summer time). +BARE_CONFIG = HEADER + "ip default-gateway 192.168.0.254\n" + + +class FakeSwitch: + """The time lines of a switch's running configuration, as the CLI changes them.""" + + def __init__(self, config: str) -> None: + self.lines = config.splitlines() + self.sent: list[str] = [] + self.saved = 0 + self.refuse = False + + @property + def config(self) -> str: + return "\n".join(self.lines) + "\n" + + def _drop(self, prefix: str) -> None: + self.lines = [x for x in self.lines if not x.startswith(prefix)] + + def send_command(self, cmd: str, **_kw: object) -> str: + if cmd == "show running-config": + return self.config + if cmd in ("configure", "end"): + return "" + if cmd == "write memory": + self.saved += 1 + return "" + self.sent.append(cmd) + if self.refuse: + return "Invalid input: " + cmd.split()[-1] + if cmd.startswith("no "): + before = len(self.lines) + self._drop(cmd[3:]) + return "" if len(self.lines) < before else "The server is not configured." + if cmd.startswith("sntp server priority"): + prefix = " ".join(cmd.split()[:4]) + " " + if any(x.startswith(prefix) for x in self.lines): + return "Error: this priority is already in use." + self.lines.append(cmd) + elif cmd.startswith("ntp server "): + self.lines.append(cmd) + else: # time timezone, time daylight-time-rule, timesync, sntp unicast + words = 2 if cmd.startswith(("time ", "sntp ")) else 1 + self._drop(" ".join(cmd.split()[:words]) + " ") + self.lines.append(cmd) + return "" + + +def _cli_driver(switch: FakeSwitch) -> ProcurveDriver: + d = ProcurveDriver("10.0.0.40", "manager", "pw") + d._transport = "ssh" + d._device = MagicMock() + d._device.base_prompt = "HP-2530-8G-PoEP" + d._device.send_command.side_effect = switch.send_command + return d + + +@pytest.fixture +def switch() -> FakeSwitch: + return FakeSwitch(SNTP_CONFIG) + + +@pytest.fixture +def driver(switch: FakeSwitch) -> ProcurveDriver: + return _cli_driver(switch) + + +# -- reading ----------------------------------------------------------------- + + +def test_the_driver_is_a_time_sync_driver(): + assert issubclass(ProcurveDriver, TimeSyncMixin) + assert callable(getattr(ProcurveDriver, "get_time_sync", None)) + assert ProcurveDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"}) + + +def test_reads_the_sntp_servers_by_priority_and_no_zone_name(driver): + assert driver.get_time_sync() == { + "ntp_servers": ["10.0.0.1", "10.0.0.2"], + "timezone": None, # minutes and a summer-time rule, no name + "synchronized": None, + "daemon": None, + } + + +def test_sntp_servers_read_in_priority_order(): + config = parse_time_config("sntp server priority 2 10.0.0.2\nsntp server priority 1 10.0.0.1\n") + + assert config.servers == ["10.0.0.1", "10.0.0.2"] + + +def test_reads_the_ntp_servers_in_ntp_mode(driver, switch): + switch.lines = NTP_CONFIG.splitlines() + + assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.1", "10.0.0.2"] + + +def test_a_bare_switch_has_no_servers_in_utc(): + config = parse_time_config(BARE_CONFIG) + + assert (config.servers, config.offset, config.dst_rule) == ([], 0, "none") + + +def test_get_ntp_servers_lists_what_get_time_sync_reads(driver): + assert driver.get_ntp_servers() == {"10.0.0.1": {}, "10.0.0.2": {}} + + +def test_reads_over_rest_through_the_cli_endpoint(): + d = ProcurveDriver("10.0.0.40", "manager", "pw") + d._transport = "api" + d._api = MagicMock() + encoded = base64.b64encode(SNTP_CONFIG.encode() + b"\x00").decode() + d._api.post.return_value.ok = True + d._api.post.return_value.json.return_value = {"result_base64_encoded": encoded} + + assert d.get_time_sync()["ntp_servers"] == ["10.0.0.1", "10.0.0.2"] + d._api.post.assert_called_once_with("cli", json={"cmd": "show running-config"}) + + +def test_a_failed_rest_read_raises(): + d = ProcurveDriver("10.0.0.40", "manager", "pw") + d._transport = "api" + d._api = MagicMock() + d._api.post.return_value.ok = False + d._api.post.return_value.status_code = 500 + + with pytest.raises(CommandErrorException, match="HTTP 500"): + d.get_ntp_servers() + + +SHOW_NTP_ASSOCIATIONS = """\ + NTP associations + + Address Ref-clock St When Poll Reach Delay Offset Jitter + --------------- --------- -- ----- ---- ----- ------ ------ ------ + *10.0.0.10 10.0.0.1 2 64 1024 377 0.620 0.000 0.000 + 10.0.0.20 .INIT. 16 - 1024 0 0.000 - 0.000 +""" + + +def test_get_ntp_stats_reads_the_associations(driver, switch): + driver._send_command = MagicMock(return_value=SHOW_NTP_ASSOCIATIONS) + + synced, init = driver.get_ntp_stats() + + assert (synced["remote"], synced["synchronized"], synced["stratum"]) == ("10.0.0.10", True, 2) + assert (synced["hostpoll"], synced["reachability"], synced["delay"]) == (1024, 0o377, 0.62) + assert (init["remote"], init["synchronized"], init["offset"]) == ("10.0.0.20", False, 0.0) + + +# -- the zone as the switch takes it ------------------------------------------ + + +@pytest.mark.parametrize( + "zone, settings", + [ + ("Europe/Berlin", (60, "middle-europe-and-portugal")), + ("Europe/London", (0, "western-europe")), + ("Europe/Dublin", (0, "western-europe")), # negative summer time, turned round + ("America/New_York", (-300, "canada-and-continental-us")), + ("America/Anchorage", (-540, "canada-and-continental-us")), + ("Asia/Kolkata", (330, "none")), + ("Asia/Kathmandu", (345, "none")), + ("UTC", (0, "none")), + ("Australia/Sydney", (600, "user-defined begin-date 10/01 end-date 04/01")), + ("Pacific/Auckland", (720, "user-defined begin-date 09/24 end-date 04/01")), + ], +) +def test_zone_settings(zone, settings): + assert zone_settings(zone) == settings + + +@pytest.mark.parametrize( + "zone, why", + [ + ("Australia/Lord_Howe", "one hour"), # 30 minutes of summer time + ("Asia/Jerusalem", "Sunday"), # changes on a Friday + ], +) +def test_a_zone_the_switch_cannot_keep_is_refused(zone, why): + with pytest.raises(ValueError, match=why): + zone_settings(zone) + + +# -- writing the servers ----------------------------------------------------- + + +def test_writes_new_sntp_servers_in_priority_order(driver, switch): + result = driver.configure_time_sync(ntp_servers=["10.0.0.5", "10.0.0.6"]) + + assert result["success"] is True, result + assert switch.sent == [ + "no sntp server priority 1 10.0.0.1", + "no sntp server priority 2 10.0.0.2", + "sntp server priority 1 10.0.0.5", + "sntp server priority 2 10.0.0.6", + ] + assert switch.saved == 1 + + +def test_keeps_the_servers_already_in_place(driver, switch): + result = driver.configure_time_sync(ntp_servers=["10.0.0.1", "10.0.0.9"]) + + assert result["success"] is True, result + assert switch.sent == ["no sntp server priority 2 10.0.0.2", "sntp server priority 2 10.0.0.9"] + + +def test_the_same_servers_again_change_nothing(driver, switch): + result = driver.configure_time_sync(ntp_servers=["10.0.0.1", "10.0.0.2"]) + + assert result["success"] is True, result + assert switch.sent == [] + assert switch.saved == 0 + + +def test_a_bare_switch_gets_sntp_switched_on(driver, switch): + switch.lines = BARE_CONFIG.splitlines() + + result = driver.configure_time_sync(ntp_servers=["10.0.0.5", "2001:db8::1"]) + + assert result["success"] is True, result + assert switch.sent == [ + "sntp server priority 1 10.0.0.5", + "sntp server priority 2 2001:db8::1", + "sntp unicast", + "timesync sntp", + ] + assert driver.get_time_sync()["ntp_servers"] == ["10.0.0.5", "2001:db8::1"] + + +def test_ntp_mode_keeps_its_protocol(driver, switch): + switch.lines = NTP_CONFIG.splitlines() + + result = driver.configure_time_sync(ntp_servers=["10.0.0.2", "10.0.0.3"]) + + assert result["success"] is True, result + assert switch.sent == [ + "no ntp server 10.0.0.1", + "no ntp server 10.0.0.2", + "ntp server 10.0.0.2 iburst", + "ntp server 10.0.0.3 iburst", + ] + + +@pytest.mark.parametrize( + "servers, why", + [ + (["10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4"], "at most 3"), + (["ntp.example.org"], "IP addresses"), + ], +) +def test_servers_the_switch_cannot_take_are_refused_before_writing(driver, switch, servers, why): + result = driver.configure_time_sync(ntp_servers=servers) + + assert result["success"] is False + assert why in result["output"] + assert switch.sent == [] + + +def test_ntp_mode_takes_eight_servers(driver, switch): + switch.lines = NTP_CONFIG.splitlines() + servers = [f"10.0.1.{i}" for i in range(1, 9)] + + assert driver.configure_time_sync(ntp_servers=servers)["success"] is True + assert driver.configure_time_sync(ntp_servers=[*servers, "10.0.1.9"])["success"] is False + + +def test_a_refused_command_fails_the_step_and_is_not_saved(driver, switch): + switch.refuse = True + + result = driver.configure_time_sync(ntp_servers=["10.0.0.5"]) + + assert result["success"] is False + assert "Invalid input" in result["output"] + assert switch.saved == 0 + + +# -- writing the zone -------------------------------------------------------- + + +def test_writes_minutes_and_summer_time_rule(driver, switch): + result = driver.configure_time_sync(timezone="America/New_York") + + assert result["success"] is True, result + assert switch.sent == [ + "time timezone -300", + "time daylight-time-rule canada-and-continental-us", + ] + assert switch.saved == 1 + + +def test_the_same_zone_again_changes_nothing(driver, switch): + result = driver.configure_time_sync(timezone="Europe/Berlin") + + assert result["success"] is True, result + assert switch.sent == [] + assert switch.saved == 0 + + +def test_either_european_rule_stands_for_the_eu_dates(driver, switch): + switch.lines = [x.replace("middle-europe-and-portugal", "western-europe") for x in switch.lines] + + assert driver.configure_time_sync(timezone="Europe/Berlin")["success"] is True + assert switch.sent == [] + + +def test_a_user_defined_rule_reads_back_by_its_dates(driver, switch): + switch.lines[3:5] = [ + "time timezone 600", + "time daylight-time-rule user-defined begin-date 10/1 end-date 4/1", + ] + + assert driver.configure_time_sync(timezone="Australia/Sydney")["success"] is True + assert switch.sent == [] + + +def test_a_bare_switch_gets_its_zone(driver, switch): + switch.lines = BARE_CONFIG.splitlines() + + result = driver.configure_time_sync(timezone="Asia/Kolkata") + + assert result["success"] is True, result + assert switch.sent == ["time timezone 330"] + + +def test_servers_and_zone_together(driver, switch): + result = driver.configure_time_sync(ntp_servers=["10.0.0.1"], timezone="UTC") + + assert result["success"] is True, result + assert switch.sent == [ + "no sntp server priority 2 10.0.0.2", + "time timezone 0", + "time daylight-time-rule none", + ] + assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"] + assert switch.saved == 2 + + +# -- over REST: the CLI on a temporary SSH session --------------------------- + + +def _rest_driver(switch: FakeSwitch) -> tuple[ProcurveDriver, MagicMock]: + d = ProcurveDriver("10.0.0.40", "manager", "pw") + d._transport = "api" + d._api = MagicMock() + d._api.post.side_effect = lambda _ep, json: MagicMock( + ok=True, + json=MagicMock( + return_value={ + "result_base64_encoded": base64.b64encode( + switch.send_command(json["cmd"]).encode() + b"\x00" + ).decode() + } + ), + ) + ssh = MagicMock() + ssh.base_prompt = "HP-2530-8G-PoEP" + ssh.send_command.side_effect = switch.send_command + d._ssh_connect = MagicMock(return_value=ssh) + return d, ssh + + +def test_over_rest_writes_through_ssh_and_reads_through_rest(switch): + d, ssh = _rest_driver(switch) + + result = d.configure_time_sync(ntp_servers=["10.0.0.5"]) + + assert result["success"] is True, result + assert switch.sent[-1] == "sntp server priority 1 10.0.0.5" + assert switch.saved == 1 + d._ssh_connect.assert_called_once() + ssh.disconnect.assert_called_once() + assert d._transport == "api" + + +def test_over_rest_nothing_to_write_opens_no_ssh(switch): + d, _ssh = _rest_driver(switch) + + assert d.configure_time_sync(ntp_servers=["10.0.0.1", "10.0.0.2"])["success"] is True + d._ssh_connect.assert_not_called() + + +def test_over_rest_without_ssh_the_step_fails(switch): + d, _ssh = _rest_driver(switch) + d._ssh_connect.side_effect = ConnectionException("connection refused") + + result = d.configure_time_sync(timezone="UTC") + + assert result["success"] is False + assert "no SSH for the CLI" in result["output"] + assert switch.sent == [] -- 2.54.1