feat(time-sync): NTP servers and time zone through TimeSyncMixin
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 53s
driver / test (3.12) (pull_request) Successful in 58s
driver / test (3.13) (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 27s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m26s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 53s
driver / test (3.12) (pull_request) Successful in 58s
driver / test (3.13) (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 27s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m26s
driver / publish (pull_request) Skipped
netOrk aligns every device's time sources and zone through the driver (NetOrk/netork#2360); for APs that replaces the UCI commands netOrk built itself for the AP profile fields (NetOrk/netork#2364). Both values live in UCI's system config: - The servers are system.ntp.server. A write replaces the list, enables the client, sets use_dhcp=0 so the servers of a DHCP lease are not added, and restarts sysntpd: the router ends up with exactly these. A disabled client reads as no servers. - The zone is zonename (the IANA name, in LuCI's spelling with spaces) and timezone, the POSIX rule from posix_tz that libc reads as TZ. The rule is what counts (NetOrk/netork#1849), so the name is read as the zone only where the rule in force is that zone's; a rule alone reads as the one zone that has it, or None where several share it. A write sets both, reloads /etc/init.d/system and restarts logd, which reads the zone at start. netOrk aligns on every poll, so each step compares first and writes and restarts nothing when the router already has the values. GMT0 (the stock rule) counts as UTC's time. get_ntp_servers now uses the same reading, so it agrees with get_time_sync; it used to keep only the first server of a list, as uci prints a list as 'a' 'b' on one line. synchronized is None: BusyBox ntpd keeps no state to read. The floor on napalm-device-types is 4.35.0, the first with TimeSyncMixin.
This commit is contained in:
1 parent
e7bd0c17f5
commit
7bb15f5af3
8 files changed
+870
-37
No files matched your search
@@ -50,6 +50,7 @@ from napalm_openwrt.packages_mixin import OpenWrtPackageMixin
|
||||
from napalm_openwrt.routing_mixin import OpenWrtRoutingMixin
|
||||
from napalm_openwrt.scheduled_jobs_mixin import OpenWrtScheduledJobsMixin
|
||||
from napalm_openwrt.system_mixin import _RC_MARKER, OpenWrtSystemMixin, _split_status
|
||||
from napalm_openwrt.time_sync_mixin import OpenWrtTimeSyncMixin
|
||||
from napalm_openwrt.vlan_mixin import OpenWrtVLANMixin
|
||||
from napalm_openwrt.wireless_mixin import OpenWrtWirelessMixin
|
||||
|
||||
@@ -76,6 +77,7 @@ class OpenWrtDriver(
|
||||
OpenWrtWirelessMixin,
|
||||
OpenWrtLLDPMixin,
|
||||
OpenWrtConfigMixin,
|
||||
OpenWrtTimeSyncMixin,
|
||||
OpenWrtSystemMixin,
|
||||
OpenWrtPackageMixin,
|
||||
OpenWrtRoutingMixin,
|
||||
|
||||
@@ -532,38 +532,9 @@ class OpenWrtSystemMixin:
|
||||
return {"success": False, "output": output, "error": error}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# NTP
|
||||
# NTP statistics (the servers: time_sync_mixin)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, Any]:
|
||||
"""Return configured NTP servers from ``uci show system``.
|
||||
|
||||
UCI example::
|
||||
|
||||
system.ntp.server='0.openwrt.pool.ntp.org 1.openwrt.pool.ntp.org'
|
||||
"""
|
||||
uci_out = self._send_command("uci show system")
|
||||
servers: dict[str, Any] = {}
|
||||
|
||||
for line in uci_out.splitlines():
|
||||
# Handles both list and single-value UCI representations
|
||||
m = re.match(r"system\.ntp\.server(?:\[\d+\])?='([^']*)'", line.strip())
|
||||
if m:
|
||||
for srv in m.group(1).split():
|
||||
srv = srv.strip()
|
||||
if srv:
|
||||
servers[srv] = {}
|
||||
|
||||
return servers
|
||||
|
||||
def get_ntp_peers(self) -> dict[str, Any]:
|
||||
"""Return NTP peers from ``uci show system``.
|
||||
|
||||
OpenWrt's busybox ntpd does not differentiate peers from servers;
|
||||
the same UCI ``ntp.server`` list is returned.
|
||||
"""
|
||||
return self.get_ntp_servers()
|
||||
|
||||
def get_ntp_stats(self) -> list[dict[str, Any]]:
|
||||
"""Return NTP synchronisation statistics.
|
||||
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Time sync on OpenWrt: UCI's ``system`` config (napalm-device-types ``TimeSyncMixin``).
|
||||
|
||||
OpenWrt keeps both values in ``/etc/config/system`` (NetOrk/netork#2364):
|
||||
|
||||
* **The servers** are the ``system.ntp.server`` list, which ``/etc/init.d/sysntpd``
|
||||
hands to BusyBox ntpd while ``system.ntp.enabled`` is on. A disabled client has no
|
||||
servers: the list names nothing the clock takes time from. sysntpd also adds the
|
||||
servers of a DHCP lease unless ``use_dhcp`` is ``0``; a write turns that off, so the
|
||||
router ends up with exactly the servers given.
|
||||
* **The zone** is kept twice: ``zonename`` (the IANA name, as LuCI writes it -- with
|
||||
spaces where the IANA name has underscores) and ``timezone``, the POSIX rule
|
||||
``/etc/init.d/system`` writes to ``/tmp/TZ`` for libc. The rule is what the clock
|
||||
runs on: an IANA name written there left an AP on UTC (NetOrk/netork#1849). So the
|
||||
name is read as the zone only where the rule in force is that zone's; a rule
|
||||
without a matching name is read as the one zone that has it, or as no zone where
|
||||
several do (``CET-1CEST,...`` is Berlin, Paris, Madrid, ...).
|
||||
|
||||
Reading is one ``uci -q show system`` as the login user. Every write compares
|
||||
first and sends nothing when the router already has the values -- an application
|
||||
aligns on every poll -- else sets the options, commits ``system`` and applies them:
|
||||
``/etc/init.d/sysntpd restart`` for the servers, ``/etc/init.d/system reload`` and a
|
||||
restart of logd, which reads the zone when it starts, for the zone. Writes run as
|
||||
root (``run_command(privileged=True)``); OpenWrt has no sudo.
|
||||
|
||||
``synchronized`` is None: BusyBox ntpd keeps no state another process can read, and
|
||||
``ubus call system info`` says nothing about the clock's source.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from importlib.resources import files
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm_device_types import FixStepOutcomeDict
|
||||
from napalm_device_types.posix_tz import is_iana_zone, parse_posix_tz, posix_tz
|
||||
from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
READ_COMMAND = "uci -q show system"
|
||||
#: The rule ``/etc/init.d/system`` uses where the section names none.
|
||||
DEFAULT_RULE = "UTC"
|
||||
#: A zone of the database that stands for "not known", not for a place.
|
||||
_NO_PLACE = frozenset({"Factory"})
|
||||
#: ``system.<section>.<option>='value' ['value' ...]`` of the two sections that count.
|
||||
_OPTION = re.compile(r"^system\.(?P<section>@system\[0\]|ntp)\.(?P<option>\w+)=(?P<value>.*)$")
|
||||
_FALSE = frozenset({"0", "no", "off", "false", "disabled"})
|
||||
|
||||
|
||||
@dataclass
|
||||
class SystemUci:
|
||||
"""What ``uci -q show system`` says about the clock."""
|
||||
|
||||
has_system: bool = False
|
||||
has_ntp: bool = False
|
||||
system: dict[str, list[str]] = field(default_factory=dict)
|
||||
ntp: dict[str, list[str]] = field(default_factory=dict)
|
||||
|
||||
def _one(self, options: dict[str, list[str]], name: str) -> str | None:
|
||||
values = options.get(name)
|
||||
return values[0] if values else None
|
||||
|
||||
@property
|
||||
def configured_servers(self) -> list[str]:
|
||||
"""The list as it stands; an option of servers apart by spaces is split, as sysntpd does."""
|
||||
return [s for value in self.ntp.get("server", []) for s in value.split()]
|
||||
|
||||
@property
|
||||
def ntp_enabled(self) -> bool:
|
||||
return (self._one(self.ntp, "enabled") or "1").lower() not in _FALSE
|
||||
|
||||
@property
|
||||
def dhcp_servers(self) -> bool:
|
||||
return (self._one(self.ntp, "use_dhcp") or "1").lower() not in _FALSE
|
||||
|
||||
@property
|
||||
def servers(self) -> list[str]:
|
||||
"""The servers the clock takes time from: none while the client is off."""
|
||||
return self.configured_servers if self.has_ntp and self.ntp_enabled else []
|
||||
|
||||
@property
|
||||
def zonename(self) -> str | None:
|
||||
"""``zonename`` as an IANA name: LuCI's spaces back to underscores."""
|
||||
name = self._one(self.system, "zonename")
|
||||
return name.strip().replace(" ", "_") if name and name.strip() else None
|
||||
|
||||
@property
|
||||
def rule(self) -> str:
|
||||
return (self._one(self.system, "timezone") or "").strip() or DEFAULT_RULE
|
||||
|
||||
@property
|
||||
def zone(self) -> str | None:
|
||||
"""The zone the clock runs in, by name; None where no single zone is it."""
|
||||
if not self.has_system:
|
||||
return None
|
||||
name = self.zonename
|
||||
named = posix_tz(name) if name and is_iana_zone(name) else None
|
||||
if name and named and same_time(self.rule, named):
|
||||
return name
|
||||
return zone_for_rule(self.rule)
|
||||
|
||||
|
||||
def parse_system_uci(output: str) -> SystemUci:
|
||||
"""``uci show system`` in parts: the first system section and the ``ntp`` one."""
|
||||
parsed = SystemUci()
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("system.@system[0]="):
|
||||
parsed.has_system = True
|
||||
elif line.startswith("system.ntp="):
|
||||
parsed.has_ntp = True
|
||||
match = _OPTION.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
try:
|
||||
values = shlex.split(match["value"])
|
||||
except ValueError:
|
||||
continue
|
||||
options = parsed.system if match["section"] == "@system[0]" else parsed.ntp
|
||||
options[match["option"]] = values
|
||||
return parsed
|
||||
|
||||
|
||||
def _time_of(rule: str) -> tuple[Any, ...] | None:
|
||||
"""The offsets and transitions of *rule*, without the names it gives them."""
|
||||
parts = parse_posix_tz(rule)
|
||||
if parts is None:
|
||||
return None
|
||||
return (
|
||||
parts["utc_offset"],
|
||||
parts["dst_offset"],
|
||||
tuple(sorted((parts["dst_start"] or {}).items())),
|
||||
tuple(sorted((parts["dst_end"] or {}).items())),
|
||||
)
|
||||
|
||||
|
||||
def same_time(rule: str, other: str) -> bool:
|
||||
"""Whether two rules keep the same time: ``GMT0`` is ``UTC0`` by another name."""
|
||||
time = _time_of(rule)
|
||||
return rule == other if time is None else time == _time_of(other)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _zones_by_rule() -> dict[str, tuple[str, ...]]:
|
||||
"""Every zone of the database (not its links) by its rule, names and all."""
|
||||
source = files("tzdata").joinpath("zoneinfo", "tzdata.zi").read_text(encoding="utf-8")
|
||||
zones: defaultdict[str, list[str]] = defaultdict(list)
|
||||
for line in source.splitlines():
|
||||
if not line.startswith("Z "):
|
||||
continue
|
||||
zone = line.split()[1]
|
||||
rule = posix_tz(zone)
|
||||
if rule is not None and zone not in _NO_PLACE:
|
||||
zones[_rule_key(rule)].append(zone)
|
||||
return {rule: tuple(names) for rule, names in zones.items()}
|
||||
|
||||
|
||||
def _rule_key(rule: str) -> str:
|
||||
parts = parse_posix_tz(rule)
|
||||
return rule if parts is None else repr(sorted(parts.items()))
|
||||
|
||||
|
||||
def zone_for_rule(rule: str) -> str | None:
|
||||
"""The one zone whose rule *rule* is; None where none or several are.
|
||||
|
||||
Several zones share most rules (``CET-1CEST,M3.5.0,M10.5.0/3`` is Berlin, Paris,
|
||||
Madrid, ...): which of them a router means is not the driver's to guess. Links
|
||||
(``Asia/Calcutta``) count as the zone they point at.
|
||||
"""
|
||||
if not rule:
|
||||
return None
|
||||
zones = _zones_by_rule().get(_rule_key(rule), ())
|
||||
return zones[0] if len(zones) == 1 else None
|
||||
|
||||
|
||||
def _luci_name(zone: str) -> str:
|
||||
"""*zone* as LuCI keeps it in ``zonename``, so its zone list shows it chosen."""
|
||||
return zone.replace("_", " ")
|
||||
|
||||
|
||||
def _uci_command(*words: str) -> str:
|
||||
return shlex.join(words)
|
||||
|
||||
|
||||
class OpenWrtTimeSyncMixin(TimeSyncMixin):
|
||||
"""The servers and the zone in UCI's ``system`` config; see the module."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
def _ts_read(self) -> SystemUci:
|
||||
result = self.run_command(READ_COMMAND, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or result.stdout.strip() or f"exit {result.exit_code}"
|
||||
raise RuntimeError(f"{READ_COMMAND}: {said}")
|
||||
return parse_system_uci(result.stdout)
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""The router's time servers and zone, from one ``uci -q show system``.
|
||||
|
||||
:raises RuntimeError: when uci could not be read.
|
||||
"""
|
||||
reading = self._ts_read()
|
||||
return {
|
||||
"ntp_servers": reading.servers,
|
||||
"timezone": reading.zone,
|
||||
"synchronized": None,
|
||||
"daemon": None,
|
||||
}
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, dict[str, Any]]:
|
||||
"""The servers of :meth:`get_time_sync`, as NAPALM's ``{server: {}}``."""
|
||||
return {server: {} for server in self._ts_read().servers}
|
||||
|
||||
def get_ntp_peers(self) -> dict[str, dict[str, Any]]:
|
||||
"""BusyBox ntpd has no peers apart from its servers: the same list."""
|
||||
return self.get_ntp_servers()
|
||||
|
||||
# -- writing ---------------------------------------------------------------------------------
|
||||
|
||||
def _ts_apply(self, commands: list[str], done: str) -> FixStepOutcomeDict:
|
||||
result = self.run_command(" && ".join(commands), privileged=True, timeout=60)
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or result.stdout.strip() or f"exit {result.exit_code}"
|
||||
return {"ok": False, "output": said[-300:]}
|
||||
return {"ok": True, "output": done}
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
now = self._ts_read()
|
||||
if [s.lower() for s in now.servers] == [
|
||||
s.lower() for s in servers
|
||||
] and not now.dhcp_servers:
|
||||
return {"ok": True, "output": "the router already has these servers"}
|
||||
commands = []
|
||||
if not now.has_ntp:
|
||||
commands.append(_uci_command("uci", "set", "system.ntp=timeserver"))
|
||||
if "server" in now.ntp:
|
||||
commands.append(_uci_command("uci", "delete", "system.ntp.server"))
|
||||
commands += [_uci_command("uci", "add_list", f"system.ntp.server={s}") for s in servers]
|
||||
commands += [
|
||||
"uci set system.ntp.enabled=1",
|
||||
"uci set system.ntp.use_dhcp=0",
|
||||
"uci commit system",
|
||||
"/etc/init.d/sysntpd enable",
|
||||
"/etc/init.d/sysntpd restart",
|
||||
]
|
||||
return self._ts_apply(commands, f"ntpd takes time from {', '.join(servers)}")
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
rule = posix_tz(zone)
|
||||
if rule is None: # the template lets only zones of the database through
|
||||
return {"ok": False, "output": f"no POSIX rule for {zone}"}
|
||||
now = self._ts_read()
|
||||
if now.has_system and now.zonename == zone and same_time(now.rule, rule):
|
||||
return {"ok": True, "output": f"the router is already in {zone}"}
|
||||
commands = [
|
||||
_uci_command("uci", "set", f"system.@system[0].zonename={_luci_name(zone)}"),
|
||||
_uci_command("uci", "set", f"system.@system[0].timezone={rule}"),
|
||||
"uci commit system",
|
||||
"/etc/init.d/system reload",
|
||||
"/etc/init.d/log restart",
|
||||
]
|
||||
return self._ts_apply(commands, f"time zone set to {zone} ({rule})")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"OpenWrtTimeSyncMixin",
|
||||
"SystemUci",
|
||||
"parse_system_uci",
|
||||
"same_time",
|
||||
"zone_for_rule",
|
||||
]
|
||||
Reference in new issue
Block a user