feat(time-sync): keep DHCP's NTP servers and read them apart
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m2s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 42s
driver / security (pull_request) Successful in 1m17s
CI / driver (pull_request) Successful in 2m36s
driver / publish (pull_request) Skipped

DHCP option 42 counts (NetOrk/netork#2380): a router that gets the
site's time giver from its lease is aligned. The first time sync commit
set use_dhcp=0 on every write, which cut a router off from the giver its
DHCP server hands out.

A write now leaves use_dhcp as the router has it, and the "already has
these servers" check no longer rewrites a router only because use_dhcp
is on. get_time_sync() reads what sysntpd adds to ntpd's list while
use_dhcp is on -- each interface's data.ntpserver in ubus call
network.interface dump, which /lib/netifd/dhcp.script fills from
udhcpc's ntpsrv, only the dhcp_interface list's where it names any -- in
the same round trip as uci, into dhcp_ntp_servers: [] while use_dhcp or
the client is off, None where netifd gives no answer.

Needs napalm-device-types 4.36.0 (TimeSyncDict.dhcp_ntp_servers).
This commit is contained in:
Christian Manivong committed 2026-11-11 22:13:19 +01:00
1 parent 836539d1fe
commit 85a679fe1a
5 files changed
+234 -35

No files matched your search

+70 -14
View File
@@ -16,9 +16,13 @@ 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.
servers: the list names nothing the clock takes time from.
* **What DHCP brings** (option 42) counts too (NetOrk/netork#2380): while ``use_dhcp``
is on (the default) sysntpd adds the NTP servers of every interface's lease -- or of
the ``dhcp_interface`` list's only -- that netifd keeps as ``data.ntpserver`` in
``ubus call network.interface dump`` (``/lib/netifd/dhcp.script`` stores udhcpc's
``ntpsrv`` there). They are read from the same place, in the same order, as
``dhcp_ntp_servers``; a write leaves ``use_dhcp`` as the router has it.
* **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
@@ -27,7 +31,8 @@ OpenWrt keeps both values in ``/etc/config/system`` (NetOrk/netork#2364):
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
Reading is one round trip as the login user: ``uci -q show system``, then netifd's
dump (:data:`READ_WITH_DHCP`). A write reads ``uci`` alone. 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
@@ -40,6 +45,7 @@ root (``run_command(privileged=True)``); OpenWrt has no sudo.
from __future__ import annotations
import json
import re
import shlex
from collections import defaultdict
@@ -56,6 +62,14 @@ if TYPE_CHECKING:
from napalm_device_types import CommandResult
READ_COMMAND = "uci -q show system"
#: The line between uci's answer and netifd's in :data:`READ_WITH_DHCP`.
DHCP_MARK = "@@napalm-openwrt: network.interface dump"
#: ``get_time_sync``'s reading: uci's ``system`` config, then netifd's interfaces, where
#: a lease keeps its NTP servers. Its exit code is uci's: ubus may refuse, uci may not.
READ_WITH_DHCP = (
f"{READ_COMMAND} && {{ echo {shlex.quote(DHCP_MARK)}; "
"ubus call network.interface dump 2>/dev/null || true; }"
)
#: 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.
@@ -89,7 +103,14 @@ class SystemUci:
@property
def dhcp_servers(self) -> bool:
return (self._one(self.ntp, "use_dhcp") or "1").lower() not in _FALSE
"""Whether sysntpd adds a lease's servers: the client runs and ``use_dhcp`` is on."""
use_dhcp = (self._one(self.ntp, "use_dhcp") or "1").lower() not in _FALSE
return self.has_ntp and self.ntp_enabled and use_dhcp
@property
def dhcp_interfaces(self) -> list[str]:
"""The interfaces whose leases count; [] for every interface, as sysntpd does."""
return [i for value in self.ntp.get("dhcp_interface", []) for i in value.split()]
@property
def servers(self) -> list[str]:
@@ -139,6 +160,31 @@ def parse_system_uci(output: str) -> SystemUci:
return parsed
def _lease_servers(entry: Any, interfaces: list[str]) -> list[str]:
"""One interface's ``data.ntpserver``, if it is one of *interfaces* (or they are [])."""
if not isinstance(entry, dict) or (interfaces and entry.get("interface") not in interfaces):
return []
data = entry.get("data")
servers = data.get("ntpserver") if isinstance(data, dict) else None
return servers.split() if isinstance(servers, str) else []
def lease_ntp_servers(dump: str, interfaces: list[str]) -> list[str] | None:
"""The NTP servers in netifd's ``network.interface dump``, as sysntpd collects them:
each interface's ``data.ntpserver`` (apart by spaces) in netifd's order, of
*interfaces* only where it names any, each once. None for no readable answer."""
try:
parsed = json.loads(dump)
except ValueError:
return None
if not isinstance(parsed, dict) or not isinstance(parsed.get("interface"), list):
return None
found: list[str] = []
for entry in parsed["interface"]:
found.extend(s for s in _lease_servers(entry, interfaces) if s not in found)
return found
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)
@@ -218,24 +264,34 @@ class OpenWrtTimeSyncMixin(TimeSyncMixin):
# -- reading ---------------------------------------------------------------------------------
def _ts_read(self) -> SystemUci:
result = self.run_command(READ_COMMAND, timeout=30)
def _ts_run_read(self, command: str) -> str:
result = self.run_command(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)
return result.stdout
def _ts_read(self) -> SystemUci:
return parse_system_uci(self._ts_run_read(READ_COMMAND))
def get_time_sync(self) -> TimeSyncDict:
"""The router's time servers and zone, from one ``uci -q show system``.
"""The router's time servers and zone, and what its DHCP leases bring, in one
round trip (:data:`READ_WITH_DHCP`).
``dhcp_ntp_servers`` is None where sysntpd would add a lease's servers but
netifd gave no answer.
:raises RuntimeError: when uci could not be read.
"""
reading = self._ts_read()
uci, _, dump = self._ts_run_read(READ_WITH_DHCP).partition(f"{DHCP_MARK}\n")
reading = parse_system_uci(uci)
dhcp = lease_ntp_servers(dump, reading.dhcp_interfaces) if reading.dhcp_servers else []
return {
"ntp_servers": reading.servers,
"timezone": reading.zone,
"synchronized": None,
"daemon": None,
"dhcp_ntp_servers": dhcp,
}
def get_ntp_servers(self) -> dict[str, dict[str, Any]]:
@@ -257,9 +313,7 @@ class OpenWrtTimeSyncMixin(TimeSyncMixin):
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:
if [s.lower() for s in now.servers] == [s.lower() for s in servers]:
return {"ok": True, "output": "the router already has these servers"}
commands = []
if not now.has_ntp:
@@ -269,7 +323,6 @@ class OpenWrtTimeSyncMixin(TimeSyncMixin):
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",
@@ -294,8 +347,11 @@ class OpenWrtTimeSyncMixin(TimeSyncMixin):
__all__ = [
"DHCP_MARK",
"READ_WITH_DHCP",
"OpenWrtTimeSyncMixin",
"SystemUci",
"lease_ntp_servers",
"parse_system_uci",
"same_time",
"zone_for_rule",