"""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