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 v2 6/9] api: metrics export: fetch remote nodes asynchronously
Date: Tue,  1 Dec 2026 11:19:01 +0100	[thread overview]
Message-ID: <20261201101913.1885484-7-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com>

Cluster-wide GET /cluster/metrics/export runs inside the pveproxy
worker handling the request 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.

Each export can fetch up to 16 peers at once; overlapping exports share
32 slots per worker via Pool's shared limiter and a 128 MiB dispatch
admission threshold on completed retained wire bodies (not a hard RSS
bound, with the oldest all-peers export exempt so overlapping scrapes
cannot deadlock). Waiting for a worker slot counts toward the 60-second
fan-out timeout. The timer pauses when downstream backpressure prevents
a queued request from starting. Peer calls use non-persistent HTTPS
sockets, SHA-256 leaf fingerprint pinning, PVEDisableProxy: true,
Accept-Encoding: gzip, IPv6 host bracketing, a 20s per-peer timeout,
and immediate disconnect cancellation. Add an opt-in fail-on-error
parameter (default 0, omitted from remote local-only=1 calls) so
cursor-based scrapers can require all online target nodes to succeed
while preserving best-effort partial results by default. A strict peer
timeout or overall fan-out timeout produces API status 504; other
strict peer fetch or read failures produce 502. /api2/json uses that
HTTP status, while /api2/extjs returns HTTP 200
with success: 0 and the error code in status. Decoded peer entries
enforce signed 64-bit JSON integer timestamps before merging, and
finalization errors are forwarded to reject().

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---

Changes in v2:
- Enforce the worker-wide 32-peer cap through Pool's shared
  create_limiter() instead of separate manual waiter queues so busy-
  worker waits count toward the 60s overall timeout.
