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
This commit is contained in:
1 parent
4ee74e4b3d
commit
5195cebfca
4 files changed
+207
-30
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user