From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 8121E1FF0B7 for ; Mon, 30 Nov 2026 02:02:21 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 9D10B2176C; Mon, 30 Nov 2026 02:01:58 +0100 (CET) From: Thomas Lamprecht 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 Message-ID: <20261130010113.2166775-9-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com> References: <20261130010113.2166775-1-t.lamprecht@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796000481190 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.003 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) POISEN_SPAM_PILL 0.1 Meta: its spam POISEN_SPAM_PILL_1 0.1 random spam to be learned in bayes POISEN_SPAM_PILL_3 0.1 random spam to be learned in bayes RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: 2AZ4KWEU6O5ESZGIXSD6JBKSCTKXAWLQ X-Message-ID-Hash: 2AZ4KWEU6O5ESZGIXSD6JBKSCTKXAWLQ X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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