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 9A5891FF09F for ; Tue, 01 Dec 2026 11:45:21 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id F308B21680; Tue, 01 Dec 2026 11:45:08 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH manager v2 9/9] test: add pull metric export test suite Date: Tue, 1 Dec 2026 11:19:04 +0100 Message-ID: <20261201101913.1885484-10-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com> References: <20261201101913.1885484-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: 1796120359365 X-SPAM-LEVEL: Spam detection results: 0 AWL -1.001 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) KAM_MAILER 2 Automated Mailer Tag Left in Email 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 X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Hits: max-size X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; news-moderation; no-subject; digests; suspicious-header Message-ID-Hash: JOTYMHKEVC5CURPFPMBNPGLWFYPSMVK2 X-Message-ID-Hash: JOTYMHKEVC5CURPFPMBNPGLWFYPSMVK2 X-Mailman-Approved-At: Tue, 01 Dec 2026 11:45:06 +0100 X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Add test/PullMetricExport_test.pl and wire it into test/Makefile's check target, covering PVE::PullMetricExport, PVE::PullMetricExport::Reader, and PVE::API2::Cluster::MetricServer with mocked peer HTTP transport plus real PVE::APIServer::AsyncStream and loopback PVE::APIServer::AnyEvent dispatch: - Buffered async fan-out: concurrency cap, synchronous callback stacks, IPv6 URI bracketing, node-list deduplication, strict signed 64-bit JSON integer timestamp validation, single-peer request_timeout partial results vs fail-on-error=1 two-scrape cursor recovery, overall_timeout 504 rejection, and CLI CondVar fallback. - Sorted k-way merge and unsorted pass-through streaming: ordering, non-monotonic per-peer timestamp abort, first-read vs subsequent-read corrupt-peer boundaries, /api2/extjs/ envelopes, write backpressure, overall_timeout pre-start 504 vs post-start abort, fail-on-error=1 two-scrape recovery, shared worker limiter gating with can_dispatch backpressure pausing overall_timeout, and worker-wide retained-byte budgeting across overlapping sorted and backpressured pass-through exports. - Direct Reader tests: multi-chunk gzip and whitespace boundaries, duplicate-timestamp rejection, non-integer/integral-float/overflow timestamp rejection, truncated objects and complete oversized objects on both reader paths, trailing-data bounds, and bytes after Z_STREAM_END. - Wire framing against real PVE::APIServer::AsyncStream (gzip + chunked + extjs, keep-alive finish() backpressure deferral, status validation) and loopback PVE::APIServer::AnyEvent::handle_api2_request() dispatch: pipelined keep-alive ordering and disconnect cancel for both streaming and pending buffered AsyncResponse, pre-header strict JSON/ExtJS 502 formatting, custom JSON page formatter fallback, HTTP/1.1 + HTTP/1.0 late stream aborts, and downstream proxy_request() framing for empty and "0" chunked responses. Signed-off-by: Thomas Lamprecht --- Changes in v2: - Add event-driven loopback PVE::APIServer::AnyEvent::handle_api2_request() tests covering pipelined keep-alive ordering with exact chunked and Content-Length response boundaries, client disconnect cancel for both streaming and pending buffered AsyncResponse, pre-header strict JSON/ExtJS 502 formatting, custom JSON page-formatter fallback, mid-stream HTTP/1.1 + HTTP/1.0 late aborts (after flushing HTTP 200 and a metric chunk), and downstream proxy_request() framing (including transfer_encoding underscore-guard coverage) for empty and "0" chunked 200 responses. - Add tests for AsyncStream::finish() keep-alive backpressure deferral, non-reusable wtimeout preservation, and invalid status rejection, inclusive INT64_MIN/INT64_MAX and literal/escaped duplicate-key parity across flat, fallback, and buffered paths, multi-chunk (>200 KiB inflated) boundary-straddling escape fallback Reader scanning, non-timeout 596 -> 502 mapping, bare API token forwarding with '=', ';', and '%', synchronous strict first-peer failure stopping remaining peers, worker-wide retained-byte budgeting across overlapping sorted (verifying oldest-holder admission above budget) and writable-vs- stalled pass-through exports, live inflater verification before disconnect, and history-gated two-scrape fail-on-error=1 cursor recovery. - Fail fast on unexpected stream aborts in MockStream tests and clean up import grouping, call style, line wrapping, and test wording. test/Makefile | 6 +- test/PullMetricExport_test.pl | 3590 +++++++++++++++++++++++++++++++++ 2 files changed, 3595 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..d97fd0d0b --- /dev/null +++ b/test/PullMetricExport_test.pl @@ -0,0 +1,3590 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use lib ('.', '..'); + +use AnyEvent; +use AnyEvent::Handle; +use AnyEvent::Socket qw(tcp_connect); +use AnyEvent::Util; +use Compress::Raw::Zlib qw(WANT_GZIP Z_STREAM_END); +use Compress::Zlib qw(memGzip); +use File::Temp qw(tempfile); +use IO::Socket::INET; +use JSON qw(decode_json encode_json); +use Scalar::Util qw(weaken); +use Test::MockModule; +use Test::More; + +use PVE::APIServer::AnyEvent; +use PVE::APIServer::AsyncStream; +use PVE::APIServer::Formatter; +use PVE::APIServer::Formatter::Standard; + +use PVE::HTTPServer; +use PVE::PullMetricExport; +use PVE::PullMetricExport::Reader; + +use PVE::API2::Cluster::MetricServer; + +{ + + 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}, + fail_cv => $opts{fail_cv}, + 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}; + if ($self->{on_abort}) { + $self->{on_abort}->($self, $err); + } elsif ($self->{fail_cv}) { + $self->{fail_cv}->croak("unexpected stream abort: " . ($err // 'unknown')); + } + } +} + +my sub wait_cv { + my ($cv, $label, $timeout) = @_; + $timeout //= 5; + AnyEvent->now_update(); + my $guard = AnyEvent->timer( + after => $timeout, + cb => sub { $cv->croak("$label timed out after ${timeout}s\n"); }, + ); + return $cv->recv(); +} + +{ + + 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(); }, fail_cv => $cv); + 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 in nondecreasing timestamp order'); + 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(); }, fail_cv => $cv2); + 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(); }, fail_cv => $cv); + 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) + isolating a peer that fails on open or first read. + 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(); }, + fail_cv => $cv_inc, + ); + 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 peer failing on open or first read', + ); + is( + scalar(@{ $inc_parsed->{data}->{data} }), + 200, + 'pass-through kept all 200 healthy metrics', + ); + is(scalar(@syslogs), 1, 'pass-through logged warning for peer failing on open or first read'); + + # 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(); }, + fail_cv => $pt_ts_cv, + ); + 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(); }, + fail_cv => $cv, + ); + 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(); }, + fail_cv => $cv_bp, + ); + 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(); }, + fail_cv => $cv_bad, + ); + + 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 skipped peers failing on open or first read and produced valid output", + ); + my @ids = map { $_->{id} } @{ $parsed->{data}->{data} }; + is_deeply( + \@ids, + ['node/ok'], + "$label skipped malformed objects on open or first read and kept valid output", + ); + is(scalar(@syslogs), 5, "$label logged errors for all 5 peers failing on open or first read"); + + # A trailing comma found after the first successful metric read 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 $live_before_disconnect = 0; + 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 { + $live_before_disconnect = + scalar(grep { defined($_) } @weak_inflaters); + $s->disconnect($cancel) if $s; + $cv_res->send(); + }); + }, + on_finish => sub { $cv_res->send(); }, + on_abort => sub { + $cv_res->croak("unexpected stream abort: " . ($_[1] // 'unknown')); + }, + ); + $weak_stream = $s; + weaken($weak_stream); + + # Exceed one 64 KiB inflate chunk so an active inflater stays live past the + # first slice write when testing mid-stream disconnect cancellation. + my @payload = map { make_metric(100 + $_, "qemu/res/$_") } (1 .. 1000); + 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"); + ok( + $live_before_disconnect > 0, + "$label (cancel) had a live gzip inflater immediately before disconnect", + ) if $action eq 'cancel'; + 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 top-level timestamp keys are rejected instead of forwarding ambiguous wire JSON. + { + eval { + my $r_dup = PVE::PullMetricExport::Reader->open( + body => '{"data":{"data":[{"timestamp":1,"timestamp":2,"id":"x"}]}}', + gzip => 0, + ); + $r_dup->next(); + }; + like($@, qr/duplicate timestamp key/, 'duplicate integer timestamp key rejected'); + } + + # 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/duplicate timestamp key/, + ], + [ + '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; }, + fail_cv => $cv, + ); + push @streams, $s; + my $async = PVE::API2::Cluster::MetricServer->export({ 'start-time' => $eid }); + $async->{start}->($s); + } + wait_cv($cv, 'worker-wide peer cap test'); + }, + ); + + 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; + }, + fail_cv => $cv_c, + ); + push @c_streams, $s; + my $async = PVE::API2::Cluster::MetricServer->export({ 'start-time' => $eid }); + push @c_cancels, $async->{start}->($s); + } + # Export 1 holds four slots and export 2 holds two; exports 2 and 3 each have one pool + # waiting for capacity. + $e2_cancelled = 1; + $c_streams[1]->disconnect($c_cancels[1]); + wait_cv($cv_c, 'worker-wide cancel waiter test'); + }, + ); + + 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 'gzip + extjs wire framing 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; + } + + # Keep-alive finish() defers finish_response() onto on_drain with wtimeout armed when the + # final write crosses buf_size. + { + my $drain_cb; + my @wtimeouts; + my $bp_hdl = bless { + wire => '', + wbuf => '', + _tls_wbuf => '', + }, 'BackpressuredHandle'; + { + no warnings qw(redefine once); + *BackpressuredHandle::push_write = sub { + $_[0]->{wire} .= $_[1]; + $_[0]->{wbuf} .= $_[1]; + }; + *BackpressuredHandle::wtimeout = sub { push @wtimeouts, $_[1]; }; + *BackpressuredHandle::wtimeout_reset = sub { }; + *BackpressuredHandle::timeout = sub { }; + *BackpressuredHandle::timeout_reset = sub { }; + *BackpressuredHandle::on_drain = sub { $drain_cb = $_[1]; }; + } + my $bp_srv = RecordingServer->new(); + my $bp_reqstate = { + hdl => $bp_hdl, + accept_gzip => 0, + proto => { ver => 1001, str => 'HTTP/1.1' }, + keep_alive => 1, + log => {}, + request => {}, + }; + my $bp_stream = PVE::APIServer::AsyncStream->new( + server => $bp_srv, + reqstate => $bp_reqstate, + format => 'json', + buf_size => 16, + ); + ok($bp_stream->start(), 'backpressured finish() test started stream'); + $bp_stream->write('{"data":[{"timestamp":1}]}'); + $bp_stream->finish(); + + is( + $bp_srv->{finished}, + 0, + 'keep-alive finish_response() deferred while final frame exceeds buf_size', + ); + ok(defined($drain_cb), 'keep-alive finish() armed on_drain while backpressured'); + ok( + scalar(grep { $_ && $_ == 30 } @wtimeouts) >= 1, + 'keep-alive finish() armed wtimeout while waiting to drain', + ); + + $bp_hdl->{wbuf} = ''; + $drain_cb->($bp_hdl); + is( + $bp_srv->{finished}, + 1, + 'keep-alive finish_response() ran exactly once after final bytes drained', + ); + is($wtimeouts[-1], 0, 'keep-alive finish() cleared wtimeout on drain'); + } + + # Non-reusable finish() (HTTP/1.0 or Connection: close) keeps a write-only timeout active + # while finish_response() drains queued output so inbound bytes cannot reset the deadline. + { + my (@nr_timeouts, @nr_wtimeouts); + my $nr_hdl = bless { wire => '', wbuf => '', _tls_wbuf => '' }, 'NonReusableHandle'; + { + no warnings qw(redefine once); + *NonReusableHandle::push_write = sub { $_[0]->{wire} .= $_[1]; }; + *NonReusableHandle::timeout = sub { push @nr_timeouts, $_[1]; }; + *NonReusableHandle::timeout_reset = sub { }; + *NonReusableHandle::wtimeout = sub { push @nr_wtimeouts, $_[1]; }; + *NonReusableHandle::wtimeout_reset = sub { }; + *NonReusableHandle::on_drain = sub { }; + } + my $nr_srv = RecordingServer->new(); + my $nr_reqstate = { + hdl => $nr_hdl, + accept_gzip => 0, + proto => { ver => 1001, str => 'HTTP/1.1' }, + keep_alive => 0, + log => {}, + request => {}, + }; + my $nr_stream = PVE::APIServer::AsyncStream->new( + server => $nr_srv, + reqstate => $nr_reqstate, + format => 'json', + ); + ok($nr_stream->start(), 'non-reusable finish() test started stream'); + $nr_stream->write('{"data":[{"timestamp":1}]}'); + $nr_stream->finish(); + + is($nr_srv->{finished}, 1, 'non-reusable finish() called finish_response()'); + is($nr_timeouts[-1], 0, 'non-reusable finish() cleared bidirectional read/write timeout'); + is( + $nr_wtimeouts[-1], + 30, + 'non-reusable finish() kept write-only wtimeout armed during final drain', + ); + } + + # AsyncStream::start() rejects invalid non-3-digit HTTP status values via pre-start abort. + { + my $early_err; + my $bad_hdl = RecordingHandle->new(); + my $bad_srv = RecordingServer->new(); + my $bad_reqstate = { + hdl => $bad_hdl, + accept_gzip => 0, + proto => { ver => 1001, str => 'HTTP/1.1' }, + keep_alive => 1, + log => {}, + request => {}, + }; + my $bad_stream = PVE::APIServer::AsyncStream->new( + server => $bad_srv, + reqstate => $bad_reqstate, + format => 'json', + on_early_error => sub { ($early_err) = @_; }, + ); + is( + $bad_stream->start(status => "200 OK\r\nX-Injected: 1"), + 0, + 'AsyncStream::start() rejected non-3-digit status code', + ); + like($early_err // '', qr/invalid HTTP status code/, 'invalid status triggered early error'); + is($bad_hdl->{wire}, '', 'invalid status wrote zero header bytes to wire'); + } +}; + +subtest 'Reader canonicalization, size cap, and monotonicity invariants' => sub { + # 1. Non-integer, integral-float, and out-of-i64-range timestamps must be rejected on all paths + # (flat Reader, fallback Reader, and buffered decode_peer_metrics). + for my $bad_ts ( + '"42"', + '"0042"', + '1.0', + '1e2', + '1.5', + 'true', + 'null', + '9223372036854775808', + '-9223372036854775809', + '99999999999999999999', + ('9' x 310), + '-' . ('9' x 310), + ) { + my $raw = qq({"data":{"data":[{"id":"vm/1","timestamp":$bad_ts,"value":1}]}}); + eval { + my $r = PVE::PullMetricExport::Reader->open(body => $raw, gzip => 0); + $r->next(); + }; + like($@, qr/missing integer timestamp/, "Reader flat rejects timestamp $bad_ts"); + + my $fb_raw = qq({"data":{"data":[{"id":"vm\\u002f1","timestamp":$bad_ts,"value":1}]}}); + eval { + my $r = PVE::PullMetricExport::Reader->open(body => $fb_raw, gzip => 0); + $r->next(); + }; + like($@, qr/missing integer timestamp/, "Reader fallback rejects timestamp $bad_ts"); + + setup_cluster(1); + local $stream_format = undef; + @syslogs = (); + my $res; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->($raw, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $cv = AnyEvent->condvar(); + my $async = PVE::API2::Cluster::MetricServer->export({}); + $async->{start}->( + sub { $res = $_[0]; $cv->send(); }, sub { $cv->croak($_[0]); }, + ); + $cv->recv(); + }, + ); + is( + scalar(@{ $res->{data} }), + 2, + "buffered decode_peer_metrics rejects peer with timestamp $bad_ts (local only)", + ); + ok( + scalar(grep { /missing integer timestamp/ } @syslogs) >= 1, + "buffered decode_peer_metrics logged rejection for timestamp $bad_ts", + ); + } + + # Both inclusive signed 64-bit endpoints are accepted across flat, fallback, and buffered paths. + for my $edge_ts ( + ['INT64_MIN', '-9223372036854775808', (-9223372036854775807 - 1)], + ['INT64_MAX', '9223372036854775807', 9223372036854775807], + ) { + my ($label, $ts_str, $expected) = @$edge_ts; + for my $variant ( + ['flat', qq({"data":{"data":[{"id":"vm/1","timestamp":$ts_str,"value":1}]}})], + ['fallback', qq({"data":{"data":[{"id":"vm\\u002f1","timestamp":$ts_str,"value":1}]}})], + ) { + my ($vlabel, $raw) = @$variant; + my $r = PVE::PullMetricExport::Reader->open(body => $raw, gzip => 0); + ok(defined($r->next()), "Reader ($vlabel) accepts $label"); + is($r->ts(), $expected, "Reader ($vlabel) decoded exact IV for $label"); + } + + my $raw = qq({"data":{"data":[{"id":"vm/edge","timestamp":$ts_str,"value":1}]}}); + setup_cluster(1); + local $stream_format = undef; + my $res; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->($raw, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $cv = AnyEvent->condvar(); + my $async = PVE::API2::Cluster::MetricServer->export({}); + $async->{start}->( + sub { $res = $_[0]; $cv->send(); }, sub { $cv->croak($_[0]); }, + ); + $cv->recv(); + }, + ); + my ($edge) = grep { $_->{id} eq 'vm/edge' } @{ $res->{data} }; + ok(defined($edge), "buffered decode_peer_metrics accepts $label"); + is($edge->{timestamp}, $expected, "buffered decode_peer_metrics preserves exact $label IV"); + } + + # 2. Duplicate top-level timestamp keys (including escaped forms) are rejected on both + # streaming Reader and buffered decode_peer_metrics; nested keys are allowed. + for my $dup_case ( + [ + 'literal duplicate timestamp', + '{"data":{"data":[{"id":"vm/1","timestamp":1,"timestamp":2,"value":1}]}}', + ], + [ + 'escaped duplicate timestamp', + '{"data":{"data":[{"id":"vm/1","timestamp":1,"time\\u0073tamp":2,"value":1}]}}', + ], + ) { + my ($label, $raw) = @$dup_case; + eval { + my $r = PVE::PullMetricExport::Reader->open(body => $raw, gzip => 0); + $r->next(); + }; + like($@, qr/duplicate timestamp key/, "Reader rejects $label"); + + setup_cluster(1); + local $stream_format = undef; + @syslogs = (); + my $res; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->($raw, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $cv = AnyEvent->condvar(); + my $async = PVE::API2::Cluster::MetricServer->export({}); + $async->{start}->( + sub { $res = $_[0]; $cv->send(); }, sub { $cv->croak($_[0]); }, + ); + $cv->recv(); + }, + ); + is( + scalar(@{ $res->{data} }), + 2, + "buffered decode_peer_metrics rejects $label (local only)", + ); + ok( + scalar(grep { /duplicate timestamp key/ } @syslogs) >= 1, + "buffered decode_peer_metrics logged rejection for $label", + ); + } + + # 3. Multi-chunk gzipped object (>200 KiB after inflation) with an escaped quote straddling + # the 65535/65536 inflate-chunk boundary scans incrementally in one pass. + my $pad_len = 65479; + my $big_val = ('a' x $pad_len) . '\\"' . ('b' x 140_000); + my $expected_big_obj = qq({"id":"vm/big","timestamp":777,"note":"$big_val"}); + my $big_raw = qq({"data":{"data":[$expected_big_obj]}}); + my $big_gz = memGzip($big_raw); + my $big_reader = PVE::PullMetricExport::Reader->open(body => $big_gz, gzip => 1); + my $big_obj = $big_reader->next(); + is($big_reader->ts(), 777, 'multi-chunk gzipped fallback object extracted exact timestamp'); + is( + $big_obj, + $expected_big_obj, + 'multi-chunk gzipped fallback object preserved verbatim across 64 KiB refills', + ); + is($big_reader->next(), undef, 'multi-chunk gzipped fallback object reached clean EOF'); + + my $nested_raw = + '{"data":{"data":[{"nested":{"timestamp":99},"timestamp":2,"id":"vm/1"}]}}'; + my $nested_reader = PVE::PullMetricExport::Reader->open(body => $nested_raw, gzip => 0); + my $nested_out = $nested_reader->next(); + is($nested_reader->ts(), 2, + 'nested timestamp key does not trigger duplicate key rejection'); + is( + $nested_out, + '{"nested":{"timestamp":99},"timestamp":2,"id":"vm/1"}', + 'nested object preserved verbatim', + ); + is($nested_reader->next(), undef, 'nested timestamp reader reaches clean EOF'); + + # 3. Complete objects exceeding MAX_METRIC_OBJECT_BYTES must fail on BOTH fast and fallback paths. + { + local $PVE::PullMetricExport::Reader::MAX_METRIC_OBJECT_BYTES = 1024; + my $big_ascii = 'x' x 1200; + my $big_flat = + qq({"data":{"data":[{"id":"vm/1","timestamp":10,"metric":"$big_ascii","value":1}]}}); + eval { + my $r = PVE::PullMetricExport::Reader->open(body => $big_flat, gzip => 0); + $r->next(); + }; + like( + $@, + qr/metric object exceeds maximum size/, + 'Reader rejects complete oversized object on fast path', + ); + + my $big_fallback = + qq({"data":{"data":[{"id":"vm/1","timestamp":10,"metric":"\\u0078$big_ascii","value":1}]}}); + eval { + my $r = PVE::PullMetricExport::Reader->open(body => $big_fallback, gzip => 0); + $r->next(); + }; + like( + $@, + qr/metric object exceeds maximum size/, + 'Reader rejects complete oversized object on fallback path', + ); + } + + # 4. k-way merge aborts on decreasing timestamps within a peer, while allowing equal timestamps. + setup_cluster(1); + local $stream_format = 'json'; + my $non_mono = make_payload([ + make_metric(50, 'qemu/100', 'cpu'), make_metric(40, 'qemu/100', 'cpu'), + ], 0); + my $ms_bad = MockStream->new(format => 'json'); + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->($non_mono, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $async = PVE::API2::Cluster::MetricServer->export({}); + $async->{start}->($ms_bad); + my $cv = AnyEvent->condvar(); + my $t = AnyEvent->timer(after => 0.05, cb => sub { $cv->send() }); + $cv->recv(); + }, + ); + ok( + defined($ms_bad->{aborted_err}) && $ms_bad->{aborted_err} =~ /non-monotonic/, + 'k-way merge aborts stream when a peer emits decreasing timestamps', + ); + is($ms_bad->{finished}, 0, 'non-monotonic peer stream never closes with success'); + + my $equal_ts = make_payload([ + make_metric(50, 'qemu/100', 'cpu'), make_metric(50, 'qemu/100', 'mem'), + ], 0); + my $ms_eq = MockStream->new(format => 'json'); + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->($equal_ts, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $async = PVE::API2::Cluster::MetricServer->export({}); + $async->{start}->($ms_eq); + my $cv = AnyEvent->condvar(); + my $t = AnyEvent->timer(after => 0.05, cb => sub { $cv->send() }); + $cv->recv(); + }, + ); + is($ms_eq->{finished}, 1, 'k-way merge allows equal consecutive peer timestamps'); + is($ms_eq->{aborted_err}, undef, 'equal consecutive peer timestamps do not abort'); +}; + +subtest 'worker waiter queue rechecks can_dispatch on backpressured unsorted export' => sub { + local $PVE::PullMetricExport::MAX_WORKER_CONCURRENT_PEERS = 2; + local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 16; + + my %started_by_export; + my @pending_cbs; + + with_http_mock( + sub { + my (undef, $url, undef, $cb) = @_; + my $entry = { url => $url, cb => $cb }; + push @pending_cbs, $entry; + return AnyEvent::Util::guard {}; + }, + sub { + # Export 1 holds both worker slots (2 peers). + my $ms1 = MockStream->new(format => 'json'); + my $s1 = PVE::PullMetricExport::build_passthrough_stream( + targets => [ + { name => 'e1-p1', ip => '10.0.1.1', fingerprint => 'AA' }, + { name => 'e1-p2', ip => '10.0.1.2', fingerprint => 'BB' }, + ], + params => { 'local-only' => 1 }, + credentials => {}, + max_concurrent => 2, + ); + $s1->($ms1); + is(scalar(@pending_cbs), 2, 'export 1 filled both worker slots'); + + # Export 2 (unsorted) has 2 local metrics (exceeding 16-byte slice): first write + # succeeds (so start_metric_fanout runs and queues its peer waiter), then the second + # local slice hits write backpressure and registers on_drain before any worker slot frees. + my $ms2 = MockStream->new(format => 'json'); + my $s2 = PVE::PullMetricExport::build_passthrough_stream( + targets => [ + { name => 'e2-p1', ip => '10.0.2.1', fingerprint => 'CC' }, + ], + local_json => make_payload( + [make_metric(1, 'local/e2/1'), make_metric(2, 'local/e2/2')], 0, + ), + params => { 'local-only' => 1 }, + credentials => {}, + overall_timeout => 0.08, + max_concurrent => 2, + ); + my $c2 = $s2->($ms2); + is(scalar(@pending_cbs), 2, 'export 2 peer is queued behind worker cap'); + + # Export 3 queues behind export 2 and stays un-backpressured. + my $ms3 = MockStream->new(format => 'json'); + my $s3 = PVE::PullMetricExport::build_passthrough_stream( + targets => [ + { name => 'e3-p1', ip => '10.0.3.1', fingerprint => 'DD' }, + ], + params => { 'local-only' => 1 }, + credentials => {}, + max_concurrent => 2, + ); + $s3->($ms3); + + # Mark export 2's stream backpressured and let its scheduled second local slice hit + # write backpressure so after_stream_write registers on_drain cleanly. + $ms2->{backpressured} = 1; + { + my $cv = AnyEvent->condvar(); + my $t = AnyEvent->timer(after => 0.03, cb => sub { $cv->send() }); + $cv->recv(); + } + ok( + defined($ms2->{drain_cb}), + 'export 2 entered real backpressure and registered on_drain', + ); + + # Complete export 1's first peer: export 2's waiter MUST stay parked and export 3 MUST run! + my $first = shift @pending_cbs; + $first->{cb}->(make_payload([make_metric(10, 'vm/1')], 0), { Status => 200 }); + + my @urls = map { $_->{url} } @pending_cbs; + ok( + scalar(grep { /10\.0\.3\.1/ } @urls) == 1, + 'export 3 claimed freed worker slot ahead of backpressured export 2', + ); + ok( + scalar(grep { /10\.0\.2\.1/ } @urls) == 0, + 'backpressured export 2 waiter did NOT start while stream was backpressured', + ); + + # Complete remaining export 1 & export 3 peers. + while (my $p = shift @pending_cbs) { + $p->{cb}->(make_payload([make_metric(20, 'vm/2')], 0), { Status => 200 }); + } + is(scalar(@pending_cbs), 0, 'export 2 still parked while backpressured'); + + # Wait past export 2's 0.08s overall_timeout while backpressured: because Pool keeps + # the unadmitted peer in its queue and can_dispatch paused the deadline, export 2 + # must NOT abort solely for waiting on its slow reader! + { + my $wait_cv = AnyEvent->condvar(); + my $wait_t = AnyEvent->timer(after => 0.14, cb => sub { $wait_cv->send() }); + $wait_cv->recv(); + } + is( + $ms2->{aborted_err}, + undef, + 'export 2 did not time out past overall_timeout while backpressured with free worker slot', + ); + + # Clear backpressure on export 2 and fire on_drain: parked waiter wakes immediately! + $ms2->trigger_drain(); + is( + scalar(@pending_cbs), + 1, + 'export 2 parked waiter woke once on_drain cleared backpressure', + ); + like($pending_cbs[0]->{url}, qr/10\.0\.2\.1/, 'woken waiter is export 2 peer'); + my $p2 = shift @pending_cbs; + $p2->{cb}->(make_payload([make_metric(30, 'vm/e2')], 0), { Status => 200 }); + my $cv = AnyEvent->condvar(); + my $t = AnyEvent->timer(after => 0.05, cb => sub { $cv->send() }); + $cv->recv(); + is($ms2->{finished}, 1, 'export 2 completed cleanly after backpressure cleared'); + $c2->(); + }, + ); +}; + +subtest 'HTTP server handle_api2_request dispatch, pipelining, and disconnect cancel' => sub { + { + + package TestAPIServer; + use base qw(PVE::APIServer::AnyEvent); + + sub auth_handler { + return { userid => 'root@pam', ticket => 'PVE:root@pam:test' }; + } + + sub rest_handler { + my ($self, $clientip, $method, $rel_uri, $auth, $params) = @_; + return $self->{_test_rest}->($self, $clientip, $method, $rel_uri, $auth, $params); + } + } + + my @events; + my @pending_peer_cbs; + my $cancel_calls = 0; + + my $sock = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', + LocalPort => 0, + Proto => 'tcp', + Listen => 16, + ReuseAddr => 1, + ) or die "cannot bind test socket: $!\n"; + my $port = $sock->sockport(); + + my ($lockfh, $lockfile) = tempfile(UNLINK => 1); + my $srv = TestAPIServer->new( + socket => $sock, + lockfh => $lockfh, + lockfile => $lockfile, + keep_alive => 5, + timeout => 5, + compression => 0, + base_uri => '/api2', + dirs => {}, + _test_rest => sub { + my ($self, $clientip, $method, $rel_uri, $auth, $params) = @_; + if ($rel_uri eq '/ping') { + push @events, 'ping'; + return { status => 200, data => { pong => 1 } }; + } + push @events, "export:$rel_uri"; + setup_cluster(1); + my $data = PVE::API2::Cluster::MetricServer->export($params); + return { status => 200, data => $data }; + }, + ); + $srv->accept_connections(); + + # Use real PVE::APIServer::AnyEvent::async_stream_supported() / async_supported() here! + $ae_mock->unmock_all(); + + # Case 1: Pipelined keep-alive request #2 (/ping) is held until export #1 completes, and the + # wire response boundary cleanly separates export #1's chunked body from /ping's status line. + { + my $cv = AnyEvent->condvar(); + my $raw = ''; + my $client_hdl; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + push @pending_peer_cbs, $cb; + AE::postpone(sub { + is( + scalar(@events), + 1, + 'pipelined /ping held while streaming export is still pending', + ); + is(scalar(@pending_peer_cbs), 1, 'peer fetch in flight for export #1'); + my $peer_cb = shift @pending_peer_cbs; + push @events, 'peer_done'; + $peer_cb->( + make_payload([make_metric(100, 'qemu/1')], 0), { Status => 200 }, + ); + }); + return AnyEvent::Util::guard { $cancel_calls++; }; + }, + sub { + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { + $raw .= delete $_[0]->{rbuf}; + }, + on_eof => sub { $cv->send(); }, + on_error => sub { $cv->send(); }, + ); + $client_hdl->push_write( + "GET /api2/json/cluster/metrics/export HTTP/1.1\r\nHost: x\r\n\r\n" + . "GET /api2/json/ping HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" + ); + }, + ); + + my $guard_t = AnyEvent->timer( + after => 2, + cb => sub { $cv->croak('pipelined streaming test timed out'); }, + ); + $cv->recv(); + undef $client_hdl; + }, + ); + + is_deeply( + \@events, + ['export:/cluster/metrics/export', 'peer_done', 'ping'], + 'handle_api2_request dispatched export via $res->{data} and ran /ping only after completion', + ); + my ($resp1_hdr, $rest) = split(/\r\n\r\n/, $raw, 2); + like($resp1_hdr, qr{\AHTTP/1\.1 200 OK\r\n}, 'first pipelined response started with 200 OK'); + my $term_idx = index($rest // '', "\r\n0\r\n\r\n"); + cmp_ok($term_idx, '>=', 0, 'first pipelined response ended with terminating 0-chunk'); + my $resp1_body = substr($rest, 0, $term_idx); + my $resp2_raw = substr($rest, $term_idx + length("\r\n0\r\n\r\n")); + like($resp1_body, qr/"qemu\/1"/, 'first response contained streamed remote metric'); + like( + $resp2_raw, + qr{\AHTTP/1\.1 200 OK\r\n.*\r\n\r\n.*"pong":1}s, + 'second pipelined response started cleanly after terminating 0-chunk with /ping body', + ); + } + + # Case 2: Client disconnect mid-fan-out triggers cancel exactly once and releases the server + # connection. + @events = (); + @pending_peer_cbs = (); + $cancel_calls = 0; + { + my $cv = AnyEvent->condvar(); + my $client_hdl; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + push @pending_peer_cbs, $cb; + AE::postpone(sub { + $client_hdl->destroy() if $client_hdl; + undef $client_hdl; + }); + return AnyEvent::Util::guard { + $cancel_calls++; + AE::postpone(sub { $cv->send(); }); + }; + }, + sub { + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { }, + on_error => sub { }, + ); + $client_hdl->push_write( + "GET /api2/json/cluster/metrics/export HTTP/1.1\r\nHost: x\r\n\r\n"); + }, + ); + + my $guard_t = AnyEvent->timer( + after => 2, + cb => sub { $cv->croak('streaming disconnect cancel test timed out'); }, + ); + $cv->recv(); + }, + ); + + is( + $cancel_calls, + 1, + 'client disconnect mid-fan-out cancels in-flight peer exactly once', + ); + is($srv->{conn_count}, 0, 'server conn_count returned to 0 after disconnect'); + } + + # Case 3: Client receives HTTP 200 + first metric chunk, then observes late stream abort + # (HTTP/1.1 lacks terminating 0-chunk; HTTP/1.0 gets transport error / TCP RST). + for my $proto ('HTTP/1.1', 'HTTP/1.0') { + # Force slice 1 to flush the first metric (ts=100, refilling heap with valid ts=110) before + # slice 2 pops ts=110 and hits the decreasing timestamp (ts=50). + local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 1; + my $corrupt_late = + '{"data":{"data":[{"id":"qemu/1","metric":"cpu","timestamp":100,"type":"gauge","value":1},' + . '{"id":"qemu/1","metric":"cpu","timestamp":110,"type":"gauge","value":1},' + . '{"id":"qemu/1","metric":"cpu","timestamp":50,"type":"gauge","value":1}]}}'; + my $raw = ''; + my $err_msg; + my $saw_eof = 0; + my $guard_fired = 0; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->($corrupt_late, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $cv = AnyEvent->condvar(); + my $client_hdl; + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { + $raw .= delete $_[0]->{rbuf}; + }, + on_eof => sub { + $saw_eof = 1; + $cv->send(); + }, + on_error => sub { + $err_msg = $_[2]; + $cv->send(); + }, + ); + $client_hdl->push_write( + "GET /api2/json/cluster/metrics/export $proto\r\nHost: x\r\nConnection: close\r\n\r\n" + ); + }, + ); + my $guard_t = AnyEvent->timer( + after => 2, + cb => sub { + $guard_fired = 1; + $cv->send(); + }, + ); + $cv->recv(); + undef $client_hdl; + }, + ); + ok(!$guard_fired, "$proto late stream abort completed without hitting guard timeout"); + like( + $raw, + qr{\AHTTP/1\.[01] 200 }, + "$proto client observed HTTP 200 response header before late abort", + ); + like($raw, qr/"qemu\/1"/, "$proto client observed first metric chunk before late abort"); + if ($proto eq 'HTTP/1.1') { + unlike( + $raw, + qr/\015\0120\015\012\015\012\z/, + 'HTTP/1.1 late stream abort omits terminating 0-chunk', + ); + } else { + ok( + defined($err_msg) && !$saw_eof, + 'HTTP/1.0 late stream abort ends with transport error (TCP RST), not clean EOF', + ); + } + } + + # Case 4: Pre-header strict fail-on-error=1 unreadable first peer record formats HTTP 502 on + # /api2/json and HTTP 200 with success:0, status:502 on /api2/extjs. + for my $fmt ('json', 'extjs') { + my $raw = ''; + my $guard_fired = 0; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $cb->('{"data":{"data":[{"id":"bad","timestamp":"nope"}]}}', { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $cv = AnyEvent->condvar(); + my $client_hdl; + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { $raw .= delete $_[0]->{rbuf}; }, + on_eof => sub { $cv->send(); }, + on_error => sub { $cv->send(); }, + ); + $client_hdl->push_write( + "GET /api2/$fmt/cluster/metrics/export?fail-on-error=1 HTTP/1.1\r\n" + . "Host: x\r\nConnection: close\r\n\r\n" + ); + }, + ); + my $guard_t = AnyEvent->timer( + after => 2, + cb => sub { $guard_fired = 1; $cv->send(); }, + ); + $cv->recv(); + undef $client_hdl; + }, + ); + ok(!$guard_fired, "pre-header strict $fmt error completed without guard timeout"); + my ($hdr_part, $body_part) = split(/\r\n\r\n/, $raw, 2); + if ($fmt eq 'json') { + like($hdr_part, qr{\AHTTP/1\.1 502 }, 'strict /api2/json peer failure returns HTTP 502'); + } else { + like($hdr_part, qr{\AHTTP/1\.1 200 }, 'strict /api2/extjs peer failure returns HTTP 200'); + my $parsed = eval { decode_json($body_part) }; + is($parsed->{success}, 0, 'strict /api2/extjs response has success: 0'); + is($parsed->{status}, 502, 'strict /api2/extjs response carries status: 502'); + } + } + + # Case 5: A custom JSON page formatter disables async_stream_supported() so MetricServer falls + # back to the deferred buffered AsyncResponse path; verify both pipelined /ping hold and + # client disconnect cancel while the buffered starter is pending. + PVE::APIServer::Formatter::register_page_formatter( + format => 'json', + method => 'GET', + path => '/cluster/metrics/page-export', + code => sub { + my ($res) = @_; + my $count = ref($res->{data}) eq 'HASH' && ref($res->{data}->{data}) eq 'ARRAY' + ? scalar(@{ $res->{data}->{data} }) + : -1; + return (encode_json({ custom_page_count => $count }), 'application/json;charset=UTF-8'); + }, + ); + { + @events = (); + @pending_peer_cbs = (); + my $raw = ''; + my $cv = AnyEvent->condvar(); + my $client_hdl; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + push @pending_peer_cbs, $cb; + AE::postpone(sub { + is( + scalar(@events), + 1, + 'pipelined /ping held while buffered AsyncResponse is pending', + ); + is(scalar(@pending_peer_cbs), 1, 'buffered peer fetch in flight'); + my $peer_cb = shift @pending_peer_cbs; + push @events, 'buffered_peer_done'; + $peer_cb->( + make_payload([make_metric(120, 'qemu/9')], 0), { Status => 200 }, + ); + }); + return AnyEvent::Util::guard {}; + }, + sub { + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { $raw .= delete $_[0]->{rbuf}; }, + on_eof => sub { $cv->send(); }, + on_error => sub { $cv->send(); }, + ); + $client_hdl->push_write( + "GET /api2/json/cluster/metrics/page-export HTTP/1.1\r\nHost: x\r\n\r\n" + . "GET /api2/json/ping HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" + ); + }, + ); + my $guard_t = AnyEvent->timer( + after => 2, + cb => sub { $cv->croak('pending buffered pipelined test timed out'); }, + ); + $cv->recv(); + undef $client_hdl; + }, + ); + is_deeply( + \@events, + ['export:/cluster/metrics/page-export', 'buffered_peer_done', 'ping'], + 'pipelined /ping ran only after pending buffered AsyncResponse resolved', + ); + my ($resp1_hdr, $rest) = split(/\r\n\r\n/, $raw, 2); + like($resp1_hdr, qr{\AHTTP/1\.1 200 OK\r\n}, 'buffered response started with 200 OK'); + my ($cl1) = $resp1_hdr =~ /^Content-Length:\s*(\d+)\r?$/mi; + ok(defined($cl1), 'buffered response declared Content-Length'); + my $resp1_body = substr($rest // '', 0, $cl1 // 0); + my $resp2_raw = substr($rest // '', $cl1 // 0); + is_deeply( + eval { decode_json($resp1_body) }, + { custom_page_count => 3 }, + 'custom JSON page formatter emitted buffered deferred count (2 local + 1 remote)', + ); + like( + $resp2_raw, + qr{\AHTTP/1\.1 200 OK\r\n.*\r\n\r\n.*"pong":1}s, + 'pipelined /ping response started cleanly after buffered Content-Length boundary', + ); + } + + { + @events = (); + @pending_peer_cbs = (); + $cancel_calls = 0; + my $cv = AnyEvent->condvar(); + my $client_hdl; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + push @pending_peer_cbs, $cb; + AE::postpone(sub { + $client_hdl->destroy() if $client_hdl; + undef $client_hdl; + }); + return AnyEvent::Util::guard { + $cancel_calls++; + AE::postpone(sub { $cv->send(); }); + }; + }, + sub { + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { }, + on_error => sub { }, + ); + $client_hdl->push_write( + "GET /api2/json/cluster/metrics/page-export HTTP/1.1\r\nHost: x\r\n\r\n" + ); + }, + ); + my $guard_t = AnyEvent->timer( + after => 2, + cb => sub { $cv->croak('buffered disconnect cancel test timed out'); }, + ); + $cv->recv(); + }, + ); + is( + $cancel_calls, + 1, + 'disconnect while buffered AsyncResponse is pending invokes cancel exactly once', + ); + } + + # Case 6: Downstream proxy_request() framing strips upstream Transfer-Encoding/Trailer, + # prevents underscore normalization of Transfer_Encoding, and frames empty and 1-byte "0" + # decoded chunked 200 bodies with exact Content-Length. + { + no warnings qw(redefine once); + *TestAPIServer::initialize_cert_cache = sub { }; + } + my $proxy_ae_mock = Test::MockModule->new('PVE::APIServer::AnyEvent'); + for my $case (['empty body', '', 0], ['single-byte zero body', '0', 1]) { + my ($label, $upstream_body, $expected_len) = @$case; + my $raw = ''; + my $guard_fired = 0; + $proxy_ae_mock->redefine( + http_request => sub { + my $cb = pop @_; + $cb->( + $upstream_body, + { + Status => 200, + Reason => 'OK', + 'transfer-encoding' => 'chunked', + 'transfer_encoding' => 'chunked', + trailer => 'Expires', + 'content-type' => 'text/plain', + }, + ); + return AnyEvent::Util::guard {}; + }, + ); + local $srv->{_test_rest} = sub { + return { proxy => 'node001', proxynode => 'node001' }; + }; + my $cv = AnyEvent->condvar(); + my $client_hdl; + tcp_connect( + '127.0.0.1', + $port, + sub { + my ($fh) = @_; + $client_hdl = AnyEvent::Handle->new( + fh => $fh, + on_read => sub { $raw .= delete $_[0]->{rbuf}; }, + on_eof => sub { $cv->send(); }, + on_error => sub { $cv->send(); }, + ); + $client_hdl->push_write( + "GET /api2/json/proxy-framing-test HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" + ); + }, + ); + my $guard_t = AnyEvent->timer(after => 2, cb => sub { $guard_fired = 1; $cv->send(); }); + $cv->recv(); + undef $client_hdl; + $proxy_ae_mock->unmock_all(); + + ok(!$guard_fired, "proxy_request() $label completed without guard timeout"); + my ($hdr_part, $body_part) = split(/\r\n\r\n/, $raw, 2); + like($hdr_part, qr{\AHTTP/1\.1 200 OK\r\n}, "proxy_request() $label returned HTTP 200 OK"); + unlike( + $hdr_part, + qr{^Transfer-Encoding:}mi, + "proxy_request() $label stripped Transfer-Encoding and kept transfer_encoding unnormalized", + ); + unlike( + $hdr_part, + qr{^Trailer:}mi, + "proxy_request() $label stripped Trailer", + ); + like( + $hdr_part, + qr{^Content-Length:\s*$expected_len\r?$}mi, + "proxy_request() $label emitted Content-Length: $expected_len", + ); + is($body_part, $upstream_body, "proxy_request() $label preserved exact body bytes"); + } + + undef $srv->{socket_watch}; + close($sock); +}; + +subtest 'fail-on-error=1 two-scrape cursor recovery vs default best-effort' => sub { + # Re-install $ae_mock so buffered/k-way/pass-through paths can be tested cleanly. + $ae_mock->redefine( + async_supported => sub { return 1; }, + async_stream_supported => sub { return defined($stream_format) ? 1 : 0; }, + ); + + # 1. Retrying from cursor 100 returns both recovered remote samples (115 and 120); pass-through + # reports the first failure by aborting the stream. Non-timeout 596 maps to 502 (not 504). + for my $mode ('buffered', 'kway', 'passthrough') { + setup_cluster(2); + local $stream_format = $mode eq 'buffered' ? undef : 'json'; + my $unsorted = $mode eq 'passthrough' ? 1 : 0; + my $cursor = 100; + my $peer2_err; + my $saw_fail_param = 0; + + my $run_scrape = sub { + my ($fail_on_error, $req_cursor) = @_; + $req_cursor //= $cursor; + my ($ok_data, $err_val, $stream_aborted); + with_http_mock( + sub { + my (undef, $url, undef, $cb) = @_; + $saw_fail_param = 1 if $url =~ /fail-on-error/; + if ($url =~ /10\.0\.0\.2/ && defined($peer2_err)) { + $cb->(undef, { Status => 596, Reason => $peer2_err }); + return AnyEvent::Util::guard {}; + } + my ($start_q) = $url =~ /[?&]start-time=(-?\d+)/; + $start_q //= 0; + my ($hist_q) = $url =~ /[?&]history=(\d+)/; + $hist_q //= 0; + my @all_rows; + if ($url =~ /10\.0\.0\.1/) { + @all_rows = (make_metric(120, 'node/node001')); + } else { + # Peer 2 exposes its missed 115 sample only when history=1 is requested, + # alongside its newer latest sample at 130. + push @all_rows, make_metric(115, 'node/node002') if $hist_q; + push @all_rows, make_metric(130, 'node/node002'); + } + my $rows = [grep { $_->{timestamp} > $start_q } @all_rows]; + $cb->(make_payload($rows, 0), { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $handle = PVE::API2::Cluster::MetricServer->export({ + 'start-time' => $req_cursor, + history => 1, + unsorted => $unsorted, + 'fail-on-error' => $fail_on_error, + }); + if ($mode eq 'buffered') { + my $cv = AnyEvent->condvar(); + $handle->{start}->( + sub { $ok_data = $_[0]->{data}; $cv->send(); }, + sub { $err_val = $_[0]; $cv->send(); }, + ); + $cv->recv(); + } else { + my $ms = MockStream->new(format => 'json'); + $handle->{start}->($ms); + my $cv = AnyEvent->condvar(); + my $t = AnyEvent->timer(after => 0.05, cb => sub { $cv->send(); }); + $cv->recv(); + if ($ms->{finished}) { + my $parsed = decode_json($ms->{buf}); + $ok_data = $parsed->{data}->{data}; + } else { + $err_val = $ms->{aborted_err}; + $stream_aborted = 1; + } + } + }, + ); + return ($ok_data, $err_val, $stream_aborted); + }; + + # Scrape 1 with fail-on-error=1: peer2 timeout fails export (504) so cursor stays at 100. + $peer2_err = 'Request timed out'; + my ($d1, $e1, $ab1) = $run_scrape->(1); + is($d1, undef, "$mode fail-on-error=1 scrape 1 did not return partial 200"); + ok(defined($e1), "$mode fail-on-error=1 scrape 1 reported peer timeout error"); + if ($mode ne 'passthrough') { + isa_ok($e1, 'PVE::Exception'); + is($e1->{code}, 504, "$mode fail-on-error=1 peer timeout sets exception code 504"); + } else { + ok($ab1, 'passthrough fail-on-error=1 peer timeout aborted in-progress stream'); + } + + # Non-timeout 596 (e.g. TLS verification failure) must set exception code 502, not 504. + if ($mode ne 'passthrough') { + $peer2_err = 'TLS certificate verify failed'; + my ($d_tls, $e_tls) = $run_scrape->(1); + is($d_tls, undef, "$mode fail-on-error=1 non-timeout 596 did not return 200"); + isa_ok($e_tls, 'PVE::Exception'); + is( + $e_tls->{code}, + 502, + "$mode fail-on-error=1 non-timeout 596 sets exception code 502", + ); + } + + # Scrape 2 after peer2 recovers with unchanged cursor=100: recovers both 115 (history) and + # 130 (latest) from peer2 alongside 120 from peer1. + $peer2_err = undef; + my ($d2, $e2) = $run_scrape->(1, 100); + is($e2, undef, "$mode fail-on-error=1 scrape 2 succeeded after peer2 recovered"); + my %ts_list_by_id; + push @{ $ts_list_by_id{ $_->{id} } }, $_->{timestamp} for @$d2; + is_deeply( + [sort { $a <=> $b } @{ $ts_list_by_id{'node/node001'} // [] }], + [120], + "$mode scrape 2 collected node001 sample at ts 120", + ); + is_deeply( + [sort { $a <=> $b } @{ $ts_list_by_id{'node/node002'} // [] }], + [115, 130], + "$mode scrape 2 recovered node002 history sample at ts 115 and latest at ts 130", + ); + + # Advancing cursor to 130 omits already-collected <=130 samples. + my ($d_adv, $e_adv) = $run_scrape->(1, 130); + is($e_adv, undef, "$mode scrape from cursor 130 succeeded"); + my %adv_ids = map { $_->{id} => 1 } @$d_adv; + ok( + !$adv_ids{'node/node001'} && !$adv_ids{'node/node002'}, + "$mode scrape from cursor 130 omits <=130 samples", + ); + + # Default fail-on-error=0 still preserves best-effort partial 200 when peer2 times out. + $peer2_err = 'Request timed out'; + my ($d3, $e3) = $run_scrape->(0, 100); + is($e3, undef, "$mode default fail-on-error=0 preserves best-effort partial 200"); + my %ids3 = map { $_->{id} => 1 } @$d3; + ok( + $ids3{'node/node001'} && !$ids3{'node/node002'}, + "$mode best-effort returned healthy peer1", + ); + is( + $saw_fail_param, + 0, + "$mode never forwards fail-on-error to remote local-only=1 peers", + ); + } + + # 2. Forwarded bare API tokens with '=', ';', or '%' in the user ID are URI-escaped. + setup_cluster(1); + local $stream_format = undef; + local $mock_rpcenv->{credentials} = { api_token => 'cn=alice;bob%20@ldap!tok=secret' }; + my $seen_auth; + with_http_mock( + sub { + my (undef, undef, $opts, $cb) = @_; + $seen_auth = $opts->{headers}->{authorization}; + $cb->(make_payload([make_metric(120, 'node/node001')], 0), { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $cv = AnyEvent->condvar(); + my $async = PVE::API2::Cluster::MetricServer->export({}); + $async->{start}->(sub { $cv->send(); }, sub { $cv->croak($_[0]); }); + $cv->recv(); + }, + ); + is( + $seen_auth, + 'PVEAPIToken=cn%3Dalice%3Bbob%2520%40ldap%21tok%3Dsecret', + 'PullMetricExport prefixes and URI-escapes bare API tokens with =, ;, and %', + ); + + # 3. A synchronous strict failure on peer 1 inside Pool::start() stops remaining peers from + # being started across buffered, k-way, and pass-through modes. + for my $mode ('buffered', 'kway', 'passthrough') { + setup_cluster(5); + local $stream_format = $mode eq 'buffered' ? undef : 'json'; + my $unsorted = $mode eq 'passthrough' ? 1 : 0; + my $started = 0; + with_http_mock( + sub { + my (undef, undef, undef, $cb) = @_; + $started++; + $cb->(undef, { Status => 596, Reason => 'TLS certificate verify failed' }); + return AnyEvent::Util::guard {}; + }, + sub { + my $handle = PVE::API2::Cluster::MetricServer->export({ + unsorted => $unsorted, + 'fail-on-error' => 1, + }); + if ($mode eq 'buffered') { + my $cv = AnyEvent->condvar(); + $handle->{start}->(sub { $cv->send(); }, sub { $cv->send(); }); + $cv->recv(); + } else { + my $ms = MockStream->new(format => 'json'); + $handle->{start}->($ms); + } + }, + ); + is( + $started, + 1, + "$mode synchronous strict first-peer failure leaves remaining peers unstarted", + ); + } +}; + +subtest 'worker-wide retained-byte budget across overlapping exports' => sub { + my $big_payload = make_payload( + [map { make_metric(100 + $_, "qemu/$_") } (1 .. 40)], + 0, + ); + cmp_ok(length($big_payload), '>', 1024, 'test peer payload exceeds small retained-byte budget'); + + # 1. Overlapping sorted k-way exports with concurrency 1 per export and a 1 KiB budget: + # export 1 starts only peer 1, crosses the threshold on peer 1's response, then must still + # admit peer 2 above budget via the oldest-holder exemption (preventing self-deadlock), + # while export 2 stays at 0 started peers until export 1 drains and frees its retained bytes. + { + setup_cluster(2); + local $stream_format = 'json'; + local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 1; + local $PVE::PullMetricExport::MAX_WORKER_RETAINED_BYTES = 1024; + + my %started_by_export = (1 => 0, 2 => 0); + my @e1_cbs; + my @e2_cbs; + my $cv = AnyEvent->condvar(); + my $e1_done = 0; + my $e2_done = 0; + my $e1_started_over_budget; + my $e2_started_while_e1_held; + + with_http_mock( + sub { + my (undef, $url, undef, $cb) = @_; + my ($eid) = $url =~ /start-time=(\d+)/; + $started_by_export{$eid}++; + if ($eid == 1) { + push @e1_cbs, $cb; + } else { + push @e2_cbs, $cb; + } + return AnyEvent::Util::guard {}; + }, + sub { + my $s1 = MockStream->new( + format => 'json', + on_finish => sub { + $e1_done = 1; + $cv->send() if $e1_done && $e2_done; + }, + on_abort => sub { + $cv->croak("unexpected e1 abort: " . ($_[1] // 'unknown')); + }, + ); + my $s2 = MockStream->new( + format => 'json', + on_finish => sub { + $e2_done = 1; + $cv->send() if $e1_done && $e2_done; + }, + on_abort => sub { + $cv->croak("unexpected e2 abort: " . ($_[1] // 'unknown')); + }, + ); + + my $h1 = PVE::API2::Cluster::MetricServer->export({ 'start-time' => 1 }); + $h1->{start}->($s1); + is($started_by_export{1}, 1, 'export 1 started only peer 1 under concurrency cap 1'); + + # Deliver export 1 peer 1 (> 1 KiB budget): oldest-holder exception admits peer 2. + (shift @e1_cbs)->($big_payload, { Status => 200 }); + $e1_started_over_budget = $started_by_export{1}; + + # Start export 2 while export 1 retains peer 1 above budget: export 2 must stay at 0. + my $h2 = PVE::API2::Cluster::MetricServer->export({ 'start-time' => 2 }); + $h2->{start}->($s2); + $e2_started_while_e1_held = $started_by_export{2}; + + # Finish export 1 peer 2: export 1 drains and wakes export 2. + (shift @e1_cbs)->($big_payload, { Status => 200 }); + + my $drive; + $drive = AnyEvent->timer( + after => 0.01, + interval => 0.01, + cb => sub { + while (my $cb = shift @e2_cbs) { + $cb->($big_payload, { Status => 200 }); + } + undef $drive if $e1_done && $e2_done; + }, + ); + my $guard = AnyEvent->timer( + after => 2, + cb => sub { $cv->croak('retained-byte budget k-way test timed out'); }, + ); + $cv->recv(); + }, + ); + + is( + $e1_started_over_budget, + 2, + 'oldest all-peers holder admitted peer 2 while already over worker byte budget', + ); + is( + $e2_started_while_e1_held, + 0, + 'export 2 held at 0 started peers while export 1 retained bodies above worker byte budget', + ); + is($e1_done, 1, 'export 1 finished without self-deadlock despite exceeding budget'); + is($e2_done, 1, 'export 2 woke and completed once export 1 drained its retained bodies'); + is($started_by_export{2}, 2, 'export 2 fetched both peers after waking'); + } + + # 2. Worker-wide byte accounting across overlapping pass-through exports: export 1 (stalled on + # downstream write backpressure) retains a > 1 KiB peer body, which must hold a second, + # un-backpressured writable export 2 at 0 started peers despite free worker peer slots + # until export 1 drains and releases its retained bytes. + { + setup_cluster(1); + $local_metrics = []; + local $stream_format = 'json'; + local $PVE::PullMetricExport::MAX_WORKER_RETAINED_BYTES = 1024; + local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128; + + my %started = (10 => 0, 20 => 0); + my ($e1_done, $e2_done) = (0, 0); + my ($e1_drain_armed, $e2_started_while_e1_retained) = (0, undef); + my $cv_pt = AnyEvent->condvar(); + + with_http_mock( + sub { + my (undef, $url, undef, $cb) = @_; + my ($eid) = $url =~ /start-time=(\d+)/; + $started{$eid}++; + $cb->($big_payload, { Status => 200 }); + return AnyEvent::Util::guard {}; + }, + sub { + my $s1 = MockStream->new( + format => 'json', + bp_after_bytes => 64, + on_finish => sub { + $e1_done = 1; + $cv_pt->send() if $e1_done && $e2_done; + }, + on_abort => sub { + $cv_pt->croak("unexpected pt e1 abort: " . ($_[1] // 'unknown')); + }, + ); + my $s2 = MockStream->new( + format => 'json', + on_finish => sub { + $e2_done = 1; + $cv_pt->send() if $e1_done && $e2_done; + }, + on_abort => sub { + $cv_pt->croak("unexpected pt e2 abort: " . ($_[1] // 'unknown')); + }, + ); + + my $h1 = PVE::API2::Cluster::MetricServer->export({ + unsorted => 1, + 'start-time' => 10, + }); + $h1->{start}->($s1); + + # Start writable export 2 while export 1 retains peer 1's > 1 KiB body. + my $h2 = PVE::API2::Cluster::MetricServer->export({ + unsorted => 1, + 'start-time' => 20, + }); + $h2->{start}->($s2); + + my $t = AnyEvent->timer( + after => 0.02, + cb => sub { + $e1_drain_armed = defined($s1->{drain_cb}) ? 1 : 0; + $e2_started_while_e1_retained = $started{20}; + $s1->{bp_after_bytes} = 10_000_000; + $s1->trigger_drain(); + }, + ); + my $guard = AnyEvent->timer( + after => 2, + cb => sub { $cv_pt->croak('retained-byte budget pass-through test timed out'); }, + ); + $cv_pt->recv(); + }, + ); + is($e1_drain_armed, 1, 'slow pass-through export 1 stalled a write and armed drain_cb'); + is( + $e2_started_while_e1_retained, + 0, + 'writable export 2 held at 0 started peers despite free worker slots while export 1 exceeded byte budget', + ); + is($e1_done, 1, 'pass-through export 1 completed cleanly after trigger_drain()'); + is($e2_done, 1, 'pass-through export 2 woke and completed once export 1 released bytes'); + is($started{20}, 1, 'pass-through export 2 fetched its peer after waking'); + } +}; + +done_testing(); -- 2.47.3