all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH manager 06/09] api: metrics export: fetch remote nodes asynchronously
Date: Mon, 30 Nov 2026 01:58:10 +0100	[thread overview]
Message-ID: <20261130010113.2166775-7-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com>

Cluster-wide GET /cluster/metrics/export runs inside pveproxy's 3
AnyEvent workers and is primarily driven by Proxmox Datacenter Manager
(PDM) scraping /api2/extjs/cluster/metrics/export alongside external
/api2/json/ and pvesh consumers. Previously, synchronous per-node LWP
fetches serialized peer latency across the cluster and blocked the
worker event loop for all unrelated requests.

Add PVE::PullMetricExport with a single export() entry point backed by
PVE::APIClient::AnyEvent and PVE::APIClient::AnyEvent::Pool, and wire
MetricServer::export() to delegate remote fan-out to it. Inside
pveproxy it returns an AsyncResponse via PVE::APIServer::AnyEvent
(dispatched by pve-http-server directly from $res->{data}); outside an
async HTTP request (such as CLI/pvesh) it runs the same bounded fan-out
via an AnyEvent CondVar.

Concurrent peer fetches are capped at 16 per export and 32 worker-wide
across overlapping exports (FIFO-queued without pausing overall
timeouts) with non-persistent HTTPS sockets, SHA-256 leaf fingerprint
pinning, PVEDisableProxy: true, Accept-Encoding: gzip, IPv6 host
bracketing, an overall timeout, and immediate disconnect cancellation.
Non-persistent sockets and the worker-wide peer cap keep open FDs flat
well below AnyEvent::Impl::Perl's select() 1024 limit at the trade-off
of one fresh TLS handshake per peer per scrape. Decoded peer entries
are validated per peer before merging, and finalization errors are
forwarded to reject().

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
 PVE/API2/Cluster/MetricServer.pm | 100 ++++++----
 PVE/Makefile                     |   1 +
 PVE/PullMetricExport.pm          | 324 +++++++++++++++++++++++++++++++
 3 files changed, 385 insertions(+), 40 deletions(-)
 create mode 100644 PVE/PullMetricExport.pm

diff --git a/PVE/API2/Cluster/MetricServer.pm b/PVE/API2/Cluster/MetricServer.pm
index e494c27f9..8dc8db7b0 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -3,7 +3,6 @@ package PVE::API2::Cluster::MetricServer;
 use warnings;
 use strict;
 
-use PVE::APIClient::LWP;
 use PVE::AccessControl;
 use PVE::Cluster;
 use PVE::INotify;
@@ -13,9 +12,15 @@ use PVE::Tools qw(extract_param extract_sensitive_params);
 
 use PVE::ExtMetric;
 use PVE::PullMetric;
+use PVE::PullMetricExport;
 
 use base qw(PVE::RESTHandler);
 
