From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option
Date: Mon, 30 Nov 2026 01:58:12 +0100 [thread overview]
Message-ID: <20261130010113.2166775-9-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com>
The default k-way merge preserves global cross-node timestamp ordering
for existing clients with zero migration effort, but must wait for all
peers before TTFB and hold all compressed peer bodies until the final
peer arrives.
Add an optional boolean `unsorted` parameter to GET
/cluster/metrics/export and build_passthrough_stream() to
PVE::PullMetricExport. When unsorted=1 is requested, the local node
slice is flushed immediately for minimal TTFB without sorting and each
remote peer is drained incrementally through
PVE::PullMetricExport::Reader as it arrives, pausing queued peer
dispatch (and suspending the pool's overall timeout budget) via
can_dispatch whenever the downstream socket is backpressured. Overall
fan-out timeouts and late mid-stream Reader errors abort the
in-progress stream (TCP RST) so consumers retry rather than advancing
their cursor past uncontacted or truncated nodes.
Carrying a second streaming state machine and can_dispatch backpressure
gating adds complexity, traded for keeping backwards-compatible global
sorting by default while cutting TTFB across all tested scenarios
(25x100 latest: 118 -> 2.3 ms, ~51x; 25x100 hist10: 129 -> 6.7 ms,
~19x; 100x100 latest: 401 -> 2.8 ms, ~143x; 100x1000: 360 -> 7.5 ms,
~48x), lowering peak RAM by ~10%, and reducing total time by ~10-25%
for opt-in clients that sort before RRD ingestion (older PVE nodes
reject the unknown unsorted parameter with HTTP 400; cluster fan-out
always forwards local-only=1 without unsorted to peers).
Measured on the same single-worker mock harness (25 ms/peer, 16-peer
cap, 34 FDs; scenarios are nodes x guests with latest or 10 history
generations, and /ping HOL is head-of-line delay for a concurrent
/ping request reported as max or median across samples):
Scenario | Mode | Total | TTFB | VmHWM | /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | K-way stream | 188ms | 118ms | 83 MiB | 7.9 ms (max)
(25,475 metrics) | Pass-through | 154ms | 2.3ms | 81 MiB | 6.6 ms (max)
25x100 hist10 | K-way stream | 827ms | 129ms | 98 MiB | 5.3 ms (max)
(254,750 metrics) | Pass-through | 744ms | 6.7ms | 92 MiB | 5.3 ms (med)
100x100 latest | K-way stream | 644ms | 401ms | 90 MiB | 13.3 ms (max)
(101,900 metrics) | Pass-through | 463ms | 2.8ms | 81 MiB | 13.7 ms (max)
100x1000 | K-way stream | 2969ms | 360ms | 103 MiB | 10.5 ms (max)
(1,001,900 metrics) | Pass-through | 2790ms | 7.5ms | 93 MiB | 5.5 ms (med)
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
PVE/API2/Cluster/MetricServer.pm | 19 ++-
PVE/PullMetricExport.pm | 213 +++++++++++++++++++++++++++++--
2 files changed, 218 insertions(+), 14 deletions(-)
diff --git a/PVE/API2/Cluster/MetricServer.pm b/PVE/API2/Cluster/MetricServer.pm
index 8dc8db7b0..f1b6e62b6 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -352,6 +352,17 @@ __PACKAGE__->register_method({
optional => 1,
default => 0,
},
+ 'unsorted' => {
+ type => 'boolean',
+ description => 'Do not sort metrics by timestamp. Skips cross-node sorting and'
+ . ' permits incremental streaming on supported HTTP endpoints (buffered and'
+ . ' CLI paths still return the full response once complete). When streaming'
+ . ' has already started, a fan-out timeout terminates the response'
+ . ' incompletely instead of returning HTTP 504. Cluster fan-out forwards'
+ . ' local-only=1 without unsorted to remote nodes.',
+ optional => 1,
+ default => 0,
+ },
},
},
returns => {
@@ -360,8 +371,8 @@ __PACKAGE__->register_method({
properties => {
data => {
type => 'array',
- description =>
- 'Array of system metrics. Metrics are sorted by their timestamp.',
+ description => 'Array of system metrics. Sorted by timestamp by default'
+ . ' (unsorted=0), or in arrival order when unsorted is set.',
items => {
type => 'object',
additionalProperties => 0,
@@ -401,6 +412,7 @@ __PACKAGE__->register_method({
my $local_only = $param->{'local-only'} // 0;
my $start = $param->{'start-time'};
my $history = $param->{'history'} // 0;
+ my $unsorted = $param->{'unsorted'} // 0;
my $now = time();
@@ -487,7 +499,7 @@ __PACKAGE__->register_method({
if (!@targets) {
# In-place sort avoids allocating a second copy of large metric arrays.
- @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+ @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics if !$unsorted;
return {
data => \@metrics,
};
@@ -508,6 +520,7 @@ __PACKAGE__->register_method({
params => $remote_params,
credentials => $credentials,
metrics => \@metrics,
+ unsorted => $unsorted,
port => $REMOTE_PORT,
request_timeout => $REMOTE_REQUEST_TIMEOUT,
overall_timeout => $FANOUT_OVERALL_TIMEOUT,
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
index 9464246c2..869bd6f99 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,10 +1,12 @@
package PVE::PullMetricExport;
# Asynchronous cluster-wide pull-metric fan-out and streaming export for GET
-# /cluster/metrics/export. export() selects between two paths:
-# - Incremental k-way merge stream (default when AsyncStream is supported): keeps remote peer
-# responses gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then
-# merges local and remote streams in global timestamp order in cooperative 256 KiB slices.
+# /cluster/metrics/export. export() selects between three paths:
+# - Default k-way merge stream (when AsyncStream is supported): keeps remote peer bodies
+# gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then merges local
+# and remote streams in global timestamp order in cooperative 256 KiB slices.
+# - Opt-in unsorted=1 pass-through stream: flushes local metrics immediately for minimal TTFB and
+# drains remote peers as they arrive with can_dispatch backpressure gating.
# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers).
use v5.36;
@@ -590,26 +592,215 @@ sub build_kway_merge_stream(%opts) {
};
}
+my sub passthrough_drain_reader($state, $max_bytes) {
+ my $out = '';
+ my $entry = $state->{active_reader};
+ return $out if !$entry;
+
+ my $reader = $entry->{reader};
+ my $exhausted = 0;
+
+ eval {
+ while (length($out) < $max_bytes) {
+ $out .= ',' if !$state->{first_item};
+ $state->{first_item} = 0;
+ $out .= $entry->{obj};
+
+ my $obj = $reader->next();
+ if (!defined($obj)) {
+ $exhausted = 1;
+ last;
+ }
+ $entry->{obj} = $obj;
+ }
+ };
+ if (my $err = $@) {
+ log_peer_error($entry->{name}, $err);
+ $reader->close();
+ delete $state->{active_reader};
+ abort_stream($state, "could not stream metrics from $entry->{name}: $err");
+ return undef;
+ }
+
+ delete $state->{active_reader} if $exhausted;
+ return $out;
+}
+
+my sub passthrough_emit_step($state) {
+ my $self = __SUB__;
+ clear_slice_watchers($state);
+ my $stream = $state->{stream};
+ return if $state->{done} || !$stream || $stream->is_closed();
+
+ my $out = '';
+ my $ready = $state->{ready_peers};
+ while (length($out) < $STREAM_SLICE_BYTES) {
+ if (!defined($state->{active_reader})) {
+ last if !@$ready;
+ my $peer = shift @$ready;
+ my $entry = open_peer_reader($peer->{name}, $peer->{body}, $peer->{gzip});
+ undef $peer;
+ next if !$entry;
+ $state->{active_reader} = $entry;
+ }
+ my $chunk = passthrough_drain_reader($state, $STREAM_SLICE_BYTES - length($out));
+ return if $state->{done} || !defined($chunk);
+ $out .= $chunk;
+ }
+
+ if (!length($out)) {
+ if ($state->{fetch_done}) {
+ finish_stream($state, '');
+ return;
+ }
+ $state->{fanout}->{dispatch}->() if $state->{fanout};
+ return;
+ }
+
+ if (!defined($state->{active_reader}) && !@$ready && $state->{fetch_done}) {
+ finish_stream($state, $out);
+ return;
+ }
+
+ my $ok = $stream->write($out);
+ after_stream_write(
+ $state,
+ $ok,
+ sub { $self->($state) },
+ sub { $state->{fanout}->{dispatch}->() if $state->{fanout} },
+ );
+}
+
+my sub passthrough_schedule_emit($state) {
+ my $stream = $state->{stream};
+ if (
+ $state->{done}
+ || $state->{waiting_drain}
+ || defined($state->{slice_idle})
+ || defined($state->{slice_timer})
+ || !$stream
+ || $stream->is_closed()
+ ) {
+ return;
+ }
+ schedule_slice($state, sub { passthrough_emit_step($state) });
+}
+
+sub build_passthrough_stream(%opts) {
+ my $local_json = $opts{local_json};
+ my $max_concurrent = int($opts{max_concurrent} // 16);
+ $max_concurrent = 1 if $max_concurrent < 1;
+
+ return sub {
+ my ($stream) = @_;
+
+ my $state = {
+ stream => $stream,
+ done => 0,
+ fetch_done => 0,
+ waiting_drain => 0,
+ ready_peers => [],
+ active_reader => undef,
+ first_item => 1,
+ };
+
+ my $cancel = sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ cleanup_stream($state);
+ };
+
+ # Emit wrapper + first local slice immediately for minimal TTFB.
+ $stream->start();
+ my $out = $STREAM_PREFIX;
+ if (defined($local_json)) {
+ my $local_entry = open_peer_reader('local', $local_json, 0);
+ undef $local_json;
+ if ($local_entry) {
+ $state->{active_reader} = $local_entry;
+ my $chunk = passthrough_drain_reader($state, $STREAM_SLICE_BYTES);
+ return $cancel if $state->{done} || !defined($chunk);
+ $out .= $chunk;
+ }
+ }
+
+ my $ok = $stream->write($out);
+ if (!$state->{done} && !$stream->is_closed()) {
+ $ok = $stream->flush() if $ok;
+ }
+ return $cancel if $state->{done} || $stream->is_closed();
+
+ $state->{fanout} = start_metric_fanout(
+ %opts,
+ # Bound queued ready_peers alongside socket backpressure so slow consumers cap buffered
+ # peer payloads while the pool suspends its overall_timeout countdown.
+ can_dispatch => sub {
+ return
+ !$state->{waiting_drain}
+ && !$stream->is_backpressured()
+ && !$stream->is_closed()
+ && scalar(@{ $state->{ready_peers} }) < $max_concurrent;
+ },
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ push @{ $state->{ready_peers} },
+ {
+ name => $name,
+ body => $$body_ref,
+ gzip => $is_gzip,
+ };
+ passthrough_schedule_emit($state);
+ },
+ on_done => sub($timed_out, $timeout) {
+ return if $state->{done} || $stream->is_closed();
+ $state->{fetch_done} = 1;
+ delete $state->{fanout};
+ if ($timed_out) {
+ abort_stream($state,
+ "cluster metric fan-out timed out after ${timeout}s\n");
+ return;
+ }
+ eval { passthrough_schedule_emit($state); };
+ abort_stream($state, $@) if $@;
+ },
+ );
+
+ if (!$ok || $stream->is_backpressured() || defined($state->{active_reader})) {
+ after_stream_write(
+ $state,
+ $ok,
+ sub { passthrough_emit_step($state) },
+ sub { $state->{fanout}->{dispatch}->() if $state->{fanout} },
+ );
+ }
+
+ return $cancel;
+ };
+}
+
sub export(%opts) {
my $metrics = $opts{metrics} // [];
+ my $unsorted = $opts{unsorted} ? 1 : 0;
if (PVE::APIServer::AnyEvent::async_stream_supported()) {
my $local_json;
if (@$metrics) {
- # Encode local metrics into the same wire envelope as remote peers so the streaming
- # reader and k-way merge heap drain local and remote sources uniformly.
- @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ # Encode local metrics into the same wire envelope as remote peers so both streaming
+ # modes drain local and remote sources through Reader uniformly.
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics if !$unsorted;
$local_json = encode_json({ data => { data => $metrics } });
@$metrics = ();
}
- return PVE::APIServer::AnyEvent::async_stream_response(
- build_kway_merge_stream(%opts, local_json => $local_json),
- );
+ my $starter =
+ $unsorted
+ ? build_passthrough_stream(%opts, local_json => $local_json)
+ : build_kway_merge_stream(%opts, local_json => $local_json);
+ return PVE::APIServer::AnyEvent::async_stream_response($starter);
}
my $finalize = sub {
# In-place sort avoids allocating a second copy of large metric arrays.
- @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics if !$unsorted;
return {
data => $metrics,
};
--
2.47.3
next prev 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 ` [PATCH manager 06/09] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
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 ` Thomas Lamprecht [this message]
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-9-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.