"""The switch's time sources and zone (napalm-device-types ``TimeSyncMixin``). A JetStream keeps both in one line of its configuration (CLI reference guide, "System Time Commands"):: system-time ntp system-time dst recurring The zone is a UTC offset from the list the switch offers (``UTC+01:00``, ``UTC``), the servers are two IPv4 addresses, the rate is in hours. Summer time is a line of its own. The switch keeps no zone name, so ``timezone`` reads as None; an IANA name is written as its offset and summer-time rule, from the zone's POSIX rule. Writing the ``ntp`` line also switches the clock from manual time to NTP. Every change is saved to the startup configuration, and nothing is sent when the switch already has what is asked. """ from __future__ import annotations import ipaddress import re from collections.abc import Sequence from typing import TYPE_CHECKING, ClassVar, NamedTuple from napalm_device_types import TimeSyncDict, TimeSyncMixin from napalm_device_types.models import FixResultDict, FixStepOutcomeDict from napalm_device_types.posix_tz import DstTransitionDict, parse_posix_tz, posix_tz #: ``system-time ntp`` takes a primary and a backup server. MAX_SERVERS = 2 #: Hours between two fetches when the switch had no ``ntp`` line yet (its default). DEFAULT_FETCHING_RATE = 12 #: An empty backup server as the switch lists it. _NO_SERVER = "0.0.0.0" # nosec B104 - a listed value, nothing binds to it #: The offsets ``system-time ntp`` offers, in minutes east of UTC. OFFERED_OFFSETS = frozenset( [hours * 60 for hours in range(-12, 14)] + [-270, -210, 210, 270, 330, 345, 390, 570] ) _DAYS = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") _ZONE = re.compile(r"UTC(?:([+-])(\d{1,2}):(\d{2}))?", re.I) _NTP_LINE = re.compile(r"system-time\s+ntp\s+(\S+)\s+(.*)", re.I) class NtpLine(NamedTuple): """The ``system-time ntp`` line: zone token, servers in order, fetching rate.""" zone: str servers: list[str] rate: int def parse_ntp_line(running: str) -> NtpLine | None: """The ``system-time ntp`` line of *running*; None on manual time. A server listed as primary and backup counts once, an empty backup not at all. """ for line in running.splitlines(): match = _NTP_LINE.fullmatch(line.strip()) if match is None: continue tokens = match.group(2).split() rate = int(tokens[-1]) if tokens and tokens[-1].isdigit() else DEFAULT_FETCHING_RATE servers: list[str] = [] for token in tokens: if not token.isdigit() and token != _NO_SERVER and token not in servers: servers.append(token) return NtpLine(match.group(1), servers, rate) return None def _dst_line(running: str) -> str | None: for line in running.splitlines(): if line.strip().lower().startswith("system-time dst"): return " ".join(line.split()) return None def _zone_minutes(token: str) -> int | None: match = _ZONE.fullmatch(token) if match is None: return None sign, hours, minutes = match.groups() if sign is None: return 0 return (1 if sign == "+" else -1) * (int(hours) * 60 + int(minutes)) def zone_token(utc_offset: int) -> str: """*utc_offset* (seconds east of UTC) as ``system-time ntp`` takes it. :raises ValueError: for an offset the switch does not offer. """ minutes, rest = divmod(utc_offset, 60) if rest or minutes not in OFFERED_OFFSETS: raise ValueError(f"the switch does not offer the UTC offset {utc_offset / 3600:+g} h") if minutes == 0: return "UTC" hours, mins = divmod(abs(minutes), 60) return f"UTC{'+' if minutes > 0 else '-'}{hours:02d}:{mins:02d}" def _when(transition: DstTransitionDict) -> str: seconds = transition["time"] if not 0 <= seconds < 86400 or seconds % 60: raise ValueError("the switch takes a summer-time change at a time of day (HH:MM)") clock = f"{seconds // 3600:02d}:{seconds % 3600 // 60:02d}" weekday, month = _DAYS[transition["weekday"]], _MONTHS[transition["month"] - 1] return f"{transition['week']} {weekday} {month} {clock}" def dst_command(zone: str) -> tuple[str, str | None]: """*zone* as the switch keeps it: the zone token and the ``system-time dst`` line. The line is None for a zone without summer time. 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 show. """ 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 token = zone_token(std) if summer is None: return token, None if start is None or end is None: raise ValueError(f"{zone} has summer time without a rule for it") shift = (summer - std) // 60 return token, f"system-time dst recurring {_when(start)} {_when(end)} {shift}" def _check_servers(servers: Sequence[str]) -> None: if len(servers) > MAX_SERVERS: raise ValueError(f"the switch takes at most {MAX_SERVERS} NTP servers, not {len(servers)}") for server in servers: try: ipaddress.IPv4Address(server) except ValueError: raise ValueError( f"the switch takes NTP servers as IPv4 addresses only, not {server!r}" ) from None def _ntp_command(zone: str, servers: Sequence[str], rate: int) -> str: backup = servers[1] if len(servers) > 1 else servers[0] return f"system-time ntp {zone} {servers[0]} {backup} {rate}" class JetstreamTimeSyncMixin(TimeSyncMixin): """``get_time_sync`` and ``configure_time_sync`` over the switch's CLI.""" time_sync_writes: ClassVar[frozenset[str]] = frozenset({"ntp_servers", "timezone"}) #: The zone a running configure_time_sync was asked for: its servers step #: writes the ``ntp`` line with that zone's offset already. _zone_asked: str | None = None if TYPE_CHECKING: # pragma: no cover - the driver's own helpers def _send_command(self, command: str | list[str]) -> str: ... 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 get_time_sync(self) -> TimeSyncDict: """The servers of the ``system-time ntp`` line; no zone name, no sync state. The switch shows neither whether its last fetch worked nor a zone name. """ line = parse_ntp_line(self._send_command("show running-config")) return { "ntp_servers": line.servers if line else [], "timezone": None, "synchronized": None, "daemon": None, } def configure_time_sync( self, ntp_servers: Sequence[str] | None = None, timezone: str | None = None ) -> FixResultDict: """The template's steps; servers and zone share one ``ntp`` line.""" self._zone_asked = timezone try: return TimeSyncMixin.configure_time_sync(self, ntp_servers, timezone) finally: self._zone_asked = None def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict: _check_servers(servers) line = parse_ntp_line(self._send_command("show running-config")) if self._zone_asked is not None: zone = dst_command(self._zone_asked)[0] else: zone = line.zone if line else "UTC" if line and _same_zone(line.zone, zone) and _same(line.servers, servers): return {"ok": True, "output": "the switch already has these servers"} rate = line.rate if line else DEFAULT_FETCHING_RATE self._apply_time_commands([_ntp_command(zone, servers, rate)]) return {"ok": True, "output": f"NTP servers set: {', '.join(servers)}"} def _write_time_zone(self, zone: str) -> FixStepOutcomeDict: token, dst = dst_command(zone) running = self._send_command("show running-config") line = parse_ntp_line(running) if line is None: raise ValueError( "the switch keeps its time zone with its NTP servers and has none:" " name the NTP servers too" ) commands = ( [] if _same_zone(line.zone, token) else [_ntp_command(token, line.servers, line.rate)] ) current = _dst_line(running) if dst is None and current is not None: commands.append("no system-time dst") elif dst is not None and (current or "").lower() != dst.lower(): commands.append(dst) 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: {token}, " + (dst or "no summer time")} def _apply_time_commands(self, commands: list[str]) -> None: """Send *commands* in ``configure`` and save them; raise on a refused one.""" 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() def _same(have: Sequence[str], want: Sequence[str]) -> bool: return [s.lower() for s in have] == [s.lower() for s in want] def _same_zone(have: str, want: str) -> bool: minutes = _zone_minutes(have) return minutes is not None and minutes == _zone_minutes(want) __all__ = ["JetstreamTimeSyncMixin", "NtpLine", "dst_command", "parse_ntp_line", "zone_token"]