+our $REMOTE_PORT = 8006;
+our $REMOTE_REQUEST_TIMEOUT = 20;
+our $FANOUT_OVERALL_TIMEOUT = 60;
+our $MAX_CONCURRENT_REQUESTS = 16;
+
 __PACKAGE__->register_method({
     name => 'index',
     path => '',
@@ -311,7 +316,11 @@ __PACKAGE__->register_method({
     path => 'export',
     method => 'GET',
     expose_credentials => 1,
-    description => "Retrieve metrics of the cluster.",
+    description => "Retrieve metrics of the cluster. If a cluster-wide fan-out exceeds the"
+        . " overall timeout before completing, the request fails with HTTP 504 on /api2/json"
+        . " (or HTTP 200 with success: 0 and status: 504 on /api2/extjs). Cursor-based"
+        . " scrapers should retry from their previous start-time on error or timeout rather"
+        . " than advancing it.",
     permissions => {
         check => ['perm', '/', ['Sys.Audit']],
     },
@@ -411,6 +420,10 @@ __PACKAGE__->register_method({
 
         my @node_list =
             $param->{'node-list'} ? PVE::Tools::split_list($param->{'node-list'}) : ();
+        if (@node_list) {
+            my %seen;
+            @node_list = grep { !$seen{$_}++ } @node_list;
+        }
 
         my $nodename = PVE::INotify::nodename();
         my $include_local_metrics =
@@ -418,31 +431,29 @@ __PACKAGE__->register_method({
 
         my @metrics;
         if ($include_local_metrics) {
-            @metrics = @{ PVE::PullMetric::get_local_metrics($generations) };
-
+            my $local_metrics = PVE::PullMetric::get_local_metrics($generations);
             if (defined($start)) {
                 @metrics = grep {
-                    $_->{timestamp} > ($start)
-                } @metrics;
+                    $_->{timestamp} > $start
+                } $local_metrics->@*;
+            } else {
+                @metrics = $local_metrics->@*;
             }
         }
 
         # Fan out to cluster members
         # Do NOT remove this check
+        my @targets;
         if (!$local_only || @node_list) {
             my $members = PVE::Cluster::get_members();
 
-            @node_list = keys $members->%* if !@node_list;
+            @node_list = sort keys $members->%* if !@node_list;
 
             if (my @unknown_nodes = grep { !exists($members->{$_}) } @node_list) {
                 die "Requested node-list contains unknown nodes - "
                     . join(', ', @unknown_nodes) . "\n";
             }
 
-            my $rpcenv = PVE::RPCEnvironment::get();
-            my $authuser = $rpcenv->get_user();
-            my $credentials = $rpcenv->get_credentials();
-
             for my $name (@node_list) {
                 if ($name eq $nodename) {
                     # Skip own node, for that one we already have the metrics
@@ -453,46 +464,55 @@ __PACKAGE__->register_method({
                     next;
                 }
 
-                my $status = eval {
+                my $target = eval {
                     my $fingerprint = PVE::Cluster::get_node_fingerprint($name);
+                    die "unable to get certificate fingerprint for node '$name'\n"
+                        if !$fingerprint;
                     my $ip = scalar(PVE::Cluster::remote_node_ip($name));
-
-                    my $conn_args = {
-                        protocol => 'https',
-                        host => $ip,
-                        port => 8006,
-                        ticket => $credentials->{ticket},
-                        api_token => $credentials->{api_token},
-                        timeout => 20,
+                    die "unable to get remote IP address for node '$name'\n"
+                        if !$ip;
+                    return {
+                        name => $name,
+                        ip => $ip,
+                        fingerprint => $fingerprint,
                     };
-
-                    $conn_args->{cached_fingerprints} = { $fingerprint => 1 };
-
-                    my $api_client = PVE::APIClient::LWP->new(%$conn_args);
-
-                    my $params = {
-                        # Do NOT remove 'local-only' - potential for request recursion!
-                        'local-only' => 1,
-                        history => $history,
-                    };
-                    $params->{'start-time'} = $start if defined($start);
-
-                    $api_client->get('/cluster/metrics/export', $params);
                 };
-
-                if ($@) {
-                    syslog('warning', "could not fetch metrics from $name: $@");
+                if (my $err = $@) {
+                    syslog('warning', "could not fetch metrics from $name: $err");
                 } else {
-                    push @metrics, $status->{data}->@*;
+                    push @targets, $target;
                 }
             }
         }
 
-        my @sorted = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+        if (!@targets) {
+            # In-place sort avoids allocating a second copy of large metric arrays.
+            @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+            return {
+                data => \@metrics,
+            };
+        }
 
-        return {
-            data => \@sorted,
+        my $rpcenv = PVE::RPCEnvironment::get();
+        my $credentials = $rpcenv->get_credentials() // {};
+
+        my $remote_params = {
+            # Do NOT remove 'local-only' - potential for request recursion!
+            'local-only' => 1,
+            history => $history,
         };
+        $remote_params->{'start-time'} = $start if defined($start);
+
+        return PVE::PullMetricExport::export(
+            targets => \@targets,
+            params => $remote_params,
+            credentials => $credentials,
+            metrics => \@metrics,
+            port => $REMOTE_PORT,
+            request_timeout => $REMOTE_REQUEST_TIMEOUT,
+            overall_timeout => $FANOUT_OVERALL_TIMEOUT,
+            max_concurrent => $MAX_CONCURRENT_REQUESTS,
+        );
     },
 });
 
diff --git a/PVE/Makefile b/PVE/Makefile
index f7691fe7e..81a42f8d0 100644
--- a/PVE/Makefile
+++ b/PVE/Makefile
@@ -15,6 +15,7 @@ PERLSOURCE = 			\
 	MultipathNotification.pm	\
 	NodeConfig.pm		\
 	PullMetric.pm		\
+	PullMetricExport.pm	\
 	Report.pm		\
 	VZDump.pm
 
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
new file mode 100644
index 000000000..f657a1c34
--- /dev/null
+++ b/PVE/PullMetricExport.pm
@@ -0,0 +1,324 @@
+package PVE::PullMetricExport;
+
+# Asynchronous cluster-wide pull-metric fan-out for GET /cluster/metrics/export.
+# export() fetches remote nodes concurrently (capped via PVE::APIClient::AnyEvent::Pool),
+# returning a deferred PVE::APIServer::AnyEvent::AsyncResponse inside pveproxy or blocking on an
+# AnyEvent CondVar for CLI/pvesh callers.
+
+use v5.36;
+
+use AnyEvent;
+
+use PVE::APIClient::AnyEvent;
+use PVE::APIClient::AnyEvent::Pool;
+use PVE::APIServer::AnyEvent;
+use PVE::Exception;
+use PVE::SafeSyslog ();
+
+our $MAX_WORKER_CONCURRENT_PEERS = 32;
+
+my $WORKER_ACTIVE_PEERS = 0;
+my @WORKER_WAIT_QUEUE;
+my $WORKER_DRAINING = 0;
+my $WORKER_DRAIN_SCHEDULED = 0;
+
+my sub log_peer_error($name, $err) {
+    PVE::SafeSyslog::syslog('warning', "could not fetch metrics from $name: $err");
+}
+
+my sub worker_peer_limit() {
+    my $limit = int($MAX_WORKER_CONCURRENT_PEERS // 32);
+    return $limit < 1 ? 1 : $limit;
+}
+
+my sub drain_worker_waiters() {
+    return if $WORKER_DRAINING;
+    $WORKER_DRAINING = 1;
+    eval {
+        while (@WORKER_WAIT_QUEUE && $WORKER_ACTIVE_PEERS < worker_peer_limit()) {
+            my $waiter = shift @WORKER_WAIT_QUEUE;
+            next if $waiter->{cancelled};
+            $WORKER_ACTIVE_PEERS++;
+            $waiter->{granted} = 1;
+            my $start_cb = delete $waiter->{start};
+            $start_cb->();
+        }
+    };
+    my $err = $@;
+    $WORKER_DRAINING = 0;
+    die $err if $err;
+}
+
+my sub schedule_drain_worker_waiters() {
+    return if $WORKER_DRAIN_SCHEDULED || !@WORKER_WAIT_QUEUE;
+    $WORKER_DRAIN_SCHEDULED = 1;
+    AE::postpone(sub {
+        $WORKER_DRAIN_SCHEDULED = 0;
+        drain_worker_waiters();
+    });
+}
+
+my sub start_metric_fanout(%opts) {
+    my @items = map { { id => $_->{name}, %$_ } } @{ $opts{targets} // [] };
+    my $credentials = $opts{credentials} // {};
+    my $port = $opts{port} // 8006;
+    my $request_timeout = $opts{request_timeout} // 20;
+    my $overall_timeout = $opts{overall_timeout} // 60;
+    my $max_concurrent = int($opts{max_concurrent} // 16);
+    $max_concurrent = 1 if $max_concurrent < 1;
+
+    my ($params, $on_peer, $on_done) = @opts{ 'params', 'on_peer', 'on_done' };
+
+    my %auth_args;
+    if (defined($credentials->{api_token})) {
+        $auth_args{api_token} = $credentials->{api_token};
+    } elsif (defined($credentials->{ticket})) {
+        $auth_args{ticket} = $credentials->{ticket};
+    }
+
+    return PVE::APIClient::AnyEvent::Pool::start(
+        items => \@items,
+        max_concurrent => $max_concurrent,
+        overall_timeout => $overall_timeout,
+        can_dispatch => $opts{can_dispatch},
+        on_start_error => sub {
+            my ($name, $err) = @_;
+            log_peer_error($name, $err);
+        },
+        start_item => sub {
+            my ($target, $finish_item) = @_;
+
+            my ($name, $ip, $fingerprint) = $target->@{qw(name ip fingerprint)};
+            my $released = 0;
+            my $req_cancel;
+            my $waiter;
+
+            my $release_slot = sub {
+                my ($defer_drain) = @_;
+                return if $released;
+                $released = 1;
+                $WORKER_ACTIVE_PEERS-- if $WORKER_ACTIVE_PEERS > 0;
+                if ($defer_drain) {
+                    schedule_drain_worker_waiters();
+                } else {
+                    drain_worker_waiters();
+                }
+            };
+
+            my $start_request = sub {
+                my $done_called = 0;
+                my $finish_with_release = sub {
+                    return if $done_called;
+                    $done_called = 1;
+                    undef $req_cancel;
+                    $release_slot->();
+                    $finish_item->();
+                };
+
+                my $client = eval {
+                    PVE::APIClient::AnyEvent->new(
+                        protocol => 'https',
+                        host => $ip,
+                        port => $port,
+                        timeout => $request_timeout,
+                        cached_fingerprints => { $fingerprint => 1 },
+                        headers => {
+                            'Accept-Encoding' => 'gzip',
+                            PVEDisableProxy => 'true',
+                        },
+                        %auth_args,
+                    );
+                };
+                if (my $err = $@) {
+                    log_peer_error($name, $err);
+                    $finish_with_release->();
+                    return;
+                }
+
+                my $cancel = eval {
+                    $client->request_raw(
+                        'GET',
+                        '/cluster/metrics/export',
+                        $params,
+                        on_response => sub {
+                            my ($status, $body_ref, $hdr) = @_;
+
+                            my $cb_err;
+                            if ($status != 200) {
+                                my $reason = $hdr->{Reason} // 'unknown error';
+                                log_peer_error($name, "$status $reason");
+                            } elsif ($on_peer) {
+                                my $is_gzip =
+                                    (($hdr->{'content-encoding'} // '') =~ /\bgzip\b/i) ? 1 : 0;
+                                eval { $on_peer->($name, $body_ref, $is_gzip); };
+                                $cb_err = $@;
+                            }
+                            $finish_with_release->();
+                            die $cb_err if $cb_err;
+                        },
+                        on_error => sub {
+                            my ($err) = @_;
+                            log_peer_error($name, $err);
+                            $finish_with_release->();
+                        },
+                    );
+                };
+                if (my $err = $@) {
+                    log_peer_error($name, $err);
+                    $finish_with_release->();
+                    return;
+                }
+
+                if ($waiter->{cancelled}) {
+                    $cancel->() if !$done_called && ref($cancel) eq 'CODE';
+                } elsif (!$done_called) {
+                    $req_cancel = $cancel;
+                }
+            };
+
+            $waiter = {
+                granted => 0,
+                cancelled => 0,
+                start => $start_request,
+            };
+
+            if ($WORKER_ACTIVE_PEERS < worker_peer_limit()) {
+                $WORKER_ACTIVE_PEERS++;
+                $waiter->{granted} = 1;
+                delete $waiter->{start};
+                $start_request->();
+            } else {
+                push @WORKER_WAIT_QUEUE, $waiter;
+            }
+
+            return sub {
+                return if $waiter->{cancelled};
+                $waiter->{cancelled} = 1;
+                delete $waiter->{start};
+                if (!$waiter->{granted}) {
+                    @WORKER_WAIT_QUEUE = grep { $_ != $waiter } @WORKER_WAIT_QUEUE;
+                    return;
+                }
+                if (my $cancel = $req_cancel) {
+                    undef $req_cancel;
+                    $cancel->();
+                }
+                # Defer draining queued waiters until all items in a cancelling or timing-out pool
+                # have run their cancel callbacks so another waiter from the same pool is not started.
+                $release_slot->(1);
+            };
+        },
+        on_done => sub {
+            my ($timed_out, $pending_ids) = @_;
+
+            if ($timed_out) {
+                for my $peer_name (@$pending_ids) {
+                    log_peer_error($peer_name, "overall fan-out timeout (${overall_timeout}s)");
+                }
+            }
+            $on_done->($timed_out, $overall_timeout) if $on_done;
+        },
+    );
+}
+
+my sub decode_peer_metrics($body_ref, $is_gzip = 0) {
+    my $decoded = PVE::APIClient::AnyEvent::decode_json_body($body_ref, $is_gzip);
+    if (
+        ref($decoded) ne 'HASH'
+        || ref($decoded->{data}) ne 'HASH'
+        || ref($decoded->{data}->{data}) ne 'ARRAY'
+    ) {
+        die "unexpected response format\n";
+    }
+
+    my $items = $decoded->{data}->{data};
+    for my $item (@$items) {
+        if (
+            ref($item) ne 'HASH'
+            || !defined($item->{timestamp})
+            || ref($item->{timestamp})
+            || $item->{timestamp} !~ /^-?(?:0|[1-9][0-9]*)$/
+        ) {
+            die "unexpected metric entry format\n";
+        }
+    }
+
+    return $items;
+}
+
+sub build_buffered_fanout(%opts) {
+    my ($metrics, $finalize) = @opts{ 'metrics', 'finalize' };
+
+    return sub {
+        my ($resolve, $reject) = @_;
+
+        my $state = { done => 0 };
+        $state->{fanout} = start_metric_fanout(
+            %opts,
+            on_peer => sub {
+                my ($name, $body_ref, $is_gzip) = @_;
+                eval {
+                    my $peer_metrics = decode_peer_metrics($body_ref, $is_gzip);
+                    push @$metrics, @$peer_metrics;
+                };
+                log_peer_error($name, $@) if $@;
+            },
+            on_done => sub($timed_out, $timeout) {
+                return if $state->{done};
+                $state->{done} = 1;
+                delete $state->{fanout};
+                if ($timed_out) {
+                    @$metrics = ();
+                    $reject->(
+                        PVE::Exception->new(
+                            "cluster metric fan-out timed out after ${timeout}s\n",
+                            code => 504,
+                        ),
+                    );
+                    return;
+                }
+                my $res = eval { $finalize->() };
+                if (my $err = $@) {
+                    $reject->($err);
+                    return;
+                }
+                $resolve->($res);
+            },
+        );
+
+        return sub {
+            return if $state->{done};
+            $state->{done} = 1;
+            if (my $fanout = delete $state->{fanout}) {
+                $fanout->{cancel}->();
+            }
+            @$metrics = ();
+        };
+    };
+}
+
+sub export(%opts) {
+    my $metrics = $opts{metrics} // [];
+
+    my $finalize = sub {
+        # In-place sort avoids allocating a second copy of large metric arrays.
+        @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+        return {
+            data => $metrics,
+        };
+    };
+
+    if (PVE::APIServer::AnyEvent::async_supported()) {
+        return PVE::APIServer::AnyEvent::async_response(
+            build_buffered_fanout(%opts, metrics => $metrics, finalize => $finalize),
+        );
+    }
+
+    my $cv = AnyEvent->condvar;
+    build_buffered_fanout(%opts, metrics => $metrics, finalize => $finalize)->(
+        sub { $cv->send($_[0]) }, sub { $cv->croak($_[0]) },
+    );
+    return $cv->recv;
+}
+
+1;
-- 
2.47.3





  parent reply	other threads:[~2026-11-30  1:02 UTC|newest]

Thread overview: 12+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-30  0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
2026-11-30  0:58 ` [PATCH http-server 01/09] response: support deferred async API2 responses Thomas Lamprecht
2026-11-30  0:58 ` [PATCH http-server 02/09] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
2026-11-30  0:58 ` [PATCH http-server 03/09] response: support incremental streaming API2 responses Thomas Lamprecht
2026-11-30  0:58 ` [PATCH apiclient 04/09] add non-blocking AnyEvent API client Thomas Lamprecht
2026-11-30  0:58 ` [PATCH apiclient 05/09] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
2026-11-30  0:58 ` Thomas Lamprecht [this message]
2026-11-30  0:58 ` [PATCH manager 07/09] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
2026-11-30  0:58 ` [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-11-30  0:58 ` [PATCH manager 09/09] test: add pull metric export test suite Thomas Lamprecht
2026-12-01 10:13 ` [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Jonas Theisen
2026-12-01 10:22 ` superseded: " Thomas Lamprecht

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=20261130010113.2166775-7-t.lamprecht@proxmox.com \
    --to=t.lamprecht@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