- Add a deadlock-free 128 MiB worker-wide dispatch admission threshold
  on completed retained peer wire bodies across overlapping exports
  (exempting the oldest all-peers export while holding newer exports in
  Pool's queue).
- Stop initial Pool::start() dispatch immediately if a strict peer
  failure marks the export done synchronously before start() returns.
- Add opt-in fail-on-error=1 (default 0, never forwarded to local-only=1
  peers) so scrapers can fail on online peer fetch/read errors, import
  PVE::Exception explicitly, and map only actual timeouts (504 or
  timed-out reason) to API status 504 and other peer failures (including
  non-timeout 596 TLS errors) to 502.
- Refine fail-on-error parameter and endpoint descriptions.

 PVE/API2/Cluster/MetricServer.pm | 119 ++++++---
 PVE/Makefile                     |   1 +
 PVE/PullMetricExport.pm          | 426 +++++++++++++++++++++++++++++++
 3 files changed, 506 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..14f065fd6 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -3,9 +3,9 @@ package PVE::API2::Cluster::MetricServer;
 use warnings;
 use strict;
 
-use PVE::APIClient::LWP;
 use PVE::AccessControl;
 use PVE::Cluster;
+use PVE::Exception ();
 use PVE::INotify;
 use PVE::RPCEnvironment;
 use PVE::SafeSyslog;
@@ -13,9 +13,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 +317,14 @@ __PACKAGE__->register_method({
     path => 'export',
     method => 'GET',
     expose_credentials => 1,
-    description => "Retrieve metrics of the cluster.",
+    description =>
+        "Retrieve metrics of the cluster. By default, remote peer failures are logged"
+        . " and skipped (best-effort across reachable nodes); set fail-on-error=1 to fail the"
+        . " export if any online target node cannot be fetched or fails validation. If a"
+        . " cluster-wide fan-out exceeds its overall timeout (or fails with fail-on-error=1)"
+        . " before response headers are sent, /api2/json returns HTTP 504/502 and /api2/extjs"
+        . " returns HTTP 200 with success: 0 and status: 504/502. Cursor-based scrapers should"
+        . " retry with the same start-time on error or timeout rather than advancing it.",
     permissions => {
         check => ['perm', '/', ['Sys.Audit']],
     },
@@ -343,6 +356,13 @@ __PACKAGE__->register_method({
                 optional => 1,
                 default => 0,
             },
+            'fail-on-error' => {
+                type => 'boolean',
+                description => 'Fail instead of skipping an online target that cannot be fetched'
+                    . ' or whose metric response cannot be read.',
+                optional => 1,
+                default => 0,
+            },
         },
     },
     returns => {
@@ -392,6 +412,7 @@ __PACKAGE__->register_method({
         my $local_only = $param->{'local-only'} // 0;
         my $start = $param->{'start-time'};
         my $history = $param->{'history'} // 0;
+        my $fail_on_error = $param->{'fail-on-error'} // 0;
 
         my $now = time();
 
@@ -411,6 +432,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 +443,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 +476,62 @@ __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");
+                    if ($fail_on_error) {
+                        die PVE::Exception->new(
+                            "could not fetch metrics from $name: $err",
+                            code => 502,
+                        );
+                    }
                 } 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,
+            fail_on_error => $fail_on_error,
+            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..867909977
--- /dev/null
+++ b/PVE/PullMetricExport.pm
@@ -0,0 +1,426 @@
+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 B;
+
+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;
+# Dispatch admission threshold on completed retained wire bodies across overlapping exports (not a
+# hard worker RSS bound: in-flight responses are charged on completion, buffered mode retains
+# decoded hashes, and the oldest all-peers export may exceed it to avoid self-deadlock).
+our $MAX_WORKER_RETAINED_BYTES = 128 * 1024 * 1024;
+
+my $WORKER_RETAINED_BYTES = 0;
+my @WORKER_ALL_PEERS_HOLDERS;
+my @WORKER_BYTE_WAITERS;
+my $WORKER_BYTE_WAKE_SCHEDULED = 0;
+
+my sub log_peer_error($name, $err) {
+    PVE::SafeSyslog::syslog('warning', "could not fetch metrics from $name: $err");
+}
+
+my sub peer_error_code($err, $status = undef) {
+    return 504 if defined($status) && $status == 504;
+    return 504 if defined($err) && "$err" =~ /timed?\s*out/i;
+    return 502;
+}
+
+my sub worker_peer_limit() {
+    my $limit = int($MAX_WORKER_CONCURRENT_PEERS // 32);
+    return $limit < 1 ? 1 : $limit;
+}
+
+my sub worker_byte_limit() {
+    my $limit = int($MAX_WORKER_RETAINED_BYTES // (128 * 1024 * 1024));
+    return $limit < 1 ? 1 : $limit;
+}
+
+my sub wake_byte_waiters() {
+    my $remaining = scalar(@WORKER_BYTE_WAITERS);
+    while ($remaining-- > 0 && @WORKER_BYTE_WAITERS) {
+        my $state = shift @WORKER_BYTE_WAITERS;
+        $state->{byte_wait_queued} = 0;
+        next if $state->{done};
+        if (my $fanout = $state->{fanout}) {
+            $fanout->{dispatch}->();
+        }
+    }
+}
+
+my sub schedule_wake_byte_waiters() {
+    return if $WORKER_BYTE_WAKE_SCHEDULED || !@WORKER_BYTE_WAITERS;
+    $WORKER_BYTE_WAKE_SCHEDULED = 1;
+    AE::postpone(sub {
+        $WORKER_BYTE_WAKE_SCHEDULED = 0;
+        wake_byte_waiters();
+    });
+}
+
+my sub retain_peer_bytes($state, $bytes) {
+    return if !$bytes || $bytes <= 0;
+    $state->{retained_bytes} += $bytes;
+    $WORKER_RETAINED_BYTES += $bytes;
+    if ($state->{needs_all_peers} && !$state->{all_peers_holder}) {
+        $state->{all_peers_holder} = 1;
+        push @WORKER_ALL_PEERS_HOLDERS, $state;
+    }
+}
+
+my sub release_peer_bytes($state, $bytes) {
+    return if !$bytes || $bytes <= 0;
+    my $held = $state->{retained_bytes} // 0;
+    my $drop = $bytes > $held ? $held : $bytes;
+    return if $drop <= 0;
+    $state->{retained_bytes} -= $drop;
+    $WORKER_RETAINED_BYTES -= $drop;
+    $WORKER_RETAINED_BYTES = 0 if $WORKER_RETAINED_BYTES < 0;
+    if ($state->{retained_bytes} == 0 && $state->{all_peers_holder}) {
+        $state->{all_peers_holder} = 0;
+        @WORKER_ALL_PEERS_HOLDERS = grep { $_ != $state } @WORKER_ALL_PEERS_HOLDERS;
+    }
+    schedule_wake_byte_waiters();
+}
+
+my sub release_all_peer_bytes($state) {
+    if ($state->{byte_wait_queued}) {
+        $state->{byte_wait_queued} = 0;
+        @WORKER_BYTE_WAITERS = grep { $_ != $state } @WORKER_BYTE_WAITERS;
+    }
+    if ($state->{all_peers_holder}) {
+        $state->{all_peers_holder} = 0;
+        @WORKER_ALL_PEERS_HOLDERS = grep { $_ != $state } @WORKER_ALL_PEERS_HOLDERS;
+    }
+    if (my $held = delete $state->{retained_bytes}) {
+        $WORKER_RETAINED_BYTES -= $held;
+        $WORKER_RETAINED_BYTES = 0 if $WORKER_RETAINED_BYTES < 0;
+    }
+    schedule_wake_byte_waiters();
+}
+
+my sub can_admit_bytes($state) {
+    return 1 if $WORKER_RETAINED_BYTES < worker_byte_limit();
+    # Allow only the oldest active export that must collect all peers before draining (buffered or
+    # sorted k-way merge) to finish fetching so overlapping exports cannot deadlock each other.
+    if (
+        $state->{needs_all_peers}
+        && @WORKER_ALL_PEERS_HOLDERS
+        && $WORKER_ALL_PEERS_HOLDERS[0] == $state
+    ) {
+        return 1;
+    }
+    if (!$state->{byte_wait_queued} && !$state->{done}) {
+        $state->{byte_wait_queued} = 1;
+        push @WORKER_BYTE_WAITERS, $state;
+    }
+    return 0;
+}
+
+my $WORKER_LIMITER = PVE::APIClient::AnyEvent::Pool::create_limiter(\&worker_peer_limit);
+
+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_peer_error, $on_done, $is_done, $byte_state) =
+        @opts{ 'params', 'on_peer', 'on_peer_error', 'on_done', 'is_done', 'byte_state' };
+
+    my %auth_args;
+    if (defined($credentials->{api_token})) {
+        $auth_args{api_token} = $credentials->{api_token};
+    } elsif (defined($credentials->{ticket})) {
+        $auth_args{ticket} = $credentials->{ticket};
+    }
+
+    my $can_admit;
+    if ($is_done || $byte_state) {
+        $can_admit = sub {
+            return 0 if $is_done && $is_done->();
+            return $byte_state ? can_admit_bytes($byte_state) : 1;
+        };
+    }
+
+    return PVE::APIClient::AnyEvent::Pool::start(
+        items => \@items,
+        max_concurrent => $max_concurrent,
+        overall_timeout => $overall_timeout,
+        can_dispatch => $opts{can_dispatch},
+        can_admit => $can_admit,
+        limiter => $WORKER_LIMITER,
+        on_start_error => sub {
+            my ($name, $err) = @_;
+            log_peer_error($name, $err);
+            $on_peer_error->($name, $err, peer_error_code($err)) if $on_peer_error;
+        },
+        start_item => sub {
+            my ($target, $finish_item) = @_;
+
+            my ($name, $ip, $fingerprint) = $target->@{qw(name ip fingerprint)};
+            my $done_called = 0;
+            my $cancelled = 0;
+            my $req_cancel;
+
+            my $finish_req = sub {
+                return if $done_called;
+                $done_called = 1;
+                undef $req_cancel;
+                $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);
+                $on_peer_error->($name, $err, peer_error_code($err)) if $on_peer_error;
+                $finish_req->();
+                return undef;
+            }
+
+            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';
+                            my $msg = "$status $reason\n";
+                            log_peer_error($name, $msg);
+                            eval {
+                                $on_peer_error->($name, $msg, peer_error_code($msg, $status))
+                                    if $on_peer_error;
+                            };
+                            $cb_err = $@;
+                        } 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_req->();
+                        die $cb_err if $cb_err;
+                    },
+                    on_error => sub {
+                        my ($err) = @_;
+                        log_peer_error($name, $err);
+                        my $cb_err;
+                        eval {
+                            $on_peer_error->($name, $err, peer_error_code($err))
+                                if $on_peer_error;
+                        };
+                        $cb_err = $@;
+                        $finish_req->();
+                        die $cb_err if $cb_err;
+                    },
+                );
+            };
+            if (my $err = $@) {
+                log_peer_error($name, $err);
+                $on_peer_error->($name, $err, peer_error_code($err)) if $on_peer_error;
+                $finish_req->();
+                return undef;
+            }
+
+            if ($cancelled) {
+                $cancel->() if !$done_called && ref($cancel) eq 'CODE';
+            } elsif (!$done_called) {
+                $req_cancel = $cancel;
+            }
+
+            return sub {
+                return if $cancelled;
+                $cancelled = 1;
+                if (my $c = $req_cancel) {
+                    undef $req_cancel;
+                    $c->();
+                }
+            };
+        },
+        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 validate_integer_timestamp($val) {
+    return undef if !defined($val) || ref($val);
+    my $flags = B::svref_2object(\$val)->FLAGS;
+    return undef if ($flags & (B::SVf_POK | B::SVf_NOK | B::SVf_IVisUV)) || !($flags & B::SVf_IOK);
+    return $val + 0;
+}
+
+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') {
+            die "unexpected metric entry format\n";
+        }
+        my $ts = validate_integer_timestamp($item->{timestamp});
+        die "unexpected metric entry format\n" if !defined($ts);
+        $item->{timestamp} = $ts;
+    }
+
+    return $items;
+}
+
+sub build_buffered_fanout(%opts) {
+    my ($metrics, $finalize, $fail_on_error) = @opts{ 'metrics', 'finalize', 'fail_on_error' };
+    $fail_on_error = $fail_on_error ? 1 : 0;
+
+    return sub {
+        my ($resolve, $reject) = @_;
+
+        my $state = { done => 0, needs_all_peers => 1, retained_bytes => 0 };
+        my $fail_export = sub {
+            my ($name, $err, $code) = @_;
+            return if $state->{done};
+            $state->{done} = 1;
+            if (my $fanout = delete $state->{fanout}) {
+                $fanout->{cancel}->();
+            }
+            release_all_peer_bytes($state);
+            @$metrics = ();
+            $reject->(
+                PVE::Exception->new(
+                    "could not fetch metrics from $name: $err", code => $code,
+                ),
+            );
+        };
+
+        my $fanout = start_metric_fanout(
+            %opts,
+            is_done => sub { return $state->{done}; },
+            byte_state => $state,
+            on_peer => sub {
+                my ($name, $body_ref, $is_gzip) = @_;
+                return if $state->{done};
+                my $raw_len = length($$body_ref // '');
+                eval {
+                    my $peer_metrics = decode_peer_metrics($body_ref, $is_gzip);
+                    push @$metrics, @$peer_metrics;
+                    retain_peer_bytes($state, $raw_len);
+                };
+                if (my $err = $@) {
+                    log_peer_error($name, $err);
+                    $fail_export->($name, $err, 502) if $fail_on_error;
+                }
+            },
+            on_peer_error => $fail_on_error
+            ? sub {
+                my ($name, $err, $code) = @_;
+                $fail_export->($name, $err, $code);
+            }
+            : undef,
+            on_done => sub($timed_out, $timeout) {
+                return if $state->{done};
+                $state->{done} = 1;
+                delete $state->{fanout};
+                release_all_peer_bytes($state);
+                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);
+            },
+        );
+        if ($state->{done}) {
+            $fanout->{cancel}->();
+        } else {
+            $state->{fanout} = $fanout;
+        }
+
+        return sub {
+            return if $state->{done};
+            $state->{done} = 1;
+            if (my $fanout = delete $state->{fanout}) {
+                $fanout->{cancel}->();
+            }
+            release_all_peer_bytes($state);
+            @$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-12-01 10:21 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client Thomas Lamprecht
2026-12-01 10:19 ` [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
2026-12-01 10:19 ` Thomas Lamprecht [this message]
2026-12-01 10:19 ` [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 9/9] test: add pull metric export test suite 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=20261201101913.1885484-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