From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH manager 09/09] test: add pull metric export test suite
Date: Mon, 30 Nov 2026 01:58:13 +0100 [thread overview]
Message-ID: <20261130010113.2166775-10-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com>
Add test/PullMetricExport_test.pl and wire it into test/Makefile
covering:
- Buffered async fan-out: 16-peer concurrency cap, non-persistent
sockets, disabled redirects, IPv6 URI bracketing, synchronous
callback safety, duplicate node-list deduplication, invalid entry
rejection, finalize error forwarding to reject(), CondVar mode
outside async HTTP handlers, single-peer timeout isolation, and
overall timeout HTTP 504 rejection.
- K-way merge and pass-through streaming: inner {"data":[...]} payload
composition with server-owned json/extjs envelopes, global sorting,
escaped JSON strings, multi-chunk gzip inflation across input-chunk
and 64 KiB inflate boundaries (zero whole-body memGunzip),
pre-emission corrupt-peer isolation vs late mid-stream Reader error
stream abort, strict malformed JSON rejection, fallback to buffered
AsyncResponse for unsupported formats, and stock HTTPServer returning
AsyncResponse/AsyncStreamResponse handles under data while clearing
rpcenv credentials.
- Resilience, lifecycle, worker-wide concurrency, real AsyncStream, and
direct Reader tests: forward progress under continuously ready
competing I/O, slow-consumer backpressure pausing overall_timeout,
on_done/schedule_slice/finish_stream exception abort isolation,
disconnect cancellation, weakened-ref destruction checks, worker-wide
concurrency cap and waiter cancellation across overlapping exports,
end-to-end gzip + /api2/extjs/ verification against real
PVE::APIServer::AsyncStream (chunked 0-terminator, Z_STREAM_END,
envelope), and direct PVE::PullMetricExport::Reader unit tests
including >128 KiB inter-object whitespace compaction and trailing
comma rejection.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
test/Makefile | 6 +-
test/PullMetricExport_test.pl | 2082 +++++++++++++++++++++++++++++++++
2 files changed, 2087 insertions(+), 1 deletion(-)
create mode 100755 test/PullMetricExport_test.pl
diff --git a/test/Makefile b/test/Makefile
index bb9aba282..72edbf6a9 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -5,7 +5,11 @@ all:
export PERLLIB=..
.PHONY: check
-check: test-replication test-balloon test-vzdump test-osd test-ceph-health test-ceph-releases test-ceph-services test-ceph-auth test-ceph-key-migration test-ceph-lockbox-migration test-custom-cpu-models test-pvesh test-report test-access-log test-cluster-resources test-cluster-status test-bulk-migrate test-multipath-notification
+check: test-replication test-balloon test-vzdump test-osd test-ceph-health test-ceph-releases test-ceph-services test-ceph-auth test-ceph-key-migration test-ceph-lockbox-migration test-custom-cpu-models test-pvesh test-report test-access-log test-cluster-resources test-cluster-status test-bulk-migrate test-multipath-notification test-pull-metric-export
+
+.PHONY: test-pull-metric-export
+test-pull-metric-export:
+ ./PullMetricExport_test.pl
.PHONY: test-multipath-notification
test-multipath-notification:
diff --git a/test/PullMetricExport_test.pl b/test/PullMetricExport_test.pl
new file mode 100755
index 000000000..ac82f1218
--- /dev/null
+++ b/test/PullMetricExport_test.pl
@@ -0,0 +1,2082 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use lib ('.', '..');
+
+use AnyEvent;
+use AnyEvent::Util;
+use Compress::Raw::Zlib qw(WANT_GZIP Z_STREAM_END);
+use Compress::Zlib qw(memGzip);
+use JSON qw(decode_json encode_json);
+use Scalar::Util qw(weaken);
+use Test::MockModule;
+use Test::More;
+
+use PVE::API2::Cluster::MetricServer;
+use PVE::APIServer::AsyncStream;
+use PVE::HTTPServer;
+use PVE::PullMetricExport;
+use PVE::PullMetricExport::Reader;
+
+{
+
+ package MockStream;
+
+ sub new {
+ my ($class, %opts) = @_;
+ my ($prefix, $suffix) = ('', '');
+ if (defined($opts{format})) {
+ if ($opts{format} eq 'json') {
+ ($prefix, $suffix) = ('{"data":', '}');
+ } elsif ($opts{format} eq 'extjs') {
+ ($prefix, $suffix) = ('{"data":', ',"success":1}');
+ }
+ }
+ return bless {
+ started => 0,
+ finished => 0,
+ closed => 0,
+ flushed => 0,
+ backpressured => 0,
+ aborted_err => undef,
+ prefix => $prefix,
+ suffix => $suffix,
+ buf => '',
+ drain_cb => undef,
+ on_finish => $opts{on_finish},
+ on_abort => $opts{on_abort},
+ on_write => $opts{on_write},
+ bp_after_bytes => $opts{bp_after_bytes},
+ }, $class;
+ }
+
+ sub start {
+ my ($self) = @_;
+ return 0 if $self->{closed};
+ if (!$self->{started}) {
+ $self->{started} = 1;
+ $self->{buf} .= $self->{prefix};
+ }
+ return 1;
+ }
+
+ sub is_backpressured { return $_[0]->{backpressured}; }
+ sub is_closed { return $_[0]->{closed}; }
+ sub on_drain { $_[0]->{drain_cb} = $_[1]; }
+
+ sub write {
+ my ($self, $data) = @_;
+ return 0 if $self->{closed};
+ $self->start() if !$self->{started};
+ $self->{buf} .= $data;
+ if (defined($self->{bp_after_bytes}) && length($self->{buf}) >= $self->{bp_after_bytes}) {
+ $self->{backpressured} = 1;
+ }
+ $self->{on_write}->($self, $data) if $self->{on_write};
+ return $self->{backpressured} ? 0 : 1;
+ }
+
+ sub flush {
+ my ($self) = @_;
+ return 0 if $self->{closed};
+ $self->{flushed}++;
+ return $self->{backpressured} ? 0 : 1;
+ }
+
+ sub trigger_drain {
+ my ($self) = @_;
+ $self->{backpressured} = 0;
+ if (my $cb = delete $self->{drain_cb}) {
+ $cb->();
+ }
+ }
+
+ sub finish {
+ my ($self) = @_;
+ return if $self->{closed};
+ $self->start() if !$self->{started};
+ $self->{buf} .= $self->{suffix};
+ $self->{finished} = 1;
+ $self->{closed} = 1;
+ undef $self->{drain_cb};
+ $self->{on_finish}->($self) if $self->{on_finish};
+ }
+
+ sub disconnect {
+ my ($self, $cancel) = @_;
+ $self->{closed} = 1;
+ undef $self->{drain_cb};
+ $cancel->() if $cancel;
+ }
+
+ sub abort {
+ my ($self, $err) = @_;
+ return if $self->{closed};
+ $self->{aborted_err} = $err;
+ $self->{closed} = 1;
+ undef $self->{drain_cb};
+ $self->{on_abort}->($self, $err) if $self->{on_abort};
+ }
+}
+
+{
+
+ package MockRPCEnv;
+
+ sub get_credentials { return $_[0]->{credentials}; }
+ sub set_credentials { $_[0]->{credentials} = $_[1]; }
+ sub get_user { return $_[0]->{user}; }
+ sub set_user { $_[0]->{user} = $_[1]; }
+ sub get_result_attrib { return $_[0]->{result_attributes}->{ $_[1] }; }
+ sub check_api2_permissions { return 1; }
+}
+
+my (%members, %ips, %fps, @syslogs);
+my $local_metrics = [];
+my $mock_rpcenv = bless {
+ type => 'pub',
+ user => 'root@pam',
+ credentials => { api_token => 'root@pam!test=secret' },
+ result_attributes => {},
+ },
+ 'MockRPCEnv';
+
+our $async_flag = 1;
+our $stream_format = 'json';
+
+my $inotify_mock = Test::MockModule->new('PVE::INotify');
+$inotify_mock->redefine(nodename => sub { return 'node0'; });
+
+my $cluster_mock = Test::MockModule->new('PVE::Cluster');
+$cluster_mock->redefine(
+ get_members => sub { return \%members; },
+ remote_node_ip => sub { return $ips{ $_[0] }; },
+ get_node_fingerprint => sub { return $fps{ $_[0] }; },
+);
+
+my $pull_mock = Test::MockModule->new('PVE::PullMetric');
+$pull_mock->redefine(get_local_metrics => sub { return [@$local_metrics]; });
+
+my $rpc_mock = Test::MockModule->new('PVE::RPCEnvironment');
+$rpc_mock->redefine(get => sub { return $mock_rpcenv; });
+
+my $syslog_mock = Test::MockModule->new('PVE::SafeSyslog');
+$syslog_mock->redefine(syslog => sub { push @syslogs, "[$_[0]] $_[1]"; });
+
+my $ae_mock = Test::MockModule->new('PVE::APIServer::AnyEvent');
+$ae_mock->mock(
+ async_supported => sub { return $async_flag; },
+ async_response => sub {
+ return bless { start => $_[0] }, 'PVE::APIServer::AnyEvent::AsyncResponse';
+ },
+ async_stream_supported => sub {
+ return 0 if !$async_flag || !defined($stream_format);
+ return ($stream_format eq 'json' || $stream_format eq 'extjs') ? 1 : 0;
+ },
+ async_stream_response => sub {
+ return bless { start => $_[0] }, 'PVE::APIServer::AnyEvent::AsyncStreamResponse';
+ },
+);
+
+my sub make_metric {
+ my ($ts, $id, $metric, $value, $type) = @_;
+ return {
+ timestamp => $ts,
+ id => $id,
+ metric => $metric // 'cpu',
+ value => $value // 0.5,
+ type => $type // 'gauge',
+ };
+}
+
+my sub make_payload {
+ my ($metrics, $gzip) = @_;
+ my $json = encode_json({ data => { data => $metrics } });
+ return $gzip ? memGzip($json) : $json;
+}
+
+my sub setup_cluster {
+ my ($n, %opts) = @_;
+ %members = (node0 => { online => 1 });
+ %ips = ();
+ %fps = ();
+ @syslogs = ();
+ $local_metrics = [
+ make_metric(105, 'node/node0', 'uptime', 10),
+ make_metric(101, 'node/node0', 'cpu', 0.5),
+ ];
+ for my $i (1 .. $n) {
+ my $name = sprintf("node%03d", $i);
+ $members{$name} = { online => 1 };
+ $ips{$name} = $opts{ipv6} && $i == 1 ? '2001:db8::1' : "10.0.0.$i";
+ $fps{$name} = sprintf("%064X", $i);
+ }
+}
+
+my sub with_http_mock {
+ my ($handler, $code) = @_;
+ my $tls_mock = Test::MockModule->new('AnyEvent::TLS');
+ $tls_mock->redefine(new => sub { return bless {}, 'MockTLS'; });
+ my $http_mock = Test::MockModule->new('AnyEvent::HTTP');
+ $http_mock->redefine(
+ http_request => sub {
+ my $cb = pop @_;
+ my ($method, $url, %opts) = @_;
+ return $handler->($method, $url, \%opts, $cb);
+ },
+ );
+ return $code->();
+}
+
+my sub is_sorted_by_ts {
+ my ($arr) = @_;
+ for my $i (1 .. $#$arr) {
+ return 0 if $arr->[$i - 1]->{timestamp} > $arr->[$i]->{timestamp};
+ }
+ return 1;
+}
+
+subtest 'buffered async fan-out: concurrency cap, sync callbacks, IPv6, dedup, and CondVar mode' =>
+ sub {
+ setup_cluster(50, ipv6 => 1);
+ local $stream_format = undef;
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 16;
+
+ my ($in_flight, $peak, $started, $ipv6_seen) = (0, 0, 0, 0);
+ my ($result, $weak_cancel);
+ {
+ my $cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my ($method, $url, $opts, $cb) = @_;
+ my $idx = ++$started;
+ $in_flight++;
+ $peak = $in_flight if $in_flight > $peak;
+ $ipv6_seen = 1 if $url =~ m{^https://\[2001:db8::1\]:8006/};
+ if ($idx == 1) {
+ is($opts->{persistent}, 0, 'non-persistent peer sockets');
+ is($opts->{recurse}, 0, 'redirects disabled');
+ }
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ $in_flight--;
+ if ($idx == 10) {
+ $cb->(undef, { Status => 595, Reason => 'Connection refused' });
+ return;
+ }
+ $cb->(
+ make_payload([make_metric(200 - $idx, "node/p$idx", 'm', $idx)], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ isa_ok($async, 'PVE::APIServer::AnyEvent::AsyncResponse');
+ my $cancel = $async->{start}->(
+ sub { $result = $_[0]; $cv->send; }, sub { $cv->croak($_[0]); },
+ );
+ $weak_cancel = $cancel;
+ weaken($weak_cancel);
+ $cv->recv;
+ },
+ );
+ }
+
+ is($started, 50, 'all 50 peers fetched');
+ is($peak, 16, 'peak in-flight capped at 16');
+ is($ipv6_seen, 1, 'IPv6 host bracketed in URI');
+ is(scalar(@{ $result->{data} }), 51, '2 local + 49 remote metrics (1 failed)');
+ ok(is_sorted_by_ts($result->{data}), 'buffered metrics sorted by timestamp');
+ is($weak_cancel, undef, 'buffered cancel closure freed without cycle');
+
+ # Synchronous http_request callbacks across 150 peers must not recurse.
+ setup_cluster(150);
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, @_; };
+ my $sync_started = 0;
+ my $sync_res;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $sync_started++;
+ $cb->(
+ make_payload([make_metric(300, "node/s$sync_started", 'm', 1)]),
+ { Status => 200 },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(sub { $sync_res = $_[0]; }, sub { die $_[0]; });
+ },
+ );
+ is($sync_started, 150, '150 synchronous callbacks completed');
+ is(scalar(@warnings), 0, 'no recursion warnings on 150 sync callbacks');
+
+ # Duplicate node-list entries deduplicated.
+ setup_cluster(3);
+ my $dedup_calls = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $dedup_calls++;
+ $cb->('{"data":{"data":[]}}', { Status => 200 });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({
+ 'node-list' => 'node001,node001,node002',
+ });
+ $async->{start}->(sub { }, sub { die $_[0]; });
+ },
+ );
+ is($dedup_calls, 2, 'duplicate node-list entries deduplicated');
+
+ # Reject invalid buffered peer entries (including boolean timestamps) and forward finalize errors.
+ setup_cluster(4);
+ $local_metrics = [];
+ @syslogs = ();
+ my @buf_payloads = (
+ make_payload([make_metric(10, 'node/good')]),
+ '{"data":{"data":["oops"]}}',
+ '{"data":{"data":[{"id":"node/missing-ts","value":1}]}}',
+ '{"data":{"data":[{"timestamp":true,"id":"node/bool-ts","value":1}]}}',
+ );
+ my $bidx = 0;
+ my $buf_res;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->(
+ memGzip($buf_payloads[$bidx++]),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(sub { $buf_res = $_[0]; }, sub { die $_[0]; });
+ },
+ );
+ is(scalar(@{ $buf_res->{data} }), 1, 'buffered fan-out skipped malformed peer entries');
+ is($buf_res->{data}->[0]->{id}, 'node/good', 'buffered fan-out preserved valid peer entry');
+ is(scalar(@syslogs), 3, 'buffered fan-out logged all three invalid entry payloads');
+
+ for my $mode (qw(sync async)) {
+ my ($resolved, $rejected_err);
+ my $cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $body = '{"data":{"data":[]}}';
+ if ($mode eq 'sync') {
+ $cb->($body, { Status => 200 });
+ return AnyEvent::Util::guard {};
+ }
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($body, { Status => 200 });
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $starter = PVE::PullMetricExport::build_buffered_fanout(
+ targets => [{ name => 'node1', ip => '10.0.0.1', fingerprint => 'AA:BB' }],
+ params => { 'local-only' => 1 },
+ credentials => {},
+ metrics => [],
+ finalize => sub { die "finalize boom ($mode)\n"; },
+ );
+ $starter->(
+ sub { $resolved = 1; $cv->send; },
+ sub { $rejected_err = $_[0]; $cv->send; },
+ );
+ $cv->recv;
+ },
+ );
+ ok(!$resolved, "buffered fan-out did not resolve on throwing finalize ($mode)");
+ like(
+ $rejected_err // '',
+ qr/finalize boom \($mode\)/,
+ "buffered fan-out invoked reject on throwing finalize ($mode)",
+ );
+ }
+
+ # CondVar mode outside an async HTTP handler (e.g. CLI/pvesh).
+ setup_cluster(4);
+ local $async_flag = 0;
+ local $mock_rpcenv->{type} = 'cli';
+ my $cli_res = with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ $cb->(
+ make_payload([make_metric(42, 'node/cli', 'm', 1)]),
+ { Status => 200 },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub { return PVE::API2::Cluster::MetricServer->export({}); },
+ );
+ is(scalar(@{ $cli_res->{data} }), 6, 'CLI CondVar mode returns 2 local + 4 remote metrics');
+
+ # Single hanging peer hitting request_timeout logs warning while healthy peers return 200.
+ setup_cluster(3);
+ local $async_flag = 1;
+ local $stream_format = undef;
+ @syslogs = ();
+ my $req_to_idx = 0;
+ my $req_to_res;
+ my $req_to_cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $i = ++$req_to_idx;
+ if ($i == 2) {
+ $cb->(undef, { Status => 596, Reason => 'Request timed out' });
+ return AnyEvent::Util::guard {};
+ }
+ $cb->(
+ make_payload([make_metric(50 + $i, "node/ok$i", 'm', 1)], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(
+ sub { $req_to_res = $_[0]; $req_to_cv->send; },
+ sub { $req_to_cv->croak($_[0]); },
+ );
+ $req_to_cv->recv;
+ },
+ );
+ is(
+ scalar(@{ $req_to_res->{data} }),
+ 4,
+ 'single-peer request_timeout still returns 2 local + 2 healthy peer metrics',
+ );
+ ok(
+ scalar(grep { /Request timed out/ } @syslogs) == 1,
+ 'single-peer request_timeout logged warning',
+ );
+
+ # Buffered overall_timeout rejects with HTTP 504 instead of partial 200 OK.
+ setup_cluster(4);
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.08;
+ @syslogs = ();
+ my ($buf_to_resolved, $buf_to_err);
+ my $buf_to_cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ return AnyEvent::Util::guard { undef $cb; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(
+ sub { $buf_to_resolved = 1; $buf_to_cv->send; },
+ sub { $buf_to_err = $_[0]; $buf_to_cv->send; },
+ );
+ $buf_to_cv->recv;
+ },
+ );
+ ok(!$buf_to_resolved, 'buffered overall_timeout did not resolve with partial 200');
+ isa_ok($buf_to_err, 'PVE::Exception');
+ is($buf_to_err->{code}, 504, 'buffered overall_timeout rejects with HTTP 504');
+ like("$buf_to_err", qr/timed out/, 'buffered overall_timeout exception mentions timeout');
+ };
+
+subtest
+ 'k-way merge stream: sort, escapes, multi-chunk, corrupt peers, extjs, backpressure and timeout'
+ => sub {
+ setup_cluster(12);
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 512;
+
+ my ($in_flight, $peak, $idx) = (0, 0, 0);
+ my $cv = AnyEvent->condvar;
+ my $stream = MockStream->new(on_finish => sub { $cv->send; });
+ my $weak_cancel;
+
+ {
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $my_idx = ++$idx;
+ $in_flight++;
+ $peak = $in_flight if $in_flight > $peak;
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ $in_flight--;
+ if ($my_idx == 1) {
+ $cb->(
+ memGzip('{"data":{"data":[ ]}}'),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ if ($my_idx == 2) {
+ my $body = make_payload(
+ [
+ make_metric(
+ 102,
+ 'node/a"b{c}d\\"timestamp":999',
+ 'escaped',
+ 1,
+ ),
+ make_metric(104, 'node/bare}brace', 'brace', 2),
+ ],
+ 1,
+ );
+ $cb->($body, { Status => 200, 'content-encoding' => 'gzip' });
+ return;
+ }
+ if ($my_idx == 3) {
+ $cb->(
+ "\x1f\x8b\x08\x00corrupt-gzip",
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ if ($my_idx == 4) {
+ $cb->('{"bad":1}', { Status => 200 });
+ return;
+ }
+ if ($my_idx == 5) {
+ $cb->('error',
+ { Status => 500, Reason => 'Internal Server Error' });
+ return;
+ }
+ my $ts_base = 90 + ($my_idx * 2);
+ my $is_gz = $my_idx % 2 == 0;
+ my $body = make_payload(
+ [
+ make_metric($ts_base, "node/p$my_idx", 'm1', 1),
+ make_metric($ts_base + 5, "node/p$my_idx", 'm2', 2),
+ ],
+ $is_gz,
+ );
+ $cb->(
+ $body,
+ { Status => 200, $is_gz ? ('content-encoding' => 'gzip') : () },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ isa_ok($async, 'PVE::APIServer::AnyEvent::AsyncStreamResponse');
+ my $cancel = $async->{start}->($stream);
+ $weak_cancel = $cancel;
+ weaken($weak_cancel);
+ $cv->recv;
+ },
+ );
+ }
+
+ is($peak, 4, 'k-way merge capped concurrency at 4');
+ my $parsed = eval { decode_json($stream->{buf}) };
+ ok(!$@ && ref($parsed) eq 'HASH', 'k-way merge output is valid JSON despite corrupt peers');
+ # PullMetricExport emits the inner {"data":[...]} payload; AsyncStream owns the outer envelope.
+ my $arr = $parsed->{data};
+ # 2 local + 0 (p1) + 2 (p2) + 0 (p3) + 0 (p4 bad envelope) + 0 (p5) + 7*2 (p6..p12) = 18
+ is(scalar(@$arr), 18, 'k-way merge emitted exact 18 metrics');
+ ok(is_sorted_by_ts($arr), 'k-way merge output strictly sorted by timestamp');
+ my ($esc) = grep { $_->{metric} eq 'escaped' } @$arr;
+ is($esc->{timestamp}, 102, 'k-way merge extracted real timestamp outside escaped string');
+ is($weak_cancel, undef, 'k-way merge cancel closure freed without cycle');
+
+ # Late mid-stream Reader error aborts k-way merge stream instead of finishing with 200.
+ setup_cluster(2);
+ $local_metrics = [];
+ @syslogs = ();
+ my $cv_trunc = AnyEvent->condvar;
+ my $s_trunc = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_trunc->send; },
+ on_finish => sub { $cv_trunc->send; },
+ );
+ my $trunc_idx = 0;
+ my @trunc_bodies = (
+ make_payload([make_metric(105, 'node/ok')]),
+ '{"data":{"data":[{"timestamp":100,"id":"partial/ok","metric":"m","value":1,"type":"gauge"},{"timestamp":109,"id":"trunc',
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->($trunc_bodies[$trunc_idx++], { Status => 200 });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s_trunc);
+ $cv_trunc->recv;
+ },
+ );
+ ok($s_trunc->{started}, 'k-way merge late Reader error occurred after stream started');
+ ok(!$s_trunc->{finished}, 'k-way merge late Reader error did not finish with 200');
+ like(
+ $s_trunc->{aborted_err} // '',
+ qr/could not stream metrics from node002/,
+ 'k-way merge late Reader error aborted stream with peer context',
+ );
+ ok($s_trunc->is_closed(), 'k-way merge late Reader error closed stream');
+ ok(
+ scalar(grep { /could not fetch metrics from node002/ } @syslogs) >= 1,
+ 'k-way merge late Reader error logged peer warning',
+ );
+
+ # Multi-chunk (~180 KiB uncompressed) across 64 KiB inflate and input-chunk boundaries + extjs.
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'extjs';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 16384;
+ local $PVE::PullMetricExport::Reader::GZIP_INPUT_CHUNK_BYTES = 1024;
+ my $cv2 = AnyEvent->condvar;
+ my $s2 = MockStream->new(format => 'extjs', on_finish => sub { $cv2->send; });
+ my $pno = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $p = ++$pno;
+ my @m = map {
+ make_metric(
+ 1000 + $_ * 2 + $p,
+ ($_ % 97 == 0) ? "qemu/$p\\\"$_\\{x}" : "qemu/$p/$_",
+ )
+ } (1 .. 1500);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s2);
+ $cv2->recv;
+ },
+ );
+ my $p2 = eval { decode_json($s2->{buf}) };
+ ok(!$@ && $p2->{success} == 1, 'k-way merge extjs multi-chunk output has success:1');
+ is(scalar(@{ $p2->{data}->{data} }), 3000, 'k-way merge merged all 3,000 metrics');
+ ok(is_sorted_by_ts($p2->{data}->{data}), 'k-way merge 3,000 metrics strictly sorted');
+
+ # Backpressure resume via on_drain.
+ setup_cluster(2);
+ local $stream_format = 'json';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+
+ my ($bp_idx, $bp_hits) = (0, 0);
+ my $cv_bp = AnyEvent->condvar;
+ my $s_bp = MockStream->new(
+ format => 'json',
+ bp_after_bytes => 200,
+ on_write => sub {
+ my ($s) = @_;
+ if ($s->{backpressured}) {
+ $bp_hits++;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.01,
+ cb => sub {
+ undef $t;
+ $s->{bp_after_bytes} = 10_000_000;
+ $s->trigger_drain();
+ },
+ );
+ }
+ },
+ on_finish => sub { $cv_bp->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $i = ++$bp_idx;
+ my @m = map { make_metric(50 + $_, "node/ok$i/$_", 'm', 1) } (1 .. 4);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s_bp);
+ $cv_bp->recv;
+ },
+ );
+ ok($bp_hits >= 1, 'k-way merge paused on backpressure and resumed via on_drain');
+ is(
+ scalar(@{ decode_json($s_bp->{buf})->{data}->{data} }),
+ 10,
+ 'k-way merge emitted 2 local + 8 fast metrics after backpressure drain',
+ );
+
+ # Overall timeout cancels in-flight guards and aborts stream pre-start with HTTP 504.
+ setup_cluster(8);
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.10;
+ my ($started_to, $cancelled_to) = (0, 0);
+ my $cv_to = AnyEvent->condvar;
+ my $s_to = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_to->send; },
+ on_finish => sub { $cv_to->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $started_to++;
+ if ($started_to <= 2) {
+ my @m = map { make_metric(50 + $_, "node/ok$started_to/$_", 'm', 1) } (1 .. 4);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ }
+ return AnyEvent::Util::guard { undef $cb; $cancelled_to++; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s_to);
+ $cv_to->recv;
+ },
+ );
+ is($cancelled_to, 4, 'k-way merge overall timeout cancelled 4 in-flight guards');
+ is(
+ scalar(grep { /overall fan-out timeout/ } @syslogs),
+ 6,
+ 'k-way merge logged all 6 unfinished peers',
+ );
+ ok(!$s_to->{started}, 'k-way merge overall timeout aborted pre-start');
+ ok(!$s_to->{finished}, 'k-way merge overall timeout did not finish with 200');
+ isa_ok($s_to->{aborted_err}, 'PVE::Exception');
+ is($s_to->{aborted_err}->{code}, 504, 'k-way merge overall timeout aborts with HTTP 504');
+ };
+
+subtest
+ 'pass-through stream: TTFB flush, incremental inflate, corrupt safety, extjs and backpressure'
+ => sub {
+ setup_cluster(8);
+ local $stream_format = 'extjs';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 256;
+
+ my ($started_before, $flushed_before, $idx) = (0, 0, 0);
+ my ($local_only_ok, $unsorted_leaked) = (0, 0);
+ my $cv = AnyEvent->condvar;
+ my $stream = MockStream->new(format => 'extjs', on_finish => sub { $cv->send; });
+ my $weak_cancel;
+
+ {
+ with_http_mock(
+ sub {
+ my (undef, $url, undef, $cb) = @_;
+ $local_only_ok++ if $url =~ /[?&]local-only=1(?:&|$)/;
+ $unsorted_leaked++ if $url =~ /[?&]unsorted=/;
+ my $my_idx = ++$idx;
+ if ($my_idx == 1) {
+ $started_before = $stream->{started};
+ $flushed_before = $stream->{flushed};
+ }
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ if ($my_idx == 1) {
+ $cb->(
+ memGzip('{"data":{"data":[]}}'),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ if ($my_idx == 2) {
+ $cb->('{"data":{"data":[{not_valid_json}]}}', { Status => 200 });
+ return;
+ }
+ if ($my_idx == 3) {
+ $cb->(
+ make_payload([make_metric(50, 'node/esc"}{quote', 'm', 1)], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ $cb->(
+ make_payload(
+ [make_metric(200 - $my_idx, "node/b$my_idx", 'm', 1)], 1,
+ ),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ isa_ok($async, 'PVE::APIServer::AnyEvent::AsyncStreamResponse');
+ my $cancel = $async->{start}->($stream);
+ $weak_cancel = $cancel;
+ weaken($weak_cancel);
+ $cv->recv;
+ },
+ );
+ }
+
+ is($started_before, 1, 'pass-through started stream before peers completed');
+ is($flushed_before, 1, 'pass-through flushed initial local slice for minimal TTFB');
+ is($local_only_ok, 8, 'remote peer requests always set local-only=1');
+ is($unsorted_leaked, 0, 'remote peer requests never forward unsorted parameter');
+ my $parsed = eval { decode_json($stream->{buf}) };
+ ok(!$@ && $parsed->{success} == 1,
+ 'pass-through extjs output is valid JSON with success:1');
+ # 2 local + 0 (p1 empty) + 0 (p2 corrupt) + 1 (p3 escaped) + 5 (p4..p8) = 8
+ is(scalar(@{ $parsed->{data}->{data} }), 8, 'pass-through emitted exact 8 metrics');
+ is_deeply(
+ [map { $_->{timestamp} } @{ $parsed->{data}->{data} }[0, 1]],
+ [105, 101],
+ 'pass-through emitted both local metrics first without sorting',
+ );
+ is($weak_cancel, undef, 'pass-through cancel closure freed without cycle');
+
+ # Incremental slicing (zero memGunzip) + pre-emission corrupt peer isolation.
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+ @syslogs = ();
+
+ my $gunzip_calls = 0;
+ my $zlib_mock = Test::MockModule->new('Compress::Zlib');
+ my $orig_memgunzip = \&Compress::Zlib::memGunzip;
+ $zlib_mock->redefine(
+ memGunzip => sub {
+ $gunzip_calls++;
+ return $orig_memgunzip->(@_);
+ },
+ );
+
+ my $writes = 0;
+ my $cv_inc = AnyEvent->condvar;
+ my $inc_stream = MockStream->new(
+ format => 'json',
+ on_write => sub { $writes++; },
+ on_finish => sub { $cv_inc->send; },
+ );
+ my $inc_idx = 0;
+ my @m200 = map { make_metric(500 + $_, "qemu/1/$_", 'cpu', 0.25) } (1 .. 200);
+ my @inc_bodies = (
+ make_payload(\@m200, 1), memGzip('{"data":{"data":[{"timestamp":11,"value":BROKEN}]}}'),
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->($inc_bodies[$inc_idx++], { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($inc_stream);
+ $cv_inc->recv;
+ },
+ );
+ undef $zlib_mock;
+
+ is($gunzip_calls, 0, 'pass-through incremental reader never calls whole-body memGunzip');
+ ok($writes > 5, "pass-through drained multi-chunk peer across multiple slices ($writes)");
+ my $inc_parsed = eval { decode_json($inc_stream->{buf}) };
+ ok(
+ !$@ && ref($inc_parsed) eq 'HASH',
+ 'pass-through output is valid JSON after skipping pre-emission corrupt peer',
+ );
+ is(
+ scalar(@{ $inc_parsed->{data}->{data} }),
+ 200,
+ 'pass-through kept all 200 healthy metrics',
+ );
+ is(scalar(@syslogs), 1, 'pass-through logged pre-emission corrupt peer warning');
+
+ # Late mid-array Reader error aborts pass-through stream instead of finishing with 200.
+ setup_cluster(2);
+ $local_metrics = [];
+ @syslogs = ();
+ my $cv_mid = AnyEvent->condvar;
+ my $mid_stream = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_mid->send; },
+ on_finish => sub { $cv_mid->send; },
+ );
+ my $mid_idx = 0;
+ my @mid_bodies = (
+ make_payload([make_metric(10, 'node/ok')], 1),
+ memGzip(
+ '{"data":{"data":[{"timestamp":10,"id":"node/valid1","metric":"cpu","value":1,"type":"gauge"},'
+ . '{"timestamp":11,"value":BROKEN}]}}'
+ ),
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->($mid_bodies[$mid_idx++], { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($mid_stream);
+ $cv_mid->recv;
+ },
+ );
+ ok($mid_stream->{started}, 'pass-through late Reader error occurred after stream started');
+ ok(!$mid_stream->{finished}, 'pass-through late Reader error did not finish with 200');
+ like(
+ $mid_stream->{aborted_err} // '',
+ qr/could not stream metrics from node002/,
+ 'pass-through late Reader error aborted stream with peer context',
+ );
+ ok($mid_stream->is_closed(), 'pass-through late Reader error closed stream');
+ ok(
+ scalar(grep { /could not fetch metrics from node002/ } @syslogs) >= 1,
+ 'pass-through late Reader error logged peer warning',
+ );
+
+ # Backpressure pauses peer dispatch; drain resumes; disconnect cancels guards.
+ setup_cluster(16);
+ local $stream_format = 'json';
+ my ($dispatched, $cancelled_bp) = (0, 0);
+ my $bp_stream = MockStream->new(bp_after_bytes => 10);
+ my $weak_bp;
+ {
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $dispatched++;
+ return AnyEvent::Util::guard { undef $cb; $cancelled_bp++; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ my $cancel = $async->{start}->($bp_stream);
+ $weak_bp = $cancel;
+ weaken($weak_bp);
+ is($dispatched, 0, 'pass-through paused peer dispatch while backpressured');
+ $bp_stream->{bp_after_bytes} = 10_000_000;
+ $bp_stream->trigger_drain();
+ is($dispatched, 4, 'pass-through resumed peer dispatch on drain (capped at 4)');
+ $bp_stream->disconnect($cancel);
+ is($cancelled_bp, 4, 'pass-through cancelled active guards on disconnect');
+ },
+ );
+ }
+ is($weak_bp, undef, 'pass-through disconnect freed cancel closure');
+
+ # Pass-through rejects peer metric objects missing integer timestamp.
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ @syslogs = ();
+ my $pt_ts_cv = AnyEvent->condvar;
+ my $pt_ts_stream = MockStream->new(format => 'json', on_finish => sub { $pt_ts_cv->send; });
+ my @pt_ts_bodies = (
+ make_payload([make_metric(10, 'node/good')]),
+ '{"data":{"data":[{"id":"node/missing-ts","value":1}]}}',
+ );
+ my $pt_ts_idx = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->(
+ memGzip($pt_ts_bodies[$pt_ts_idx++]),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($pt_ts_stream);
+ $pt_ts_cv->recv;
+ },
+ );
+ my $pt_ts_parsed = eval { decode_json($pt_ts_stream->{buf}) };
+ is_deeply(
+ [map { $_->{id} } @{ $pt_ts_parsed->{data}->{data} }],
+ ['node/good'],
+ 'unsorted=1 rejected peer metric object missing timestamp',
+ );
+ ok(
+ scalar(grep { /missing integer timestamp/ } @syslogs) == 1,
+ 'unsorted=1 logged missing integer timestamp warning',
+ );
+
+ # Pass-through overall_timeout aborts post-start stream instead of finishing with 200.
+ setup_cluster(2);
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.08;
+ my $pt_to_cv = AnyEvent->condvar;
+ my $pt_to_stream = MockStream->new(
+ format => 'json',
+ on_abort => sub { $pt_to_cv->send; },
+ on_finish => sub { $pt_to_cv->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ return AnyEvent::Util::guard { undef $cb; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($pt_to_stream);
+ $pt_to_cv->recv;
+ },
+ );
+ ok($pt_to_stream->{started}, 'pass-through overall_timeout had already started stream');
+ ok(!$pt_to_stream->{finished}, 'pass-through overall_timeout did not finish stream');
+ like(
+ $pt_to_stream->{aborted_err} // '',
+ qr/timed out/,
+ 'pass-through overall_timeout aborted stream on timeout',
+ );
+
+ # Unsupported stream formats fall back to buffered AsyncResponse.
+ local $stream_format = 'htmljs';
+ isa_ok(
+ PVE::API2::Cluster::MetricServer->export({ unsorted => 1 }),
+ 'PVE::APIServer::AnyEvent::AsyncResponse',
+ 'htmljs format falls back to buffered AsyncResponse',
+ );
+ };
+
+subtest 'stock HTTPServer returns AsyncResponse/AsyncStreamResponse under data and clears auth' =>
+ sub {
+ my $server = bless { rpcenv => $mock_rpcenv }, 'PVE::HTTPServer';
+ my $api2_mock = Test::MockModule->new('PVE::API2');
+
+ for my $case (
+ [
+ 'AsyncResponse',
+ PVE::APIServer::AnyEvent::async_response(sub {
+ return sub { };
+ }),
+ ],
+ [
+ 'AsyncStreamResponse',
+ PVE::APIServer::AnyEvent::async_stream_response(sub {
+ return sub { };
+ }),
+ ],
+ ) {
+ my ($label, $obj) = @$case;
+ $mock_rpcenv->set_user('root@pam');
+ $mock_rpcenv->set_credentials({ ticket => 'PVE:secret' });
+
+ my $handler = bless { obj => $obj }, 'TestAsyncHandler';
+ {
+ no warnings qw(redefine once);
+ *TestAsyncHandler::handle = sub { return $_[0]->{obj}; };
+ }
+ $api2_mock->redefine(
+ find_handler => sub {
+ return (
+ $handler,
+ {
+ allowtoken => 1,
+ expose_credentials => 1,
+ permissions => { user => 'all' },
+ },
+ );
+ },
+ );
+
+ my $resp = $server->rest_handler(
+ '127.0.0.1',
+ 'GET',
+ '/cluster/metrics/export',
+ { userid => 'root@pam', ticket => 'PVE:secret' },
+ {},
+ );
+ is($resp->{status}, 200, "HTTPServer returns 200 for $label");
+ is($resp->{data}, $obj, "stock HTTPServer returns $label handle under data");
+ is($mock_rpcenv->get_user(), undef, "rpcenv user cleared before yielding ($label)");
+ is(
+ $mock_rpcenv->get_credentials(),
+ undef,
+ "rpcenv credentials cleared before yielding ($label)",
+ );
+ }
+ };
+
+subtest
+ 'streaming resilience: competing I/O, slow-consumer deadline pause, malformed JSON and cleanup'
+ => sub {
+ # 1. Continuously ready competing I/O must not starve either streaming mode.
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+ local $PVE::PullMetricExport::SLICE_FALLBACK_INTERVAL = 0.005;
+
+ pipe(my $r_fh, my $w_fh) or die "pipe failed: $!\n";
+ syswrite($w_fh, 'x');
+ my $io_hits = 0;
+ my $io_w = AnyEvent->io(fh => $r_fh, poll => 'r', cb => sub { $io_hits++; });
+
+ my $cv = AnyEvent->condvar;
+ my $timed_out = 0;
+ AnyEvent->now_update;
+ my $guard_t = AnyEvent->timer(after => 5, cb => sub { $timed_out = 1; $cv->send; });
+
+ my $stream = MockStream->new(format => 'json', on_finish => sub { $cv->send; });
+ my $pno = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $p = ++$pno;
+ my @m = map { make_metric(1000 + $_ * 2 + $p, "qemu/$p/$_") } (1 .. 40);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($stream);
+ $cv->recv;
+ },
+ );
+ undef $io_w;
+ undef $guard_t;
+ close($r_fh);
+ close($w_fh);
+
+ ok(!$timed_out, "$label finished under continuously ready competing I/O");
+ ok($io_hits > 0, "$label yielded to competing I/O ($io_hits events)");
+ my $parsed = eval { decode_json($stream->{buf}) };
+ ok(!$@ && ref($parsed) eq 'HASH', "$label output under competing I/O is valid JSON");
+ is(
+ scalar(@{ $parsed->{data}->{data} }),
+ 80,
+ "$label emitted all 80 metrics under competing I/O",
+ );
+ }
+
+ # 2. Slow-consumer backpressure pauses overall_timeout budget so queued peers are not dropped.
+ setup_cluster(6);
+ local $stream_format = 'json';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 2;
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.15;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 1024;
+ @syslogs = ();
+
+ my $cv_bp = AnyEvent->condvar;
+ my $bp_stream = MockStream->new(
+ format => 'json',
+ bp_after_bytes => 10,
+ on_finish => sub { $cv_bp->send; },
+ );
+ my ($bp_dispatched, $mid_paused) = (0, 0);
+ my @resume_timers;
+
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $idx = ++$bp_dispatched;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.01,
+ cb => sub {
+ undef $t;
+ if ($idx == 2 && !$mid_paused) {
+ $mid_paused = 1;
+ $bp_stream->{bp_after_bytes} = length($bp_stream->{buf}) + 1;
+ AnyEvent->now_update;
+ push @resume_timers, AnyEvent->timer(
+ after => 0.25,
+ cb => sub {
+ $bp_stream->{bp_after_bytes} = 10_000_000;
+ $bp_stream->trigger_drain();
+ },
+ );
+ }
+ $cb->(
+ make_payload([make_metric(200 + $idx, "node/bp$idx")], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($bp_stream);
+ AnyEvent->now_update;
+ push @resume_timers, AnyEvent->timer(
+ after => 0.25,
+ cb => sub {
+ $bp_stream->{bp_after_bytes} = 10_000_000;
+ $bp_stream->trigger_drain();
+ },
+ );
+ $cv_bp->recv;
+ },
+ );
+ @resume_timers = ();
+
+ my $bp_parsed = eval { decode_json($bp_stream->{buf}) };
+ ok(!$@ && ref($bp_parsed) eq 'HASH', 'slow-consumer pass-through produced valid JSON');
+ is(
+ scalar(@{ $bp_parsed->{data}->{data} }),
+ 8,
+ 'slow-consumer pass-through delivered all 2 local + 6 queued peers',
+ );
+ is(
+ scalar(@syslogs), 0, 'slow-consumer backpressure caused zero overall_timeout warnings',
+ );
+
+ # 3. Malformed peer JSON rejected strictly by both streaming modes (no backtracking stall).
+ my $large_bad_pairs = join(',', map { "\"k$_\":$_" } (1 .. 2000));
+ my $large_bad_obj = '{"data":{"data":[{' . $large_bad_pairs . ',"value":BROKEN}]}}';
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ setup_cluster(6);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ @syslogs = ();
+
+ my @payloads = (
+ make_payload([make_metric(100, 'node/ok')]),
+ '{"data":{"data":[{"timestamp":10,"value":BROKEN}]}}',
+ '{"data":{"data":[{"timestamp":11,"value":01}]}}',
+ '{"data":{"data":[{"timestamp":12,"value":1,}]}}',
+ "{\"data\":{\"data\":[{\"timestamp\":13,\"id\":\"bad\x01ctrl\",\"value\":1}]}}",
+ $large_bad_obj,
+ );
+ my $idx = 0;
+ my $cv_bad = AnyEvent->condvar;
+ my $bad_stream = MockStream->new(format => 'json', on_finish => sub { $cv_bad->send; });
+
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $body = $payloads[$idx++];
+ $cb->(memGzip($body), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($bad_stream);
+ $cv_bad->recv;
+ },
+ );
+
+ my $parsed = eval { decode_json($bad_stream->{buf}) };
+ ok(
+ !$@ && ref($parsed) eq 'HASH',
+ "$label rejected pre-emission malformed peer JSON and produced valid output",
+ );
+ my @ids = map { $_->{id} } @{ $parsed->{data}->{data} };
+ is_deeply(
+ \@ids,
+ ['node/ok'],
+ "$label skipped pre-emission malformed objects and kept valid output",
+ );
+ is(scalar(@syslogs), 5, "$label logged errors for all 5 pre-emission malformed peers");
+
+ # Late trailing-comma syntax error after emitting a valid object aborts the stream.
+ setup_cluster(2);
+ $local_metrics = [];
+ @syslogs = ();
+ my @late_payloads = (
+ make_payload([make_metric(100, 'node/ok')]),
+ '{"data":{"data":[{"timestamp":14,"id":"node/trailing","value":1},]}}',
+ );
+ my $late_idx = 0;
+ my $cv_late = AnyEvent->condvar;
+ my $late_stream = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_late->send; },
+ on_finish => sub { $cv_late->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $body = $late_payloads[$late_idx++];
+ $cb->(memGzip($body), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($late_stream);
+ $cv_late->recv;
+ },
+ );
+ ok(!$late_stream->{finished}, "$label aborted on late trailing-comma error");
+ like(
+ $late_stream->{aborted_err} // '',
+ qr/could not stream metrics from node002/,
+ "$label reported peer context on late trailing-comma abort",
+ );
+ ok($late_stream->is_closed(), "$label closed stream on late trailing-comma error");
+ }
+
+ # 4. Direct resource destruction: HTTP guards, gzip inflaters, and stream refs released.
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ for my $action (qw(finish cancel)) {
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+
+ my (@weak_guards, @weak_inflaters, $weak_stream);
+ my $inflate_mock = Test::MockModule->new(
+ 'Compress::Raw::Zlib::Inflate', no_auto => 1,
+ );
+ my $orig_inflate_new = \&Compress::Raw::Zlib::Inflate::new;
+ $inflate_mock->redefine(
+ new => sub {
+ my ($inf, $st) = $orig_inflate_new->(@_);
+ if (defined($inf)) {
+ push @weak_inflaters, $inf;
+ weaken($weak_inflaters[-1]);
+ }
+ return ($inf, $st);
+ },
+ );
+
+ {
+ my $cv_res = AnyEvent->condvar;
+ my ($cancel, $did_cancel) = (undef, 0);
+ my $s;
+ $s = MockStream->new(
+ bp_after_bytes => ($action eq 'cancel' ? 60 : undef),
+ on_write => sub {
+ return if $action ne 'cancel' || $did_cancel || !@weak_inflaters;
+ $did_cancel = 1;
+ AE::postpone(sub {
+ $s->disconnect($cancel) if $s;
+ $cv_res->send;
+ });
+ },
+ on_finish => sub { $cv_res->send; },
+ );
+ $weak_stream = $s;
+ weaken($weak_stream);
+
+ my @payload = map { make_metric(100 + $_, "qemu/res/$_") } (1 .. 30);
+ my $gz = make_payload(\@payload, 1);
+
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($gz, { Status => 200, 'content-encoding' => 'gzip' });
+ },
+ );
+ my $g = AnyEvent::Util::guard { undef $t; undef $cb; };
+ push @weak_guards, $g;
+ weaken($weak_guards[-1]);
+ return $g;
+ },
+ sub {
+ my $export_params = { unsorted => $unsorted };
+ my $async = PVE::API2::Cluster::MetricServer->export($export_params);
+ $cancel = $async->{start}->($s);
+ AnyEvent->now_update;
+ my $guard_t = AnyEvent->timer(
+ after => 5,
+ cb => sub { $cv_res->croak("resource cleanup test timed out\n"); },
+ );
+ $cv_res->recv;
+ undef $guard_t;
+ },
+ );
+ undef $cancel;
+ undef $s;
+ }
+ undef $inflate_mock;
+
+ ok(scalar(@weak_guards) > 0, "$label ($action) tracked active HTTP guards");
+ ok(scalar(@weak_inflaters) > 0, "$label ($action) tracked active gzip inflaters");
+ is(scalar(grep { defined($_) } @weak_guards), 0, "$label ($action) freed guards");
+ is(
+ scalar(grep { defined($_) } @weak_inflaters),
+ 0,
+ "$label ($action) freed gzip inflaters",
+ );
+ is($weak_stream, undef, "$label ($action) freed stream reference");
+ }
+ }
+
+ # 5. Slice callback and on_done exceptions abort the stream cleanly without unwinding.
+ for my $case (['on_done', 1], ['schedule_slice', 2]) {
+ my ($phase, $fail_on_write) = @$case;
+ setup_cluster(1);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+
+ my $cv_ab = AnyEvent->condvar;
+ my $timed_out = 0;
+ AnyEvent->now_update;
+ my $guard_t = AnyEvent->timer(after => 5, cb => sub { $timed_out = 1; $cv_ab->send; });
+
+ my $writes = 0;
+ my $ab_stream = MockStream->new(
+ on_write => sub {
+ die "slice write boom ($phase)\n" if ++$writes == $fail_on_write;
+ },
+ on_abort => sub { $cv_ab->send; },
+ on_finish => sub { $cv_ab->send; },
+ );
+
+ my @payload = map { make_metric(100 + $_, "qemu/ab/$_") } (1 .. 30);
+ my $gz = make_payload(\@payload, 1);
+
+ my $recv_err = '';
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($gz, { Status => 200, 'content-encoding' => 'gzip' });
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($ab_stream);
+ eval { $cv_ab->recv; };
+ $recv_err = $@;
+ },
+ );
+ undef $guard_t;
+
+ is($recv_err, '', "$phase exception did not unwind out of event loop");
+ ok(!$timed_out, "$phase exception aborted stream before guard timeout");
+ like(
+ $ab_stream->{aborted_err} // '',
+ qr/slice write boom \(\Q$phase\E\)/,
+ "$phase exception passed error to stream->abort()",
+ );
+ ok($ab_stream->is_closed(), "$phase exception closed stream");
+ }
+
+ # 6. Exception inside finish_stream() aborts the stream cleanly without unwinding.
+ {
+ setup_cluster(1);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 4096;
+
+ my $cv_fin = AnyEvent->condvar;
+ my $fin_stream = MockStream->new(
+ format => 'json',
+ on_write => sub { die "finish_stream write boom\n"; },
+ on_abort => sub { $cv_fin->send; },
+ on_finish => sub { $cv_fin->send; },
+ );
+ my $gz1 = make_payload([make_metric(100, 'qemu/fin/1')], 1);
+ my $recv_err = '';
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($gz1, { Status => 200, 'content-encoding' => 'gzip' });
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($fin_stream);
+ eval { $cv_fin->recv; };
+ $recv_err = $@;
+ },
+ );
+ is($recv_err, '', 'finish_stream exception did not unwind out of event loop');
+ like(
+ $fin_stream->{aborted_err} // '',
+ qr/finish_stream write boom/,
+ 'finish_stream exception invoked stream->abort()',
+ );
+ ok($fin_stream->is_closed(), 'finish_stream exception closed stream');
+ }
+ };
+
+subtest 'PVE::PullMetricExport::Reader direct unit tests' => sub {
+ # 1. Plain and gzipped payloads with negative timestamps, escapes, and UTF-8.
+ my $plain = make_payload([
+ make_metric(-42, 'node/neg', 'cpu', 0.1),
+ make_metric(100, 'node/esc"}{\\"timestamp":999', 'escaped', 1),
+ make_metric(200, "node/utf8-\x{c3}\x{a9}", 'utf8', 2),
+ ]);
+ for my $gz (0, 1) {
+ my $body = $gz ? memGzip($plain) : $plain;
+ my $r = PVE::PullMetricExport::Reader->open(body => $body, gzip => $gz);
+ my (@ts, @objs);
+ while (defined(my $obj = $r->next())) {
+ is($obj, $r->obj(), "Reader (gzip=$gz) next() return value matches obj()");
+ push @ts, $r->ts();
+ push @objs, $obj;
+ }
+ is_deeply(\@ts, [-42, 100, 200], "Reader (gzip=$gz) extracted exact timestamps");
+ is(scalar(@objs), 3, "Reader (gzip=$gz) yielded all 3 objects");
+ is(
+ decode_json($objs[1])->{id},
+ 'node/esc"}{\\"timestamp":999',
+ "Reader (gzip=$gz) preserved escaped JSON object",
+ );
+ is($r->next(), undef, "Reader (gzip=$gz) next() after EOF returns undef");
+ $r->close(); # idempotent
+ }
+
+ # 2. Empty array with whitespace.
+ my $empty = PVE::PullMetricExport::Reader->open(
+ body => memGzip('{"data":{"data":[ ]}}'),
+ gzip => 1,
+ );
+ is($empty->next(), undef, 'empty metrics array returns undef on first next()');
+
+ # 3. Multi-chunk gzip inflation across tiny input slices and 64 KiB inflate chunks.
+ {
+ local $PVE::PullMetricExport::Reader::GZIP_INPUT_CHUNK_BYTES = 128;
+ my @m500 = map { make_metric(1000 + $_, "qemu/reader/$_", 'cpu', 0.5) } (1 .. 500);
+ my $gz500 = make_payload(\@m500, 1);
+ my $r = PVE::PullMetricExport::Reader->open(body => $gz500, gzip => 1);
+ my ($count, $first_ts, $last_ts) = (0, undef, undef);
+ while (defined($r->next())) {
+ $count++;
+ $first_ts //= $r->ts();
+ $last_ts = $r->ts();
+ }
+ is($count, 500, 'Reader inflated all 500 metrics across 128 B input slices');
+ is($first_ts, 1001, 'Reader first multi-chunk timestamp matches');
+ is($last_ts, 1500, 'Reader last multi-chunk timestamp matches');
+ }
+
+ # 3b. Multi-chunk (>128 KiB) whitespace between metrics compacts cleanly and rejects trailing comma.
+ {
+ my $ws140k = ' ' x 140_000;
+ my $ws_payload =
+ '{"data":{"data":['
+ . '{"timestamp":10,"id":"node/a","metric":"cpu","value":1,"type":"gauge"}'
+ . $ws140k . ','
+ . $ws140k
+ . '{"timestamp":20,"id":"node/b","metric":"cpu","value":2,"type":"gauge"}'
+ . $ws140k . ']}}';
+ for my $gz (0, 1) {
+ my $body = $gz ? memGzip($ws_payload) : $ws_payload;
+ my $r = PVE::PullMetricExport::Reader->open(body => $body, gzip => $gz);
+ my (@ts, $max_buf);
+ $max_buf = 0;
+ while (defined($r->next())) {
+ push @ts, $r->ts();
+ my $blen = length($r->{buf} // '');
+ $max_buf = $blen if $blen > $max_buf;
+ }
+ is_deeply(
+ \@ts,
+ [10, 20],
+ "Reader (gzip=$gz) parsed >128 KiB inter-object whitespace",
+ );
+ if ($gz) {
+ ok(
+ $max_buf <= 131_072,
+ "Reader (gzip=1) kept buffer compacted across >128 KiB whitespace ($max_buf B)",
+ );
+ }
+ }
+
+ my $trailing_ws_payload =
+ '{"data":{"data":['
+ . '{"timestamp":10,"id":"node/a","metric":"cpu","value":1,"type":"gauge"},'
+ . $ws140k . ']}}';
+ for my $gz (0, 1) {
+ my $body = $gz ? memGzip($trailing_ws_payload) : $trailing_ws_payload;
+ my $r;
+ eval {
+ $r = PVE::PullMetricExport::Reader->open(body => $body, gzip => $gz);
+ while (defined($r->next())) { }
+ };
+ my $err = $@;
+ $r->close() if $r;
+ like(
+ $err,
+ qr/unexpected token in metrics array/,
+ "Reader (gzip=$gz) rejected trailing comma after >128 KiB whitespace",
+ );
+ }
+ }
+
+ # 4. Missing integer timestamp is always rejected.
+ my $no_ts_body = '{"data":{"data":[{"id":"node/no-ts","value":1}]}}';
+ {
+ my $r_no_ts;
+ eval {
+ $r_no_ts = PVE::PullMetricExport::Reader->open(body => $no_ts_body, gzip => 0);
+ $r_no_ts->next();
+ };
+ my $err = $@;
+ $r_no_ts->close() if $r_no_ts;
+ like($err, qr/missing integer timestamp/, 'Reader always enforces integer timestamp');
+ }
+
+ # Duplicate timestamp keys fall back to decode_json for exact last-key-wins parity.
+ {
+ my $r_dup = PVE::PullMetricExport::Reader->open(
+ body => '{"data":{"data":[{"timestamp":1,"timestamp":2,"id":"x"}]}}',
+ gzip => 0,
+ );
+ ok(defined($r_dup->next()), 'duplicate integer timestamp key accepted via fallback');
+ is($r_dup->ts(), 2, 'duplicate timestamp key uses last-key-wins value (2)');
+ is($r_dup->next(), undef, 'duplicate timestamp reader reaches EOF cleanly');
+ }
+
+ # 5. Strict error cases die cleanly (callers close reader on error).
+ for my $case (
+ ['bad opening envelope', '{"bad":1}', 0, qr/unexpected response format/],
+ [
+ 'corrupt gzip',
+ "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xff\xff\xff\xffcorrupt-deflate-payload",
+ 1,
+ qr/failed to gunzip stream/,
+ ],
+ [
+ 'truncated gzip',
+ substr(memGzip($plain), 0, int(length(memGzip($plain)) / 2)),
+ 1,
+ qr/truncated gzip stream|unexpected response format/,
+ ],
+ [
+ 'truncated array', '{"data":{"data":[{"timestamp":1}', 0,
+ qr/truncated metrics array/,
+ ],
+ [
+ 'truncated object',
+ '{"data":{"data":[{"timestamp":1,"id":"abc',
+ 0,
+ qr/truncated metric object/,
+ ],
+ [
+ 'non-object element',
+ '{"data":{"data":[123]}}',
+ 0,
+ qr/unexpected token in metrics array/,
+ ],
+ [
+ 'missing comma',
+ '{"data":{"data":[{"timestamp":1}{"timestamp":2}]}}',
+ 0,
+ qr/unexpected token in metrics array/,
+ ],
+ [
+ 'trailing comma',
+ '{"data":{"data":[{"timestamp":1},]}}',
+ 0,
+ qr/unexpected token in metrics array/,
+ ],
+ ['malformed JSON', '{"data":{"data":[{"timestamp":1,"v":BROKEN}]}}', 0, qr/./],
+ ['missing timestamp', $no_ts_body, 0, qr/missing integer timestamp/],
+ [
+ 'boolean timestamp',
+ '{"data":{"data":[{"timestamp":true,"id":"x"}]}}',
+ 0,
+ qr/missing integer timestamp/,
+ ],
+ [
+ 'duplicate timestamp with non-integer value',
+ '{"data":{"data":[{"timestamp":1,"timestamp":"bad","id":"x"}]}}',
+ 0,
+ qr/missing integer timestamp/,
+ ],
+ [
+ 'non-integer timestamp',
+ '{"data":{"data":[{"timestamp":1.5,"id":"x"}]}}',
+ 0,
+ qr/missing integer timestamp/,
+ ],
+ [
+ 'trailing data after empty array',
+ '{"data":{"data":[]}}extra',
+ 0,
+ qr/unexpected trailing data/,
+ ],
+ [
+ 'trailing data after items',
+ '{"data":{"data":[{"timestamp":1}]}}extra',
+ 0,
+ qr/unexpected trailing data/,
+ ],
+ [
+ '>4 KiB trailing gzip payload after ]',
+ memGzip('{"data":{"data":[]}}' . (' ' x 8192)),
+ 1,
+ qr/unexpected trailing data/,
+ ],
+ [
+ 'trailing bytes after Z_STREAM_END',
+ memGzip('{"data":{"data":[]}}') . 'extra',
+ 1,
+ qr/unexpected trailing data after gzip stream/,
+ ],
+ ) {
+ my ($label, $body, $gz, $re) = @$case;
+ my $r;
+ eval {
+ $r = PVE::PullMetricExport::Reader->open(
+ body => $body,
+ gzip => $gz,
+ );
+ while (defined($r->next())) { }
+ };
+ my $err = $@;
+ $r->close() if $r;
+ like($err, $re, "Reader dies on $label");
+ }
+
+ # 6. Early close() releases gzip inflater reference and stops iteration.
+ my $weak_inf;
+ my $inflate_mock = Test::MockModule->new('Compress::Raw::Zlib::Inflate', no_auto => 1);
+ my $orig_new = \&Compress::Raw::Zlib::Inflate::new;
+ $inflate_mock->redefine(
+ new => sub {
+ my ($inf, $st) = $orig_new->(@_);
+ $weak_inf = $inf;
+ weaken($weak_inf) if defined($weak_inf);
+ return ($inf, $st);
+ },
+ );
+ # >64 KiB uncompressed so open() leaves the gzip inflater active until close().
+ my @m1000 = map { make_metric(10 + $_, "qemu/close/$_") } (1 .. 1000);
+ my $r_close = PVE::PullMetricExport::Reader->open(
+ body => make_payload(\@m1000, 1),
+ gzip => 1,
+ );
+ ok(defined($weak_inf), 'Reader holds live inflater while open');
+ ok(defined($r_close->next()), 'Reader yields first item before close');
+ $r_close->close();
+ is($weak_inf, undef, 'Reader->close() immediately releases gzip inflater');
+ is($r_close->next(), undef, 'Reader->next() returns undef after close()');
+ undef $inflate_mock;
+};
+
+subtest 'worker-wide peer concurrency cap across overlapping exports and cancel cleanup' => sub {
+ setup_cluster(10);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::MAX_WORKER_CONCURRENT_PEERS = 6;
+
+ # 1. Three overlapping exports stay <= 6 worker-wide and <= 4 per export.
+ my ($worker_active, $worker_peak, $total_started) = (0, 0, 0);
+ my (%per_export_active, %per_export_peak);
+ my $remaining = 3;
+ my $cv = AnyEvent->condvar;
+ my @streams;
+
+ with_http_mock(
+ sub {
+ my (undef, $url, undef, $cb) = @_;
+ my ($eid) = $url =~ /[?&]start-time=([0-9]+)/;
+ $total_started++;
+ $worker_active++;
+ $worker_peak = $worker_active if $worker_active > $worker_peak;
+ $per_export_active{$eid}++;
+ $per_export_peak{$eid} = $per_export_active{$eid}
+ if $per_export_active{$eid} > ($per_export_peak{$eid} // 0);
+
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $worker_active--;
+ $per_export_active{$eid}--;
+ $cb->(
+ make_payload([make_metric(1000 + $eid, "node/e$eid")], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ for my $eid (1 .. 3) {
+ my $s = MockStream->new(
+ format => 'json',
+ on_finish => sub { $cv->send if --$remaining == 0; },
+ );
+ push @streams, $s;
+ my $async = PVE::API2::Cluster::MetricServer->export({ 'start-time' => $eid });
+ $async->{start}->($s);
+ }
+ $cv->recv;
+ },
+ );
+
+ is($total_started, 30, 'all 30 peer fetches across 3 overlapping exports completed');
+ is($worker_peak, 6,
+ 'worker-wide in-flight peers capped at MAX_WORKER_CONCURRENT_PEERS (6)');
+ for my $eid (1 .. 3) {
+ ok(
+ ($per_export_peak{$eid} // 0) <= 4,
+ "export $eid peak in-flight <= 4 ($per_export_peak{$eid})",
+ );
+ my $parsed = decode_json($streams[$eid - 1]->{buf});
+ is(scalar(@{ $parsed->{data}->{data} }), 10,
+ "export $eid received all 10 peer metrics");
+ }
+
+ # 2. Cancelling a queued overlapping export frees its active slots and drops queued waiters.
+ setup_cluster(6);
+ $local_metrics = [];
+ my ($c_active, $c_peak, $cancelled_e2_started) = (0, 0, 0);
+ my $c_rem = 2;
+ my $cv_c = AnyEvent->condvar;
+ my (@c_streams, @c_cancels);
+ my $e2_cancelled = 0;
+
+ with_http_mock(
+ sub {
+ my (undef, $url, undef, $cb) = @_;
+ my ($eid) = $url =~ /[?&]start-time=([0-9]+)/;
+ $cancelled_e2_started++ if $eid == 2 && $e2_cancelled;
+ $c_active++;
+ $c_peak = $c_active if $c_active > $c_peak;
+ my $done = 0;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.01,
+ cb => sub {
+ undef $t;
+ return if $done;
+ $done = 1;
+ $c_active--;
+ $cb->(
+ make_payload([make_metric(2000 + $eid, "node/c$eid")], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard {
+ undef $t;
+ if (!$done) {
+ $done = 1;
+ $c_active--;
+ }
+ };
+ },
+ sub {
+ for my $eid (1 .. 3) {
+ my $s = MockStream->new(
+ format => 'json',
+ on_finish => sub {
+ $cv_c->send if $eid != 2 && --$c_rem == 0;
+ },
+ );
+ push @c_streams, $s;
+ my $async = PVE::API2::Cluster::MetricServer->export({ 'start-time' => $eid });
+ push @c_cancels, $async->{start}->($s);
+ }
+ # Export 2 holds 2 active slots + 2 queued worker waiters (1 holds 4, 3 holds 4 queued).
+ $e2_cancelled = 1;
+ $c_streams[1]->disconnect($c_cancels[1]);
+ $cv_c->recv;
+ },
+ );
+
+ is($cancelled_e2_started, 0, 'queued worker waiters for cancelled export never started');
+ ok($c_peak <= 6, "worker-wide peak stayed <= 6 after cancel ($c_peak)");
+ is($c_active, 0, 'all worker peer slots cleanly released');
+ for my $idx (0, 2) {
+ my $parsed = decode_json($c_streams[$idx]->{buf});
+ is(
+ scalar(@{ $parsed->{data}->{data} }),
+ 6,
+ "surviving export $idx completed with all 6 peer metrics",
+ );
+ }
+};
+
+subtest 'end-to-end gzip + extjs against real PVE::APIServer::AsyncStream' => sub {
+ {
+
+ package RecordingHandle;
+
+ sub new { return bless { wire => '', wbuf => '', _tls_wbuf => '' }, $_[0]; }
+ sub push_write { $_[0]->{wire} .= $_[1]; }
+ sub wtimeout { }
+ sub wtimeout_reset { }
+ sub timeout { }
+ sub timeout_reset { }
+ sub on_drain { $_[1]->($_[0]) if ref($_[1]) eq 'CODE'; }
+ }
+ {
+
+ package RecordingServer;
+
+ sub new {
+ my ($class, $on_finish) = @_;
+ return bless {
+ compression => 1,
+ timeout => 30,
+ end_loop => 0,
+ logged => 0,
+ finished => 0,
+ aborted => 0,
+ on_finish => $on_finish,
+ }, $class;
+ }
+ sub log_request { $_[0]->{logged}++; }
+
+ sub finish_response {
+ $_[0]->{finished}++;
+ $_[0]->{on_finish}->() if $_[0]->{on_finish};
+ }
+ sub log_aborted_request { $_[0]->{aborted}++; }
+ sub client_do_disconnect { }
+ }
+
+ my $decode_chunked = sub {
+ my ($raw) = @_;
+ my $out = '';
+ my $pos = 0;
+ my $len = length($raw);
+ while ($pos < $len) {
+ my $crlf = index($raw, "\015\012", $pos);
+ return (undef, 'missing chunk size CRLF') if $crlf < 0;
+ my $size_hex = substr($raw, $pos, $crlf - $pos);
+ return (undef, "invalid chunk size '$size_hex'") if $size_hex !~ /^[0-9a-fA-F]+$/;
+ my $size = hex($size_hex);
+ $pos = $crlf + 2;
+ if ($size == 0) {
+ return (undef, 'missing terminating CRLF after 0-chunk')
+ if substr($raw, $pos) ne "\015\012";
+ return ($out, undef);
+ }
+ return (undef, 'truncated chunk body') if $pos + $size + 2 > $len;
+ $out .= substr($raw, $pos, $size);
+ return (undef, 'missing CRLF after chunk payload')
+ if substr($raw, $pos + $size, 2) ne "\015\012";
+ $pos += $size + 2;
+ }
+ return (undef, 'missing terminating 0-chunk');
+ };
+
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ setup_cluster(3);
+ local $stream_format = 'extjs';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 256;
+
+ my $cv = AnyEvent->condvar;
+ my $hdl = RecordingHandle->new();
+ my $srv = RecordingServer->new(sub { $cv->send; });
+ my $reqstate = {
+ hdl => $hdl,
+ accept_gzip => 1,
+ proto => { ver => 1001, str => 'HTTP/1.1' },
+ keep_alive => 1,
+ log => {},
+ request => {},
+ };
+ my $stream = PVE::APIServer::AsyncStream->new(
+ server => $srv,
+ reqstate => $reqstate,
+ format => 'extjs',
+ );
+
+ my $pno = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $p = ++$pno;
+ my @m = map { make_metric(200 + $_ * 3 + $p, "qemu/e2e/$p/$_") } (1 .. 10);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($stream);
+ $cv->recv;
+ },
+ );
+
+ is($srv->{finished}, 1, "$label real AsyncStream called finish_response()");
+ is($srv->{aborted}, 0, "$label real AsyncStream did not abort");
+ my ($hdr_block, $body_raw) = split(/\015\012\015\012/, $hdl->{wire}, 2);
+ like($hdr_block, qr{^HTTP/1\.1 200 OK\015\012}, "$label emitted HTTP/1.1 200 OK");
+ like($hdr_block, qr{^Content-Encoding: gzip\015?$}mi,
+ "$label negotiated gzip encoding");
+ like(
+ $hdr_block,
+ qr{^Transfer-Encoding: chunked\015?$}mi,
+ "$label used HTTP/1.1 chunked framing",
+ );
+
+ my ($gz_body, $chunk_err) = $decode_chunked->($body_raw);
+ is($chunk_err, undef, "$label chunked framing terminated cleanly with 0\\r\\n\\r\\n");
+
+ my ($inf, $st) = Compress::Raw::Zlib::Inflate->new(-WindowBits => WANT_GZIP);
+ my $json_str = '';
+ my $in_copy = $gz_body;
+ my $inf_st = $inf->inflate($in_copy, $json_str);
+ cmp_ok(
+ $inf_st,
+ '==',
+ Z_STREAM_END,
+ "$label gzip stream finalized cleanly (Z_STREAM_END)",
+ );
+ is(length($in_copy), 0, "$label zero trailing bytes after gzip Z_STREAM_END");
+
+ my $parsed = eval { decode_json($json_str) };
+ ok(!$@ && ref($parsed) eq 'HASH', "$label decoded valid JSON envelope");
+ is($parsed->{success}, 1, "$label extjs envelope has success => 1");
+ is(
+ scalar(@{ $parsed->{data}->{data} }),
+ 32,
+ "$label extjs payload contains 2 local + 30 remote metrics",
+ );
+ ok(is_sorted_by_ts($parsed->{data}->{data}), "$label k-way output sorted")
+ if !$unsorted;
+ }
+};
+
+done_testing();
--
2.47.3
next prev parent reply other threads:[~2026-11-30 1:15 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 ` [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-11-30 0:58 ` Thomas Lamprecht [this message]
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-10-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 a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox