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

+141 -12
View File
@@ -8,11 +8,15 @@ OpenWrt keeps both values in UCI's ``system`` config: the servers in the
The device is a fake ``uci`` behind ``run_command``: it renders ``uci -q show system``
the way uci prints it, and applies the ``uci set``/``delete``/``add_list`` lines a
write sends, so the template's ``verify`` step reads back what was written.
write sends, so the template's ``verify`` step reads back what was written. Behind it
is netifd's ``ubus call network.interface dump``, where a DHCP lease's NTP servers
(option 42) are ``data.ntpserver`` -- sysntpd hands them to ntpd too while
``use_dhcp`` is on, and they count (NetOrk/netork#2380).
"""
from __future__ import annotations
import json
import shlex
from typing import Any
from unittest.mock import MagicMock, patch
@@ -23,7 +27,7 @@ from napalm_device_types.posix_tz import UnknownTimezone, posix_tz
from napalm_device_types.time_sync import TIME_SYNC_VALUES
from napalm_openwrt.openwrt import OpenWrtDriver
from napalm_openwrt.time_sync_mixin import parse_system_uci, zone_for_rule
from napalm_openwrt.time_sync_mixin import DHCP_MARK, parse_system_uci, zone_for_rule
# ``uci show system`` of OpenWrt 23.05 out of the box: zonename 'UTC', the rule GMT0,
# the four pool servers as a list.
@@ -81,6 +85,23 @@ system.ntp.enabled='1'
"""
def _interface(name: str, ntpserver: str | None = None, **more: Any) -> dict[str, Any]:
"""One interface of ``ubus call network.interface dump``, as netifd prints it."""
data = {} if ntpserver is None else {"ntpserver": ntpserver}
return {"interface": name, "up": True, "proto": "dhcp", "data": data, **more}
#: A router whose WAN lease brings two NTP servers (udhcpc's ``ntpsrv``, apart by
#: spaces, as /lib/netifd/dhcp.script stores it) and a LAN of its own.
LEASE = {
"interface": [
_interface("lan", proto="static"),
_interface("wan", "192.168.1.1 192.168.1.2", leasetime=43200),
_interface("wan6", proto="dhcpv6"),
]
}
def _render(sections: list[tuple[str, str, dict[str, list[str] | str]]]) -> str:
"""*sections* as ``uci show system`` prints them."""
lines = []
@@ -115,13 +136,16 @@ def _parse(output: str) -> list[tuple[str, str, dict[str, list[str] | str]]]:
class _Uci:
"""A router's ``system`` config behind ``run_command``; keeps every command it ran."""
def __init__(self, show: str = STOCK, fail: str = "") -> None:
def __init__(
self, show: str = STOCK, fail: str = "", dump: dict[str, Any] | str | None = None
) -> None:
self.sections = _parse(show)
self.fail = fail
self.dump = {"interface": []} if dump is None else dump
self.ran: list[tuple[str, bool]] = []
def writes(self) -> list[str]:
return [c for c, _ in self.ran if c != "uci -q show system"]
return [c for c, _ in self.ran if not c.startswith("uci -q show system")]
def __call__(
self,
@@ -134,6 +158,10 @@ class _Uci:
self.ran.append((command, privileged))
if command == "uci -q show system":
return CommandResult(_render(self.sections), "", 0)
if command.startswith("uci -q show system &&"):
assert "ubus call network.interface dump" in command
dump = self.dump if isinstance(self.dump, str) else json.dumps(self.dump, indent=1)
return CommandResult(f"{_render(self.sections)}{DHCP_MARK}\n{dump}\n", "", 0)
for part in command.split(" && "):
if self.fail and self.fail in part:
return CommandResult("", f"{self.fail}: failed", 1)
@@ -173,8 +201,8 @@ def _driver(uci: _Uci, username: str = "root") -> OpenWrtDriver:
return drv
def _read(show: str) -> dict[str, Any]:
return dict(_driver(_Uci(show)).get_time_sync())
def _read(show: str, dump: dict[str, Any] | str | None = None) -> dict[str, Any]:
return dict(_driver(_Uci(show, dump=dump)).get_time_sync())
# -- the driver takes part ----------------------------------------------------------------------
@@ -203,14 +231,94 @@ def test_a_stock_router_reads_its_pool_servers_and_utc():
"timezone": "UTC",
"synchronized": None,
"daemon": None,
"dhcp_ntp_servers": [],
}
def test_the_read_is_one_uci_show_as_the_login_user():
def test_the_read_is_one_round_trip_as_the_login_user():
uci = _Uci()
_driver(uci).get_time_sync()
assert uci.ran == [("uci -q show system", False)]
((command, privileged),) = uci.ran
assert command.startswith("uci -q show system &&")
assert privileged is False
# -- reading what DHCP brought ------------------------------------------------------------------
def test_a_lease_s_ntp_servers_are_read_apart_from_the_configured_ones():
reading = _read(STOCK, LEASE)
assert reading["dhcp_ntp_servers"] == ["192.168.1.1", "192.168.1.2"]
assert reading["ntp_servers"] == [
"0.openwrt.pool.ntp.org",
"1.openwrt.pool.ntp.org",
"2.openwrt.pool.ntp.org",
"3.openwrt.pool.ntp.org",
]
def test_every_interface_s_lease_counts_in_netifd_s_order_each_once():
dump = {
"interface": [
_interface("wan", "192.168.1.1"),
_interface("iot", "10.40.100.1 192.168.1.1"),
]
}
assert _read(STOCK, dump)["dhcp_ntp_servers"] == ["192.168.1.1", "10.40.100.1"]
def test_an_interface_without_a_lease_or_with_an_odd_one_brings_nothing():
dump = {
"interface": [
"wan",
{"interface": "wan", "data": "192.168.1.1"},
{"interface": "wan", "data": {"ntpserver": ["192.168.1.1"]}},
{"interface": "wan"},
_interface("iot", "10.40.100.1"),
]
}
assert _read(STOCK, dump)["dhcp_ntp_servers"] == ["10.40.100.1"]
def test_dhcp_interface_names_the_interfaces_whose_leases_count():
show = STOCK + "system.ntp.dhcp_interface='iot'\n"
dump = {
"interface": [
_interface("wan", "192.168.1.1"),
_interface("iot", "10.40.100.1"),
]
}
assert _read(show, dump)["dhcp_ntp_servers"] == ["10.40.100.1"]
def test_use_dhcp_off_takes_nothing_from_a_lease():
show = STOCK + "system.ntp.use_dhcp='0'\n"
assert _read(show, LEASE)["dhcp_ntp_servers"] == []
def test_a_disabled_client_takes_nothing_from_a_lease():
show = STOCK.replace("system.ntp.enabled='1'", "system.ntp.enabled='0'")
assert _read(show, LEASE)["dhcp_ntp_servers"] == []
@pytest.mark.parametrize(
"dump", ["", "Command failed: Permission denied", "{", "[]", '{"interface": {}}']
)
def test_without_netifd_s_answer_dhcp_is_unknown(dump):
assert _read(STOCK, dump)["dhcp_ntp_servers"] is None
def test_without_netifd_s_answer_a_router_that_takes_nothing_from_dhcp_still_says_so():
show = STOCK + "system.ntp.use_dhcp='0'\n"
assert _read(show, "")["dhcp_ntp_servers"] == []
def test_a_zone_set_through_luci_reads_by_its_name():
@@ -346,12 +454,33 @@ def test_the_servers_replace_the_list_and_ntpd_restarts():
assert all(privileged for c, privileged in uci.ran if c in uci.writes())
def test_writing_servers_turns_off_the_ones_dhcp_brings():
# sysntpd adds the servers of a DHCP lease to the list unless use_dhcp is 0.
uci = _Uci(STOCK)
_driver(uci).configure_time_sync(ntp_servers=["10.0.0.1"])
def test_writing_servers_leaves_the_ones_dhcp_brings():
# DHCP option 42 counts (NetOrk/netork#2380): sysntpd keeps adding a lease's servers.
uci = _Uci(STOCK, dump=LEASE)
result = _driver(uci).configure_time_sync(ntp_servers=["10.0.0.1"])
assert result["success"] is True, result["output"]
assert "use_dhcp" not in uci._section("ntp")
assert "use_dhcp" not in uci.writes()[0]
def test_writing_servers_keeps_use_dhcp_as_the_router_has_it():
uci = _Uci(STOCK + "system.ntp.use_dhcp='0'\n")
result = _driver(uci).configure_time_sync(ntp_servers=["10.0.0.1"])
assert result["success"] is True, result["output"]
assert uci._section("ntp")["use_dhcp"] == "0"
assert "use_dhcp" not in uci.writes()[0]
def test_the_same_servers_with_dhcp_on_write_nothing():
uci = _Uci(LUCI_BERLIN, dump=LEASE)
result = _driver(uci).configure_time_sync(
ntp_servers=["0.openwrt.pool.ntp.org", "1.openwrt.pool.ntp.org"]
)
assert result["success"] is True, result["output"]
assert uci.writes() == []
def test_writing_servers_enables_a_disabled_client():