"""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", # napalm-device-types 4.36.0: the servers it got by DHCP, none here (#75). "dhcp_ntp_servers": [], } 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" ]