From 5195cebfcabd0a4b8ee7a1f07b997e690bd5bb61 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 21:52:03 +0100 Subject: [PATCH] fix(ntp): read chrony's sources in get_ntp_stats The getter ran "chronyc tracking || ntpq -pn" and parsed ntpq's format. Proxmox VE ships chrony, so ntpq never ran and nothing matched. chrony is now read in CSV mode (sources plus sourcestats); ntpq stays the fallback and keeps peers without a tally mark. Closes #18 --- CHANGELOG.md | 4 ++ napalm_proxmox/ntp.py | 113 +++++++++++++++++++++++++++++++++ napalm_proxmox/system_mixin.py | 34 ++-------- tests/test_ntp_stats.py | 86 +++++++++++++++++++++++++ 4 files changed, 207 insertions(+), 30 deletions(-) create mode 100644 napalm_proxmox/ntp.py create mode 100644 tests/test_ntp_stats.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ca4f96b..e3845bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 user level 15 when the ACL grants it the Administrator role on `/`, directly or through a group; `root@pam` is always 15. Before, practically every Proxmox user was level 1 (#19). +- `get_ntp_stats()` reports chrony's sources, Proxmox VE's default, instead of + always returning an empty list: offset in ms, the poll interval in seconds, + the offset's standard deviation as `jitter`; chrony reports no delay, so + `delay` is 0.0. On ntpd, a peer without tally mark is no longer dropped (#18). ## [0.8.0] - 2026-10-23 diff --git a/napalm_proxmox/ntp.py b/napalm_proxmox/ntp.py new file mode 100644 index 0000000..c795dd8 --- /dev/null +++ b/napalm_proxmox/ntp.py @@ -0,0 +1,113 @@ +"""NTP statistics (``get_ntp_stats``) from chrony or ntpd, in NAPALM's NTPStats shape. + +Proxmox VE ships chrony; ntpd is read only where chrony is not installed. +chrony is read in its CSV mode (``chronyc -c``): ``sources`` names each source +with its state, ``sourcestats`` adds the spread of its offset, reported as +jitter. chrony reports no delay per source, so ``delay`` is 0.0. Times are in +milliseconds and the poll interval in seconds, as ``ntpq -pn`` gives them. +""" + +from __future__ import annotations + +import re +from typing import Any + +CHRONY_SOURCES_MARK = "CHRONY_SOURCES" +CHRONY_SOURCESTATS_MARK = "CHRONY_SOURCESTATS" + +#: chrony when it is installed, ntpd's ntpq otherwise. +NTP_STATS_COMMAND = ( + "if command -v chronyc >/dev/null 2>&1; then " + f"echo {CHRONY_SOURCES_MARK}; chronyc -n -c sources; " + f"echo {CHRONY_SOURCESTATS_MARK}; chronyc -n -c sourcestats; " + "else ntpq -pn; fi 2>/dev/null" +) + +#: chrony's source mode as ntpq's type: server (unicast), peer (symmetric), refclock (local). +_CHRONY_TYPES = {"^": "u", "=": "s", "#": "l"} +_MS_PER_S = 1000.0 + +#: ``*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123``; the first +#: column is the tally mark, a space for a peer without one. +_NTPQ_LINE = re.compile( + r"^([ *+#ox.-])(\S+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)" + r"\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)" +) + + +def parse_ntp_stats(output: str) -> list[dict[str, Any]]: + """The NTPStats list in the output of :data:`NTP_STATS_COMMAND`.""" + if output.lstrip().startswith(CHRONY_SOURCES_MARK): + return parse_chrony(output) + return parse_ntpq(output) + + +def parse_chrony(output: str) -> list[dict[str, Any]]: + """Sources and their statistics from ``chronyc -n -c sources`` / ``sourcestats``.""" + sources, _, sourcestats = output.partition(CHRONY_SOURCESTATS_MARK) + jitter = _chrony_jitter(sourcestats) + stats = [] + for line in sources.splitlines(): + fields = line.strip().split(",") + if len(fields) < 10: + continue + mode, state, name, stratum, poll, reach, last_rx, _, offset, _ = fields[:10] + try: + stats.append( + { + "remote": name, + "referenceid": "", + "synchronized": state == "*", + "stratum": int(stratum), + "type": _CHRONY_TYPES.get(mode, ""), + "when": last_rx, + "hostpoll": 2 ** int(poll), + "reachability": int(reach), + "delay": 0.0, + "offset": float(offset) * _MS_PER_S, + "jitter": jitter.get(name, 0.0), + } + ) + except ValueError: + continue + return stats + + +def _chrony_jitter(sourcestats: str) -> dict[str, float]: + """Each source's offset standard deviation in ms (``sourcestats``' last column).""" + jitter = {} + for line in sourcestats.splitlines(): + fields = line.strip().split(",") + if len(fields) < 8: + continue + try: + jitter[fields[0]] = float(fields[7]) * _MS_PER_S + except ValueError: + continue + return jitter + + +def parse_ntpq(output: str) -> list[dict[str, Any]]: + """Peers from ``ntpq -pn``.""" + stats = [] + for line in output.splitlines(): + m = _NTPQ_LINE.match(line) + if not m: + continue + tally, remote, refid, stratum, kind, when, poll, reach, delay, offset, jitter = m.groups() + stats.append( + { + "remote": remote, + "referenceid": refid, + "synchronized": tally == "*", + "stratum": int(stratum), + "type": kind, + "when": when, + "hostpoll": int(poll), + "reachability": int(reach), + "delay": float(delay), + "offset": float(offset), + "jitter": float(jitter), + } + ) + return stats diff --git a/napalm_proxmox/system_mixin.py b/napalm_proxmox/system_mixin.py index a1903ba..669f078 100644 --- a/napalm_proxmox/system_mixin.py +++ b/napalm_proxmox/system_mixin.py @@ -28,6 +28,8 @@ from typing import Any from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable +from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats + logger = logging.getLogger(__name__) _JsonDict = dict[str, Any] @@ -197,36 +199,8 @@ class ProxmoxSystemMixin: return servers def get_ntp_stats(self) -> list[_JsonDict]: - """Return NTP synchronisation statistics from chronyc/ntpq output.""" - raw = self._exec_ssh_command( - "chronyc -n tracking 2>/dev/null || ntpq -pn 2>/dev/null || true" - ) - stats: list[_JsonDict] = [] - for line in raw.splitlines(): - line = line.strip() - # ntpq -pn format: *remote refid st t when poll reach delay offset jitter - m = re.match( - r"^([\*\+\-\s])([\d.]+)\s+([\d.]+)\s+(\d+)\s+\S+\s+(\S+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+([-\d.]+)\s+([\d.]+)", - line, - ) - if m: - synced = m.group(1).strip() == "*" - stats.append( - { - "remote": m.group(2), - "referenceid": m.group(3), - "synchronized": synced, - "stratum": int(m.group(4)), - "type": "", - "when": m.group(5), - "hostpoll": int(m.group(6)), - "reachability": int(m.group(7)), - "delay": float(m.group(8)), - "offset": float(m.group(9)), - "jitter": float(m.group(10)), - } - ) - return stats + """Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing.""" + return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND)) # ------------------------------------------------------------------ # # get_snmp_information diff --git a/tests/test_ntp_stats.py b/tests/test_ntp_stats.py new file mode 100644 index 0000000..6f41a28 --- /dev/null +++ b/tests/test_ntp_stats.py @@ -0,0 +1,86 @@ +"""get_ntp_stats on chrony (Proxmox VE's default) and on ntpd (#18).""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest + +# chrony 4.x, ``chronyc -n -c sources`` then ``chronyc -n -c sourcestats``, +# behind the markers the driver's command prints. +CHRONY = """\ +CHRONY_SOURCES +^,*,192.168.1.1,2,6,377,8,-0.000012345,-0.000013000,0.012345678 +^,+,10.0.0.2,3,10,17,301,0.000250000,0.000251000,0.020000000 +^,?,10.0.0.3,0,6,0,-,0.000000000,0.000000000,0.000000000 +CHRONY_SOURCESTATS +192.168.1.1,10,6,320,-0.012,0.150,-0.000001234,0.000045678 +10.0.0.2,6,4,1200,0.003,0.400,0.000200000,0.000500000 +""" + +# ntpd's ``ntpq -pn``: a candidate without tally mark keeps its leading space. +NTPQ = """\ + remote refid st t when poll reach delay offset jitter +============================================================================== +*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123 + 192.168.1.5 10.0.0.1 3 u 40 64 377 2.000 0.100 0.050 +""" + + +def _stats(driver, output): + with patch.object(driver, "_exec_ssh_command", return_value=output): + return driver.get_ntp_stats() + + +class TestChrony: + def test_every_source_is_reported(self, driver): + assert [s["remote"] for s in _stats(driver, CHRONY)] == [ + "192.168.1.1", + "10.0.0.2", + "10.0.0.3", + ] + + def test_the_selected_source_is_synchronized(self, driver): + stats = _stats(driver, CHRONY) + + assert [s["synchronized"] for s in stats] == [True, False, False] + + def test_fields_in_ntpq_units(self, driver): + first = _stats(driver, CHRONY)[0] + + assert first == { + "remote": "192.168.1.1", + "referenceid": "", + "synchronized": True, + "stratum": 2, + "type": "u", + "when": "8", + "hostpoll": 64, + "reachability": 377, + "delay": 0.0, + "offset": pytest.approx(-0.013), + "jitter": pytest.approx(0.045678), + } + + def test_a_source_without_statistics_has_no_jitter(self, driver): + last = _stats(driver, CHRONY)[2] + + assert last["jitter"] == 0.0 + assert last["when"] == "-" + assert last["reachability"] == 0 + + def test_the_command_asks_chrony_first(self, driver): + with patch.object(driver, "_exec_ssh_command", return_value="") as exec_: + driver.get_ntp_stats() + + assert "chronyc -n -c sources" in exec_.call_args[0][0] + assert "ntpq -pn" in exec_.call_args[0][0] + + +class TestNtpd: + def test_a_peer_without_tally_mark_is_kept(self, driver): + stats = _stats(driver, NTPQ) + + assert [s["remote"] for s in stats] == ["192.168.1.1", "192.168.1.5"] + assert [s["synchronized"] for s in stats] == [True, False] + assert stats[1]["stratum"] == 3