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.
306 lines
12 KiB
Python
306 lines
12 KiB
Python
"""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"]
|