all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Jonas Theisen <j.theisen@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH common 04/16] systemd: add helper to list the current NTP sources
Date: Thu, 26 Nov 2026 14:40:01 +0100	[thread overview]
Message-ID: <20261126134128.316681-5-j.theisen@proxmox.com> (raw)
In-Reply-To: <20261126134128.316681-1-j.theisen@proxmox.com>

To be able to provide a detailed state of the local clock
versus the clock sources this commit introduces the helpers
to get an overview.

This includes the currently used sources, their state and
the offset between each source.

For chrony, the machine-readable output of 'chronyc -c sources' is
parsed. It is queried twice, once for the numeric addresses and once
for the names the sources were configured with, so that pool members
can be attributed to their pool. For systemd-timesyncd, which only
ever uses a single server, the output of 'timedatectl timesync-status'
is parsed, as the machine-readable variant does not include the
offset.

Signed-off-by: Jonas Theisen <j.theisen@proxmox.com>
---
 src/PVE/Systemd.pm | 121 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 121 insertions(+)

diff --git a/src/PVE/Systemd.pm b/src/PVE/Systemd.pm
index 35551a3..5d33ea4 100644
--- a/src/PVE/Systemd.pm
+++ b/src/PVE/Systemd.pm
@@ -586,6 +586,127 @@ sub sync_ntp {
     return;
 }
 
