feat(time-sync): the switch's NTP servers and zone through TimeSyncMixin
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 53s
driver / test (3.13) (pull_request) Successful in 51s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Successful in 2m16s
driver / publish (pull_request) Skipped

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 <minutes> 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.
This commit is contained in:
Christian Manivong committed 2026-11-11 15:25:06 +01:00
1 parent bb8b3a7182
commit 6bd3372933
11 files changed
+801 -111

No files matched your search

-10
View File
@@ -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.
-23
View File
@@ -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
# ---------------------------------------------------------------------------
+21 -59
View File
@@ -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.
+305
View File
@@ -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 <minutes east of UTC>
time daylight-time-rule <rule>
timesync sntp
sntp unicast
sntp server priority <1-3> <address>
ArubaOS-Switch 16.x can run NTP instead: ``timesync ntp`` with ``ntp server
<address>`` 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"]