From c2e7ea5789db2fe70626b07b052608bda1f5a0ec Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Wed, 11 Nov 2026 14:32:29 +0100 Subject: [PATCH] feat(time-sync): the host's time sources and zone through PosixTimeSyncMixin netOrk aligns every device's NTP servers and time zone with the site's (NetOrk/netork#2360). A Linux host gets get_time_sync() and configure_time_sync() from napalm-device-types 4.35.0's PosixTimeSyncMixin (#2361): one reading as the login user, the zone by timedatectl, chrony's servers in a file of their own with every other source commented out, systemd-timesyncd's in a drop-in. The driver only carries the commands across run_command. The mixin comes in with PosixScheduledJobsMixin through LinuxPosixMixin, the implementations napalm-device-types makes for any POSIX host, so linux.py does not grow. OpenMediaVault and QNAP inherit both. --- CHANGELOG.md | 10 +++- napalm_linux/_posix.py | 15 ++++++ napalm_linux/linux.py | 4 +- pyproject.toml | 2 +- tests/test_time_sync.py | 102 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 129 insertions(+), 4 deletions(-) create mode 100644 napalm_linux/_posix.py create mode 100644 tests/test_time_sync.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 897a950..6b018ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- `get_time_sync()` and `configure_time_sync()` through napalm-device-types' + `PosixTimeSyncMixin` (4.35.0): the host's NTP servers in its client's order, its time zone, + whether the clock is synchronised and which client keeps it (chrony, systemd-timesyncd, + ntpd, OpenNTPD), read in one round trip as the login user. The zone is set with + `timedatectl set-timezone`; chrony's servers go to `/etc/chrony/sources.d/netork.sources` + (else a `confdir` or an included file) with every other source commented out, + systemd-timesyncd's to `/etc/systemd/timesyncd.conf.d/netork.conf`. The host ends up with + exactly the servers given (NetOrk/netork#2361). OpenMediaVault and QNAP inherit it. - `get_running_backups()` through napalm-device-types' `RunningBackupsMixin` (4.34.0): the host's own backups a restart would abort -- a process of restic, resticprofile, autorestic, borg, borgmatic, duplicity, duply, rsnapshot, rdiff-backup, proxmox-backup-client, kopia or @@ -25,7 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 admin groups. The account stays open and logs in with its other keys only. ### Changed -- Needs napalm-device-types 4.34.0. +- Needs napalm-device-types 4.35.0. ## [0.17.0] - 2026-11-04 diff --git a/napalm_linux/_posix.py b/napalm_linux/_posix.py new file mode 100644 index 0000000..b311619 --- /dev/null +++ b/napalm_linux/_posix.py @@ -0,0 +1,15 @@ +"""What napalm-device-types implements for any POSIX host over ``run_command``. + +The driver supplies ``run_command``; the readings, their parses and the writes are +the mixins': scheduled jobs (cron, anacron, systemd timers) and time sync (chrony, +systemd-timesyncd, ``timedatectl``). Their default paths are Debian's, which a +Linux host shares. +""" + +from __future__ import annotations + +from napalm_device_types import PosixScheduledJobsMixin, PosixTimeSyncMixin + + +class LinuxPosixMixin(PosixScheduledJobsMixin, PosixTimeSyncMixin): + """Scheduled jobs and time sync of the host, over the driver's ``run_command``.""" diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index 73513ae..5e551d5 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -41,7 +41,6 @@ from napalm_device_types import ( LldpNeighborDict, OpenSshServerMixin, OSDriver, - PosixScheduledJobsMixin, ServiceClustersMixin, ServicePackagesMixin, SnmpAgentMixin, @@ -78,6 +77,7 @@ from napalm_linux._dpkg import DPKG_QUERY_COMMAND, parse_dpkg_query from napalm_linux._hostname import HostnameMixin from napalm_linux._local_accounts import LinuxLocalAccountsMixin from napalm_linux._ping import parse_ping, ping_command +from napalm_linux._posix import LinuxPosixMixin from napalm_linux._readings import LinuxProcessReadingsMixin from napalm_linux._routes import IP_ROUTE_COMMANDS, IpRoute, parse_ip_route, with_length from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password @@ -310,7 +310,7 @@ class LinuxDriver( SystemIdentityMixin, OpenSshServerMixin, SystemdServicesMixin, - PosixScheduledJobsMixin, + LinuxPosixMixin, HostStatusMixin, ContainerEngineMixin, HostnameMixin, diff --git a/pyproject.toml b/pyproject.toml index 2cbed6d..b5becd2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,7 +34,7 @@ classifiers = [ ] dependencies = [ "napalm>=4.0", - "napalm-device-types>=4.34.0", + "napalm-device-types>=4.35.0", "netmiko>=4.0.0", "paramiko>=5.0.0", # CVE-2026-44405 ] diff --git a/tests/test_time_sync.py b/tests/test_time_sync.py new file mode 100644 index 0000000..fb6a7c5 --- /dev/null +++ b/tests/test_time_sync.py @@ -0,0 +1,102 @@ +"""Time sync on a Linux host: napalm-device-types' POSIX implementation (NetOrk/netork#2361). + +The reading, its parse and every write are ``PosixTimeSyncMixin``'s; the driver +carries the commands across ``run_command`` -- the reading as the login user in one +round trip, the writes as root, and root never reads stdin. +""" + +from __future__ import annotations + +from napalm_device_types import CommandResult, PosixTimeSyncMixin, TimeSyncMixin + +from napalm_linux import LinuxDriver + +#: Debian 12 with chrony: the reading as PosixTimeSyncMixin's command prints it. +READING = """\ +@@ts timedatectl +Timezone=Europe/Berlin +NTP=yes +NTPSynchronized=yes +@@ts zone +Europe/Berlin +@@ts active +chrony chrony active +chronyd chrony active +systemd-timesyncd systemd-timesyncd inactive +@@ts timesync +@@ts chronyc +MS Name/IP address Stratum Poll Reach LastRx Last sample +=============================================================================== +^* 192.168.1.1 2 6 377 40 -45us[ -63us] +/- 10ms +@@ts chrony 0 main /etc/chrony/chrony.conf +pool 2.debian.pool.ntp.org iburst +sourcedir /etc/chrony/sources.d + +@@ts end +""" + + +class _Channel: + """Records every command; answers the reading, and a staged file's path.""" + + def __init__(self) -> None: + self.calls: list[tuple[str, bool, bytes | None]] = [] + + def __call__(self, command, *, privileged=False, timeout=60, stdin=None): # type: ignore[no-untyped-def] + self.calls.append((command, privileged, stdin)) + if "@@ts" in command: + return CommandResult(READING, "", 0) + if "mktemp" in command: + return CommandResult("/tmp/tmp.abc123", "", 0) + return CommandResult("", "", 0) + + +def _driver() -> tuple[LinuxDriver, _Channel]: + driver = LinuxDriver("host", "user", "pw", optional_args={"sudo_password": "pw"}) + channel = _Channel() + driver.run_command = channel # type: ignore[method-assign] + return driver, channel + + +def test_a_linux_host_keeps_its_clock_through_the_posix_mixin(): + assert issubclass(LinuxDriver, PosixTimeSyncMixin) + assert issubclass(LinuxDriver, TimeSyncMixin) + assert callable(getattr(LinuxDriver, "get_time_sync", None)) + assert callable(getattr(LinuxDriver, "configure_time_sync", None)) + assert LinuxDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"}) + + +def test_the_reading_is_one_round_trip_as_the_login_user(): + driver, channel = _driver() + + assert driver.get_time_sync() == { + "ntp_servers": ["2.debian.pool.ntp.org"], + "timezone": "Europe/Berlin", + "synchronized": True, + "daemon": "chrony", + } + assert [privileged for _, privileged, _ in channel.calls] == [False] + + +def test_the_zone_is_set_as_root(): + driver, channel = _driver() + result = driver.configure_time_sync(timezone="Europe/Berlin") + + assert result["success"] is True, result["output"] + assert ("timedatectl set-timezone Europe/Berlin", True, None) in channel.calls + + +def test_root_never_reads_stdin(): + # With a sudo password, sudo -S reads it from stdin: a privileged command given + # stdin as well would hand the password on (LinuxDriver refuses it). + driver, channel = _driver() + result = driver.configure_time_sync(["ntp1.example.org"], "UTC") + + assert result["steps"][0]["step"] == "ntp_servers" + assert result["steps"][0]["ok"] is True, result["output"] + assert any(stdin for _, privileged, stdin in channel.calls if not privileged) + assert all(stdin is None for _, privileged, stdin in channel.calls if privileged) + installed = [c for c, privileged, _ in channel.calls if privileged and c.startswith("install")] + assert installed == [ + "install -D -m 644 -- /tmp/tmp.abc123 /etc/chrony/sources.d/netork.sources" + ]