Merge pull request 'feat(time-sync): the box's NTP servers through TimeSyncMixin' (#13) from feature/time-sync-2367 into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 13s
driver / types (push) Successful in 58s
driver / test (3.13) (push) Successful in 52s
driver / test (3.12) (push) Successful in 56s
driver / lowest (push) Successful in 29s
driver / build (push) Successful in 30s
driver / security (push) Successful in 59s
CI / driver (push) Successful in 2m8s
driver / publish (push) Skipped

This commit was merged in pull request #13.
This commit is contained in:
christianmanivong committed 2026-11-11 14:51:42 +00:00
commit c587915584
5 files changed
+273 -7

No files matched your search

+13
View File
@@ -6,7 +6,20 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- `get_time_sync()` and `configure_time_sync()` through napalm-device-types'
`TimeSyncMixin` (4.35.0), over TR-064's `Time:1` service: the box's NTP servers
in its order (`GetInfo`, an empty slot is no server), written with
`SetNTPServers` (NetOrk/netork#2367). `time_sync_writes` is `{"ntp_servers"}`:
AVM documents the zone fields as not supported, and the box keeps its zone as an
offset with a summer-time rule, so `timezone` reads `None` unless the box names
an IANA zone. The box keeps two servers; a longer list is refused before
anything is written, and servers the box already has are not written again.
TR-064 says nothing about whether the clock is synchronised (`None`), nor whether
the box serves time to its network (NetOrk/netork#2371).
### Changed
- Needs napalm-device-types 4.35.0.
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
+21 -2
View File
@@ -78,10 +78,29 @@ box does not offer leaves its fields out). Two of them are easy to misread:
`firmware_update_available` without `firmware_version`.
- `timezone` is the box's time zone name (`NewLocalTimeZoneName`).
## Time sync
`get_time_sync()` and `configure_time_sync()` (napalm-device-types'
`TimeSyncMixin`) use TR-064's `Time:1` service
([AVM: TR-064 Support – Time](https://fritz.support/resources/TR-064_Time.pdf)):
- `ntp_servers` are `NewNTPServer1` and `NewNTPServer2` from `GetInfo`; an empty
slot is no server. `configure_time_sync(ntp_servers=[...])` writes them with
`SetNTPServers`: two at most (a longer list is refused before anything is
written), a missing second one as an empty slot. Servers the box already has,
in that order, are not written again.
- The zone is not written (`time_sync_writes == {"ntp_servers"}`): AVM documents
the zone fields as not supported. The box reports its zone, if at all, as a
POSIX rule (`CET-1CEST,M3.5.0,M10.5.0/3`), so `timezone` is `None` unless it
names an IANA zone.
- `synchronized` and `daemon` are `None`: TR-064 says neither.
- Whether the box serves time to its home network ("FRITZ!Box als Zeitserver im
Heimnetz bereitstellen") is not in TR-064 either, so the driver cannot report it.
## Limitations
- Read-only: configuration management methods (`load_merge_candidate`,
`commit_config`, ...) are not implemented.
- Configuration management methods (`load_merge_candidate`, `commit_config`, ...)
are not implemented; the only write is the NTP servers (see *Time sync*).
- `get_nat_translations()` is derived from the enabled port-forwarding rules —
TR-064 does not expose a live connection-tracking table.
- `get_vpn_tunnels()` returns an empty dict — FritzOS does not expose VPN
+67 -4
View File
@@ -26,8 +26,9 @@ FritzBox always serves TR-064 over HTTPS with a self-signed certificate;
``fritzconnection`` does not verify it, so no separate ``verify`` option is
needed.
This driver is read-only: it does not implement NAPALM's configuration
management methods (``load_merge_candidate``, ``commit_config``, ...).
The driver writes one thing: the box's NTP servers (``configure_time_sync``,
TR-064 ``Time:1``). It does not implement NAPALM's configuration management
methods (``load_merge_candidate``, ``commit_config``, ...).
"""
from __future__ import annotations
@@ -46,6 +47,7 @@ from fritzconnection.core.exceptions import (
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from napalm_device_types import FingerprintRule, ResidentialGatewayDriver
from napalm_device_types.models import (
FixStepOutcomeDict,
HostDict,
NATTranslationDict,
PortForwardDict,
@@ -55,6 +57,8 @@ from napalm_device_types.models import (
WANStatusDict,
WirelessClientDict,
)
from napalm_device_types.posix_tz import is_iana_zone
from napalm_device_types.time_sync import TimeSyncDict, TimeSyncMixin
logger = logging.getLogger(__name__)
@@ -78,8 +82,8 @@ def _to_float(value: Any, default: float = 0.0) -> float:
return default
class FritzBoxDriver(ResidentialGatewayDriver):
"""NAPALM driver for AVM FritzBox (read-only, TR-064)."""
class FritzBoxDriver(ResidentialGatewayDriver, TimeSyncMixin):
"""NAPALM driver for AVM FritzBox (TR-064); it writes only its NTP servers."""
VENDOR = "AVM"
DRIVER_NAME = "fritzbox"
@@ -99,6 +103,12 @@ class FritzBoxDriver(ResidentialGatewayDriver):
_WAN_IP_SERVICES = ("WANIPConnection1", "WANPPPConnection1")
_WLAN_SERVICES = ("WLANConfiguration1", "WLANConfiguration2", "WLANConfiguration3")
#: TR-064 ``Time:1`` reads and sets the NTP servers only; its zone fields are
#: "not supported" (AVM, TR-064 Support -- Time, 2025-08-07).
time_sync_writes = frozenset({"ntp_servers"})
#: ``SetNTPServers`` takes two servers, ``NewNTPServer1`` and ``NewNTPServer2``.
_NTP_SLOTS = 2
def __init__(
self,
hostname: str,
@@ -432,6 +442,59 @@ class FritzBoxDriver(ResidentialGatewayDriver):
)
return arp_table
# ------------------------------------------------------------------
# Time sync (napalm-device-types TimeSyncMixin)
# ------------------------------------------------------------------
def _time_info(self) -> dict[str, Any]:
if self.fc is not None and "Time1" not in self.fc.services:
raise FritzServiceError("this FRITZ!Box offers no TR-064 Time service")
return self._call("Time1", "GetInfo")
def get_time_sync(self) -> TimeSyncDict:
"""The box's NTP servers, from ``Time1.GetInfo``; one TR-064 call.
An empty server slot is no server. The box keeps its zone as an offset with
a summer-time rule (``NewLocalTimeZoneName`` holds a POSIX rule, or nothing),
so ``timezone`` is None unless the box names an IANA zone. TR-064 says
neither whether the clock is synchronised nor anything about the client.
"""
info = self._time_info()
servers = [
name
for name in (
str(info.get(f"NewNTPServer{slot}") or "").strip()
for slot in range(1, self._NTP_SLOTS + 1)
)
if name
]
zone = str(info.get("NewLocalTimeZoneName") or "").strip()
return {
"ntp_servers": servers,
"timezone": zone if is_iana_zone(zone) else None,
"synchronized": None,
"daemon": None,
}
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
"""``Time1.SetNTPServers`` with *servers*, an empty slot for a missing second.
More than two are refused: the box would drop the rest. Servers the box
already has, in this order, are not written again.
"""
if len(servers) > self._NTP_SLOTS:
return {
"ok": False,
"output": f"a FRITZ!Box keeps two NTP servers, not {len(servers)}: "
+ ", ".join(servers),
}
now = self.get_time_sync()["ntp_servers"]
if [s.lower() for s in now] == [s.lower() for s in servers]:
return {"ok": True, "output": "the box already has these NTP servers"}
first, second = [*servers, "", ""][: self._NTP_SLOTS]
self._call("Time1", "SetNTPServers", NewNTPServer1=first, NewNTPServer2=second)
return {"ok": True, "output": f"NTP servers set to {', '.join(servers)}"}
# ------------------------------------------------------------------
# Residential gateway extensions
# ------------------------------------------------------------------
+1 -1
View File
@@ -23,7 +23,7 @@ classifiers = [
]
dependencies = [
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.21.1",
"napalm-device-types>=4.35.0",
"fritzconnection>=1.13.0",
]
+171
View File
@@ -0,0 +1,171 @@
"""get_time_sync() / configure_time_sync() over TR-064's Time:1 service (NetOrk/netork#2367).
The answers are what AVM documents for ``urn:dslforum-org:service:Time:1``
(TR-064 Support -- Time, version 5, 2025-08-07): ``GetInfo`` returns the two NTP
servers and the box's clock; the zone fields are "not supported" -- a box fills
``NewLocalTimeZoneName`` with a POSIX rule or leaves it empty. ``SetNTPServers``
takes exactly two names; an empty one is an unused slot.
"""
from unittest.mock import MagicMock
import pytest
from fritzconnection.core.exceptions import FritzServiceError
from napalm_fritzbox.fritzbox import FritzBoxDriver
GET_INFO = {
"NewNTPServer1": "ntp.example.com",
"NewNTPServer2": "",
"NewCurrentLocalTime": "2026-11-11T10:00:00+01:00",
"NewLocalTimeZone": "",
"NewLocalTimeZoneName": "CET-1CEST,M3.5.0,M10.5.0/3",
"NewDaylightSavingsUsed": False,
"NewDaylightSavingsStart": "0001-01-01T00:00:00",
"NewDaylightSavingsEnd": "0001-01-01T00:00:00",
}
class FakeTimeService:
"""The box's Time:1 service: GetInfo reads what SetNTPServers stored."""
def __init__(self, info: dict) -> None:
self.info = dict(info)
self.sets: list[dict] = []
def __call__(self, service: str, action: str, **kwargs: str) -> dict:
if service != "Time1":
raise FritzServiceError(f"no service {service}")
if action == "GetInfo":
return dict(self.info)
if action == "SetNTPServers":
self.sets.append(kwargs)
self.info["NewNTPServer1"] = kwargs["NewNTPServer1"]
self.info["NewNTPServer2"] = kwargs["NewNTPServer2"]
return {}
raise AssertionError(f"unexpected action {action}")
@pytest.fixture
def box():
fake = FakeTimeService(GET_INFO)
mock_fc = MagicMock()
mock_fc.services = {"Time1": MagicMock()}
mock_fc.call_action.side_effect = fake
drv = FritzBoxDriver(hostname="fritz.box", username="user", password="pass")
drv.fc = mock_fc
yield drv, fake
drv.close()
class TestRead:
def test_is_offered(self, box):
drv, _ = box
assert callable(getattr(drv, "get_time_sync", None))
assert callable(getattr(drv, "configure_time_sync", None))
def test_servers_without_the_empty_slot(self, box):
drv, _ = box
assert drv.get_time_sync() == {
"ntp_servers": ["ntp.example.com"],
"timezone": None,
"synchronized": None,
"daemon": None,
}
def test_both_servers_in_the_box_order(self, box):
drv, fake = box
fake.info.update(NewNTPServer1=" 2.europe.pool.ntp.org ", NewNTPServer2="192.0.2.1")
assert drv.get_time_sync()["ntp_servers"] == ["2.europe.pool.ntp.org", "192.0.2.1"]
def test_no_servers(self, box):
drv, fake = box
fake.info.update(NewNTPServer1="", NewNTPServer2="")
assert drv.get_time_sync()["ntp_servers"] == []
def test_a_posix_rule_is_no_zone_name(self, box):
"""The box keeps an offset and a summer-time rule, not a name."""
drv, _ = box
assert drv.get_time_sync()["timezone"] is None
def test_a_zone_name_the_box_gives_is_kept(self, box):
drv, fake = box
fake.info["NewLocalTimeZoneName"] = "Europe/Berlin"
assert drv.get_time_sync()["timezone"] == "Europe/Berlin"
def test_a_missing_zone_field_is_none(self, box):
drv, fake = box
del fake.info["NewLocalTimeZoneName"]
assert drv.get_time_sync()["timezone"] is None
def test_a_box_without_the_service_cannot_tell(self, box):
drv, _ = box
drv.fc.services = {}
with pytest.raises(FritzServiceError):
drv.get_time_sync()
def test_system_config_names_the_same_servers(self, box):
drv, fake = box
fake.info.update(NewNTPServer1="a.example.org", NewNTPServer2="b.example.org")
config = drv.get_system_config()
assert [config["ntp_server"], config["ntp_server2"]] == drv.get_time_sync()["ntp_servers"]
class TestWrite:
def test_writes_only_servers(self, box):
drv, _ = box
assert drv.time_sync_writes == frozenset({"ntp_servers"})
with pytest.raises(ValueError, match="timezone"):
drv.configure_time_sync(timezone="Europe/Berlin")
def test_two_servers(self, box):
drv, fake = box
result = drv.configure_time_sync(ntp_servers=["ntp1.example.org", "10.0.0.1"])
assert result["success"], result["output"]
assert fake.sets == [{"NewNTPServer1": "ntp1.example.org", "NewNTPServer2": "10.0.0.1"}]
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "verify"]
def test_one_server_empties_the_second_slot(self, box):
drv, fake = box
fake.info["NewNTPServer2"] = "old.example.org"
result = drv.configure_time_sync(ntp_servers=["10.0.0.1"])
assert result["success"], result["output"]
assert fake.sets == [{"NewNTPServer1": "10.0.0.1", "NewNTPServer2": ""}]
assert drv.get_time_sync()["ntp_servers"] == ["10.0.0.1"]
def test_more_than_two_is_refused_before_writing(self, box):
drv, fake = box
result = drv.configure_time_sync(ntp_servers=["a.example.org", "b.example.org", "c.org"])
assert not result["success"]
assert result["steps"][0]["step"] == "ntp_servers"
assert "two" in result["steps"][0]["output"]
assert fake.sets == []
def test_the_same_servers_again_write_nothing(self, box):
drv, fake = box
result = drv.configure_time_sync(ntp_servers=["NTP.example.com"])
assert result["success"], result["output"]
assert fake.sets == []
def test_a_box_that_keeps_other_servers_fails_verify(self, box):
drv, fake = box
drv.fc.call_action.side_effect = lambda s, a, **kw: (
{} if a == "SetNTPServers" else fake(s, a)
)
result = drv.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert result["steps"][-1]["step"] == "verify"
assert "ntp.example.com" in result["steps"][-1]["output"]
def test_a_refused_write_fails_the_step(self, box):
drv, fake = box
def refuse(service, action, **kwargs):
if action == "SetNTPServers":
raise FritzServiceError("UPnPError 606: Action not authorized")
return fake(service, action)
drv.fc.call_action.side_effect = refuse
result = drv.configure_time_sync(ntp_servers=["10.0.0.1"])
assert not result["success"]
assert "606" in result["steps"][0]["output"]