+sub is_ntp_sources_supported {
+    my ($service) = @_;
+
+    return 0 if !defined($service);
+    return (grep { $_ eq $service } ('chrony', 'systemd-timesyncd')) ? 1 : 0;
+}
+
+my sub get_chrony_sources {
+    my $read_sources = sub {
+        my ($option) = @_;
+        my $rows = [];
+        run(
+            ['chronyc', '-c', $option, 'sources'],
+            outfunc => sub { push @$rows, [split(/,/, shift)] },
+        );
+        return $rows;
+    };
+
+    # '-n' prints the numeric addresses, '-N' the names the sources were configured with, e.g. the
+    # name of the pool for all of its members
+    my $rows = $read_sources->('-n');
+    my $names = $read_sources->('-N');
+    $names = [] if scalar(@$names) != scalar(@$rows); # the sources changed in between
+
+    my $states = {
+        '*' => 'selected',
+        '+' => 'combined',
+        '-' => 'candidate',
+        'x' => 'falseticker',
+        '~' => 'unusable', # too variable
+        '?' => 'unusable', # e.g. unreachable or not enough measurements yet
+    };
+
+    my $sources = [];
+    for my $i (0 .. $#$rows) {
+        my ($mode, $state, $address, $stratum, $poll, $reach, $last_rx, $offset) = $rows->[$i]->@*;
+        next if !defined($offset);
+
+        my $source = {
+            address => $address,
+            state => $states->{$state} // 'unusable',
+            stratum => int($stratum),
+            poll => 2**$poll, # logarithm to base 2
+            reach => oct($reach), # octal
+            offset => $offset + 0,
+        };
+        # never received samples are reported with the maximum unsigned 32-bit value
+        $source->{'last-rx'} = int($last_rx) if $last_rx =~ m/^\d+$/ && $last_rx < 0xffffffff;
+
+        my $name = $names->[$i]->[2];
+        $source->{name} = $name if defined($name) && $name ne $address;
+
+        push @$sources, $source;
+    }
+
+    return $sources;
+}
+
+# Converts a time span as printed by systemd, e.g. '-1.234ms' or '34min 8s', to seconds.
+my sub parse_systemd_timespan {
+    my ($text) = @_;
+
+    my $factors = { us => 1e-6, ms => 1e-3, s => 1, min => 60, h => 3600, d => 86400 };
+
+    my $sign = $text =~ s/^([+-])// && $1 eq '-' ? -1 : 1;
+    my $seconds;
+    while ($text =~ m/\G\s*(\d+(?:\.\d+)?)(min|ms|us|s|h|d)\b/gc) {
+        $seconds += $1 * $factors->{$2};
+    }
+    return undef if !defined($seconds) || pos($text) != length($text);
+
+    return $sign * $seconds;
+}
+
+# timesyncd only reports the server it currently uses
+my sub get_timesyncd_sources {
+    my $status = {};
+    run(
+        ['timedatectl', 'timesync-status', '--no-pager'],
+        outfunc => sub {
+            my ($line) = @_;
+            $status->{ lc($1) } = $2 if $line =~ m/^\s*([^:]+?):\s*(.*?)\s*$/;
+        },
+    );
+
+    my ($address, $name) = ($status->{server} // '') =~ m/^(\S+)(?:\s+\((.*)\))?$/;
+    return [] if !defined($address) || $address eq 'n/a';
+
+    my $source = { address => $address, state => 'unusable' };
+    $source->{name} = $name if defined($name) && $name ne $address;
+    $source->{stratum} = int($1) if ($status->{stratum} // '') =~ m/^(\d+)$/;
+
+    # e.g. '34min 8s (min: 32s; max 34min 8s)'
+    if (($status->{'poll interval'} // '') =~ m/^(.*?)\s*\(/) {
+        my $poll = parse_systemd_timespan($1);
+        $source->{poll} = $poll if defined($poll);
+    }
+
+    # Only reported once a sample was received. timesyncd reports the offset of the source to the
+    # local clock, while chrony reports it the other way round, i.e. positive if the local clock is
+    # ahead, so flip it to match.
+    my $offset = parse_systemd_timespan($status->{offset} // '');
+    if (defined($offset)) {
+        $source->{offset} = -$offset;
+        $source->{state} = 'selected';
+    }
+
+    return [$source];
+}
+
+# Returns the sources the active time synchronization service currently uses, including the
+# members of pools, see is_ntp_sources_supported() for the supported services.
+sub get_ntp_sources {
+    my $service = get_ntp_service();
+
+    die "listing the sources is not supported for the active time synchronization service\n"
+        if !is_ntp_sources_supported($service);
+
+    return $service eq 'chrony' ? get_chrony_sources() : get_timesyncd_sources();
+}
+
 =head3 notify()
 
 This is a pure Perl reimplementation of systemd's C<sd_notify()> mechanism as defined in
-- 
2.47.3





  parent reply	other threads:[~2026-11-26 13:42 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26 13:39 [PATCH common/manager/widget-toolkit 00/16] partially fix #3809: configure and monitor NTP in the node time panel Jonas Theisen
2026-11-26 13:39 ` [PATCH common 01/16] systemd: add helpers to get and set NTP servers Jonas Theisen
2026-11-26 13:39 ` [PATCH common 02/16] systemd: add helper to query clock synchronization status Jonas Theisen
2026-11-26 13:40 ` [PATCH common 03/16] systemd: add helpers to synchronize the clock immediately Jonas Theisen
2026-11-26 13:40 ` Jonas Theisen [this message]
2026-11-26 13:40 ` [PATCH widget-toolkit 05/16] node: time: do not open the editor for the server time row Jonas Theisen
2026-11-26 13:40 ` [PATCH widget-toolkit 06/16] partially fix #3809: node: time: show and edit NTP servers if supported Jonas Theisen
2026-11-26 13:40 ` [PATCH widget-toolkit 07/16] node: time: show clock synchronization status Jonas Theisen
2026-11-26 13:40 ` [PATCH widget-toolkit 08/16] window: add reusable service log window Jonas Theisen
2026-11-26 13:40 ` [PATCH widget-toolkit 09/16] node: time: add button to open the NTP service log Jonas Theisen
2026-11-26 13:40 ` [PATCH widget-toolkit 10/16] node: time: add button to synchronize the clock immediately Jonas Theisen
2026-11-26 13:40 ` [PATCH widget-toolkit 11/16] node: time: add window listing the current NTP sources Jonas Theisen
2026-11-26 13:40 ` [PATCH manager 12/16] partially fix #3809: api: nodes: time: allow configuring NTP servers Jonas Theisen
2026-11-26 13:40 ` [PATCH manager 13/16] api: nodes: time: report clock synchronization status Jonas Theisen
2026-11-26 13:40 ` [PATCH manager 14/16] ui: node: time: use journal for the NTP service log Jonas Theisen
2026-11-26 13:40 ` [PATCH manager 15/16] api: nodes: time: add endpoint to synchronize the clock immediately Jonas Theisen
2026-11-26 13:40 ` [PATCH manager 16/16] api: nodes: time: add endpoint to list the current NTP sources Jonas Theisen

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126134128.316681-5-j.theisen@proxmox.com \
    --to=j.theisen@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal