From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option
Date: Tue, 1 Dec 2026 11:19:03 +0100 [thread overview]
Message-ID: <20261201101913.1885484-9-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com>
Sorted streaming waits for peer collection before sending its first
byte and retains 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. An unsorted streaming cluster request writes its
first slice of pre-encoded local metrics before fetching peers, then
reads completed peer bodies in slices through
PVE::PullMetricExport::Reader, pausing queued peer dispatch (via Pool's
can_dispatch backpressure gate ahead of the shared worker limiter)
whenever the downstream socket is backpressured. CLI, buffered
formatters, and requests without remote targets do not gain incremental
delivery from unsorted=1. By default, a peer that fails to open or
yield its first metric is skipped with a warning (or aborts the stream
when fail-on-error=1); overall fan-out timeouts or subsequent reader
errors abort the in-progress stream (TCP RST) so consumers retry rather
than advancing their cursor past missing samples.
Carrying a second streaming state machine and can_dispatch backpressure
gating adds complexity. The trade-off keeps backwards-compatible global
sorting by default while reducing first-byte and total time for callers
that handle ordering themselves; omit unsorted when querying older
nodes, which reject the unknown parameter.
Measured on the same single-worker mock harness (25 ms/peer, 16-peer
per-export cap, 36 FDs; scenarios are nodes x guests, hist10 = 10
history generations per node; Max /ping HOL = maximum concurrent /ping
head-of-line latency on the same worker):
Scenario | Mode | Total | TTFB | VmHWM | Max /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | K-way stream | 196ms | 114ms | 84 MiB | 5.0 ms
(25,475 metrics) | Pass-through | 147ms | 2.0ms | 82 MiB | 8.0 ms
25x100 hist10 | K-way stream | 871ms | 123ms | 99 MiB | 9.4 ms
(254,750 metrics) | Pass-through | 761ms | 6.2ms | 93 MiB | 6.0 ms
100x100 latest | K-way stream | 687ms | 399ms | 91 MiB | 7.3 ms
(101,900 metrics) | Pass-through | 445ms | 2.1ms | 82 MiB | 9.5 ms
100x1000 | K-way stream | 3296ms | 397ms | 103 MiB | 9.5 ms
(1,001,900 metrics) | Pass-through | 2955ms | 5.3ms | 94 MiB | 8.6 ms
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Account queued ready_peers and active readers against the worker-wide
retained-byte admission threshold (pausing further peer fetches until
queued bodies drain), drop local_json from %opts on starter entry, and
wire fail-on-error=1 and synchronous strict-failure dispatch stopping
into pass-through streaming.
- Clarify endpoint and unsorted cursor descriptions (API 504 vs 502
mapping, non-snapshot semantics of fail-on-error=1, per-node or
overlap+dedup cursor guidance, and post-start incomplete-response
rules) and refresh commit message trade-off prose and benchmark
numbers.
PVE/API2/Cluster/MetricServer.pm | 36 +++--
PVE/PullMetricExport.pm | 268 +++++++++++++++++++++++++++++--
2 files changed, 284 insertions(+), 20 deletions(-)
diff --git a/PVE/API2/Cluster/MetricServer.pm b/PVE/API2/Cluster/MetricServer.pm
index 14f065fd6..0a9d7b838 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -319,12 +319,18 @@ __PACKAGE__->register_method({
expose_credentials => 1,
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.",
+ . " and skipped (best-effort across reachable nodes). Setting fail-on-error=1 detects"
+ . " fetch and read errors on online target nodes; it does not provide a cluster-wide"
+ . " snapshot, as a node can publish another sample after it has answered. Before"
+ . " response headers are sent, an overall timeout or a strict peer timeout returns"
+ . " 504, and other strict peer failures return 502 (as the HTTP status on /api2/json,"
+ . " or HTTP 200 with success: 0 and the error code in status on /api2/extjs). Invalid"
+ . " peer data discovered after sending starts can leave the response incomplete, and"
+ . " with unsorted=1 this can also happen on an overall timeout or a strict peer"
+ . " failure. Cursor-based scrapers should retry errors and incomplete responses with"
+ . " the same start-time; loss-sensitive scrapers should track per-node cursors or"
+ . " overlap with deduplication rather than relying solely on the maximum returned"
+ . " timestamp.",
permissions => {
check => ['perm', '/', ['Sys.Audit']],
},
@@ -363,6 +369,15 @@ __PACKAGE__->register_method({
optional => 1,
default => 0,
},
+ 'unsorted' => {
+ type => 'boolean',
+ description =>
+ 'Do not sort metrics by timestamp. No global order is guaranteed;'
+ . ' callers must not assume the last record carries the response maximum'
+ . ' timestamp.',
+ optional => 1,
+ default => 0,
+ },
},
},
returns => {
@@ -371,8 +386,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 unless unsorted is'
+ . ' set; no global order is guaranteed in unsorted mode.',
items => {
type => 'object',
additionalProperties => 0,
@@ -413,6 +428,7 @@ __PACKAGE__->register_method({
my $start = $param->{'start-time'};
my $history = $param->{'history'} // 0;
my $fail_on_error = $param->{'fail-on-error'} // 0;
+ my $unsorted = $param->{'unsorted'} // 0;
my $now = time();
@@ -505,7 +521,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,
};
@@ -516,6 +532,7 @@ __PACKAGE__->register_method({
my $remote_params = {
# Do NOT remove 'local-only' - potential for request recursion!
+ # Intentionally omit 'unsorted' so mixed-version peers never reject the unknown parameter.
'local-only' => 1,
history => $history,
};
@@ -527,6 +544,7 @@ __PACKAGE__->register_method({
credentials => $credentials,
metrics => \@metrics,
fail_on_error => $fail_on_error,
+ 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 272d9bb1a..fd05eca72 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,10 +1,13 @@
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: writes its first slice of pre-encoded local metrics
+# before fetching peers, then drains completed peer bodies in slices with can_dispatch
+# backpressure gating.
# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers).
use v5.36;
@@ -727,26 +730,269 @@ 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;
+ }
+
+ if ($exhausted) {
+ release_peer_bytes($state, delete $entry->{retained_bytes});
+ delete $state->{active_reader};
+ }
+ 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 $bytes = $peer->{retained_bytes};
+ my $entry = eval {
+ open_peer_reader(
+ $peer->{name},
+ $peer->{body},
+ $peer->{gzip},
+ $state->{fail_on_error},
+ );
+ };
+ my $err = $@;
+ undef $peer;
+ if ($err) {
+ release_peer_bytes($state, $bytes);
+ abort_stream($state, $err);
+ return;
+ }
+ if (!$entry) {
+ release_peer_bytes($state, $bytes);
+ next;
+ }
+ $entry->{retained_bytes} = $bytes;
+ $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 = delete $opts{local_json};
+ my $fail_on_error = $opts{fail_on_error} ? 1 : 0;
+ 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,
+ needs_all_peers => 0,
+ retained_bytes => 0,
+ fetch_done => 0,
+ waiting_drain => 0,
+ fail_on_error => $fail_on_error,
+ 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.
+ return $cancel if !$stream->start();
+ my $out = $STREAM_PREFIX;
+ if (defined($local_json)) {
+ my $local_entry =
+ eval { open_peer_reader('local', $local_json, 0, $fail_on_error) };
+ my $err = $@;
+ undef $local_json;
+ if ($err) {
+ abort_stream($state, $err);
+ return $cancel;
+ }
+ 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();
+
+ my $fanout = start_metric_fanout(
+ %opts,
+ is_done => sub { return $state->{done}; },
+ byte_state => $state,
+ # 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) = @_;
+ return if $state->{done};
+ my $bytes = length($$body_ref // '');
+ retain_peer_bytes($state, $bytes);
+ push @{ $state->{ready_peers} },
+ {
+ name => $name,
+ body => $$body_ref,
+ gzip => $is_gzip,
+ retained_bytes => $bytes,
+ };
+ passthrough_schedule_emit($state);
+ },
+ on_peer_error => $fail_on_error
+ ? sub {
+ my ($name, $err, $code) = @_;
+ abort_stream(
+ $state,
+ PVE::Exception->new(
+ "could not fetch metrics from $name: $err",
+ code => $code,
+ ),
+ );
+ }
+ : undef,
+ 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 ($state->{done}) {
+ $fanout->{cancel}->();
+ } elsif (!$state->{fetch_done}) {
+ $state->{fanout} = $fanout;
+ }
+
+ 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-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 ` [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
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 ` Thomas Lamprecht [this message]
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-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.