* [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export
@ 2026-12-01 10:18 Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
` (8 more replies)
0 siblings, 9 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:18 UTC (permalink / raw)
To: pve-devel
GET /cluster/metrics/export runs inside the pveproxy worker handling
the request and is polled regularly by Proxmox Datacenter Manager (PDM)
via /api2/extjs/cluster/metrics/export (often with history=1) as well
as external /api2/json/ and pvesh consumers.
Today, the endpoint fetches every remote cluster node serially with
blocking PVE::APIClient::LWP calls, stalling the worker event loop for
all other clients while waiting on peer responses. On larger clusters
or history scrapes, decoding all remote metrics into Perl hashes before
sorting and compressing also drives worker memory into gigabytes and
blocks the loop during JSON encoding and gzip compression.
This series replaces the synchronous serial fan-out with non-blocking
concurrent peer fetches and incremental streaming responses across three
repositories:
- pve-http-server (patches 1-3): add deferred async and incremental
streaming API2 responses (PVE::APIServer::AsyncStream) with on-the-fly
compression and backpressure, plus chunked proxy response framing
fixes.
- pve-apiclient (patches 4-5): add PVE::APIClient::AnyEvent as a
non-blocking counterpart to LWP.pm with fingerprint pinning and raw
body access, plus a bounded-concurrency request pool
(PVE::APIClient::AnyEvent::Pool) with separate backpressure and
capacity gates.
- pve-manager (patches 6-9): switch GET /cluster/metrics/export to
bounded async fan-out (16 peers per export, 32 per worker), add an
opt-in fail-on-error=1 option to fail on online peer fetch/read
errors, stream timestamp-sorted metrics incrementally without
decoding each metric into Perl hashes, add an opt-in unsorted=1
pass-through streaming mode, and add a test suite.
Default unsorted=0 preserves the existing global timestamp order and
/api2/extjs/ envelope, so existing PDM and API clients benefit without
changes. Rolling cluster upgrades work in any node order because peer
fetches continue calling GET /api2/json/cluster/metrics/export with
local-only=1.
Changes in v2 (see individual patches for full per-patch changelogs):
- pve-http-server: harden proxy header framing and HTTP 205 handling,
verify the selected formatter in async_stream_supported(), validate
status codes and compressor init in AsyncStream::start(), gate final
keep-alive reuse on write backpressure, preserve write-only wtimeout
on non-reusable final drain, and document the async/streaming
contracts.
- pve-apiclient: tighten TLS peername/fingerprint verification, anchor
HTTP method validation with \A...\z, encode bare API tokens for
PVE/PBS/PDM schemes (keeping literal TOKENID: for PBS/PDM and
URI-escaping bare PVE tokens with '=', ';', or '%'), report ExtJS
success: 0 via on_error in get()/post()/put()/delete() while call()
still delivers the full envelope to on_response, add a shared
exception-isolated Pool capacity limiter with re-entrant wake safety
and distinct capacity/backpressure timeout semantics, and enforce
monotonic timeout expiration in resume_timeout().
- pve-manager: wire the worker-wide peer cap through Pool's shared
limiter and add a deadlock-free 128 MiB retained-byte dispatch
admission threshold, add opt-in fail-on-error=1 with API 504/502 error
mapping, unify wire-level signed 64-bit integer timestamp and
duplicate-key validation across buffered and streaming paths with
incremental multi-chunk scanning and monotonicity aborts, refine
endpoint docs, and expand loopback, proxy-framing, wire-abort,
formatter, budget, and recovery tests.
Measured on a single pveproxy worker in a mock harness (25 ms per-peer
latency, TLS with SHA-256 pinning, gzip, 16-peer cap; scenarios are
nodes x guests, hist10 = 10 history generations; Max /ping HOL =
maximum concurrent /ping latency on the same worker):
Scenario | Mode | Total | TTFB | VmHWM | Max /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | Sync LWP | 1034ms | - | 106 MiB | 1024 ms
(25,475 metrics) | K-way stream | 196ms | 114ms | 84 MiB | 5.0 ms
| Pass-through | 147ms | 2.0ms | 82 MiB | 8.0 ms
25x100 hist10 | Sync LWP | 2302ms | - | 338 MiB | 2354 ms
(254,750 metrics) | K-way stream | 871ms | 123ms | 99 MiB | 9.4 ms
| Pass-through | 761ms | 6.2ms | 93 MiB | 6.0 ms
100x100 latest | Sync LWP | 4195ms | - | 180 MiB | 4178 ms
(101,900 metrics) | K-way stream | 687ms | 399ms | 91 MiB | 7.3 ms
| Pass-through | 445ms | 2.1ms | 82 MiB | 9.5 ms
100x1000 | Buffered | 5.1 s | - | 973 MiB | -
(1,001,900 metrics) | K-way stream | 3296ms | 397ms | 103 MiB | 9.5 ms
| Pass-through | 2955ms | 5.3ms | 94 MiB | 8.6 ms
Repo (build-)dependencies:
pve-manager -> pve-http-server, pve-apiclient
pve-http-server and pve-apiclient are independent of each other and must
both be released before pve-manager, with pve-manager's Build-Depends
and Depends bumped to the resulting package versions on apply.
pve-http-server:
Thomas Lamprecht (3):
response: support deferred async API2 responses
proxy: strip chunked framing headers from decoded responses
response: support incremental streaming API2 responses
src/Makefile | 1 +
src/PVE/APIServer/AnyEvent.pm | 375 +++++++++++++++++++++++++++++++----
src/PVE/APIServer/AsyncStream.pm | 411 +++++++++++++++++++++++++++++++++++++++
3 files changed, 749 insertions(+), 38 deletions(-)
pve-apiclient:
Thomas Lamprecht (2):
add non-blocking AnyEvent API client
add bounded AnyEvent request pool with backpressure and timeout
Makefile | 4 +
debian/control | 12 +-
src/Makefile | 8 +-
src/PVE/APIClient/AnyEvent.pm | 574 +++++++++++
src/PVE/APIClient/AnyEvent/Pool.pm | 444 ++++++++
src/test/anyevent_client.t | 1974 ++++++++++++++++++++++++++++++++++++
src/test/anyevent_pool.t | 995 ++++++++++++++++++
7 files changed, 4009 insertions(+), 2 deletions(-)
pve-manager:
Thomas Lamprecht (4):
api: metrics export: fetch remote nodes asynchronously
api: metrics export: stream sorted metrics via incremental k-way merge
api: metrics export: add unsorted pass-through streaming option
test: add pull metric export test suite
PVE/API2/Cluster/MetricServer.pm | 141 +-
PVE/Makefile | 3 +-
PVE/PullMetricExport.pm | 1014 +++++++++++
PVE/PullMetricExport/Makefile | 15 +
PVE/PullMetricExport/Reader.pm | 396 +++++
test/Makefile | 6 +-
test/PullMetricExport_test.pl | 3590 ++++++++++++++++++++++++++++++++++++++
7 files changed, 5121 insertions(+), 44 deletions(-)
--
2.47.3
^ permalink raw reply [flat|nested] 10+ messages in thread
* [PATCH http-server v2 1/9] response: support deferred async API2 responses
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
@ 2026-12-01 10:18 ` Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
` (7 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:18 UTC (permalink / raw)
To: pve-devel
API2 handlers currently return synchronously from rest_handler(). An
endpoint that performs remote I/O therefore blocks the event loop of
the pveproxy worker handling the request until every outbound request
has finished. One example is /cluster/metrics/export, which Proxmox
Datacenter Manager (PDM) and external monitoring scrape periodically
and which queries every other online cluster node in turn.
Allow rest_handler() to return a deferred response via async_response()
in $res->{data} when async_supported() is true, unblocking workers
without forking per request and working uniformly across API server
subclasses. While pending, the server disables the inactivity timeout,
keeps EOF detection active on plain and TLS sockets, holds pipelined
keep-alive requests until completion, and runs the starter's cancel
callback on client disconnect. OpenSSL's error queue and AnyEvent's
clock are refreshed around starter and completion callbacks so outbound
TLS work cannot abort the client connection or skew timeouts.
Trade-offs: the server enforces no global async deadline, so handlers
must bound their own wait (for example a 60 s fan-out timeout), and a
client half-close cancels the in-flight handler immediately rather than
running to completion as a synchronous handler would.
In a single-worker TLS benchmark harness for a 16-node pull-metric
fan-out, moving to async cut total export time from 486 ms to 84 ms
with uniform 25 ms peer latency, and dropped concurrent /ping tail
latency on the same worker from 1,137 ms to 2.1 ms when one peer took
600 ms.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Document deadline ownership and disconnect-cancellation contract on
async_response().
src/PVE/APIServer/AnyEvent.pm | 256 +++++++++++++++++++++++++++++-----
1 file changed, 223 insertions(+), 33 deletions(-)
diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm
index b4d3f21..fa4076d 100644
--- a/src/PVE/APIServer/AnyEvent.pm
+++ b/src/PVE/APIServer/AnyEvent.pm
@@ -54,6 +54,21 @@ my $limit_max_header_size = 8 * 1024;
my $limit_max_post = 512 * 1024;
my $limit_max_request_line = 64 * 1024;
+my $ASYNC_SUPPORTED = 0;
+
+sub async_supported {
+ return $ASYNC_SUPPORTED;
+}
+
+# Wrap a deferred API2 response starter: sub ($resolve, $reject) -> optional cancel coderef.
+# The server disables its inactivity timeout while waiting; the starter must bound its own wait
+# and may return a cancel callback invoked on client disconnect.
+sub async_response {
+ my ($starter) = @_;
+ die "async_response requires a CODE ref\n" if ref($starter) ne 'CODE';
+ return bless { start => $starter }, 'PVE::APIServer::AnyEvent::AsyncResponse';
+}
+
my $known_methods = {
GET => 1,
POST => 1,
@@ -147,6 +162,13 @@ sub client_do_disconnect {
return if $reqstate->{disconnected};
$reqstate->{disconnected} = 1;
+ if (my $on_disconnect = delete $reqstate->{on_disconnect}) {
+ eval { $on_disconnect->(); };
+ warn $@ if $@;
+ # HACK: see Note 1
+ Net::SSLeay::ERR_clear_error();
+ }
+
cleanup_reqstate($reqstate, 1);
my $shutdown_hdl = sub {
@@ -1025,6 +1047,184 @@ sub extract_params {
return $params;
}
+my sub prepare_async_handle {
+ my ($reqstate) = @_;
+
+ return 0 if !$reqstate->{hdl};
+
+ # Disable the inactivity timeout while waiting (also covers callers bypassing handle_request()).
+ # Keep an empty on_read callback so plain sockets still detect client EOF while holding any
+ # pipelined request until this response finishes.
+ $reqstate->{hdl}->timeout(0);
+ $reqstate->{hdl}->on_read(sub { });
+
+ return $reqstate->{hdl} ? 1 : 0;
+}
+
+my sub set_error_result {
+ my ($res, $err) = @_;
+
+ delete $res->{data};
+ delete $res->{total};
+ delete $res->{changes};
+ if (ref($err) eq 'PVE::Exception') {
+ $res->{status} = $err->{code} || HTTP_INTERNAL_SERVER_ERROR;
+ $res->{errors} = $err->{errors} if $err->{errors};
+ $res->{message} = $err->{msg};
+ } else {
+ $res->{status} = HTTP_INTERNAL_SERVER_ERROR;
+ $res->{message} = defined($err) ? "$err" : 'internal server error';
+ }
+}
+
+my sub run_async_starter {
+ my ($label, $state, $starter, $on_error) = @_;
+
+ my $cb = eval { $starter->() };
+ my $err = $@;
+
+ # HACK: see Note 1
+ Net::SSLeay::ERR_clear_error();
+ AnyEvent->now_update();
+
+ if ($err) {
+ if ($state->{finished}) {
+ warn "$label starter died after completion: $err";
+ } else {
+ $on_error->($err);
+ }
+ } elsif ($state->{disconnected} || $state->{aborted}) {
+ if (ref($cb) eq 'CODE') {
+ eval { $cb->(); };
+ warn $@ if $@;
+ Net::SSLeay::ERR_clear_error();
+ }
+ } elsif (!$state->{finished}) {
+ if (ref($cb) eq 'CODE') {
+ $state->{cancel} = $cb;
+ } elsif (defined($cb)) {
+ warn "$label starter returned non-CODE cancel value\n";
+ }
+ }
+}
+
+my sub finish_api2_request {
+ my ($self, $reqstate, $res, $formatter, $params, $path, $auth) = @_;
+
+ eval {
+ my $delay = 0;
+ if (($res->{status} // 0) == HTTP_UNAUTHORIZED) {
+ # always delay unauthorized calls by 3 seconds
+ $delay = 3 - tv_interval($reqstate->{starttime});
+ $delay = 0 if $delay < 0;
+ }
+
+ my $download;
+ $download = $res->{data}->{download}
+ if defined($res->{data}) && ref($res->{data}) eq 'HASH';
+ if (defined($download)) {
+ # TODO: remove ->{download} with PVE 9.0
+ if (
+ $res->{info}
+ && ($res->{info}->{download_allowed} || $res->{info}->{download})
+ ) {
+ send_file_start($self, $reqstate, $download);
+ return;
+ } else {
+ warn "Download attempted for non-marked API endpoint '$path'\n";
+ }
+ }
+
+ my ($raw, $ct, $nocomp) = $formatter->(
+ $res, $res->{data}, $params, $path, $auth, $self->{formatter_config},
+ );
+
+ my $resp;
+ if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
+ $resp = $raw;
+ } else {
+ $resp = HTTP::Response->new($res->{status}, $res->{message});
+ $resp->header("Content-Type" => $ct);
+ $resp->content($raw);
+ }
+ $self->response($reqstate, $resp, undef, $nocomp, $delay);
+ };
+ if (my $err = $@) {
+ $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, $err)
+ if $reqstate->{hdl};
+ }
+}
+
+my sub start_async_response {
+ my ($self, $reqstate, $async, $res, $finish) = @_;
+
+ if (
+ ref($async) ne 'PVE::APIServer::AnyEvent::AsyncResponse'
+ || ref($async->{start}) ne 'CODE'
+ ) {
+ die "invalid async response\n";
+ }
+
+ return if !prepare_async_handle($reqstate);
+
+ my $state = {
+ finished => 0,
+ disconnected => 0,
+ cancel => undef,
+ reqstate => $reqstate,
+ res => $res,
+ finish => $finish,
+ };
+
+ my $complete = sub {
+ my ($cb) = @_;
+ return if $state->{finished};
+ $state->{finished} = 1;
+
+ my ($rs, $r_res, $finish_cb) = delete $state->@{qw(reqstate res finish cancel)};
+
+ delete $rs->{on_disconnect};
+ return if !$rs->{hdl};
+
+ # HACK: see Note 1
+ Net::SSLeay::ERR_clear_error();
+ AnyEvent->now_update();
+
+ $cb->($r_res, $finish_cb);
+ };
+
+ my $resolve = sub {
+ my ($data) = @_;
+ $complete->(sub {
+ my ($r_res, $finish_cb) = @_;
+ $r_res->{status} //= HTTP_OK;
+ $r_res->{data} = $data;
+ $finish_cb->($r_res);
+ });
+ };
+
+ my $reject = sub {
+ my ($err) = @_;
+ $complete->(sub {
+ my ($r_res, $finish_cb) = @_;
+ set_error_result($r_res, $err);
+ $finish_cb->($r_res);
+ });
+ };
+
+ $reqstate->{on_disconnect} = sub {
+ return if $state->{finished};
+ $state->{finished} = 1;
+ $state->{disconnected} = 1;
+ my ($cb) = delete $state->@{qw(cancel reqstate res finish)};
+ $cb->() if ref($cb) eq 'CODE';
+ };
+
+ run_async_starter(
+ 'async_response', $state, sub { $async->{start}->($resolve, $reject) }, $reject,
+ );
+}
+
sub handle_api2_request {
my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
@@ -1058,13 +1258,27 @@ sub handle_api2_request {
my $clientip = $reqstate->{peer_host};
- my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
+ my $res = do {
+ my $prev_async = $ASYNC_SUPPORTED;
+ my $guard = guard { $ASYNC_SUPPORTED = $prev_async };
+ $ASYNC_SUPPORTED = 1;
+ $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
+ };
# HACK: see Note 1
Net::SSLeay::ERR_clear_error();
AnyEvent->now_update(); # in case somebody called sleep()
+ if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncResponse') {
+ my $async = delete $res->{data};
+ my $finish = sub {
+ finish_api2_request($self, $reqstate, $_[0], $formatter, $params, $path, $auth);
+ };
+ start_async_response($self, $reqstate, $async, $res, $finish);
+ return;
+ }
+
my $upgrade = $r->header('upgrade');
$upgrade = lc($upgrade) if $upgrade;
@@ -1111,38 +1325,7 @@ sub handle_api2_request {
}
}
- my $delay = 0;
- if ($res->{status} == HTTP_UNAUTHORIZED) {
- # always delay unauthorized calls by 3 seconds
- $delay = 3 - tv_interval($reqstate->{starttime});
- $delay = 0 if $delay < 0;
- }
-
- my $download;
- $download = $res->{data}->{download}
- if defined($res->{data}) && ref($res->{data}) eq 'HASH';
- if (defined($download)) {
- # TODO: remove ->{download} with PVE 9.0
- if ($res->{info}->{download_allowed} || $res->{info}->{download}) {
- send_file_start($self, $reqstate, $download);
- return;
- } else {
- warn "Download attempted for non-marked API endpoint '$path'\n";
- }
- }
-
- my ($raw, $ct, $nocomp) =
- $formatter->($res, $res->{data}, $params, $path, $auth, $self->{formatter_config});
-
- my $resp;
- if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
- $resp = $raw;
- } else {
- $resp = HTTP::Response->new($res->{status}, $res->{message});
- $resp->header("Content-Type" => $ct);
- $resp->content($raw);
- }
- $self->response($reqstate, $resp, undef, $nocomp, $delay);
+ finish_api2_request($self, $reqstate, $res, $formatter, $params, $path, $auth);
};
if (my $err = $@) {
$self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, $err);
@@ -2442,6 +2625,13 @@ sub rest_handler {
# to download aspecific file use:
# { download => "/path/to/file" };
+
+ # to complete the request asynchronously via the event loop use:
+ # {
+ # data => PVE::APIServer::AnyEvent::async_response($starter),
+ # info => $info,
+ # status => HTTP_OK,
+ # };
}
sub check_cert_fingerprint {
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
@ 2026-12-01 10:18 ` Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Thomas Lamprecht
` (6 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:18 UTC (permalink / raw)
To: pve-devel
AnyEvent::HTTP decodes chunked upstream responses but leaves the
Transfer-Encoding and Trailer headers intact. Forwarding them alongside
the Content-Length of the decoded body causes clients to misparse the
body as chunked. In addition, response() checked Perl truthiness on
$content rather than definedness and length, so a decoded empty body
("") omitted Content-Length on keep-alive 200 OK responses and a "0"
body was dropped altogether.
Strip Transfer-Encoding and Trailer before forwarding, disable
HTTP::Headers underscore translation so an upstream Transfer_Encoding
header cannot be normalized back into Transfer-Encoding, and frame
non-stream responses whenever the status permits a body and $content
is defined (keeping 1xx, 204, and 304 without Content-Length or body,
and omitting Content-Length for file/pipe streams). This is needed once
API2 endpoints stream chunked HTTP/1.1 responses (for example from
pvedaemon through pveproxy). The proxy still buffers the full response
rather than forwarding it incrementally.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Scope local $HTTP::Headers::TRANSLATE_UNDERSCORE = 0 to a do block
around HTTP::Headers->new() so it cannot leak across pipelined
keep-alive responses while still preventing Transfer_Encoding from
normalizing into Transfer-Encoding.
- Strip any supplied body on HTTP 205 Reset Content while keeping
Content-Length: 0 for persistent connections.
src/PVE/APIServer/AnyEvent.pm | 21 ++++++++++++++++-----
1 file changed, 16 insertions(+), 5 deletions(-)
diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm
index fa4076d..8f77737 100644
--- a/src/PVE/APIServer/AnyEvent.pm
+++ b/src/PVE/APIServer/AnyEvent.pm
@@ -408,8 +408,10 @@ sub response {
$content = '';
}
- if ($code =~ /^(1\d\d|[23]04)$/) {
- # make sure informational, no content and not modified response send no content
+ my $no_body = $code =~ /^(1[0-9][0-9]|[23]04)$/;
+ if ($no_body || $code == 205) {
+ # Informational, 204, 205, and 304 responses must not send a body (205 keeps
+ # Content-Length: 0 for persistent connections).
$content = "";
}
@@ -434,7 +436,7 @@ sub response {
$resp->header('Server' => "pve-api-daemon/3.0");
my $content_length;
- if ($content && !$stream_fh) {
+ if (!$stream_fh && !$no_body && defined($content)) {
$content_length = length($content);
@@ -469,7 +471,7 @@ sub response {
#print "SEND(without content) $res\n" if $self->{debug};
$res .= "\015\012";
- $res .= $content if $content && !$stream_fh;
+ $res .= $content if !$stream_fh && !$no_body && defined($content) && length($content);
$self->log_request($reqstate, $reqstate->{request});
@@ -959,7 +961,16 @@ sub proxy_request {
my $stream = delete $hdr->{pvestreamfile};
delete $hdr->{URL};
delete $hdr->{HTTPVersion};
- my $header = HTTP::Headers->new(%$hdr);
+ # AnyEvent::HTTP already decoded a chunked body but keeps the framing headers.
+ delete $hdr->{'transfer-encoding'};
+ delete $hdr->{trailer};
+ # Keep '_' untranslated only while parsing upstream headers so
+ # Transfer_Encoding cannot become Transfer-Encoding without affecting
+ # any pipelined follow-up response on the same connection.
+ my $header = do {
+ local $HTTP::Headers::TRANSLATE_UNDERSCORE = 0;
+ HTTP::Headers->new(%$hdr);
+ };
if (my $location = $header->header('Location')) {
$location =~ s|^http://localhost:85||;
$header->header(Location => $location);
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH http-server v2 3/9] response: support incremental streaming API2 responses
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
@ 2026-12-01 10:18 ` Thomas Lamprecht
2026-12-01 10:18 ` [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client Thomas Lamprecht
` (5 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:18 UTC (permalink / raw)
To: pve-devel
Deferred async API2 responses still buffer, format, and compress the
entire payload in one blocking pass. When PDM or monitoring scrapes
large clusters via /api2/extjs/ or /api2/json/cluster/metrics/export
(especially with history=1), materializing and compressing hundreds of
megabytes inside a pveproxy worker drives RSS into gigabytes and stalls
the event loop for seconds.
Add async_stream_response() and PVE::APIServer::AsyncStream so handlers
can emit formatted output incrementally. HTTP/1.1 clients receive
chunked responses with keep-alive preserved, while HTTP/1.0 clients
fall back to a close-delimited stream. Output is compressed on the fly
with Compress::Raw::Zlib at level 2 (gzip or deflate) when accepted.
Writes signal backpressure above 4 MiB queued, and on_drain() arms a
write timeout so stalled clients disconnect.
AsyncStream owns the outer API2 envelope for supported formats: json
wraps the streamed value in {"data":...} and extjs wraps it in
{"data":...,"success":1}. Handlers check the no-argument
async_stream_supported() helper and emit only the inner JSON value,
while unsupported formats are rejected in start_async_stream().
Trade-offs: level 2 produces a ~47% larger compressed payload than
memGzip level 6 on 17.8 MiB of metric JSON (still 8.2x vs 12.1x ratio)
in exchange for ~12x faster compression (769 ms -> 64 ms). Once 200 OK
headers are sent, fatal aborts omit the closing envelope and reset the
TCP connection (SO_LINGER) rather than returning HTTP 5xx so clients
cannot mistake truncated output for a complete response.
In a single-worker 100-node x 10,000-guest (10M metrics) harness,
streaming cut worker peak VmHWM from 9.02 GiB to ~209 MiB, total export
time from 53.1 s to 15.5 s (sorted) or 9.1 s (unsorted), and concurrent
/ping stalls on the same worker from 47.2 s to 37 ms.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Check that the selected formatter is the standard json or extjs
formatter in async_stream_supported() so method/path page formatters
are never silently bypassed.
- Validate the HTTP status code as a 3-digit 1xx-5xx value and route
compressor initialization failures through abort() in
AsyncStream::start() before writing headers.
- Defer keep-alive connection reuse in AsyncStream::finish() onto
on_drain() with wtimeout when the final slice crosses buf_size, and
keep a write-only wtimeout active while draining non-reusable
connections.
- Document the top-level dispatch, RPC state capture, UTF-8 JSON bytes,
2xx envelope, backpressure on_drain(sub { ... }), deadline, and
cancel-on-disconnect/abort contracts.
src/Makefile | 1 +
src/PVE/APIServer/AnyEvent.pm | 104 +++++++-
src/PVE/APIServer/AsyncStream.pm | 411 +++++++++++++++++++++++++++++++
3 files changed, 513 insertions(+), 3 deletions(-)
create mode 100644 src/PVE/APIServer/AsyncStream.pm
diff --git a/src/Makefile b/src/Makefile
index 50861bd..be6bcf9 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -7,6 +7,7 @@ all:
install: PVE
install -d -m 755 ${PERL5DIR}/PVE/APIServer
install -m 0644 PVE/APIServer/AnyEvent.pm ${PERL5DIR}/PVE/APIServer
+ install -m 0644 PVE/APIServer/AsyncStream.pm ${PERL5DIR}/PVE/APIServer
install -m 0644 PVE/APIServer/Formatter.pm ${PERL5DIR}/PVE/APIServer
install -m 0644 PVE/APIServer/Utils.pm ${PERL5DIR}/PVE/APIServer
install -d -m 755 ${PERL5DIR}/PVE/APIServer/Formatter
diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm
index 8f77737..4cf8074 100644
--- a/src/PVE/APIServer/AnyEvent.pm
+++ b/src/PVE/APIServer/AnyEvent.pm
@@ -46,6 +46,7 @@ use PVE::INotify;
use PVE::SafeSyslog;
use PVE::Tools qw(trim);
+use PVE::APIServer::AsyncStream;
use PVE::APIServer::Formatter;
use PVE::APIServer::Utils;
@@ -55,20 +56,46 @@ my $limit_max_post = 512 * 1024;
my $limit_max_request_line = 64 * 1024;
my $ASYNC_SUPPORTED = 0;
+my $ASYNC_STREAM_SUPPORTED = 0;
sub async_supported {
return $ASYNC_SUPPORTED;
}
+# Returns true only inside handle_api2_request() when the request uses the standard json or extjs
+# formatter (not a method/path page formatter). Streaming handlers pass UTF-8-encoded JSON bytes
+# for the inner `data` value; the server owns the outer envelope and does not emit `total` or
+# `changes` attributes.
+sub async_stream_supported {
+ return $ASYNC_STREAM_SUPPORTED;
+}
+
# Wrap a deferred API2 response starter: sub ($resolve, $reject) -> optional cancel coderef.
-# The server disables its inactivity timeout while waiting; the starter must bound its own wait
-# and may return a cancel callback invoked on client disconnect.
+# Only top-level API2 responses directly under $res->{data} are dispatched asynchronously. Handlers
+# must capture any request-specific RPC state (such as user or credentials) before returning, as
+# rest_handler() clears it before the starter runs. The server disables its inactivity timeout
+# while waiting; the starter owns its deadline and may return a cancel callback invoked on client
+# disconnect.
sub async_response {
my ($starter) = @_;
die "async_response requires a CODE ref\n" if ref($starter) ne 'CODE';
return bless { start => $starter }, 'PVE::APIServer::AnyEvent::AsyncResponse';
}
+# Wrap a deferred streaming API2 response starter: sub ($stream) -> optional cancel coderef.
+# Only top-level API2 responses directly under $res->{data} are dispatched asynchronously; handlers
+# must capture any request-specific RPC state before returning. The starter owns its deadline, and
+# its optional cancel callback runs on client disconnect or stream abort (including pre-start
+# abort). Pass UTF-8-encoded JSON bytes for the inner `data` value to $stream->write(); the server
+# wraps body-bearing 2xx responses in the outer json or extjs envelope (without `total` or
+# `changes` attributes). For a formatted API error, call $stream->abort($err) before
+# $stream->start().
+sub async_stream_response {
+ my ($starter) = @_;
+ die "async_stream_response requires a CODE ref\n" if ref($starter) ne 'CODE';
+ return bless { start => $starter }, 'PVE::APIServer::AnyEvent::AsyncStreamResponse';
+}
+
my $known_methods = {
GET => 1,
POST => 1,
@@ -1236,6 +1263,45 @@ my sub start_async_response {
);
}
+my sub start_async_stream {
+ my ($self, $reqstate, $async_stream, $res, $finish, $format, $stream_supported) = @_;
+
+ if (
+ ref($async_stream) ne 'PVE::APIServer::AnyEvent::AsyncStreamResponse'
+ || ref($async_stream->{start}) ne 'CODE'
+ ) {
+ die "invalid async stream response\n";
+ }
+
+ if (!$stream_supported) {
+ die "unsupported async stream format\n";
+ }
+
+ return if !prepare_async_handle($reqstate);
+
+ my $stream = PVE::APIServer::AsyncStream->new(
+ server => $self,
+ reqstate => $reqstate,
+ format => $format,
+ on_early_error => sub {
+ my ($err) = @_;
+ set_error_result($res, $err);
+ $finish->($res);
+ },
+ );
+
+ $reqstate->{on_disconnect} = sub {
+ $stream->_on_disconnect();
+ };
+
+ run_async_starter(
+ 'async_stream_response',
+ $stream,
+ sub { $async_stream->{start}->($stream) },
+ sub { $stream->abort($_[0]) },
+ );
+}
+
sub handle_api2_request {
my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
@@ -1269,10 +1335,24 @@ sub handle_api2_request {
my $clientip = $reqstate->{peer_host};
+ my $default_formatter = PVE::APIServer::Formatter::get_formatter($format);
+ my $stream_supported =
+ defined($format)
+ && ($format eq 'json' || $format eq 'extjs')
+ && defined($default_formatter)
+ && $formatter == $default_formatter
+ ? 1
+ : 0;
+
my $res = do {
my $prev_async = $ASYNC_SUPPORTED;
- my $guard = guard { $ASYNC_SUPPORTED = $prev_async };
+ my $prev_stream = $ASYNC_STREAM_SUPPORTED;
+ my $guard = guard {
+ $ASYNC_SUPPORTED = $prev_async;
+ $ASYNC_STREAM_SUPPORTED = $prev_stream;
+ };
$ASYNC_SUPPORTED = 1;
+ $ASYNC_STREAM_SUPPORTED = $stream_supported;
$self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
};
@@ -1281,6 +1361,17 @@ sub handle_api2_request {
AnyEvent->now_update(); # in case somebody called sleep()
+ if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncStreamResponse') {
+ my $async_stream = delete $res->{data};
+ my $finish = sub {
+ finish_api2_request($self, $reqstate, $_[0], $formatter, $params, $path, $auth);
+ };
+ start_async_stream(
+ $self, $reqstate, $async_stream, $res, $finish, $format, $stream_supported,
+ );
+ return;
+ }
+
if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncResponse') {
my $async = delete $res->{data};
my $finish = sub {
@@ -2643,6 +2734,13 @@ sub rest_handler {
# info => $info,
# status => HTTP_OK,
# };
+
+ # to stream the response incrementally via the event loop use:
+ # {
+ # data => PVE::APIServer::AnyEvent::async_stream_response($starter),
+ # info => $info,
+ # status => HTTP_OK,
+ # };
}
sub check_cert_fingerprint {
diff --git a/src/PVE/APIServer/AsyncStream.pm b/src/PVE/APIServer/AsyncStream.pm
new file mode 100644
index 0000000..9079fc2
--- /dev/null
+++ b/src/PVE/APIServer/AsyncStream.pm
@@ -0,0 +1,411 @@
+package PVE::APIServer::AsyncStream;
+
+# Push-based incremental HTTP response stream for API2 handlers returned via
+# PVE::APIServer::AnyEvent::async_stream_response(). Exists so endpoints with large payloads
+# (such as cluster-wide metric exports) can emit chunks incrementally with on-the-fly
+# gzip/deflate compression instead of buffering and compressing the full body in one worker stall.
+#
+# Lifecycle:
+# start() - writes HTTP/1.1 chunked (or HTTP/1.0) headers and, for json/extjs API2 streams,
+# opens the outer {"data": envelope.
+# write() - compresses and pushes a chunk of the inner JSON value. Returns 0 either when
+# the stream is already closed (check is_closed(); the chunk was dropped) or when
+# queued write-buffer bytes reach buf_size (the chunk was accepted and queued; do
+# not resend it - pause further writes and register $stream->on_drain(sub { ... })
+# to resume).
+# flush() - sync-flushes the active compressor (useful to minimize TTFB on the first slice).
+# finish() - closes the outer envelope (emitting null if nothing was written), finalizes
+# compression/chunking, logs the request, and keeps HTTP/1.1 connections reusable.
+# abort() - invokes the starter's optional cancel callback (if any); before start(), delegates
+# to normal formatted API2 error handling; after start(), omits the closing envelope
+# and terminating 0-chunk and resets the socket (TCP RST) so clients cannot mistake
+# truncated output for a complete response.
+
+use v5.36;
+
+use AnyEvent;
+use Compress::Raw::Zlib ();
+use HTTP::Date;
+use HTTP::Headers;
+use HTTP::Status qw(:constants);
+use Net::SSLeay;
+
+my $DEFAULT_BUF_SIZE = 4 * 1024 * 1024;
+my $DEFAULT_GZIP_LEVEL = 2;
+
+sub new($class, %args) {
+
+ my ($prefix, $suffix);
+ if (defined($args{format})) {
+ if ($args{format} eq 'json') {
+ ($prefix, $suffix) = ('{"data":', '}');
+ } elsif ($args{format} eq 'extjs') {
+ ($prefix, $suffix) = ('{"data":', ',"success":1}');
+ } else {
+ die "unsupported async stream format\n";
+ }
+ }
+
+ return bless {
+ server => $args{server},
+ reqstate => $args{reqstate},
+ on_early_error => $args{on_early_error},
+ buf_size => $args{buf_size} // $DEFAULT_BUF_SIZE,
+ prefix => $prefix,
+ suffix => $suffix,
+ envelope_started => 0,
+ wrote_body => 0,
+ started => 0,
+ finished => 0,
+ aborted => 0,
+ disconnected => 0,
+ chunked => 0,
+ bytes_written => 0,
+ cancel => undef,
+ deflate => undef,
+ }, $class;
+}
+
+sub _clear_refs($self) {
+ delete @$self{qw(server reqstate on_early_error cancel deflate)};
+}
+
+sub is_closed($self) {
+ return $self->{finished} || !$self->{reqstate} || !$self->{reqstate}->{hdl} ? 1 : 0;
+}
+
+sub is_backpressured($self) {
+ return 0 if $self->is_closed();
+ my $hdl = $self->{reqstate}->{hdl};
+ my $queued = length($hdl->{wbuf} // '') + length($hdl->{_tls_wbuf} // '');
+ return $queued >= $self->{buf_size} ? 1 : 0;
+}
+
+my sub push_frame($hdl, $chunked, $out) {
+ # Clear OpenSSL errors before writing so outbound TLS work cannot disrupt the client socket.
+ Net::SSLeay::ERR_clear_error();
+ if ($chunked) {
+ $hdl->push_write(sprintf("%x\015\012", length($out)) . $out . "\015\012");
+ } else {
+ $hdl->push_write($out);
+ }
+}
+
+my sub write_payload($self, $bytes, $flush_mode = undef) {
+ my $has_bytes = defined($bytes) && length($bytes);
+ return 1 if !$has_bytes && !defined($flush_mode);
+
+ my $out;
+ if (my $deflate = $self->{deflate}) {
+ $out = '';
+ if ($has_bytes) {
+ my $st = $deflate->deflate($bytes, $out);
+ if ($st != Compress::Raw::Zlib::Z_OK()) {
+ $self->abort("stream compression failed ($st)");
+ return 0;
+ }
+ }
+ if (defined($flush_mode)) {
+ my $st = $deflate->flush($out, $flush_mode);
+ if ($st != Compress::Raw::Zlib::Z_OK()) {
+ $self->abort("stream flush failed ($st)");
+ return 0;
+ }
+ }
+ } else {
+ $out = $has_bytes ? $bytes : '';
+ }
+
+ if (length($out)) {
+ my $hdl = $self->{reqstate} ? $self->{reqstate}->{hdl} : undef;
+ return 0 if !$hdl;
+ $self->{bytes_written} += length($out);
+ push_frame($hdl, $self->{chunked}, $out);
+ return 0 if $self->is_closed();
+ }
+
+ return 1;
+}
+
+sub start($self, %opts) {
+ return 0 if $self->is_closed();
+ return 1 if $self->{started};
+
+ my ($server, $reqstate) = $self->@{ 'server', 'reqstate' };
+ my $hdl = $reqstate->{hdl};
+
+ my $code = $opts{status} // HTTP_OK;
+ if (ref($code) || $code !~ /^[1-5][0-9]{2}\z/) {
+ $self->abort("invalid HTTP status code\n");
+ return 0;
+ }
+ my $msg = $opts{message} || HTTP::Status::status_message($code) // '';
+ ($msg) = $msg =~ m/^(.*)$/m;
+ if ($msg =~ /[\r\n]/) {
+ $code = HTTP_INTERNAL_SERVER_ERROR;
+ $msg = HTTP::Status::status_message($code);
+ }
+
+ # These status codes forbid a response body and cannot be streamed.
+ if ($code =~ /^(1[0-9][0-9]|20[45]|304)$/) {
+ $self->abort("HTTP status $code does not allow streaming a response body\n");
+ return 0;
+ }
+
+ my $content_type = $opts{content_type} // 'application/json;charset=UTF-8';
+ my $nocomp = $opts{nocomp} ? 1 : 0;
+ $nocomp = 1 if !$server->{compression};
+ $nocomp = 1 if !$reqstate->{accept_gzip} && !$reqstate->{accept_deflate};
+
+ my $level = $opts{level} // $DEFAULT_GZIP_LEVEL;
+ my $encoding;
+ if (!$nocomp) {
+ if ($reqstate->{accept_gzip}) {
+ my ($deflate, $st) = Compress::Raw::Zlib::Deflate->new(
+ -Level => $level,
+ -WindowBits => Compress::Raw::Zlib::WANT_GZIP(),
+ -AppendOutput => 1,
+ );
+ if ($st != Compress::Raw::Zlib::Z_OK()) {
+ $self->abort("failed to initialize gzip compressor: $st\n");
+ return 0;
+ }
+ $self->{deflate} = $deflate;
+ $encoding = 'gzip';
+ } elsif ($reqstate->{accept_deflate}) {
+ my ($deflate, $st) = Compress::Raw::Zlib::Deflate->new(
+ -Level => $level,
+ -AppendOutput => 1,
+ );
+ if ($st != Compress::Raw::Zlib::Z_OK()) {
+ $self->abort("failed to initialize deflate compressor: $st\n");
+ return 0;
+ }
+ $self->{deflate} = $deflate;
+ $encoding = 'deflate';
+ }
+ }
+
+ my $proto_ver = $reqstate->{proto} ? $reqstate->{proto}->{ver} : 1000;
+ my $proto_str = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
+ my $chunked = $proto_ver >= 1001 ? 1 : 0;
+ $self->{chunked} = $chunked;
+
+ $reqstate->{keep_alive} = 0 if !$chunked || $code >= 400 || $server->{end_loop};
+ $reqstate->{log}->{code} = $code;
+ $reqstate->{streaming} = 1;
+
+ my $date = HTTP::Date::time2str(time());
+ my $hdr = HTTP::Headers->new(
+ 'Content-Type' => $content_type,
+ 'Date' => $date,
+ 'Expires' => $date,
+ 'Cache-Control' => 'max-age=0',
+ 'Pragma' => 'no-cache',
+ 'Server' => 'pve-api-daemon/3.0',
+ );
+ $hdr->header('Content-Encoding' => $encoding) if defined($encoding);
+ $hdr->header('Transfer-Encoding' => 'chunked') if $chunked;
+
+ if (($reqstate->{keep_alive} // 0) > 0) {
+ $hdr->push_header('Connection' => 'Keep-Alive');
+ } else {
+ $hdr->header('Connection' => 'close');
+ }
+
+ my $head = "$proto_str $code $msg\015\012" . $hdr->as_string("\015\012") . "\015\012";
+ $self->{started} = 1;
+
+ Net::SSLeay::ERR_clear_error();
+ $hdl->push_write($head);
+ return 0 if $self->is_closed();
+
+ if ($code >= 200 && $code < 300 && defined($self->{prefix})) {
+ $self->{envelope_started} = 1;
+ return 0 if !write_payload($self, $self->{prefix});
+ }
+
+ return $self->is_closed() ? 0 : 1;
+}
+
+sub write($self, $bytes = undef) {
+ return 0 if $self->is_closed();
+ return 0 if !$self->{started} && !$self->start();
+ return 0 if !write_payload($self, $bytes);
+ $self->{wrote_body} = 1 if defined($bytes) && length($bytes);
+
+ return $self->is_backpressured() ? 0 : 1;
+}
+
+sub flush($self) {
+ return 0 if $self->is_closed();
+ return 1 if !$self->{started};
+
+ if ($self->{deflate}) {
+ return 0 if !write_payload($self, undef, Compress::Raw::Zlib::Z_SYNC_FLUSH());
+ }
+
+ return $self->is_backpressured() ? 0 : 1;
+}
+
+sub on_drain($self, $cb = undef) {
+ return if $self->is_closed();
+ my $hdl = $self->{reqstate}->{hdl};
+ if (!defined($cb)) {
+ $hdl->wtimeout(0);
+ $hdl->on_drain(undef);
+ return;
+ }
+ die "stream on_drain requires a CODE ref\n" if ref($cb) ne 'CODE';
+
+ # Use a write-only timeout so a stalled reader disconnects even if it sends data.
+ AnyEvent->now_update();
+ $hdl->wtimeout_reset();
+ $hdl->wtimeout($self->{server}->{timeout});
+
+ # One-shot wrapper; AnyEvent::Handle invokes on_drain synchronously if already drained.
+ $hdl->on_drain(sub($wrhdl) {
+ $wrhdl->wtimeout(0);
+ $wrhdl->on_drain(undef);
+ return if $self->is_closed();
+ eval { $cb->(); };
+ my $err = $@;
+ # The callback may have used OpenSSL for other connections, see Note 1 in AnyEvent.pm.
+ Net::SSLeay::ERR_clear_error();
+ $self->abort($err) if $err;
+ });
+}
+
+sub finish($self) {
+ return if $self->{finished};
+ return if !$self->{started} && !$self->start();
+ return if $self->{finished};
+
+ my ($server, $reqstate, $chunked) = $self->@{ 'server', 'reqstate', 'chunked' };
+
+ my $hdl = $reqstate->{hdl};
+ if (!$hdl) {
+ $self->{finished} = 1;
+ delete $reqstate->{on_disconnect};
+ $self->_clear_refs();
+ return;
+ }
+
+ $hdl->wtimeout(0);
+ $hdl->on_drain(undef);
+
+ my $suffix;
+ if ($self->{envelope_started}) {
+ $suffix = $self->{wrote_body} ? $self->{suffix} : 'null' . $self->{suffix};
+ }
+ my $flush_mode = $self->{deflate} ? Compress::Raw::Zlib::Z_FINISH() : undef;
+ if (!write_payload($self, $suffix, $flush_mode)) {
+ return if $self->{finished};
+ $self->{finished} = 1;
+ delete $reqstate->{on_disconnect};
+ $self->_clear_refs();
+ return;
+ }
+
+ if ($reqstate->{hdl} && $chunked) {
+ Net::SSLeay::ERR_clear_error();
+ $hdl->push_write("0\015\012\015\012");
+ }
+
+ my $defer_reuse =
+ $reqstate->{hdl}
+ && $chunked
+ && ($reqstate->{keep_alive} // 0) > 0
+ && $self->is_backpressured();
+
+ $self->{finished} = 1;
+ delete $reqstate->{on_disconnect};
+
+ if ($reqstate->{hdl}) {
+ $reqstate->{log}->{content_length} = $self->{bytes_written};
+ $server->log_request($reqstate, $reqstate->{request});
+
+ AnyEvent->now_update();
+
+ # Chunked bodies are delimited by the 0-chunk and may reuse the connection; HTTP/1.0
+ # streams keep streaming set until finish_response()'s on_drain writes everything out.
+ delete $reqstate->{streaming} if $chunked;
+
+ $self->_clear_refs();
+
+ if ($defer_reuse) {
+ # Wait for the write queue to drain before reusing a keep-alive connection so a slow
+ # reader cannot accumulate unbounded pipelined responses across one-slice exports.
+ $hdl->wtimeout_reset();
+ $hdl->wtimeout($server->{timeout});
+ $hdl->on_drain(sub($wrhdl) {
+ $wrhdl->wtimeout(0);
+ $wrhdl->on_drain(undef);
+ return if !$reqstate->{hdl};
+ AnyEvent->now_update();
+ $wrhdl->timeout_reset();
+ $wrhdl->timeout($server->{timeout});
+ $server->finish_response($reqstate);
+ });
+ } elsif ($server->{end_loop} || ($reqstate->{keep_alive} // 0) <= 0) {
+ # Keep a write-only deadline active while finish_response() drains queued output on a
+ # non-reusable connection so inbound client traffic cannot reset the timeout.
+ $hdl->timeout(0);
+ $hdl->wtimeout_reset();
+ $hdl->wtimeout($server->{timeout});
+ $server->finish_response($reqstate);
+ } else {
+ $hdl->timeout_reset();
+ $hdl->timeout($server->{timeout});
+ $server->finish_response($reqstate);
+ }
+ } else {
+ $self->_clear_refs();
+ }
+}
+
+sub abort($self, $err = undef) {
+ return if $self->{finished};
+ $self->{finished} = 1;
+ $self->{aborted} = 1;
+
+ my ($server, $reqstate, $on_early_error, $started, $cancel) =
+ $self->@{ 'server', 'reqstate', 'on_early_error', 'started', 'cancel' };
+
+ $self->_clear_refs();
+ delete $reqstate->{on_disconnect} if $reqstate;
+
+ if (ref($cancel) eq 'CODE') {
+ eval { $cancel->(); };
+ warn $@ if $@;
+ Net::SSLeay::ERR_clear_error();
+ }
+
+ return if !$reqstate || !$reqstate->{hdl};
+
+ Net::SSLeay::ERR_clear_error();
+ AnyEvent->now_update();
+
+ if (!$started) {
+ $on_early_error->($err) if $on_early_error;
+ return;
+ }
+
+ # Headers are already sent; keep streaming set so client_do_disconnect() sends a TCP RST.
+ $reqstate->{streaming} = 1;
+ my $reason = defined($err) ? "$err" : 'stream aborted';
+ $reason =~ s/\s+$//;
+ $server->log_aborted_request($reqstate, $reason);
+ $server->client_do_disconnect($reqstate);
+}
+
+sub _on_disconnect($self) {
+ return if $self->{finished};
+ $self->{finished} = 1;
+ $self->{disconnected} = 1;
+ my $cb = $self->{cancel};
+ $self->_clear_refs();
+ $cb->() if ref($cb) eq 'CODE';
+}
+
+1;
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
` (2 preceding siblings ...)
2026-12-01 10:18 ` [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Thomas Lamprecht
@ 2026-12-01 10:18 ` Thomas Lamprecht
2026-12-01 10:19 ` [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
` (4 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:18 UTC (permalink / raw)
To: pve-devel
Services running inside an AnyEvent event loop (such as pveproxy) cannot
use PVE::APIClient::LWP without blocking the event loop on remote API
calls. Add PVE::APIClient::AnyEvent as a non-blocking counterpart built
on AnyEvent::HTTP and AnyEvent::TLS.
The client supports API token and ticket/CSRF authentication, IPv6 host
bracketing, per-client persistent connection cache isolation, strict
header name/value validation, CA/hostname verification with SHA-256
fingerprint pinning and fallback callbacks, and idempotent request
cancellation. request_raw() exposes buffered response bodies after HTTP
transfer decoding and defers setup errors via AE::postpone, call()
delivers the full decoded JSON envelope, and
get()/post()/put()/delete() extract the response data field.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Derive one effective TLS peername policy in build_tls_ctx(), validate
verify_peername against %AnyEvent::TLS::CN_SCHEME (normalizing case),
reject verify => 0, and reject combining verify_cb with fingerprint
pinning; clarify fingerprint fallback comment (verify_fingerprint_cb).
- Reject CR, LF, and NUL and encode bare api_token credentials
(preserving literal TOKENID: and percent-encoding only the secret for
PBSAPIToken/PDMAPIToken, and URI-escaping bare PVE tokens including
user IDs with '=', ';', or '%') while leaving explicit scheme headers
untouched.
- Anchor HTTP method validation with \A...\z in request_raw() so
trailing newlines are rejected.
- Route HTTP 200 ExtJS failures (success: 0) to on_error in
get()/post()/put()/delete() with their status, message, and errors
hash while keeping call() delivering the full envelope to on_response.
- Defer invalid per-request header errors from call() to on_error and
expand unit tests (including issuer-depth TLS failure, trailing-
newline methods, and PBS/PDM bare token parsing).
Makefile | 4 +
debian/control | 12 +-
src/Makefile | 7 +-
src/PVE/APIClient/AnyEvent.pm | 574 ++++++++++
src/test/anyevent_client.t | 1974 +++++++++++++++++++++++++++++++++
5 files changed, 2569 insertions(+), 2 deletions(-)
create mode 100644 src/PVE/APIClient/AnyEvent.pm
create mode 100644 src/test/anyevent_client.t
diff --git a/Makefile b/Makefile
index c270ea1..da4831e 100644
--- a/Makefile
+++ b/Makefile
@@ -18,6 +18,10 @@ all: $(DEB)
tidy:
git ls-files ':*.p[ml]'| xargs -n4 -P0 proxmox-perltidy
+.PHONY: check
+check:
+ $(MAKE) -C src check
+
$(BUILDSRC):
rm -rf $@ $@.tmp
cp -a src $@.tmp
diff --git a/debian/control b/debian/control
index e7ed070..0887c9a 100644
--- a/debian/control
+++ b/debian/control
@@ -3,16 +3,26 @@ Section: perl
Priority: optional
Maintainer: Proxmox Support Team <support@proxmox.com>
Build-Depends: debhelper-compat (= 13),
+ libanyevent-http-perl,
+ libanyevent-perl,
+ libhttp-message-perl,
+ libjson-perl,
+ libnet-ssleay-perl,
+ liburi-perl,
+ openssl,
perl,
Standards-Version: 4.5.1
Homepage: https://www.proxmox.com
Package: libpve-apiclient-perl
Architecture: all
-Depends: libcrypt-ssleay-perl,
+Depends: libanyevent-http-perl,
+ libanyevent-perl,
+ libcrypt-ssleay-perl,
libhttp-message-perl,
libio-socket-ssl-perl,
libjson-perl,
+ libnet-ssleay-perl,
liburi-perl,
libwww-perl,
${misc:Depends},
diff --git a/src/Makefile b/src/Makefile
index bc19e9f..d6327c6 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -6,8 +6,9 @@ DOCDIR=$(DESTDIR)/usr/share/doc/$(PACKAGE)
all:
-install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm examples/*.pl
+install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm PVE/APIClient/AnyEvent.pm examples/*.pl
install -D -m 0644 PVE/APIClient/LWP.pm $(PERL5DIR)/PVE/APIClient/LWP.pm
+ install -m 0644 PVE/APIClient/AnyEvent.pm $(PERL5DIR)/PVE/APIClient/AnyEvent.pm
install -m 0644 PVE/APIClient/Exception.pm $(PERL5DIR)/PVE/APIClient/Exception.pm
install -d -m 755 $(DOCDIR)/examples
install -m 0755 examples/example1.pl $(DOCDIR)/examples
@@ -15,3 +16,7 @@ install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm examples/*.pl
install -m 0755 examples/perftest1.pl $(DOCDIR)/examples
clean:
+
+.PHONY: check
+check:
+ prove -I. test/*.t
diff --git a/src/PVE/APIClient/AnyEvent.pm b/src/PVE/APIClient/AnyEvent.pm
new file mode 100644
index 0000000..3d99d98
--- /dev/null
+++ b/src/PVE/APIClient/AnyEvent.pm
@@ -0,0 +1,574 @@
+package PVE::APIClient::AnyEvent;
+
+# Non-blocking AnyEvent counterpart to PVE::APIClient::LWP for services running inside an AnyEvent
+# event loop. Key differences from LWP.pm:
+# - Explicit ticket/CSRF or API token auth only; no auto-login or interactive fingerprint prompt.
+# - ssl_opts targets AnyEvent::TLS. With cached_fingerprints, peer-name verification defaults to off
+# (leaf fingerprint check only); when peer-name verification is active, a valid chain and
+# matching name suffice, with cached_fingerprints and verify_fingerprint_cb used as fallbacks.
+# - request_raw() yields the buffered response body after HTTP transfer decoding (before
+# decompression or JSON decoding); call() delivers the full decoded JSON envelope;
+# get()/post()/put()/delete() extract the response data field.
+# - Each client instance isolates AnyEvent::HTTP's persistent connection cache via a unique
+# sessionid so TLS verification contexts and fingerprint pins are never shared across clients.
+
+use v5.36;
+
+use AnyEvent;
+use AnyEvent::HTTP;
+use AnyEvent::TLS;
+use Carp;
+use Compress::Zlib ();
+use JSON qw(from_json);
+use Net::SSLeay;
+use URI::Escape qw(uri_escape);
+use URI;
+
+use PVE::APIClient::Exception;
+
+my $NEXT_SESSION_ID = 0;
+my $HEADER_NAME_RE = qr/^[!#\$%&'*+\-.^_`|~0-9a-zA-Z]+\z/;
+
+# Decode a raw JSON API response body, gunzipping first when $is_gzip is true.
+sub decode_json_body($body_ref, $is_gzip = 0) {
+ croak "body_ref must be a SCALAR ref" if ref($body_ref) ne 'SCALAR';
+
+ my $raw = $$body_ref;
+ if ($is_gzip) {
+ # Copy because Compress::Zlib::memGunzip consumes its input scalar in place.
+ my $copy = $raw;
+ $raw = Compress::Zlib::memGunzip($copy);
+ die "failed to gunzip response\n" if !defined($raw);
+ }
+
+ return from_json($raw, { utf8 => 1, allow_nonref => 1 });
+}
+
+my sub invoke_callback($cb, @args) {
+ eval { $cb->(@args); };
+ my $err = $@;
+ # Clear OpenSSL errors left by TLS work or user callbacks (see PVE::APIServer::AnyEvent).
+ Net::SSLeay::ERR_clear_error();
+ warn $err if $err;
+}
+
+my sub validate_header($name, $value) {
+ if (!defined($name) || ref($name) || $name !~ $HEADER_NAME_RE) {
+ croak "invalid HTTP header name";
+ }
+ if (!defined($value) || ref($value) || $value =~ /[\r\n\0]/) {
+ croak "invalid HTTP header value for '$name'";
+ }
+}
+
+my sub normalize_headers($headers = undef) {
+ my %norm;
+ return \%norm if !$headers;
+ croak "headers must be a HASH ref" if ref($headers) ne 'HASH';
+ for my $key (keys %$headers) {
+ validate_header($key, $headers->{$key});
+ $norm{ lc($key) } = $headers->{$key};
+ }
+ return \%norm;
+}
+
+my sub is_peername_disabled($verify_peername) {
+ return 1 if !defined($verify_peername);
+ return 0 if ref($verify_peername);
+ return $verify_peername eq '' || lc($verify_peername) eq 'none' ? 1 : 0;
+}
+
+my sub build_tls_ctx($self) {
+ return $self->{tls_ctx} if $self->{tls_ctx};
+
+ my %ssl_opts = %{ $self->{ssl_opts} || {} };
+ my ($fingerprints, $verify_fp_cb) = $self->@{ 'cached_fingerprints', 'verify_fingerprint_cb' };
+ my $has_cached_fp = scalar(keys %$fingerprints) > 0 ? 1 : 0;
+ my $has_fp_pinning = ($has_cached_fp || defined($verify_fp_cb)) ? 1 : 0;
+
+ if (exists($ssl_opts{verify}) && !$ssl_opts{verify}) {
+ die PVE::APIClient::Exception->new(
+ "cannot disable TLS certificate verification (verify => 0)\n");
+ }
+
+ my $has_explicit_vh = exists($ssl_opts{verify_hostname});
+ my $explicit_vh = $has_explicit_vh ? ($ssl_opts{verify_hostname} ? 1 : 0) : undef;
+ delete $ssl_opts{verify_hostname};
+
+ my $has_explicit_vp = exists($ssl_opts{verify_peername});
+ if ($has_explicit_vp) {
+ my $vp = $ssl_opts{verify_peername};
+ my $vp_ref = ref($vp);
+ if (
+ !defined($vp)
+ || ($vp_ref && $vp_ref ne 'CODE' && $vp_ref ne 'ARRAY')
+ || ($vp_ref eq 'ARRAY' && scalar(@$vp) < 3)
+ ) {
+ die PVE::APIClient::Exception->new("invalid ssl_opts->{verify_peername}\n");
+ }
+ if (!$vp_ref) {
+ # AnyEvent::TLS::verify_hostname silently returns 1 for any string not in %CN_SCHEME.
+ my $scheme = lc($vp);
+ if (!exists($AnyEvent::TLS::CN_SCHEME{$scheme})) {
+ die PVE::APIClient::Exception->new("invalid ssl_opts->{verify_peername}\n");
+ }
+ $ssl_opts{verify_peername} = $scheme;
+ }
+ my $vp_disabled = is_peername_disabled($ssl_opts{verify_peername});
+ if ($has_explicit_vh && $explicit_vh && $vp_disabled) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: verify_hostname => 1 with verify_peername => 'none'\n");
+ }
+ if ($has_explicit_vh && !$explicit_vh && !$vp_disabled) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: verify_hostname => 0 with active verify_peername\n");
+ }
+ }
+
+ if (defined($ssl_opts{verify_cb})) {
+ if (ref($ssl_opts{verify_cb}) ne 'CODE') {
+ die PVE::APIClient::Exception->new("ssl_opts->{verify_cb} must be a CODE ref\n");
+ }
+ if ($has_fp_pinning) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: cannot combine verify_cb with cached_fingerprints or verify_fingerprint_cb\n"
+ );
+ }
+ }
+
+ my %tls_args = (
+ method => 'any',
+ sslv2 => 0,
+ sslv3 => 0,
+ dh => undef,
+ %ssl_opts,
+ verify => 1,
+ );
+
+ if (
+ !defined($tls_args{ca_file})
+ && !defined($tls_args{ca_cert})
+ && !defined($tls_args{ca_path})
+ ) {
+ # Use hashed CA directory lookup so per-peer contexts skip eager CA bundle parsing.
+ $tls_args{ca_path} = '/usr/lib/ssl/certs';
+ }
+
+ if (!$has_explicit_vp) {
+ # Match LWP.pm: purely trust configured cached fingerprints by default, otherwise enforce
+ # hostname verification (falling back to verify_fingerprint_cb for untrusted certs).
+ my $want_hostname = $explicit_vh // ($has_cached_fp ? 0 : 1);
+ $tls_args{verify_peername} = $want_hostname ? 'https' : 'none';
+ }
+
+ # Single effective peername policy matching AnyEvent::TLS::_verify_hostname (lc ne 'none').
+ my $verify_peername = is_peername_disabled($tls_args{verify_peername}) ? 0 : 1;
+
+ if (!$verify_peername && !$has_fp_pinning && !$tls_args{verify_cb}) {
+ die PVE::APIClient::Exception->new(
+ "cannot disable verify_hostname without cached_fingerprints, verify_fingerprint_cb, or verify_cb\n"
+ );
+ }
+
+ if ($tls_args{verify_cb}) {
+ my $user_verify_cb = $tls_args{verify_cb};
+ $tls_args{verify_cb} = sub {
+ my $ok = eval { $user_verify_cb->(@_) };
+ if (my $err = $@) {
+ warn $err;
+ return 0;
+ }
+ return $ok ? 1 : 0;
+ };
+ } elsif ($has_fp_pinning) {
+ my %chain_failed;
+ $tls_args{verify_cb} = sub {
+ my (undef, undef, undef, $depth, $preverify_ok, $ctx, $cert) = @_;
+
+ if ($verify_peername && !$preverify_ok && defined($ctx)) {
+ $chain_failed{$ctx} = 1;
+ }
+ return 1 if $depth != 0;
+
+ my $failed = defined($ctx) ? delete($chain_failed{$ctx}) : 0;
+ return 1 if $verify_peername && $preverify_ok && !$failed;
+
+ return 0 if !$cert;
+ my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
+ return 0 if !defined($fp) || $fp eq '';
+
+ my $cached = $fingerprints->{$fp};
+ return $cached ? 1 : 0 if defined($cached);
+
+ if ($verify_fp_cb) {
+ my $valid = eval { $verify_fp_cb->($cert) ? 1 : 0 };
+ if (my $err = $@) {
+ warn $err;
+ return 0;
+ }
+ $fingerprints->{$fp} = $valid;
+ return $valid;
+ }
+
+ return 0;
+ };
+ }
+
+ Net::SSLeay::ERR_clear_error();
+ $self->{tls_ctx} = AnyEvent::TLS->new(%tls_args);
+ Net::SSLeay::ERR_clear_error();
+
+ return $self->{tls_ctx};
+}
+
+my sub build_uri($self, $path, $query_param = undef) {
+ my $uri = URI->new();
+ $uri->scheme($self->{protocol});
+ $uri->host($self->{host});
+ $uri->port($self->{port});
+
+ $path //= '';
+ $path =~ s!^/+!!;
+ if ($path !~ m!^api2/!) {
+ $uri->path("api2/json/$path");
+ } else {
+ $uri->path($path);
+ }
+
+ if (defined($query_param) && ref($query_param) eq 'HASH' && %$query_param) {
+ $uri->query_form($query_param);
+ }
+
+ return $uri;
+}
+
+sub new($class, %param) {
+ my $host = $param{host} || 'localhost';
+ my $port = $param{port} || ($host eq 'localhost' ? 85 : 8006);
+ my $protocol = $param{protocol};
+ if (!$protocol) {
+ # Match LWP.pm: default to plain HTTP only for privileged localhost ports (e.g. 85).
+ $protocol = $host eq 'localhost' && $port < 1024 ? 'http' : 'https';
+ } else {
+ $protocol = lc($protocol);
+ if ($protocol ne 'http' && $protocol ne 'https') {
+ croak "unsupported protocol '$protocol'";
+ }
+ }
+
+ my $cookie_name = $param{cookie_name} // 'PVEAuthCookie';
+ my $api_token_name = $param{api_token_name} // 'PVEAPIToken';
+
+ my $default_headers = normalize_headers($param{headers});
+
+ my $api_token = $param{api_token} // $param{apitoken};
+ if (defined($api_token)) {
+ warn "ticket will be ignored in favor of API token\n" if defined($param{ticket});
+ # Reject CR, LF, and NUL before URI-escaping a bare token.
+ validate_header('authorization', $api_token);
+ my $auth_header = $api_token;
+ # Treat only explicit scheme headers (configured scheme, known Proxmox API token schemes,
+ # or space-delimited auth schemes) as preformatted so bare user IDs containing '=' (e.g.
+ # LDAP cn=alice@realm!tok=secret) are prefixed and URI-escaped.
+ if (
+ $auth_header !~ /^\Q$api_token_name\E(?:=| )/
+ && $auth_header !~ /^(?:PVE|PBS|PMG|PDM)APIToken(?:=| )/
+ && $auth_header !~ /^[A-Za-z][A-Za-z0-9_-]* /
+ ) {
+ if ($api_token_name =~ /^(?:PBS|PDM)APIToken\z/ && $api_token =~ /\A([^:]+):(.*)\z/s) {
+ # PBS/PDM authenticators split on the literal ':' before percent-decoding only the
+ # secret, parsing the token ID verbatim as an Authid.
+ $auth_header = "${api_token_name}=$1:" . uri_escape($2);
+ } else {
+ $auth_header = "${api_token_name}=" . uri_escape($api_token);
+ }
+ }
+ $default_headers->{authorization} = $auth_header;
+ } elsif (defined($param{ticket})) {
+ my $encticket = uri_escape($param{ticket});
+ $default_headers->{cookie} = "$cookie_name=$encticket; path=/; secure; SameSite=Strict;";
+ }
+
+ if (defined($param{csrftoken})) {
+ $default_headers->{csrfpreventiontoken} = $param{csrftoken};
+ }
+
+ for my $key (keys %$default_headers) {
+ validate_header($key, $default_headers->{$key});
+ }
+
+ my $self = {
+ host => $host,
+ port => $port,
+ protocol => $protocol,
+ cookie_name => $cookie_name,
+ api_token_name => $api_token_name,
+ timeout => $param{timeout} || 60,
+ cached_fingerprints => { %{ $param{cached_fingerprints} || {} } },
+ verify_fingerprint_cb => $param{verify_fingerprint_cb},
+ ssl_opts => $param{ssl_opts} ? { %{ $param{ssl_opts} } } : {},
+ headers => $default_headers,
+ persistent => $param{persistent} ? 1 : 0,
+ keepalive => $param{keepalive} ? 1 : 0,
+ # Isolate AnyEvent::HTTP's persistent connection cache per client TLS context/pin.
+ sessionid => 'pve-apiclient-ae-' . ++$NEXT_SESSION_ID,
+ tls_ctx => undef,
+ };
+
+ return bless $self, $class;
+}
+
+# Execute a non-blocking HTTP request against the PVE API.
+#
+# Delivers at most one terminal callback (calling $cancel->() suppresses any later on_response or
+# on_error invocation, including deferred setup errors):
+# - on_response->($status, $body_ref, $hdr): AnyEvent::HTTP buffers the response body after HTTP
+# transfer decoding (e.g. chunked framing removed), and $body_ref points to it before
+# decompression or JSON decoding.
+# - on_error->($err): $err is a PVE::APIClient::Exception for transport/59x/setup failures.
+# Setup exceptions reach on_error on a later event-loop turn via AE::postpone. The transport may
+# invoke a terminal callback synchronously before request_raw() returns. Invalid callback
+# arguments or conflicting body and param arguments croak synchronously.
+# Returns an idempotent, cycle-free cancel coderef.
+sub request_raw($self, $method, $path, $param, %opts) {
+ my ($on_response, $on_error) = @opts{ 'on_response', 'on_error' };
+ croak "on_response must be a CODE ref" if ref($on_response) ne 'CODE';
+ croak "on_error must be a CODE ref" if ref($on_error) ne 'CODE';
+
+ my $uc_method = uc($method // '');
+ if (
+ ($uc_method eq 'POST' || $uc_method eq 'PUT')
+ && defined($opts{body})
+ && defined($param)
+ && ref($param) eq 'HASH'
+ && %$param
+ ) {
+ croak "cannot pass both body and param";
+ }
+
+ my $state = {
+ done => 0,
+ guard => undef,
+ };
+
+ my $cancel = sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ undef $state->{guard};
+ Net::SSLeay::ERR_clear_error();
+ };
+
+ my $guard = eval {
+ if ($uc_method !~ /\A(?:GET|POST|PUT|DELETE|HEAD)\z/) {
+ die PVE::APIClient::Exception->new("method $uc_method not implemented\n");
+ }
+
+ my %headers = (
+ %{ $self->{headers} }, %{ normalize_headers($opts{headers}) },
+ );
+ for my $key (keys %headers) {
+ validate_header($key, $headers{$key});
+ }
+
+ my ($uri, $body);
+ if ($uc_method eq 'POST' || $uc_method eq 'PUT') {
+ $uri = build_uri($self, $path);
+ if (defined($opts{body})) {
+ $body = $opts{body};
+ } elsif (defined($param) && ref($param) eq 'HASH' && %$param) {
+ my $tmpurl = URI->new('http:');
+ $tmpurl->query_form(%$param);
+ $body = $tmpurl->query;
+ if (!exists($headers{'content-type'})) {
+ $headers{'content-type'} = 'application/x-www-form-urlencoded';
+ }
+ }
+ } else {
+ $uri = build_uri($self, $path, $param);
+ }
+
+ my %req_args = (
+ headers => \%headers,
+ timeout => $opts{timeout} // $self->{timeout},
+ proxy => undef,
+ persistent => $opts{persistent} // $self->{persistent},
+ recurse => 0,
+ keepalive => $opts{keepalive} // $self->{keepalive},
+ sessionid => $self->{sessionid},
+ );
+ $req_args{body} = $body if defined($body);
+ $req_args{tls_ctx} = build_tls_ctx($self) if $self->{protocol} eq 'https';
+
+ Net::SSLeay::ERR_clear_error();
+ return AnyEvent::HTTP::http_request(
+ $uc_method => $uri->as_string(),
+ %req_args,
+ sub {
+ my (undef, $hdr) = @_;
+
+ return if $state->{done};
+ $state->{done} = 1;
+ undef $state->{guard};
+
+ Net::SSLeay::ERR_clear_error();
+
+ my $status = $hdr->{Status} // 599;
+ if ($status >= 590 && $status <= 599) {
+ my $reason = $hdr->{Reason} // 'request failed';
+ my $exc = PVE::APIClient::Exception->new("$reason\n", code => $status);
+ invoke_callback($on_error, $exc);
+ return;
+ }
+
+ invoke_callback($on_response, $status, \$_[0], $hdr);
+ },
+ );
+ };
+ my $err = $@;
+
+ Net::SSLeay::ERR_clear_error();
+
+ if ($err) {
+ if (!$state->{done}) {
+ my $exc =
+ ref($err) eq 'PVE::APIClient::Exception'
+ ? $err
+ : PVE::APIClient::Exception->new("$err");
+ AE::postpone {
+ return if $state->{done};
+ $state->{done} = 1;
+ undef $state->{guard};
+ invoke_callback($on_error, $exc);
+ };
+ } else {
+ warn $err;
+ }
+ } elsif (!$state->{done}) {
+ $state->{guard} = $guard;
+ }
+
+ return $cancel;
+}
+
+# Execute a JSON API call with gzip support and deliver the full decoded JSON response to
+# on_response (matching PVE::APIClient::LWP::call).
+sub call($self, $method, $path, $param, %opts) {
+ my ($on_response, $on_error) = delete @opts{ 'on_response', 'on_error' };
+ croak "on_response must be a CODE ref" if ref($on_response) ne 'CODE';
+ croak "on_error must be a CODE ref" if ref($on_error) ne 'CODE';
+
+ if (
+ (!defined($opts{headers}) || ref($opts{headers}) eq 'HASH')
+ && !exists($self->{headers}->{'accept-encoding'})
+ ) {
+ my %hdrs = %{ $opts{headers} // {} };
+ if (!grep { defined($_) && !ref($_) && lc($_) eq 'accept-encoding' } keys %hdrs) {
+ $hdrs{'accept-encoding'} = 'gzip';
+ $opts{headers} = \%hdrs;
+ }
+ }
+
+ return $self->request_raw(
+ $method,
+ $path,
+ $param,
+ %opts,
+ on_error => $on_error,
+ on_response => sub {
+ my ($status, $body_ref, $hdr) = @_;
+
+ my $ct = $hdr->{'content-type'} // '';
+ my $is_gzip = (($hdr->{'content-encoding'} // '') =~ /\bgzip\b/i) ? 1 : 0;
+
+ if ($status < 200 || $status >= 300) {
+ my $reason = $hdr->{Reason} // "HTTP $status";
+ my $errors = eval {
+ return if $ct !~ m|application/json|i;
+ my $res = decode_json_body($body_ref, $is_gzip);
+ return ref($res) eq 'HASH' ? $res->{errors} : undef;
+ };
+ my $exc = PVE::APIClient::Exception->new(
+ "$reason\n",
+ code => $status,
+ errors => $errors,
+ );
+ $on_error->($exc);
+ return;
+ }
+
+ if ($ct !~ m|application/json|i) {
+ $on_error->(
+ PVE::APIClient::Exception->new(
+ "got unexpected content type\n",
+ code => $status,
+ ),
+ );
+ return;
+ }
+
+ my $decoded = eval { decode_json_body($body_ref, $is_gzip) };
+ if (my $err = $@) {
+ $on_error->(PVE::APIClient::Exception->new("$err", code => $status));
+ return;
+ }
+
+ $on_response->($decoded);
+ },
+ );
+}
+
+my sub call_data($self, $method, $path, $param, %opts) {
+ my ($on_response, $on_error) = delete @opts{ 'on_response', 'on_error' };
+ croak "on_response must be a CODE ref" if ref($on_response) ne 'CODE';
+ croak "on_error must be a CODE ref" if ref($on_error) ne 'CODE';
+
+ return $self->call(
+ $method,
+ $path,
+ $param,
+ %opts,
+ on_error => $on_error,
+ on_response => sub {
+ my ($res) = @_;
+ if (ref($res) ne 'HASH') {
+ $on_error->(PVE::APIClient::Exception->new("unexpected response format\n"));
+ return;
+ }
+ if (defined($res->{success}) && !$res->{success}) {
+ my $msg = $res->{message} || 'API error';
+ $msg .= "\n" if $msg !~ /\n\z/;
+ $on_error->(
+ PVE::APIClient::Exception->new(
+ $msg,
+ code => $res->{status} || 500,
+ errors => $res->{errors},
+ ),
+ );
+ return;
+ }
+ if (!exists($res->{data})) {
+ $on_error->(PVE::APIClient::Exception->new("unexpected response format\n"));
+ return;
+ }
+ $on_response->($res->{data});
+ },
+ );
+}
+
+sub get($self, $path, $param, %opts) {
+ return call_data($self, 'GET', $path, $param, %opts);
+}
+
+sub post($self, $path, $param, %opts) {
+ return call_data($self, 'POST', $path, $param, %opts);
+}
+
+sub put($self, $path, $param, %opts) {
+ return call_data($self, 'PUT', $path, $param, %opts);
+}
+
+sub delete($self, $path, $param, %opts) {
+ return call_data($self, 'DELETE', $path, $param, %opts);
+}
+
+1;
diff --git a/src/test/anyevent_client.t b/src/test/anyevent_client.t
new file mode 100644
index 0000000..8dc5bee
--- /dev/null
+++ b/src/test/anyevent_client.t
@@ -0,0 +1,1974 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use feature 'current_sub';
+
+use AnyEvent;
+use AnyEvent::Handle;
+use AnyEvent::HTTP;
+use AnyEvent::Socket;
+use AnyEvent::TLS;
+use Compress::Zlib qw(memGzip);
+use File::Temp qw(tempdir);
+use JSON qw(to_json);
+use Net::SSLeay;
+use Scalar::Util qw(weaken);
+use Test::More;
+
+use PVE::APIClient::AnyEvent;
+use PVE::APIClient::Exception;
+
+my $tmpdir = tempdir(CLEANUP => 1);
+my $key_file = "$tmpdir/server.key";
+my $cert_file = "$tmpdir/server.crt";
+
+my @openssl_cmd = (
+ 'openssl',
+ 'req',
+ '-x509',
+ '-newkey',
+ 'ec',
+ '-pkeyopt',
+ 'ec_paramgen_curve:prime256v1',
+ '-nodes',
+ '-keyout',
+ $key_file,
+ '-out',
+ $cert_file,
+ '-days',
+ '1',
+ '-subj',
+ '/CN=127.0.0.1',
+);
+my $rc;
+{
+ open(my $saved_err, '>&', \*STDERR) or BAIL_OUT("failed to dup STDERR: $!");
+ open(STDERR, '>', '/dev/null') or BAIL_OUT("failed to redirect STDERR: $!");
+ $rc = system(@openssl_cmd, '-batch');
+ if ($rc != 0) {
+ # Fallback for older openssl without -batch
+ $rc = system(@openssl_cmd);
+ }
+ open(STDERR, '>&', $saved_err) or BAIL_OUT("failed to restore STDERR: $!");
+}
+BAIL_OUT("failed to generate ephemeral test certificate with openssl") if $rc != 0;
+
+open(my $fp_fh, '-|', 'openssl', 'x509', '-in', $cert_file, '-noout', '-fingerprint', '-sha256')
+ or BAIL_OUT("failed to compute test certificate fingerprint: $!");
+my $fp_line = <$fp_fh>;
+close($fp_fh);
+my ($cert_fp) = ($fp_line // '') =~ /([0-9A-Fa-f:]{95})/;
+BAIL_OUT("could not parse certificate SHA-256 fingerprint from '$fp_line'") if !$cert_fp;
+$cert_fp = uc($cert_fp);
+
+my $wrong_fp = $cert_fp;
+$wrong_fp =~ s/^[0-9A-F]{2}/$wrong_fp =~ m|^00| ? 'FF' : '00'/e;
+
+my $server_tls = AnyEvent::TLS->new(
+ cert_file => $cert_file,
+ key_file => $key_file,
+);
+
+my %slow_hooks;
+my $slow_req_seen = 0;
+my $slow_eof_seen = 0;
+my %active_server_handles;
+
+my sub send_http_response {
+ my ($hdl, $status_line, $headers, $body, $keepalive) = @_;
+
+ $body //= '';
+ my $resp = "HTTP/1.1 $status_line\r\n";
+ $resp .= "Content-Length: " . length($body) . "\r\n";
+ $resp .= "Connection: " . ($keepalive ? "keep-alive" : "close") . "\r\n";
+ for my $k (sort keys %$headers) {
+ $resp .= "$k: $headers->{$k}\r\n";
+ }
+ $resp .= "\r\n$body";
+
+ $hdl->push_write($resp);
+ $hdl->push_shutdown() if !$keepalive;
+}
+
+my sub dispatch_server_request {
+ my ($hdl, $id, $method, $target, $headers, $body, $on_keepalive) = @_;
+
+ my ($path, $query) = split(/\?/, $target, 2);
+
+ if ($path eq '/api2/json/keepalive') {
+ my $payload = to_json({ data => { conn_id => $id } }, { utf8 => 1 });
+ send_http_response(
+ $hdl,
+ '200 OK',
+ { 'Content-Type' => 'application/json;charset=UTF-8' },
+ $payload,
+ 1,
+ );
+ $on_keepalive->() if $on_keepalive;
+ } elsif ($path eq '/api2/json/echo-headers') {
+ my $payload = to_json(
+ {
+ data => {
+ method => $method,
+ path => $path,
+ query => $query,
+ headers => $headers,
+ body => $body,
+ },
+ },
+ { utf8 => 1 },
+ );
+ my %resp_hdr = ('Content-Type' => 'application/json;charset=UTF-8');
+ if (($headers->{'accept-encoding'} // '') =~ /\bgzip\b/i) {
+ $payload = memGzip($payload);
+ $resp_hdr{'Content-Encoding'} = 'gzip';
+ }
+ send_http_response($hdl, '200 OK', \%resp_hdr, $payload);
+ } elsif ($path eq '/api2/json/gzip-raw') {
+ my $payload = memGzip(to_json({ data => { hello => 'world' } }, { utf8 => 1 }));
+ send_http_response(
+ $hdl,
+ '200 OK',
+ {
+ 'Content-Type' => 'application/json',
+ 'Content-Encoding' => 'gzip',
+ },
+ $payload,
+ );
+ } elsif ($path eq '/api2/json/error-500') {
+ my $payload = to_json(
+ {
+ data => undef,
+ errors => { node => 'offline' },
+ },
+ { utf8 => 1 },
+ );
+ send_http_response(
+ $hdl,
+ '500 Internal Failure',
+ { 'Content-Type' => 'application/json' },
+ $payload,
+ );
+ } elsif ($path eq '/api2/json/plain-text') {
+ send_http_response($hdl, '200 OK', { 'Content-Type' => 'text/plain' }, 'plain body');
+ } elsif ($path eq '/api2/json/bad-json') {
+ send_http_response(
+ $hdl,
+ '200 OK',
+ { 'Content-Type' => 'application/json' },
+ '{not valid json',
+ );
+ } elsif ($path eq '/api2/json/with-total') {
+ send_http_response(
+ $hdl,
+ '200 OK',
+ { 'Content-Type' => 'application/json' },
+ to_json({ data => { ok => 1 }, total => 42 }, { utf8 => 1 }),
+ );
+ } elsif ($path eq '/api2/json/no-data') {
+ send_http_response(
+ $hdl,
+ '200 OK',
+ { 'Content-Type' => 'application/json' },
+ to_json({ total => 0 }, { utf8 => 1 }),
+ );
+ } elsif ($path eq '/api2/extjs/fail-502') {
+ send_http_response(
+ $hdl,
+ '200 OK',
+ { 'Content-Type' => 'application/json' },
+ to_json(
+ {
+ success => 0,
+ status => 502,
+ message => 'peer fetch failed',
+ errors => { peer => 'unreachable' },
+ data => undef,
+ },
+ { utf8 => 1 },
+ ),
+ );
+ } elsif ($path eq '/api2/json/slow') {
+ $slow_req_seen++;
+ $slow_hooks{on_seen}->() if $slow_hooks{on_seen};
+ # Keep handle open until client cancels/closes the socket.
+ $hdl->on_read(sub { });
+ $hdl->on_eof(sub {
+ $slow_eof_seen++;
+ delete $active_server_handles{$id};
+ $slow_hooks{on_eof}->() if $slow_hooks{on_eof};
+ });
+ $hdl->on_error(sub {
+ $slow_eof_seen++;
+ delete $active_server_handles{$id};
+ $slow_hooks{on_eof}->() if $slow_hooks{on_eof};
+ });
+ } else {
+ send_http_response(
+ $hdl,
+ '404 Not Found',
+ { 'Content-Type' => 'application/json' },
+ to_json({ data => undef }, { utf8 => 1 }),
+ );
+ }
+}
+
+my $server_port;
+my $next_conn_id = 1;
+my $server_guard = tcp_server(
+ '127.0.0.1',
+ 0,
+ sub {
+ my ($fh) = @_;
+ my $id = $next_conn_id++;
+ my $hdl;
+ $hdl = AnyEvent::Handle->new(
+ fh => $fh,
+ tls => 'accept',
+ tls_ctx => $server_tls,
+ on_error => sub {
+ delete $active_server_handles{$id};
+ $hdl->destroy() if $hdl;
+ },
+ on_eof => sub {
+ delete $active_server_handles{$id};
+ $hdl->destroy() if $hdl;
+ },
+ );
+ $active_server_handles{$id} = $hdl;
+
+ my $read_next;
+ $read_next = sub {
+ return if !$active_server_handles{$id};
+ $hdl->push_read(
+ regex => qr/\r?\n\r?\n/,
+ sub {
+ my ($h, $raw_hdr) = @_;
+ my @lines = split(/\r?\n/, $raw_hdr);
+ my $req_line = shift @lines // '';
+ my ($method, $target) = split(/ /, $req_line);
+ my %headers;
+ for my $line (@lines) {
+ if ($line =~ /^([^:]+):\s*(.*)$/) {
+ $headers{ lc($1) } = $2;
+ }
+ }
+ my $cl = $headers{'content-length'} // 0;
+ if ($cl > 0) {
+ $h->push_read(
+ chunk => $cl,
+ sub {
+ my ($h2, $body) = @_;
+ dispatch_server_request(
+ $h2, $id, $method, $target, \%headers, $body, $read_next,
+ );
+ },
+ );
+ } else {
+ dispatch_server_request(
+ $h, $id, $method, $target, \%headers, '', $read_next,
+ );
+ }
+ },
+ );
+ };
+ $read_next->();
+ },
+ sub {
+ my (undef, undef, $port) = @_;
+ $server_port = $port;
+ },
+);
+
+ok(defined($server_port) && $server_port > 0, "loopback TLS server listening on port $server_port");
+
+my sub run_with_timeout {
+ my ($cb, $timeout) = @_;
+ $timeout //= 5;
+ my $cv = AE::cv;
+ my $t = AE::timer($timeout, 0, sub { $cv->croak("test timed out after ${timeout}s") });
+ $cb->($cv);
+ return $cv->recv();
+}
+
+subtest 'TLS SHA-256 fingerprint pinning pass, mismatch, and callback' => sub {
+ my $ok_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my $res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $ok_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($res->{ok}, 'valid SHA-256 pinned fingerprint succeeds');
+ is(
+ $res->{data}->{path},
+ '/api2/json/echo-headers',
+ 'request path resolved under /api2/json/',
+ );
+
+ my $bad_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $wrong_fp => 1 },
+ );
+
+ my $bad_res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $bad_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$bad_res->{ok}, 'mismatched SHA-256 fingerprint is rejected');
+ isa_ok($bad_res->{err}, 'PVE::APIClient::Exception');
+ ok(
+ $bad_res->{err}->{code} >= 590 && $bad_res->{err}->{code} <= 599,
+ 'TLS mismatch yields 59x code',
+ );
+
+ my $verify_calls = 0;
+ my $cb_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ verify_fingerprint_cb => sub {
+ my ($cert) = @_;
+ $verify_calls++;
+ my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
+ return uc($fp) eq $cert_fp ? 1 : 0;
+ },
+ );
+
+ for my $i (1 .. 2) {
+ my $r = run_with_timeout(sub {
+ my ($cv) = @_;
+ $cb_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r->{ok}, "verify_fingerprint_cb request #$i succeeds");
+ }
+ is($verify_calls, 1, 'verified fingerprint is cached across subsequent requests');
+
+ my $reject_cb_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ verify_fingerprint_cb => sub { return 0; },
+ );
+ my $rej = run_with_timeout(sub {
+ my ($cv) = @_;
+ $reject_cb_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$rej->{ok}, 'verify_fingerprint_cb returning false rejects connection');
+ isa_ok($rej->{err}, 'PVE::APIClient::Exception');
+};
+
+subtest 'IPv6 URI host bracketing' => sub {
+ my @captured_urls;
+ no warnings 'redefine';
+ local *AnyEvent::HTTP::http_request = sub {
+ my $cb = pop @_;
+ my ($method, $url, %args) = @_;
+ push @captured_urls, "$method $url";
+ $cb->('{"data":1}', { Status => 200, 'content-type' => 'application/json' });
+ return undef;
+ };
+
+ my $v6 = PVE::APIClient::AnyEvent->new(
+ host => '2001:db8::1',
+ port => 8006,
+ protocol => 'http',
+ );
+ my $got;
+ $v6->get(
+ 'nodes',
+ { full => 1 },
+ on_response => sub { $got = $_[0] },
+ on_error => sub { fail("unexpected error: $_[0]") },
+ );
+ is($got, 1, 'IPv6 request delivered response');
+ is(
+ $captured_urls[0],
+ 'GET http://[2001:db8::1]:8006/api2/json/nodes?full=1',
+ 'unbracketed IPv6 host is bracketed in URI',
+ );
+
+ my $v6_bracketed = PVE::APIClient::AnyEvent->new(
+ host => '[::1]',
+ port => 8006,
+ protocol => 'http',
+ );
+ $v6_bracketed->get(
+ '/api2/extjs/version',
+ undef,
+ on_response => sub { },
+ on_error => sub { fail("unexpected error: $_[0]") },
+ );
+ is(
+ $captured_urls[1],
+ 'GET http://[::1]:8006/api2/extjs/version',
+ 'pre-bracketed IPv6 host and explicit /api2/ path handled cleanly',
+ );
+};
+
+subtest 'auth headers, custom headers, and POST form encoding' => sub {
+ my $tok_bare = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ api_token => 'root@pam!tok=secret-val',
+ headers => { PVEDisableProxy => '1' },
+ );
+ my $r1 = run_with_timeout(sub {
+ my ($cv) = @_;
+ $tok_bare->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is(
+ $r1->{headers}->{authorization},
+ 'PVEAPIToken=root%40pam%21tok%3Dsecret-val',
+ 'bare api_token gets default PVEAPIToken= prefix and URI escaping',
+ );
+ is($r1->{headers}->{pvedisableproxy}, '1', 'custom default header sent');
+
+ my $tok_special = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ api_token => 'cn=alice;bob%20@pam!tok=sec-ret',
+ );
+ my $r_special = run_with_timeout(sub {
+ my ($cv) = @_;
+ $tok_special->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is(
+ $r_special->{headers}->{authorization},
+ 'PVEAPIToken=cn%3Dalice%3Bbob%2520%40pam%21tok%3Dsec-ret',
+ 'bare api_token escapes =, ;, and % in user ID without mistaking it for a scheme header',
+ );
+
+ my $extjs_err = run_with_timeout(sub {
+ my ($cv) = @_;
+ $tok_bare->get(
+ 'api2/extjs/fail-502',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$extjs_err->{ok}, 'get() routes HTTP 200 ExtJS success:0 failure to on_error');
+ isa_ok($extjs_err->{err}, 'PVE::APIClient::Exception');
+ is($extjs_err->{err}->{code}, 502, 'ExtJS failure status code preserved');
+ like($extjs_err->{err}->{msg}, qr/peer fetch failed/, 'ExtJS failure message preserved');
+ is_deeply(
+ $extjs_err->{err}->{errors},
+ { peer => 'unreachable' },
+ 'ExtJS failure errors hash preserved',
+ );
+
+ my $tok_prefixed = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ apitoken => 'PVEAPIToken=root@pam!tok=already-prefixed',
+ );
+ my $r2 = run_with_timeout(sub {
+ my ($cv) = @_;
+ $tok_prefixed->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is(
+ $r2->{headers}->{authorization},
+ 'PVEAPIToken=root@pam!tok=already-prefixed',
+ 'prefixed apitoken is preserved without double prefix',
+ );
+
+ my $ticket_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ ticket => 'PVE:root@pam:ABC+1/2',
+ csrftoken => 'csrf-token-xyz',
+ );
+ my $r3 = run_with_timeout(sub {
+ my ($cv) = @_;
+ $ticket_client->call(
+ 'POST',
+ 'echo-headers',
+ { key => 'val 1' },
+ headers => { 'X-Extra' => 'yes' },
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ like(
+ $r3->{data}->{headers}->{cookie},
+ qr/^PVEAuthCookie=PVE%3Aroot%40pam%3AABC%2B1%2F2;/,
+ 'ticket sent as URL-encoded cookie',
+ );
+ is(
+ $r3->{data}->{headers}->{csrfpreventiontoken},
+ 'csrf-token-xyz',
+ 'CSRFPreventionToken header sent',
+ );
+ is($r3->{data}->{headers}->{'x-extra'}, 'yes', 'per-request custom header sent');
+ is(
+ $r3->{data}->{headers}->{'content-type'},
+ 'application/x-www-form-urlencoded',
+ 'POST sets form-urlencoded Content-Type',
+ );
+ is($r3->{data}->{body}, 'key=val+1', 'POST encodes param hashref into body');
+};
+
+subtest 'request_raw undecoded gzip wire bytes vs get/call decoding' => sub {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my $raw_res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->request_raw(
+ 'GET',
+ 'gzip-raw',
+ undef,
+ headers => { 'Accept-Encoding' => 'gzip' },
+ on_response => sub {
+ my ($status, $body_ref, $hdr) = @_;
+ $cv->send({ status => $status, body => $$body_ref, hdr => $hdr });
+ },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is($raw_res->{status}, 200, 'request_raw receives HTTP 200');
+ is($raw_res->{hdr}->{'content-encoding'}, 'gzip', 'request_raw preserves content-encoding');
+ is(
+ substr($raw_res->{body}, 0, 2),
+ "\x1f\x8b",
+ 'request_raw returns undecoded gzip wire bytes',
+ );
+
+ my $wire_copy = $raw_res->{body};
+ my $decoded = PVE::APIClient::AnyEvent::decode_json_body(\$wire_copy, 1);
+ is_deeply(
+ $decoded,
+ { data => { hello => 'world' } },
+ 'decode_json_body decodes gzipped JSON',
+ );
+ is($wire_copy, $raw_res->{body}, 'decode_json_body does not mutate caller scalar');
+
+ my $data = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'gzip-raw',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is_deeply($data, { hello => 'world' }, 'get() gunzips and returns decoded data field');
+};
+
+subtest 'HTTP 500 JSON errors, bad content-type/JSON, and transport errors' => sub {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my $err500 = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'error-500',
+ undef,
+ on_response => sub { $cv->croak('expected error') },
+ on_error => sub { $cv->send($_[0]) },
+ );
+ });
+ isa_ok($err500, 'PVE::APIClient::Exception');
+ is($err500->{code}, 500, 'HTTP 500 exception preserves status code');
+ is_deeply(
+ $err500->{errors},
+ { node => 'offline' },
+ 'HTTP 500 exception preserves JSON errors',
+ );
+
+ my $err_ct = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'plain-text',
+ undef,
+ on_response => sub { $cv->croak('expected error') },
+ on_error => sub { $cv->send($_[0]) },
+ );
+ });
+ isa_ok($err_ct, 'PVE::APIClient::Exception');
+ like("$err_ct", qr/unexpected content type/, 'non-JSON content-type rejected in call()');
+
+ my $err_json = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'bad-json',
+ undef,
+ on_response => sub { $cv->croak('expected error') },
+ on_error => sub { $cv->send($_[0]) },
+ );
+ });
+ isa_ok($err_json, 'PVE::APIClient::Exception');
+ is($err_json->{code}, 200, 'invalid JSON yields PVE::APIClient::Exception');
+
+ # Find an unbound port by binding and immediately closing a socket.
+ my $closed_port;
+ {
+ my $tmp_guard = tcp_server(
+ '127.0.0.1',
+ 0,
+ sub { },
+ sub { my (undef, undef, $p) = @_; $closed_port = $p; },
+ );
+ }
+ my $refused_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $closed_port,
+ protocol => 'http',
+ );
+ my $err_conn = run_with_timeout(sub {
+ my ($cv) = @_;
+ $refused_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->croak('expected connection error') },
+ on_error => sub { $cv->send($_[0]) },
+ );
+ });
+ isa_ok($err_conn, 'PVE::APIClient::Exception');
+ ok($err_conn->{code} >= 590 && $err_conn->{code} <= 599, 'transport error yields 59x code');
+
+ my $bad_method_err;
+ my $deferred_cv = AE::cv;
+ my $deferred_timeout =
+ AE::timer(5, 0, sub { $deferred_cv->croak('deferred setup error timed out') });
+ $client->request_raw(
+ 'PATCH',
+ 'echo-headers',
+ undef,
+ on_response => sub { fail('unexpected response') },
+ on_error => sub {
+ $bad_method_err = $_[0];
+ $deferred_cv->send(1);
+ },
+ );
+ is($bad_method_err, undef, 'setup error is deferred until after request_raw returns');
+ $deferred_cv->recv;
+ undef $deferred_timeout;
+ isa_ok($bad_method_err, 'PVE::APIClient::Exception');
+ like(
+ "$bad_method_err",
+ qr/not implemented/,
+ 'unsupported method yields deferred exception',
+ );
+
+ my $suppressed_err = 0;
+ my $cancel_deferred = $client->request_raw(
+ 'PATCH',
+ 'echo-headers',
+ undef,
+ on_response => sub { $suppressed_err++ },
+ on_error => sub { $suppressed_err++ },
+ );
+ $cancel_deferred->();
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ my $t;
+ $t = AE::timer(0.03, 0, sub { undef $t; $cv->send(1) });
+ });
+ is($suppressed_err, 0, 'immediate cancel suppresses deferred setup error');
+};
+
+subtest 'cancellation aborts in-flight loopback socket cleanly' => sub {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my $terminal_called = 0;
+ my $cancel;
+ my $eof_cv = AE::cv;
+ my $timeout =
+ AE::timer(5, 0, sub { $eof_cv->croak('server did not see EOF after cancel') });
+
+ %slow_hooks = (
+ on_seen => sub {
+ $cancel->();
+ $cancel->(); # idempotent second call
+ },
+ on_eof => sub {
+ $eof_cv->send(1);
+ },
+ );
+
+ $cancel = $client->get(
+ 'slow',
+ undef,
+ on_response => sub { $terminal_called++ },
+ on_error => sub { $terminal_called++ },
+ );
+
+ ok($eof_cv->recv, 'server observed EOF after client cancellation');
+ %slow_hooks = ();
+ undef $timeout;
+
+ # Drain one short timer tick to confirm no delayed terminal callback fires.
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ my $t;
+ $t = AE::timer(0.05, 0, sub { undef $t; $cv->send(1) });
+ });
+ is($terminal_called, 0, 'cancelled request fires neither on_response nor on_error');
+};
+
+subtest 'single terminal outcome and sync/async callback exception isolation' => sub {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, @_ };
+
+ my $on_error_calls = 0;
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub {
+ my $t;
+ $t = AE::timer(0.02, 0, sub { undef $t; $cv->send(1) });
+ die "async response boom\n";
+ },
+ on_error => sub { $on_error_calls++ },
+ );
+ });
+ is($on_error_calls, 0, 'async on_response exception does not invoke on_error');
+ ok(scalar(grep { /async response boom/ } @warnings) == 1,
+ 'async callback exception warned');
+
+ @warnings = ();
+ my $sync_err_calls = 0;
+ {
+ no warnings 'redefine';
+ local *AnyEvent::HTTP::http_request = sub {
+ my $cb = pop @_;
+ $cb->('{"data":42}', { Status => 200, 'content-type' => 'application/json' });
+ return undef;
+ };
+ $client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { die "sync response boom\n" },
+ on_error => sub { $sync_err_calls++ },
+ );
+ }
+ is($sync_err_calls, 0, 'sync on_response exception does not invoke on_error');
+ ok(scalar(grep { /sync response boom/ } @warnings) == 1, 'sync response exception warned');
+
+ @warnings = ();
+ my $sync_on_error_calls = 0;
+ {
+ no warnings 'redefine';
+ local *AnyEvent::HTTP::http_request = sub {
+ my $cb = pop @_;
+ $cb->(undef, { Status => 596, Reason => 'sync fail' });
+ return undef;
+ };
+ $client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { fail('unexpected response') },
+ on_error => sub {
+ $sync_on_error_calls++;
+ die "sync error boom\n";
+ },
+ );
+ }
+ is($sync_on_error_calls, 1, 'sync on_error exception does not trigger second on_error');
+ ok(scalar(grep { /sync error boom/ } @warnings) == 1, 'sync error exception warned');
+};
+
+subtest 'weakened-ref destruction (no reference cycles)' => sub {
+ my ($w_client, $w_cancel, $w_cb_token);
+ {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+ my $cb_token = { sentinel => 1 };
+ $w_client = $client;
+ $w_cb_token = $cb_token;
+ weaken($w_client);
+ weaken($w_cb_token);
+
+ my $cancel;
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ $cancel = $client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub {
+ my $keep = $cb_token;
+ $cv->send(1);
+ },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ $w_cancel = $cancel;
+ weaken($w_cancel);
+ }
+
+ is($w_client, undef, 'client object freed without reference cycles');
+ is($w_cancel, undef, 'cancel coderef freed without reference cycles');
+ is($w_cb_token, undef, 'callback captures freed without reference cycles');
+};
+
+subtest 'persistent TLS connection cache isolation per client instance' => sub {
+ my $good_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ persistent => 1,
+ keepalive => 1,
+ );
+ my $bad_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $wrong_fp => 1 },
+ persistent => 1,
+ keepalive => 1,
+ );
+
+ my $r1 = run_with_timeout(sub {
+ my ($cv) = @_;
+ $good_client->get(
+ 'keepalive',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r1->{ok}, 'persistent valid-pin client request #1 succeeds');
+ my $conn1 = $r1->{data}->{conn_id};
+
+ my $r2 = run_with_timeout(sub {
+ my ($cv) = @_;
+ $good_client->get(
+ 'keepalive',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r2->{ok}, 'persistent valid-pin client request #2 succeeds');
+ is($r2->{data}->{conn_id}, $conn1, 'same persistent client reuses its own TLS connection');
+
+ my $r_bad = run_with_timeout(sub {
+ my ($cv) = @_;
+ $bad_client->get(
+ 'keepalive',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_bad->{ok}, 'persistent wrong-pin client cannot reuse cached TLS connection');
+ isa_ok($r_bad->{err}, 'PVE::APIClient::Exception');
+ ok(
+ $r_bad->{err}->{code} >= 590 && $r_bad->{err}->{code} <= 599,
+ 'wrong-pin client fails TLS verification with 59x error',
+ );
+};
+
+subtest 'protocol normalization and validation' => sub {
+ eval {
+ PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ protocol => 'ftp',
+ );
+ };
+ like($@, qr/unsupported protocol 'ftp'/, 'unsupported protocol croaks');
+
+ my $upper_bad = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ protocol => 'HTTPS',
+ cached_fingerprints => { $wrong_fp => 1 },
+ );
+ my $bad_res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $upper_bad->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$bad_res->{ok}, 'uppercase HTTPS protocol enforces TLS fingerprint pin');
+
+ my $upper_ok = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ protocol => 'HTTPS',
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+ my $ok_res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $upper_ok->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($ok_res->{ok}, 'uppercase HTTPS protocol succeeds with valid pin');
+};
+
+subtest 'case-insensitive header merging' => sub {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ api_token => 'root@pam!tok=from-ctor',
+ headers => { authorization => 'PVEAPIToken=should-lose' },
+ );
+
+ my $ctor_res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is(
+ $ctor_res->{headers}->{authorization},
+ 'PVEAPIToken=root%40pam%21tok%3Dfrom-ctor',
+ 'constructor api_token overrides lowercase authorization in constructor headers',
+ );
+
+ my $override_ok = 0;
+ for my $i (1 .. 10) {
+ my $r = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'echo-headers',
+ undef,
+ headers => { authorization => "PVEAPIToken=override-$i" },
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ $override_ok++ if ($r->{headers}->{authorization} // '') eq "PVEAPIToken=override-$i";
+ }
+ is(
+ $override_ok,
+ 10,
+ 'per-request lowercase authorization override deterministically wins across 10 requests',
+ );
+};
+
+subtest 'fail-closed TLS verification callbacks' => sub {
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, @_ };
+
+ my $fp_throw_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ verify_fingerprint_cb => sub { die "fp verify boom\n" },
+ );
+ my $r1 = eval {
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ $fp_throw_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ };
+ is($@, '', 'throwing verify_fingerprint_cb does not escape event loop');
+ ok($r1 && !$r1->{ok}, 'throwing verify_fingerprint_cb fails closed into on_error');
+ isa_ok($r1->{err}, 'PVE::APIClient::Exception');
+ ok(
+ scalar(grep { /fp verify boom/ } @warnings) >= 1,
+ 'throwing verify_fingerprint_cb warned',
+ );
+
+ @warnings = ();
+ my $custom_cb_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ ssl_opts => {
+ verify_cb => sub { die "custom verify_cb boom\n" },
+ },
+ );
+ my $r2 = eval {
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ $custom_cb_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ };
+ is($@, '', 'throwing custom ssl_opts verify_cb does not escape event loop');
+ ok($r2 && !$r2->{ok}, 'throwing custom ssl_opts verify_cb fails closed into on_error');
+ isa_ok($r2->{err}, 'PVE::APIClient::Exception');
+ ok(
+ scalar(grep { /custom verify_cb boom/ } @warnings) >= 1,
+ 'throwing custom ssl_opts verify_cb warned',
+ );
+};
+
+subtest 'call() envelope vs get/post/put/delete helpers and body+param guard' => sub {
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my $envelope = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->call(
+ 'GET',
+ 'with-total',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is_deeply(
+ $envelope,
+ { data => { ok => 1 }, total => 42 },
+ 'call() delivers full decoded JSON envelope',
+ );
+
+ my $get_data = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'with-total',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is_deeply($get_data, { ok => 1 }, 'get() extracts data field from envelope');
+
+ my $post_data = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->post(
+ 'echo-headers',
+ { a => '1' },
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is($post_data->{method}, 'POST', 'post() sends POST and unwraps data');
+ is($post_data->{body}, 'a=1', 'post() encodes form parameters');
+
+ my $put_data = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->put(
+ 'echo-headers',
+ { b => '2' },
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is($put_data->{method}, 'PUT', 'put() sends PUT and unwraps data');
+ is($put_data->{body}, 'b=2', 'put() encodes form parameters');
+
+ my $delete_data = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->delete(
+ 'echo-headers',
+ { c => '3' },
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is($delete_data->{method}, 'DELETE', 'delete() sends DELETE and unwraps data');
+ is($delete_data->{query}, 'c=3', 'delete() encodes query parameters');
+
+ my $missing_data_err = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->get(
+ 'no-data',
+ undef,
+ on_response => sub { $cv->croak('expected unexpected response format error') },
+ on_error => sub { $cv->send($_[0]) },
+ );
+ });
+ isa_ok($missing_data_err, 'PVE::APIClient::Exception');
+ like(
+ "$missing_data_err",
+ qr/unexpected response format/,
+ 'missing data key errors in get()',
+ );
+
+ for my $m (qw(POST PUT)) {
+ eval {
+ $client->request_raw(
+ $m,
+ 'echo-headers',
+ { a => 1 },
+ body => 'raw-payload',
+ on_response => sub { },
+ on_error => sub { },
+ );
+ };
+ like($@, qr/cannot pass both body and param/, "$m with both body and param croaks");
+ }
+
+ my $raw_post = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->post(
+ 'echo-headers',
+ undef,
+ body => 'raw-payload',
+ headers => { 'Content-Type' => 'text/plain' },
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is($raw_post->{body}, 'raw-payload', 'POST with body and undef param succeeds');
+};
+
+subtest 'CA and hostname verification, custom verify_cb, and verify_fingerprint_cb fallback' =>
+ sub {
+ my $run_openssl = sub {
+ my (@cmd) = @_;
+ open(my $saved_err, '>&', \*STDERR) or BAIL_OUT("failed to dup STDERR: $!");
+ open(STDERR, '>', '/dev/null') or BAIL_OUT("failed to redirect STDERR: $!");
+ my $res = system('openssl', @cmd);
+ open(STDERR, '>&', $saved_err) or BAIL_OUT("failed to restore STDERR: $!");
+ BAIL_OUT("openssl @cmd failed with rc=$res") if $res != 0;
+ };
+
+ my $ca_key = "$tmpdir/ca.key";
+ my $ca_crt = "$tmpdir/ca.crt";
+ $run_openssl->(
+ 'req',
+ '-x509',
+ '-newkey',
+ 'ec',
+ '-pkeyopt',
+ 'ec_paramgen_curve:prime256v1',
+ '-nodes',
+ '-keyout',
+ $ca_key,
+ '-out',
+ $ca_crt,
+ '-days',
+ '1',
+ '-subj',
+ '/CN=PVE-Test-CA',
+ '-addext',
+ 'basicConstraints=critical,CA:TRUE',
+ '-addext',
+ 'keyUsage=critical,keyCertSign,cRLSign',
+ );
+
+ my $sign_leaf = sub {
+ my ($prefix, $cn, $san) = @_;
+ my $k = "$tmpdir/$prefix.key";
+ my $csr = "$tmpdir/$prefix.csr";
+ my $crt = "$tmpdir/$prefix.crt";
+ my $ext = "$tmpdir/$prefix.ext";
+ open(my $efh, '>', $ext) or BAIL_OUT("failed to write $ext: $!");
+ print {$efh} "basicConstraints=CA:FALSE\n";
+ print {$efh} "extendedKeyUsage=serverAuth\n";
+ print {$efh} "subjectAltName=$san\n";
+ close($efh);
+
+ $run_openssl->(
+ 'req',
+ '-new',
+ '-newkey',
+ 'ec',
+ '-pkeyopt',
+ 'ec_paramgen_curve:prime256v1',
+ '-nodes',
+ '-keyout',
+ $k,
+ '-out',
+ $csr,
+ '-subj',
+ "/CN=$cn",
+ );
+ $run_openssl->(
+ 'x509',
+ '-req',
+ '-in',
+ $csr,
+ '-CA',
+ $ca_crt,
+ '-CAkey',
+ $ca_key,
+ '-CAcreateserial',
+ '-out',
+ $crt,
+ '-days',
+ '1',
+ '-extfile',
+ $ext,
+ );
+ return ($crt, $k);
+ };
+
+ my ($good_crt, $good_key) = $sign_leaf->(
+ 'good_host', 'localhost', 'DNS:localhost,IP:127.0.0.1',
+ );
+ my ($wrong_crt, $wrong_key) = $sign_leaf->(
+ 'wrong_host', 'other.example.test', 'DNS:other.example.test',
+ );
+
+ my $start_leaf_server = sub {
+ my ($crt, $key) = @_;
+ my $tls = AnyEvent::TLS->new(cert_file => $crt, key_file => $key);
+ my %hdls;
+ my $port;
+ my $guard = tcp_server(
+ '127.0.0.1',
+ 0,
+ sub {
+ my ($fh) = @_;
+ my $id = "$fh";
+ my $hdl;
+ $hdl = AnyEvent::Handle->new(
+ fh => $fh,
+ tls => 'accept',
+ tls_ctx => $tls,
+ on_error => sub {
+ delete $hdls{$id};
+ $hdl->destroy() if $hdl;
+ },
+ on_eof => sub {
+ delete $hdls{$id};
+ $hdl->destroy() if $hdl;
+ },
+ );
+ $hdls{$id} = $hdl;
+ $hdl->push_read(
+ regex => qr/\r?\n\r?\n/,
+ sub {
+ my ($h) = @_;
+ send_http_response(
+ $h,
+ '200 OK',
+ { 'Content-Type' => 'application/json' },
+ to_json({ data => { ok => 1 } }, { utf8 => 1 }),
+ );
+ },
+ );
+ },
+ sub {
+ my (undef, undef, $p) = @_;
+ $port = $p;
+ },
+ );
+ return ($guard, $port, \%hdls);
+ };
+
+ my ($good_guard, $good_port, $good_hdls) = $start_leaf_server->($good_crt, $good_key);
+ my ($wrong_guard, $wrong_port, $wrong_hdls) = $start_leaf_server->($wrong_crt, $wrong_key);
+
+ # 1. Trusted CA + matching hostname succeeds; mismatched hostname fails.
+ my $ca_ok = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $good_port,
+ ssl_opts => { ca_file => $ca_crt },
+ );
+ my $r_ca_ok = run_with_timeout(sub {
+ my ($cv) = @_;
+ $ca_ok->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r_ca_ok->{ok}, 'trusted CA with matching hostname succeeds');
+
+ my $ca_mismatch = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $wrong_port,
+ ssl_opts => { ca_file => $ca_crt },
+ );
+ my $r_ca_mismatch = run_with_timeout(sub {
+ my ($cv) = @_;
+ $ca_mismatch->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_ca_mismatch->{ok}, 'trusted CA with mismatched hostname is rejected');
+ isa_ok($r_ca_mismatch->{err}, 'PVE::APIClient::Exception');
+
+ # 2. Custom verify_cb with verify_hostname => 1 enforces hostname verification.
+ my $custom_ok = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $good_port,
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_hostname => 1,
+ verify_cb => sub { return $_[4] },
+ },
+ );
+ my $r_custom_ok = run_with_timeout(sub {
+ my ($cv) = @_;
+ $custom_ok->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ $r_custom_ok->{ok},
+ 'custom verify_cb with verify_hostname => 1 accepts matching hostname',
+ );
+
+ my $custom_mismatch = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $wrong_port,
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_hostname => 1,
+ verify_cb => sub { return $_[4] },
+ },
+ );
+ my $r_custom_mismatch = run_with_timeout(sub {
+ my ($cv) = @_;
+ $custom_mismatch->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_custom_mismatch->{ok},
+ 'custom verify_cb with verify_hostname => 1 rejects mismatched hostname',
+ );
+
+ # 3. verify_fingerprint_cb-only client trusts valid CA+hostname without invoking callback,
+ # and falls back to verify_fingerprint_cb for untrusted or mismatched certs.
+ my $fp_cb_ca_calls = 0;
+ my $fp_ca_client = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $good_port,
+ ssl_opts => { ca_file => $ca_crt },
+ verify_fingerprint_cb => sub {
+ $fp_cb_ca_calls++;
+ return 0;
+ },
+ );
+ my $r_fp_ca = run_with_timeout(sub {
+ my ($cv) = @_;
+ $fp_ca_client->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r_fp_ca->{ok}, 'verify_fingerprint_cb-only client trusts valid CA+hostname cert');
+ is(
+ $fp_cb_ca_calls,
+ 0,
+ 'verify_fingerprint_cb is not called when CA and hostname verification succeed',
+ );
+
+ my $fp_cb_mismatch_calls = 0;
+ my $fp_mismatch_client = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $wrong_port,
+ ssl_opts => { ca_file => $ca_crt },
+ verify_fingerprint_cb => sub {
+ $fp_cb_mismatch_calls++;
+ return 0;
+ },
+ );
+ my $r_fp_mismatch = run_with_timeout(sub {
+ my ($cv) = @_;
+ $fp_mismatch_client->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_fp_mismatch->{ok}, 'verify_fingerprint_cb-only client rejects mismatched hostname');
+ is(
+ $fp_cb_mismatch_calls, 1, 'hostname mismatch falls back to verify_fingerprint_cb',
+ );
+
+ my $fp_cb_self_calls = 0;
+ my $fp_self_client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ ssl_opts => { ca_file => $ca_crt },
+ verify_fingerprint_cb => sub {
+ my ($cert) = @_;
+ $fp_cb_self_calls++;
+ my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
+ return uc($fp) eq $cert_fp ? 1 : 0;
+ },
+ );
+ my $r_fp_self = run_with_timeout(sub {
+ my ($cv) = @_;
+ $fp_self_client->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r_fp_self->{ok}, 'verify_fingerprint_cb-only client falls back for self-signed cert');
+ is(
+ $fp_cb_self_calls,
+ 1,
+ 'verify_fingerprint_cb invoked once for untrusted self-signed cert',
+ );
+
+ # 4. Disabling verify_hostname without pins or verify_cb fails closed before connecting.
+ my $unpinned_conns = 0;
+ my $unpinned_port;
+ my $unpinned_guard = tcp_server(
+ '127.0.0.1',
+ 0,
+ sub {
+ my ($fh) = @_;
+ $unpinned_conns++;
+ close($fh);
+ },
+ sub {
+ my (undef, undef, $p) = @_;
+ $unpinned_port = $p;
+ },
+ );
+ my $insecure_client = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $unpinned_port,
+ api_token => 'root@pam!tok=never-send-me',
+ ssl_opts => { ca_file => $ca_crt, verify_hostname => 0 },
+ );
+ my $r_insecure = run_with_timeout(sub {
+ my ($cv) = @_;
+ $insecure_client->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_insecure->{ok},
+ 'verify_hostname => 0 without pins or verify_cb fails closed via on_error',
+ );
+ isa_ok($r_insecure->{err}, 'PVE::APIClient::Exception');
+ like(
+ "$r_insecure->{err}",
+ qr/cannot disable verify_hostname/,
+ 'fail-closed error explains missing pin/callback requirement',
+ );
+ is($unpinned_conns, 0, 'no TCP connection or credentials sent when failing closed');
+
+ # 5. ssl_opts => { verify => 0 } fails closed even with cached_fingerprints or verify_fingerprint_cb.
+ my $verify_zero_pinned = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $unpinned_port,
+ api_token => 'root@pam!tok=never-send-me',
+ cached_fingerprints => { $cert_fp => 1 },
+ ssl_opts => { verify => 0 },
+ );
+ my $r_v0_pinned = run_with_timeout(sub {
+ my ($cv) = @_;
+ $verify_zero_pinned->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_v0_pinned->{ok},
+ 'ssl_opts verify => 0 with cached_fingerprints fails closed via on_error',
+ );
+ isa_ok($r_v0_pinned->{err}, 'PVE::APIClient::Exception');
+ like(
+ "$r_v0_pinned->{err}",
+ qr/verify => 0/,
+ 'verify => 0 error reports disabled TLS verification',
+ );
+
+ my $verify_zero_cb = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $unpinned_port,
+ api_token => 'root@pam!tok=never-send-me',
+ verify_fingerprint_cb => sub { return 1 },
+ ssl_opts => { verify => 0 },
+ );
+ my $r_v0_cb = run_with_timeout(sub {
+ my ($cv) = @_;
+ $verify_zero_cb->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_v0_cb->{ok},
+ 'ssl_opts verify => 0 with verify_fingerprint_cb fails closed via on_error',
+ );
+ isa_ok($r_v0_cb->{err}, 'PVE::APIClient::Exception');
+
+ # 6. Conflicting verify_hostname => 1 with verify_peername => 'none' fails closed.
+ my $conflict_client = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $unpinned_port,
+ api_token => 'root@pam!tok=never-send-me',
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_hostname => 1,
+ verify_peername => 'none',
+ },
+ );
+ my $r_conflict = run_with_timeout(sub {
+ my ($cv) = @_;
+ $conflict_client->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_conflict->{ok},
+ 'verify_hostname => 1 with verify_peername => none fails closed via on_error',
+ );
+ isa_ok($r_conflict->{err}, 'PVE::APIClient::Exception');
+ like(
+ "$r_conflict->{err}",
+ qr/conflicting ssl_opts/,
+ 'conflicting verify_hostname/verify_peername error is explicit',
+ );
+
+ # Reverse conflict (verify_hostname => 0 with active verify_peername) and uppercase 'NONE'
+ # without pinning must both fail closed before opening any socket.
+ for my $bad_tls (
+ [
+ 'verify_hostname => 0 with verify_peername => https',
+ { verify_hostname => 0, verify_peername => 'https' },
+ qr/conflicting ssl_opts/,
+ ],
+ [
+ 'uppercase verify_peername => NONE without pins',
+ { verify_peername => 'NONE' },
+ qr/cannot disable verify_hostname/,
+ ],
+ [
+ 'empty verify_peername',
+ { verify_peername => '' },
+ qr/invalid ssl_opts->\{verify_peername\}/,
+ ],
+ [
+ 'unknown verify_peername scheme',
+ { verify_peername => 'strict' },
+ qr/invalid ssl_opts->\{verify_peername\}/,
+ ],
+ [
+ 'numeric verify_peername',
+ { verify_peername => 1 },
+ qr/invalid ssl_opts->\{verify_peername\}/,
+ ],
+ [
+ 'non-CODE verify_cb',
+ { verify_cb => 'not-a-sub' },
+ qr/verify_cb\} must be a CODE ref/,
+ ],
+ ) {
+ my ($label, $opts, $re) = @$bad_tls;
+ my $c_bad = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $unpinned_port,
+ ssl_opts => $opts,
+ );
+ my $r_bad = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_bad->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_bad->{ok}, "$label fails closed via on_error");
+ like("$r_bad->{err}", $re, "$label returns explicit error");
+ }
+
+ for my $combo (
+ ['cached_fingerprints + verify_cb', { cached_fingerprints => { '00:11' => 1 } }],
+ ['verify_fingerprint_cb + verify_cb', { verify_fingerprint_cb => sub { 1 } }],
+ ) {
+ my ($label, $extra) = @$combo;
+ my $c_combo = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $unpinned_port,
+ %$extra,
+ ssl_opts => { ca_file => $ca_crt, verify_cb => sub { 1 } },
+ );
+ my $r_combo = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_combo->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_combo->{ok}, "$label fails closed via on_error");
+ like("$r_combo->{err}", qr/conflicting ssl_opts/, "$label error is explicit");
+ }
+
+ is(
+ $unpinned_conns,
+ 0,
+ 'no TCP connections opened for verify => 0 or conflicting/invalid ssl_opts',
+ );
+ undef $unpinned_guard;
+
+ # Uppercase verify_peername => 'HTTPS' must normalize to 'https' and reject wrong-host cert.
+ my $c_upper_https = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $wrong_port,
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_peername => 'HTTPS',
+ },
+ );
+ my $r_upper_https = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_upper_https->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_upper_https->{ok},
+ 'uppercase verify_peername => HTTPS normalizes and rejects wrong-host CA cert',
+ );
+
+ # verify_fingerprint_cb with verify_peername => 'none' (or 'NONE') and no explicit
+ # verify_hostname MUST NOT take the CA-chain shortcut on a wrong-host CA-signed cert.
+ for my $vp_none ('none', 'NONE') {
+ my $fp_cb_called = 0;
+ my $c_fp_vp_none = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $wrong_port,
+ verify_fingerprint_cb => sub {
+ $fp_cb_called++;
+ return 0;
+ },
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_peername => $vp_none,
+ },
+ );
+ my $r_fp_vp_none = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_fp_vp_none->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_fp_vp_none->{ok},
+ "verify_fingerprint_cb + verify_peername => '$vp_none' rejects wrong-host CA cert when cb denies",
+ );
+ is(
+ $fp_cb_called,
+ 1,
+ "verify_fingerprint_cb invoked (no CA shortcut) with verify_peername => '$vp_none'",
+ );
+ }
+
+ # Issuer verification error at depth > 0 followed by a valid matching-host leaf must
+ # still fail the chain (via %chain_failed) and consult verify_fingerprint_cb.
+ my $chain_crt = "$tmpdir/chain.crt";
+ {
+ open(my $in_leaf, '<', $good_crt) or die "open $good_crt: $!";
+ open(my $in_ca, '<', $ca_crt) or die "open $ca_crt: $!";
+ open(my $out_chain, '>', $chain_crt) or die "open $chain_crt: $!";
+ local $/;
+ my $leaf_pem = <$in_leaf>;
+ my $ca_pem = <$in_ca>;
+ print {$out_chain} $leaf_pem, $ca_pem;
+ close($out_chain);
+ }
+ my ($chain_guard, $chain_port, $chain_hdls) = $start_leaf_server->($chain_crt, $good_key);
+ my $issuer_cb_calls = 0;
+ my $c_issuer_fail = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $chain_port,
+ verify_fingerprint_cb => sub {
+ $issuer_cb_calls++;
+ return 0;
+ },
+ );
+ my $r_issuer_fail = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_issuer_fail->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_issuer_fail->{ok},
+ 'issuer failure at nonzero depth with matching-host leaf is rejected when cb denies',
+ );
+ is(
+ $issuer_cb_calls,
+ 1,
+ 'issuer failure at nonzero depth consulted verify_fingerprint_cb instead of trusting leaf',
+ );
+ undef $chain_guard;
+ %$chain_hdls = ();
+
+ undef $good_guard;
+ undef $wrong_guard;
+ %$good_hdls = ();
+ %$wrong_hdls = ();
+ };
+
+subtest 'outbound header injection validation' => sub {
+ my $hdr_conns = 0;
+ my $hdr_port;
+ my $hdr_guard = tcp_server(
+ '127.0.0.1',
+ 0,
+ sub {
+ my ($fh) = @_;
+ $hdr_conns++;
+ close($fh);
+ },
+ sub {
+ my (undef, undef, $p) = @_;
+ $hdr_port = $p;
+ },
+ );
+
+ my @bad_ctor_cases = (
+ ['default header name with CRLF', { headers => { "X-Bad\r\nInject" => 'v' } }],
+ ['default header name with space', { headers => { 'X Bad' => 'v' } }],
+ [
+ 'default header value with CRLF',
+ { headers => { 'X-Test' => "ok\r\nX-Injected: 1" } },
+ ],
+ ['default header value with NUL', { headers => { 'X-Test' => "ok\0bad" } }],
+ ['api_token with CRLF', { api_token => "root\@pam!t=sec\r\nX-Injected: 1" }],
+ ['api_token with NUL', { api_token => "root\@pam!t=sec\0bad" }],
+ ['csrftoken with CRLF', { csrftoken => "tok\r\nX-Injected: 1" }],
+ ['csrftoken with NUL', { csrftoken => "tok\0bad" }],
+ [
+ 'cookie_name with CRLF',
+ { cookie_name => "Bad\r\nCookie", ticket => 'PVE:root@pam:abc' },
+ ],
+ [
+ 'cookie_name with NUL',
+ { cookie_name => "Bad\0Cookie", ticket => 'PVE:root@pam:abc' },
+ ],
+ );
+
+ for my $case (@bad_ctor_cases) {
+ my ($label, $extra) = @$case;
+ eval {
+ PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $hdr_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ %$extra,
+ );
+ };
+ like($@, qr/invalid HTTP header/, "new() rejects $label");
+ }
+
+ my $client = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $hdr_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ );
+
+ my @bad_req_cases = (
+ ['per-request header name with CRLF', { "X-Bad\r\nInject" => 'v' }],
+ ['per-request header name with NUL', { "X-Bad\0Name" => 'v' }],
+ ['per-request header value with CRLF', { 'X-Test' => "v\r\nX-Injected: 1" }],
+ ['per-request header value with LF', { 'X-Test' => "v\nX-Injected: 1" }],
+ ['per-request header value with NUL', { 'X-Test' => "v\0bad" }],
+ );
+
+ for my $case (@bad_req_cases) {
+ my ($label, $headers) = @$case;
+ my $res = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ headers => $headers,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$res->{ok}, "request_raw rejects $label via on_error");
+ isa_ok($res->{err}, 'PVE::APIClient::Exception');
+ like("$res->{err}", qr/invalid HTTP header/, "error text identifies $label");
+ }
+
+ my $r_call_bad_hdr = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->call(
+ 'GET',
+ 'version',
+ undef,
+ headers => { 'X-Test' => "v\r\nX-Injected: 1" },
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_call_bad_hdr->{ok},
+ 'call() defers invalid per-request header to on_error without croaking',
+ );
+ isa_ok($r_call_bad_hdr->{err}, 'PVE::APIClient::Exception');
+ like(
+ "$r_call_bad_hdr->{err}",
+ qr/invalid HTTP header/,
+ 'call() error identifies invalid header',
+ );
+
+ is($hdr_conns, 0, 'no TCP connections opened for rejected per-request headers');
+
+ # Method validation must reject trailing newline (\z, not $).
+ my $r_bad_method = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->request_raw(
+ "GET\n",
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_bad_method->{ok}, 'request_raw rejects method with trailing newline');
+ isa_ok($r_bad_method->{err}, 'PVE::APIClient::Exception');
+ like("$r_bad_method->{err}", qr/not implemented/, 'trailing-newline method reports error');
+
+ # Bare PBSAPIToken and PDMAPIToken keep literal tokenid: and percent-encode only the secret.
+ for my $scheme ('PBSAPIToken', 'PDMAPIToken') {
+ my $bare_id = 'user@pbs!tok';
+ my $bare_secret = 'sec+ret%20=1:2';
+ my $c_tok = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ api_token_name => $scheme,
+ api_token => "${bare_id}:${bare_secret}",
+ );
+ my $r_tok = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_tok->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r_tok->{ok}, "$scheme bare token request succeeded");
+ my $auth_hdr = $r_tok->{data}->{headers}->{authorization} // '';
+ like(
+ $auth_hdr,
+ qr/\A\Q$scheme\E=\Q$bare_id\E:/,
+ "$scheme preserved literal tokenid and ':' delimiter",
+ );
+ my ($after_prefix) = $auth_hdr =~ /\A\Q$scheme\E=(.*)\z/s;
+ my ($parsed_id, $parsed_sec_enc) = split(/:/, $after_prefix // '', 2);
+ is($parsed_id, $bare_id, "$scheme split-on-colon recovered exact Authid");
+ require URI::Escape;
+ is(
+ URI::Escape::uri_unescape($parsed_sec_enc),
+ $bare_secret,
+ "$scheme percent-decoding secret recovered exact secret",
+ );
+ }
+
+ undef $hdr_guard;
+};
+
+undef $server_guard;
+%active_server_handles = ();
+
+done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
` (3 preceding siblings ...)
2026-12-01 10:18 ` [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client Thomas Lamprecht
@ 2026-12-01 10:19 ` Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
` (3 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:19 UTC (permalink / raw)
To: pve-devel
Fanning out asynchronous API calls across many cluster nodes needs a
concurrency cap, shared timeout budget, and clean cancellation without
reimplementing slot tracking in each caller. Add
PVE::APIClient::AnyEvent::Pool to drive bounded-concurrency batches
iteratively without deep recursion on synchronous completions.
The pool supports optional backpressure gating via can_dispatch() that
pauses the overall_timeout budget while downstream consumers are busy,
isolates synchronous start_item() and can_dispatch() exceptions, cancels
active operations on timeout or manual cancel, and releases references
cleanly to avoid cycles.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Add create_limiter() shared capacity limiter (with exception-isolated
dynamic cap evaluation, FIFO waiter wakeup with re-entrant wake
deferral so newly queued waiters cannot strand, and cancel/timeout
permit release) and an optional can_admit capacity gate so busy-worker
waits count toward overall_timeout while downstream backpressure via
can_dispatch pauses it.
- Measure elapsed timeout budget with CLOCK_MONOTONIC, sync AE::now
before arming the timeout watcher, and rearm if the watcher fires
before the monotonic budget expires.
- Document deadline/wakeup semantics and expand pool unit tests.
src/Makefile | 3 +-
src/PVE/APIClient/AnyEvent/Pool.pm | 444 +++++++++++++
src/test/anyevent_pool.t | 995 +++++++++++++++++++++++++++++
3 files changed, 1441 insertions(+), 1 deletion(-)
create mode 100644 src/PVE/APIClient/AnyEvent/Pool.pm
create mode 100644 src/test/anyevent_pool.t
diff --git a/src/Makefile b/src/Makefile
index d6327c6..178380c 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -6,9 +6,10 @@ DOCDIR=$(DESTDIR)/usr/share/doc/$(PACKAGE)
all:
-install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm PVE/APIClient/AnyEvent.pm examples/*.pl
+install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm PVE/APIClient/AnyEvent.pm PVE/APIClient/AnyEvent/Pool.pm examples/*.pl
install -D -m 0644 PVE/APIClient/LWP.pm $(PERL5DIR)/PVE/APIClient/LWP.pm
install -m 0644 PVE/APIClient/AnyEvent.pm $(PERL5DIR)/PVE/APIClient/AnyEvent.pm
+ install -D -m 0644 PVE/APIClient/AnyEvent/Pool.pm $(PERL5DIR)/PVE/APIClient/AnyEvent/Pool.pm
install -m 0644 PVE/APIClient/Exception.pm $(PERL5DIR)/PVE/APIClient/Exception.pm
install -d -m 755 $(DOCDIR)/examples
install -m 0755 examples/example1.pl $(DOCDIR)/examples
diff --git a/src/PVE/APIClient/AnyEvent/Pool.pm b/src/PVE/APIClient/AnyEvent/Pool.pm
new file mode 100644
index 0000000..c4d5903
--- /dev/null
+++ b/src/PVE/APIClient/AnyEvent/Pool.pm
@@ -0,0 +1,444 @@
+package PVE::APIClient::AnyEvent::Pool;
+
+# Bounded-concurrency async request pool for multi-target fan-out inside an AnyEvent event loop.
+# Drives queued operations iteratively up to a concurrency cap with optional backpressure gating,
+# shared timeout accounting, exception isolation, and idempotent cancellation. See start() below
+# for the full callback and backpressure contract.
+
+use v5.36;
+
+use AnyEvent;
+use Carp;
+use Net::SSLeay;
+use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
+
+my sub mono_time() {
+ return clock_gettime(CLOCK_MONOTONIC);
+}
+
+my sub invoke_callback($cb, @args) {
+ eval { $cb->(@args); };
+ my $err = $@;
+ # Clear OpenSSL errors left by TLS teardowns or user callbacks (see PVE::APIServer::AnyEvent).
+ Net::SSLeay::ERR_clear_error();
+ warn $err if $err;
+}
+
+# Create a shared capacity limiter usable across multiple Pool::start() instances.
+# $limit may be a positive integer or a CODE ref evaluated dynamically to return the current cap.
+sub create_limiter($limit) {
+ if (ref($limit) eq 'CODE') {
+ # Dynamic cap evaluated on each acquire/wake.
+ } elsif (!ref($limit) && defined($limit) && $limit =~ /^[0-9]+\z/ && $limit >= 1) {
+ $limit = int($limit);
+ } else {
+ croak "limit must be a positive integer or CODE ref";
+ }
+
+ return bless {
+ limit => $limit,
+ active => 0,
+ waiters => [],
+ waking => 0,
+ wake_scheduled => 0,
+ }, 'PVE::APIClient::AnyEvent::Pool::Limiter';
+}
+
+my sub limiter_cap($limiter) {
+ my $raw;
+ if (ref($limiter->{limit}) eq 'CODE') {
+ $raw = eval { $limiter->{limit}->() };
+ my $err = $@;
+ Net::SSLeay::ERR_clear_error();
+ if ($err) {
+ warn $err;
+ return undef;
+ }
+ } else {
+ $raw = $limiter->{limit};
+ }
+ my $cap = int($raw // 1);
+ return $cap < 1 ? 1 : $cap;
+}
+
+my sub wake_limiter_waiters($limiter) {
+ if ($limiter->{waking}) {
+ $limiter->{wake_pending} = 1;
+ return;
+ }
+ my $self = __SUB__;
+ $limiter->{waking} = 1;
+ eval {
+ my $remaining = scalar(@{ $limiter->{waiters} });
+ while ($remaining-- > 0 && @{ $limiter->{waiters} }) {
+ my $cap = limiter_cap($limiter);
+ last if !defined($cap) || $limiter->{active} >= $cap;
+ my $waiter = shift @{ $limiter->{waiters} };
+ $waiter->{queued} = 0;
+ next if $waiter->{done};
+ my $dispatch = $waiter->{dispatch};
+ $dispatch->() if $dispatch;
+ }
+ };
+ my $err = $@;
+ $limiter->{waking} = 0;
+ if (delete $limiter->{wake_pending} && !$limiter->{wake_scheduled} && @{ $limiter->{waiters} })
+ {
+ $limiter->{wake_scheduled} = 1;
+ AE::postpone(sub {
+ $limiter->{wake_scheduled} = 0;
+ $self->($limiter);
+ });
+ }
+ warn $err if $err;
+}
+
+my sub schedule_wake_limiter_waiters($limiter) {
+ return if $limiter->{wake_scheduled} || !@{ $limiter->{waiters} };
+ $limiter->{wake_scheduled} = 1;
+ AE::postpone(sub {
+ $limiter->{wake_scheduled} = 0;
+ wake_limiter_waiters($limiter);
+ });
+}
+
+my sub cleanup_state($state) {
+ my @entries = values %{ $state->{active} };
+ my $limiter = $state->{limiter};
+ if (my $waiter = $state->{limiter_waiter}) {
+ $waiter->{done} = 1;
+ delete $waiter->{dispatch};
+ if ($waiter->{queued} && $limiter && !$limiter->{waking}) {
+ $waiter->{queued} = 0;
+ @{ $limiter->{waiters} } = grep { $_ != $waiter } @{ $limiter->{waiters} };
+ }
+ }
+
+ # Clear in place so no lingering reference holds onto active guards or queued items.
+ %{ $state->{active} } = ();
+ @{ $state->{queue} } = ();
+ undef $state->{timeout_watcher};
+ undef $state->{timeout_started_at};
+ delete @{$state}{qw(start_item on_done can_dispatch can_admit on_start_error limiter limiter_waiter)};
+
+ for my $entry (@entries) {
+ if (ref($entry) eq 'HASH') {
+ invoke_callback($entry->{cancel}) if ref($entry->{cancel}) eq 'CODE';
+ $entry->{release}->(1) if ref($entry->{release}) eq 'CODE';
+ }
+ }
+}
+
+my sub complete_pool($state, $timed_out = 0) {
+ return if $state->{done};
+ $state->{done} = 1;
+
+ my @pending_ids;
+ if ($timed_out) {
+ my @ids = (keys %{ $state->{active} }, map { $_->{id} } @{ $state->{queue} });
+ @pending_ids = sort @ids;
+ }
+
+ my $on_done = $state->{on_done};
+ cleanup_state($state);
+
+ invoke_callback($on_done, $timed_out ? 1 : 0, \@pending_ids) if $on_done;
+}
+
+my sub pause_timeout($state) {
+ return if !defined($state->{remaining_timeout}) || !defined($state->{timeout_started_at});
+
+ my $elapsed = mono_time() - $state->{timeout_started_at};
+ $elapsed = 0 if $elapsed < 0;
+
+ $state->{remaining_timeout} -= $elapsed;
+ $state->{remaining_timeout} = 0 if $state->{remaining_timeout} < 0;
+ undef $state->{timeout_started_at};
+ undef $state->{timeout_watcher};
+}
+
+my sub resume_timeout($state) {
+ return if $state->{done};
+ return if !defined($state->{remaining_timeout}) || defined($state->{timeout_started_at});
+
+ my $self = __SUB__;
+ $state->{timeout_started_at} = mono_time();
+ AnyEvent->now_update();
+ $state->{timeout_watcher} = AE::timer(
+ $state->{remaining_timeout},
+ 0,
+ sub {
+ return if $state->{done} || !defined($state->{timeout_started_at});
+ my $elapsed = mono_time() - $state->{timeout_started_at};
+ $elapsed = 0 if $elapsed < 0;
+ if ($elapsed < $state->{remaining_timeout}) {
+ $state->{remaining_timeout} -= $elapsed;
+ undef $state->{timeout_started_at};
+ undef $state->{timeout_watcher};
+ $self->($state);
+ return;
+ }
+ complete_pool($state, 1);
+ },
+ );
+}
+
+my sub timeout_expired($state) {
+ return 0 if !defined($state->{remaining_timeout});
+ return $state->{remaining_timeout} <= 0 ? 1 : 0 if !defined($state->{timeout_started_at});
+
+ my $elapsed = mono_time() - $state->{timeout_started_at};
+ $elapsed = 0 if $elapsed < 0;
+ return $elapsed >= $state->{remaining_timeout} ? 1 : 0;
+}
+
+my sub check_gate($cb) {
+ return 1 if !$cb;
+
+ my $ok = eval { $cb->() };
+ my $err = $@;
+ Net::SSLeay::ERR_clear_error();
+ if ($err) {
+ warn $err;
+ return undef;
+ }
+ return $ok ? 1 : 0;
+}
+
+my sub dispatch_pool($state) {
+ return if $state->{done} || $state->{dispatching};
+ $state->{dispatching} = 1;
+ my $self = __SUB__;
+
+ my $backpressured = 0;
+ my $timed_out = 0;
+ while (!$state->{done} && @{ $state->{queue} }) {
+ my $ok = check_gate($state->{can_dispatch});
+ last if $state->{done};
+ if (!defined($ok)) {
+ # Stop dispatching on callback error without suspending overall_timeout.
+ last;
+ }
+ if (!$ok) {
+ $backpressured = 1;
+ last;
+ }
+
+ last if scalar(keys %{ $state->{active} }) >= $state->{max_concurrent};
+
+ my $admit = check_gate($state->{can_admit});
+ last if $state->{done};
+ if (!defined($admit) || !$admit) {
+ # Capacity gate: keep item queued without pausing overall_timeout.
+ last;
+ }
+
+ my $limiter = $state->{limiter};
+ if ($limiter) {
+ my $cap = limiter_cap($limiter);
+ if (!defined($cap) || $limiter->{active} >= $cap) {
+ my $waiter = $state->{limiter_waiter};
+ if ($waiter && !$waiter->{queued} && !$waiter->{done}) {
+ $waiter->{queued} = 1;
+ push @{ $limiter->{waiters} }, $waiter;
+ }
+ last;
+ }
+ }
+
+ resume_timeout($state);
+ if (timeout_expired($state)) {
+ $timed_out = 1;
+ last;
+ }
+
+ my $item = shift @{ $state->{queue} };
+ my $id = $item->{id};
+ my $item_done = 0;
+
+ my $slot_released = 0;
+ my $release_slot;
+ if ($limiter) {
+ $limiter->{active}++;
+ $release_slot = sub {
+ my ($defer_wake) = @_;
+ return if $slot_released;
+ $slot_released = 1;
+ $limiter->{active}-- if $limiter->{active} > 0;
+ if ($defer_wake) {
+ schedule_wake_limiter_waiters($limiter);
+ } else {
+ wake_limiter_waiters($limiter);
+ }
+ };
+ }
+
+ my $active_entry = { cancel => undef, release => $release_slot };
+ $state->{active}->{$id} = $active_entry;
+
+ my $finish_item = sub {
+ return if $item_done;
+ $item_done = 1;
+ if ($state->{done}) {
+ $release_slot->(0) if $release_slot;
+ return;
+ }
+
+ delete $state->{active}->{$id};
+ $release_slot->(0) if $release_slot;
+ $self->($state);
+ };
+
+ my $start_item = $state->{start_item};
+ my $cancel = eval { $start_item->($item, $finish_item) };
+ my $err = $@;
+ Net::SSLeay::ERR_clear_error();
+
+ if ($err) {
+ if (!$item_done) {
+ $item_done = 1;
+ delete $state->{active}->{$id} if !$state->{done};
+ $release_slot->(0) if $release_slot;
+ }
+ if (my $on_start_error = $state->{on_start_error}) {
+ invoke_callback($on_start_error, $id, $err);
+ } else {
+ warn $err;
+ }
+ } elsif ($state->{done}) {
+ # Pool was cancelled or timed out synchronously while starting this item.
+ if (!$item_done) {
+ invoke_callback($cancel) if ref($cancel) eq 'CODE';
+ $release_slot->(1) if $release_slot;
+ }
+ } elsif (!$item_done) {
+ $active_entry->{cancel} = ref($cancel) eq 'CODE' ? $cancel : undef;
+ }
+
+ if (!$state->{done} && timeout_expired($state)) {
+ $timed_out = 1;
+ last;
+ }
+ }
+
+ $state->{dispatching} = 0;
+
+ if (!$state->{done}) {
+ if ($timed_out || timeout_expired($state)) {
+ complete_pool($state, 1);
+ } elsif (!@{ $state->{queue} } && !%{ $state->{active} }) {
+ complete_pool($state, 0);
+ } elsif ($backpressured) {
+ pause_timeout($state);
+ } else {
+ resume_timeout($state);
+ }
+ }
+}
+
+# Run a bounded-concurrency pool of async operations (each item needs a unique scalar `id`).
+# Callers may share a worker-wide capacity cap across pools via `limiter => create_limiter($n)`
+# (releasing a permit wakes queued waiters in FIFO order; increasing a dynamic limit does not wake
+# waiters automatically, so call `$pool->{dispatch}->()` to use new capacity immediately), or
+# supply `can_dispatch` (backpressure gate) / `can_admit` (custom capacity gate) and invoke
+# `$pool->{dispatch}->()` when eligibility changes. Waiting for a worker slot (`limiter` or
+# `can_admit`) counts toward `overall_timeout`. While work remains queued, a false `can_dispatch`
+# pauses `overall_timeout` even if all slots are occupied; once the queue is empty, the deadline
+# continues to apply to active requests. A backpressured pool with no active items stays paused
+# until `dispatch()` is called. A throwing `can_dispatch` or `can_admit` warns and stops dispatch
+# without pausing `overall_timeout`. Synchronous `start_item` errors are isolated via
+# `on_start_error`, and `on_done->($timed_out, $pending_ids)` runs once on completion or timeout
+# (never after `cancel()`, and may fire synchronously inside `start()` for empty or synchronous
+# item lists).
+sub start(%opts) {
+ my ($items, $start_item, $on_done, $can_dispatch, $can_admit, $on_start_error, $limiter) =
+ @opts{
+ 'items', 'start_item', 'on_done', 'can_dispatch', 'can_admit', 'on_start_error',
+ 'limiter',
+ };
+ croak "items must be an ARRAY ref" if ref($items) ne 'ARRAY';
+
+ croak "start_item must be a CODE ref" if ref($start_item) ne 'CODE';
+ croak "on_done must be a CODE ref" if ref($on_done) ne 'CODE';
+ if (defined($can_dispatch) && ref($can_dispatch) ne 'CODE') {
+ croak "can_dispatch must be a CODE ref";
+ }
+ if (defined($can_admit) && ref($can_admit) ne 'CODE') {
+ croak "can_admit must be a CODE ref";
+ }
+ if (defined($on_start_error) && ref($on_start_error) ne 'CODE') {
+ croak "on_start_error must be a CODE ref";
+ }
+ if (defined($limiter) && ref($limiter) ne 'PVE::APIClient::AnyEvent::Pool::Limiter') {
+ croak "limiter must be a PVE::APIClient::AnyEvent::Pool::Limiter";
+ }
+
+ my $max_concurrent = $opts{max_concurrent} // 16;
+ if (ref($max_concurrent) || $max_concurrent !~ /^[0-9]+\z/ || $max_concurrent < 1) {
+ croak "max_concurrent must be a positive integer";
+ }
+
+ my $overall_timeout = $opts{overall_timeout};
+ if (defined($overall_timeout)) {
+ if (
+ ref($overall_timeout)
+ || $overall_timeout !~ /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\z/
+ || $overall_timeout <= 0
+ ) {
+ croak "overall_timeout must be a positive number";
+ }
+ }
+
+ my %seen_ids;
+ for my $item (@$items) {
+ croak "each item must be a HASH ref" if ref($item) ne 'HASH';
+ my $id = $item->{id};
+ if (!defined($id) || ref($id) || $id eq '') {
+ croak "each item must have a non-empty scalar id";
+ }
+ croak "duplicate item id '$id'" if $seen_ids{$id}++;
+ }
+
+ my $state = {
+ done => 0,
+ dispatching => 0,
+ active => {},
+ queue => [@$items],
+ remaining_timeout => $overall_timeout,
+ timeout_started_at => undef,
+ timeout_watcher => undef,
+ start_item => $start_item,
+ on_done => $on_done,
+ can_dispatch => $can_dispatch,
+ can_admit => $can_admit,
+ on_start_error => $on_start_error,
+ max_concurrent => $max_concurrent,
+ limiter => $limiter,
+ limiter_waiter => undef,
+ };
+
+ if ($limiter) {
+ $state->{limiter_waiter} = {
+ done => 0,
+ queued => 0,
+ dispatch => sub { dispatch_pool($state); },
+ };
+ }
+
+ my $pool = {
+ dispatch => sub {
+ dispatch_pool($state);
+ },
+ cancel => sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ cleanup_state($state);
+ },
+ };
+
+ dispatch_pool($state);
+
+ return $pool;
+}
+
+1;
diff --git a/src/test/anyevent_pool.t b/src/test/anyevent_pool.t
new file mode 100644
index 0000000..1dc4b9f
--- /dev/null
+++ b/src/test/anyevent_pool.t
@@ -0,0 +1,995 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use AnyEvent;
+use Scalar::Util qw(weaken);
+use Test::More;
+
+use PVE::APIClient::AnyEvent::Pool;
+
+my sub run_with_timeout {
+ my ($cb, $timeout) = @_;
+ $timeout //= 5;
+ my $cv = AE::cv;
+ my $t = AE::timer($timeout, 0, sub { $cv->croak("test timed out after ${timeout}s") });
+ $cb->($cv);
+ return $cv->recv();
+}
+
+subtest 'upfront argument and item id validation' => sub {
+ for my $case (
+ [
+ 'non-array items',
+ { items => 'bad', start_item => sub { }, on_done => sub { } },
+ qr/items must be an ARRAY ref/,
+ ],
+ [
+ 'non-hash item',
+ { items => ['bad'], start_item => sub { }, on_done => sub { } },
+ qr/each item must be a HASH ref/,
+ ],
+ [
+ 'missing id',
+ { items => [{}], start_item => sub { }, on_done => sub { } },
+ qr/non-empty scalar id/,
+ ],
+ [
+ 'empty id',
+ { items => [{ id => '' }], start_item => sub { }, on_done => sub { } },
+ qr/non-empty scalar id/,
+ ],
+ [
+ 'duplicate id',
+ {
+ items => [{ id => 'n1' }, { id => 'n2' }, { id => 'n1' }],
+ start_item => sub { },
+ on_done => sub { },
+ },
+ qr/duplicate item id 'n1'/,
+ ],
+ [
+ 'invalid max_concurrent',
+ {
+ items => [{ id => 'n1' }],
+ max_concurrent => 0,
+ start_item => sub { },
+ on_done => sub { },
+ },
+ qr/max_concurrent/,
+ ],
+ [
+ 'invalid overall_timeout',
+ {
+ items => [{ id => 'n1' }],
+ overall_timeout => -1,
+ start_item => sub { },
+ on_done => sub { },
+ },
+ qr/overall_timeout/,
+ ],
+ [
+ 'invalid can_dispatch',
+ {
+ items => [{ id => 'n1' }],
+ can_dispatch => 'nope',
+ start_item => sub { },
+ on_done => sub { },
+ },
+ qr/can_dispatch/,
+ ],
+ [
+ 'invalid on_start_error',
+ {
+ items => [{ id => 'n1' }],
+ on_start_error => [],
+ start_item => sub { },
+ on_done => sub { },
+ },
+ qr/on_start_error/,
+ ],
+ ) {
+ my ($name, $opts, $re) = @$case;
+ eval { PVE::APIClient::AnyEvent::Pool::start(%$opts) };
+ like($@, $re, "validation rejects $name");
+ }
+
+ my @done_args;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [],
+ start_item => sub { fail('start_item should not run for empty pool') },
+ on_done => sub { @done_args = @_ },
+ );
+ is_deeply(\@done_args, [0, []], 'empty items completes immediately with (0, [])');
+};
+
+subtest 'concurrency cap enforcement' => sub {
+ my @items = map { { id => "item-$_" } } (1 .. 10);
+ my $active = 0;
+ my $max_seen = 0;
+ my $finished = 0;
+ my @timers;
+
+ my $res = run_with_timeout(sub {
+ my ($cv) = @_;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => 3,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ $active++;
+ $max_seen = $active if $active > $max_seen;
+ my $t;
+ $t = AE::timer(
+ 0.01,
+ 0,
+ sub {
+ undef $t;
+ $active--;
+ $finished++;
+ $finish_item->();
+ },
+ );
+ push @timers, \$t;
+ return sub { undef $t };
+ },
+ on_done => sub {
+ $cv->send([@_]);
+ },
+ );
+ });
+
+ is($max_seen, 3, 'concurrency capped at max_concurrent => 3');
+ is($finished, 10, 'all 10 items completed');
+ is_deeply($res, [0, []], 'on_done received (0, [])');
+};
+
+subtest 'iterative safety on 200 synchronous completions' => sub {
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, @_ };
+
+ my @items = map { { id => "sync-$_" } } (1 .. 200);
+ my @seen;
+ my $done_count = 0;
+
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => 4,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ push @seen, $item->{id};
+ $finish_item->();
+ $finish_item->(); # idempotent second call
+ return undef;
+ },
+ on_done => sub {
+ my ($timed_out, $pending) = @_;
+ $done_count++;
+ is($timed_out, 0, 'synchronous pool did not time out');
+ is_deeply($pending, [], 'synchronous pool has no pending ids');
+ },
+ );
+
+ is(scalar(@seen), 200, 'all 200 synchronous items processed');
+ is($done_count, 1, 'on_done fired exactly once');
+ is_deeply(\@warnings, [], 'no deep recursion or other warnings emitted');
+};
+
+subtest 'synchronous start_item exception isolation' => sub {
+ my @items = map { { id => "err-$_" } } (1 .. 5);
+ my %start_errors;
+ my @completed;
+ my $done_calls = 0;
+
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => 2,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ die "boom $item->{id}\n" if $item->{id} eq 'err-2' || $item->{id} eq 'err-4';
+ push @completed, $item->{id};
+ $finish_item->();
+ return undef;
+ },
+ on_start_error => sub {
+ my ($id, $err) = @_;
+ $start_errors{$id} = $err;
+ },
+ on_done => sub {
+ $done_calls++;
+ is_deeply(\@_, [0, []], 'pool still completes after isolated start_item errors');
+ },
+ );
+
+ is_deeply(\@completed, [qw(err-1 err-3 err-5)], 'non-failing items ran to completion');
+ like($start_errors{'err-2'}, qr/boom err-2/, 'err-2 passed to on_start_error');
+ like($start_errors{'err-4'}, qr/boom err-4/, 'err-4 passed to on_start_error');
+ is($done_calls, 1, 'on_done fired once');
+};
+
+subtest 'backpressure pauses overall_timeout budget' => sub {
+ # Case A: paused longer than overall_timeout, then unblocks and completes.
+ my $allow_dispatch = 1;
+ my $pool;
+ my $timed_out_during_pause = 0;
+ my $pause_timer;
+
+ my $res_a = run_with_timeout(sub {
+ my ($cv) = @_;
+ $pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'a' }, { id => 'b' }],
+ max_concurrent => 1,
+ overall_timeout => 0.15,
+ can_dispatch => sub { return $allow_dispatch },
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ my $t;
+ $t = AE::timer(
+ 0.02,
+ 0,
+ sub {
+ undef $t;
+ if ($item->{id} eq 'a') {
+ # Trigger backpressure before finishing item a so item b pauses.
+ $allow_dispatch = 0;
+ $pause_timer = AE::timer(
+ 0.25,
+ 0,
+ sub {
+ undef $pause_timer;
+ $allow_dispatch = 1;
+ $pool->{dispatch}->();
+ },
+ );
+ }
+ $finish_item->();
+ },
+ );
+ return sub { undef $t };
+ },
+ on_done => sub {
+ my ($timed_out, $pending) = @_;
+ $timed_out_during_pause = 1 if $timed_out;
+ $cv->send([$timed_out, $pending]);
+ },
+ );
+ });
+
+ is($timed_out_during_pause, 0, 'pool did not time out while paused by backpressure');
+ is_deeply($res_a, [0, []], 'pool finished cleanly after backpressure cleared');
+
+ # Case B: starts paused longer than overall_timeout, then resumes and expires on remaining budget.
+ my $allow_b = 0;
+ my $b_started = 0;
+ my $b_cancelled = 0;
+ my $pool_b;
+ my $resume_t;
+
+ my $res_b = run_with_timeout(sub {
+ my ($cv) = @_;
+ $pool_b = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'z' }, { id => 'm' }],
+ max_concurrent => 1,
+ overall_timeout => 0.10,
+ can_dispatch => sub { return $allow_b },
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ $b_started++;
+ return sub { $b_cancelled++ };
+ },
+ on_done => sub {
+ $cv->send([@_]);
+ },
+ );
+
+ $resume_t = AE::timer(
+ 0.20,
+ 0,
+ sub {
+ undef $resume_t;
+ is($b_started, 0, 'no items dispatched during initial backpressure pause');
+ $allow_b = 1;
+ $pool_b->{dispatch}->();
+ },
+ );
+ });
+
+ is($b_started, 1, 'first item dispatched once backpressure cleared');
+ is($b_cancelled, 1, 'active item cancelled when remaining budget expired');
+ is_deeply($res_b, [1, ['m', 'z']], 'timeout reported sorted active + queued pending ids');
+
+ # Case C: backpressure entered while active == max_concurrent pauses overall_timeout.
+ my $allow_c = 1;
+ my $pool_c;
+ my ($bp_enter_t, $bp_clear_t);
+
+ my $res_c = run_with_timeout(sub {
+ my ($cv) = @_;
+ $pool_c = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'a' }, { id => 'b' }],
+ max_concurrent => 1,
+ overall_timeout => 0.08,
+ can_dispatch => sub { return $allow_c },
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ my $delay = $item->{id} eq 'a' ? 0.12 : 0.01;
+ my $t;
+ $t = AE::timer(
+ $delay,
+ 0,
+ sub {
+ undef $t;
+ $finish_item->();
+ },
+ );
+ return sub { undef $t };
+ },
+ on_done => sub {
+ $cv->send([@_]);
+ },
+ );
+
+ $bp_enter_t = AE::timer(
+ 0.01,
+ 0,
+ sub {
+ undef $bp_enter_t;
+ $allow_c = 0;
+ $pool_c->{dispatch}->();
+ },
+ );
+ $bp_clear_t = AE::timer(
+ 0.15,
+ 0,
+ sub {
+ undef $bp_clear_t;
+ $allow_c = 1;
+ $pool_c->{dispatch}->();
+ },
+ );
+ });
+
+ is_deeply(
+ $res_c,
+ [0, []],
+ 'backpressure entered while active == max_concurrent pauses deadline',
+ );
+
+ # Case D: throwing can_dispatch warns and does NOT pause overall_timeout.
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, @_ };
+ my $res_d = run_with_timeout(sub {
+ my ($cv) = @_;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'd1' }, { id => 'd2' }],
+ max_concurrent => 1,
+ overall_timeout => 0.08,
+ can_dispatch => sub { die "can_dispatch boom\n" },
+ start_item => sub { fail('start_item must not run when can_dispatch throws') },
+ on_done => sub { $cv->send([@_]) },
+ );
+ });
+ is_deeply(
+ $res_d,
+ [1, ['d1', 'd2']],
+ 'throwing can_dispatch does not pause overall_timeout',
+ );
+ ok(
+ scalar(grep { /can_dispatch boom/ } @warnings) >= 1,
+ 'throwing can_dispatch emits warning',
+ );
+
+ # Case E: can_dispatch synchronously finishing an active item while active == max_concurrent
+ # immediately dispatches the queued item without stalling.
+ my $first_finish;
+ my $trigger_finish = 0;
+ my @started_e;
+ my $pool_e;
+ my $res_e;
+ $pool_e = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'first' }, { id => 'second' }],
+ max_concurrent => 1,
+ overall_timeout => 2,
+ can_dispatch => sub {
+ if ($trigger_finish && $first_finish) {
+ $trigger_finish = 0;
+ my $fin = $first_finish;
+ undef $first_finish;
+ $fin->();
+ }
+ return 1;
+ },
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ push @started_e, $item->{id};
+ if ($item->{id} eq 'first') {
+ $first_finish = $finish_item;
+ return sub { };
+ }
+ $finish_item->();
+ return undef;
+ },
+ on_done => sub { $res_e = [@_] },
+ );
+ is_deeply(\@started_e, ['first'], 'only first item started before dispatch trigger');
+ $trigger_finish = 1;
+ $pool_e->{dispatch}->();
+ is_deeply(
+ \@started_e,
+ ['first', 'second'],
+ 'queued item dispatched immediately after can_dispatch finished active item',
+ );
+ is_deeply($res_e, [0, []], 'pool completed without stalling after reentrant finish');
+};
+
+subtest 'timeout returns sorted active and queued pending ids and cancels active ops' => sub {
+ my @items = map { { id => $_ } } qw(n5 n1 n4 n2 n3);
+ my %cancelled;
+ my @late_finishers;
+ my $done_calls = 0;
+
+ my $res = run_with_timeout(sub {
+ my ($cv) = @_;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => 2,
+ overall_timeout => 0.08,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ if ($item->{id} eq 'n5') {
+ $finish_item->();
+ return undef;
+ }
+ push @late_finishers, $finish_item;
+ return sub { $cancelled{ $item->{id} }++ };
+ },
+ on_done => sub {
+ $done_calls++;
+ $cv->send([@_]);
+ },
+ );
+ });
+
+ is_deeply($res, [1, [qw(n1 n2 n3 n4)]], 'timeout returns exact sorted active + queued ids');
+ is_deeply(\%cancelled, { n1 => 1, n4 => 1 }, 'active ops cancelled on timeout');
+
+ $_->() for @late_finishers;
+ is($done_calls, 1, 'late finish_item calls after timeout do not re-fire on_done');
+};
+
+subtest 'synchronous start_item exceeding overall_timeout enforces deadline' => sub {
+ # Multi-item: first synchronous start_item exceeds overall_timeout; queued items do not start.
+ my @started_multi;
+ my $done_multi;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 's1' }, { id => 's2' }, { id => 's3' }],
+ max_concurrent => 2,
+ overall_timeout => 0.03,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ push @started_multi, $item->{id};
+ select(undef, undef, undef, 0.06);
+ $finish_item->();
+ return undef;
+ },
+ on_done => sub {
+ $done_multi = [@_];
+ },
+ );
+ is_deeply(
+ \@started_multi,
+ ['s1'],
+ 'remaining queued items are not started after synchronous timeout expiry',
+ );
+ is_deeply(
+ $done_multi,
+ [1, ['s2', 's3']],
+ 'multi-item synchronous timeout reports timed_out=1 and remaining queued ids',
+ );
+
+ # Single-item: synchronous start_item finishes after exceeding overall_timeout.
+ my @started_single;
+ my $done_single;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'only' }],
+ max_concurrent => 1,
+ overall_timeout => 0.03,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ push @started_single, $item->{id};
+ select(undef, undef, undef, 0.06);
+ $finish_item->();
+ return undef;
+ },
+ on_done => sub {
+ $done_single = [@_];
+ },
+ );
+ is_deeply(\@started_single, ['only'], 'single synchronous item started');
+ is_deeply(
+ $done_single,
+ [1, []],
+ 'single-item synchronous timeout reports timed_out=1 with empty pending list',
+ );
+};
+
+subtest 'manual cancellation and synchronous cancel inside start_item' => sub {
+ my %cancelled;
+ my $done_calls = 0;
+ my @late_finishers;
+
+ my $pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'x1' }, { id => 'x2' }, { id => 'x3' }],
+ max_concurrent => 2,
+ overall_timeout => 5,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ push @late_finishers, $finish_item;
+ return sub { $cancelled{ $item->{id} }++ };
+ },
+ on_done => sub { $done_calls++ },
+ );
+
+ $pool->{cancel}->();
+ $pool->{cancel}->(); # idempotent
+ $pool->{dispatch}->();
+ $_->() for @late_finishers;
+
+ is_deeply(\%cancelled, { x1 => 1, x2 => 1 }, 'active items cancelled exactly once');
+ is($done_calls, 0, 'on_done never fires after cancel');
+
+ # Synchronous cancel during start_item cancels the returned cancel coderef too.
+ my $sync_returned_cancelled = 0;
+ my $sync_pool;
+ my $s1_finish;
+ $sync_pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 's1' }, { id => 's2' }],
+ max_concurrent => 1,
+ start_item => sub {
+ my ($item, $finish_item) = @_;
+ if ($item->{id} eq 's1') {
+ $s1_finish = $finish_item;
+ return sub { };
+ }
+ $sync_pool->{cancel}->();
+ return sub { $sync_returned_cancelled++ };
+ },
+ on_done => sub { fail('on_done must not fire after sync cancel') },
+ );
+ $s1_finish->();
+ is(
+ $sync_returned_cancelled,
+ 1,
+ 'cancel returned after sync pool cancel is invoked immediately',
+ );
+};
+
+subtest 'weakened-ref destruction across completion, timeout, and cancel' => sub {
+ # 1. Normal completion
+ my ($w_pool, $w_cb_token, $w_item);
+ {
+ my $cb_token = { done_path => 1 };
+ my $item = { id => 'c1', payload => { x => 1 } };
+ $w_cb_token = $cb_token;
+ $w_item = $item;
+ weaken($w_cb_token);
+ weaken($w_item);
+
+ my $pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [$item],
+ start_item => sub {
+ my (undef, $finish_item) = @_;
+ my $keep = $cb_token;
+ $finish_item->();
+ return sub { my $k = $cb_token };
+ },
+ on_done => sub { my $keep = $cb_token },
+ );
+ undef $cb_token;
+ undef $item;
+
+ # Callbacks and items must already be released even while $pool handle is still held.
+ is($w_cb_token, undef, 'completion frees user callbacks while pool handle is held');
+ is($w_item, undef, 'completion frees queued item while pool handle is held');
+
+ $w_pool = $pool;
+ weaken($w_pool);
+ }
+ is($w_pool, undef, 'completed pool handle freed cleanly');
+
+ # 2. Timeout path
+ my ($wt_pool, $wt_cb_token, $wt_cancel_token, $wt_item);
+ {
+ my $cb_token = { timeout_path => 1 };
+ my $cancel_token = { cancel_guard => 1 };
+ my $item = { id => 't1' };
+ $wt_cb_token = $cb_token;
+ $wt_cancel_token = $cancel_token;
+ $wt_item = $item;
+ weaken($wt_cb_token);
+ weaken($wt_cancel_token);
+ weaken($wt_item);
+
+ my $pool;
+ run_with_timeout(sub {
+ my ($cv) = @_;
+ $pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [$item],
+ overall_timeout => 0.03,
+ start_item => sub {
+ my $keep = $cb_token;
+ my $ct = $cancel_token;
+ return sub { my $c = $ct };
+ },
+ on_done => sub {
+ my $keep = $cb_token;
+ $cv->send(1);
+ },
+ );
+ });
+ undef $cb_token;
+ undef $cancel_token;
+ undef $item;
+
+ is($wt_cb_token, undef, 'timeout frees user callbacks while pool handle is held');
+ is(
+ $wt_cancel_token,
+ undef,
+ 'timeout frees active cancel closures while pool handle is held',
+ );
+ is($wt_item, undef, 'timeout frees item while pool handle is held');
+
+ $wt_pool = $pool;
+ weaken($wt_pool);
+ }
+ is($wt_pool, undef, 'timed-out pool handle freed cleanly');
+
+ # 3. Cancel path
+ my ($wc_pool, $wc_cb_token, $wc_cancel_token, $wc_item);
+ {
+ my $cb_token = { cancel_path => 1 };
+ my $cancel_token = { cancel_guard => 1 };
+ my $item = { id => 'k1' };
+ $wc_cb_token = $cb_token;
+ $wc_cancel_token = $cancel_token;
+ $wc_item = $item;
+ weaken($wc_cb_token);
+ weaken($wc_cancel_token);
+ weaken($wc_item);
+
+ my $pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [$item],
+ overall_timeout => 5,
+ start_item => sub {
+ my $keep = $cb_token;
+ my $ct = $cancel_token;
+ return sub { my $c = $ct };
+ },
+ on_done => sub { my $keep = $cb_token },
+ );
+ $pool->{cancel}->();
+ undef $cb_token;
+ undef $cancel_token;
+ undef $item;
+
+ is($wc_cb_token, undef, 'cancel frees user callbacks while pool handle is held');
+ is(
+ $wc_cancel_token,
+ undef,
+ 'cancel frees active cancel closures while pool handle is held',
+ );
+ is($wc_item, undef, 'cancel frees item while pool handle is held');
+
+ $wc_pool = $pool;
+ weaken($wc_pool);
+ }
+ is($wc_pool, undef, 'cancelled pool handle freed cleanly');
+};
+
+subtest 'can_admit capacity gate vs can_dispatch backpressure timeout accounting' => sub {
+ # 1. can_admit => 0 keeps items queued WITHOUT pausing overall_timeout.
+ my $cv1 = AE::cv;
+ my $started1 = 0;
+ my $pool1 = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'a' }, { id => 'b' }],
+ overall_timeout => 0.08,
+ can_admit => sub { return 0 },
+ start_item => sub {
+ $started1++;
+ return sub { };
+ },
+ on_done => sub {
+ my ($timed_out, $pending) = @_;
+ $cv1->send([$timed_out, $pending]);
+ },
+ );
+ my $res1 = $cv1->recv;
+ is($started1, 0, 'can_admit => 0 prevented starting items');
+ is($res1->[0], 1, 'can_admit => 0 does NOT pause overall_timeout (timed out)');
+ is_deeply($res1->[1], ['a', 'b'], 'all unadmitted items reported as pending on timeout');
+
+ # 2. When can_dispatch => 0 holds the last item back, overall_timeout pauses past deadline
+ # even if can_admit flips true while backpressured.
+ my $cv2 = AE::cv;
+ my $admit = 0;
+ my $allow_dispatch = 1;
+ my $started2 = 0;
+ my $pool2;
+ $pool2 = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'only' }],
+ overall_timeout => 0.1,
+ can_dispatch => sub { return $allow_dispatch },
+ can_admit => sub { return $admit },
+ start_item => sub {
+ my ($item, $finish) = @_;
+ $started2++;
+ $finish->();
+ return undef;
+ },
+ on_done => sub {
+ my ($timed_out, $pending) = @_;
+ $cv2->send([$timed_out, $pending]);
+ },
+ );
+ # Enter backpressure before timeout expires, then free capacity (admit = 1) while still
+ # backpressured, wait past the 0.1s deadline, then clear backpressure.
+ my $t1 = AE::timer(
+ 0.02,
+ 0,
+ sub {
+ $allow_dispatch = 0;
+ $pool2->{dispatch}->();
+ },
+ );
+ my $t2 = AE::timer(
+ 0.05,
+ 0,
+ sub {
+ $admit = 1;
+ $pool2->{dispatch}->();
+ },
+ );
+ my $t3 = AE::timer(
+ 0.22,
+ 0,
+ sub {
+ is(
+ $started2,
+ 0,
+ 'item stayed queued while backpressured even after can_admit became true',
+ );
+ $allow_dispatch = 1;
+ $pool2->{dispatch}->();
+ },
+ );
+ my $res2 = $cv2->recv;
+ is($started2, 1, 'item started once backpressure cleared');
+ is($res2->[0], 0, 'backpressure paused overall_timeout past deadline');
+ is_deeply($res2->[1], [], 'no pending items on clean completion');
+};
+
+subtest 'shared capacity limiter across multiple pools' => sub {
+ my $cap = 3;
+ my $limiter = PVE::APIClient::AnyEvent::Pool::create_limiter(sub { return $cap; });
+
+ my $in_flight = 0;
+ my $peak = 0;
+ my %pending;
+ my @done_pools;
+ my $cv = AE::cv;
+
+ my $make_pool = sub {
+ my ($prefix, $count) = @_;
+ my @items = map { { id => "$prefix-$_" } } (1 .. $count);
+ return PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => 2,
+ limiter => $limiter,
+ start_item => sub {
+ my ($item, $finish) = @_;
+ $in_flight++;
+ $peak = $in_flight if $in_flight > $peak;
+ $pending{ $item->{id} } = $finish;
+ return sub {
+ if (delete $pending{ $item->{id} }) {
+ $in_flight--;
+ }
+ };
+ },
+ on_done => sub {
+ my ($timed_out) = @_;
+ push @done_pools, [$prefix, $timed_out];
+ $cv->send if @done_pools == 2;
+ },
+ );
+ };
+
+ # Pool A takes 2 slots, pool B takes 1 (and queues 1), pool C queues all 2.
+ my $pA = $make_pool->('A', 2);
+ my $pB = $make_pool->('B', 2);
+ my $pC = $make_pool->('C', 2);
+
+ is($in_flight, 3, 'shared limiter caps total active items across pools at 3');
+ is($limiter->{active}, 3, 'limiter active count matches in-flight items');
+
+ # Cancel pool B: its active slot frees and wakes pool C cleanly without leaking waiters.
+ $pB->{cancel}->();
+ my $t_drive;
+ $t_drive = AE::timer(
+ 0.02,
+ 0.01,
+ sub {
+ my @keys = sort keys %pending;
+ if (@keys) {
+ my $k = shift @keys;
+ my $fin = delete $pending{$k};
+ $in_flight--;
+ $fin->();
+ } else {
+ undef $t_drive;
+ }
+ },
+ );
+ my $guard = AE::timer(2, 0, sub { $cv->croak('shared limiter test timed out'); });
+ $cv->recv;
+
+ is($peak, 3, 'peak concurrency never exceeded shared limiter cap');
+ is($limiter->{active}, 0, 'limiter active count returned to 0 after completion and cancel');
+ is(scalar(@{ $limiter->{waiters} }), 0, 'no stale waiters left in limiter queue');
+ is_deeply(
+ [sort map { $_->[0] } @done_pools],
+ ['A', 'C'],
+ 'surviving pools A and C both completed after B was cancelled',
+ );
+
+ # Pool waiting on a saturated limiter still times out against overall_timeout.
+ my $full_lim = PVE::APIClient::AnyEvent::Pool::create_limiter(1);
+ my $holder_fin;
+ my $holder = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'hold' }],
+ limiter => $full_lim,
+ start_item => sub {
+ my (undef, $finish) = @_;
+ $holder_fin = $finish;
+ return undef;
+ },
+ on_done => sub { },
+ );
+ my $cv_to = AE::cv;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'blocked' }],
+ limiter => $full_lim,
+ overall_timeout => 0.05,
+ start_item => sub { fail('should not start while limiter is full'); },
+ on_done => sub { $cv_to->send([@_]); },
+ );
+ my $to_res = $cv_to->recv;
+ is($to_res->[0], 1, 'pool waiting on full shared limiter timed out');
+ is_deeply($to_res->[1], ['blocked'], 'timed-out limiter waiter reported pending item');
+ $holder_fin->();
+ is($full_lim->{active}, 0, 'limiter active count returned to 0 after holder finished');
+
+ # A throwing dynamic limiter callback warns without leaving the pool stuck in dispatching=1.
+ my $throw_once = 1;
+ my $flaky_lim = PVE::APIClient::AnyEvent::Pool::create_limiter(sub {
+ die "transient cap error\n" if $throw_once;
+ return 1;
+ });
+ my @warnings;
+ my $flaky_started = 0;
+ my $cv_flaky = AE::cv;
+ my $flaky_pool;
+ {
+ local $SIG{__WARN__} = sub { push @warnings, $_[0]; };
+ $flaky_pool = PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'retry-me' }],
+ limiter => $flaky_lim,
+ start_item => sub {
+ my (undef, $finish) = @_;
+ $flaky_started++;
+ $finish->();
+ return undef;
+ },
+ on_done => sub { $cv_flaky->send($_[0]); },
+ );
+ }
+ is($flaky_started, 0, 'throwing dynamic limiter held item without crashing');
+ like(join('', @warnings), qr/transient cap error/, 'throwing dynamic limiter logged warning');
+ $throw_once = 0;
+ $flaky_pool->{dispatch}->();
+ is($cv_flaky->recv(), 0, 'pool dispatched and completed cleanly once dynamic limiter recovered');
+ is($flaky_started, 1, 'queued item ran after dynamic limiter recovered');
+};
+
+subtest 'resume_timeout respects monotonic budget despite stale loop clock' => sub {
+ require Time::HiRes;
+ # Make AE::now lag behind monotonic time by sleeping inside a callback without now_update().
+ AnyEvent->now_update();
+ Time::HiRes::usleep(120_000);
+
+ my $timed_out;
+ my $item_timer;
+ my $res = run_with_timeout(
+ sub {
+ my ($cv) = @_;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'n1' }],
+ overall_timeout => 0.15,
+ start_item => sub {
+ my (undef, $finish) = @_;
+ AnyEvent->now_update();
+ $item_timer = AE::timer(0.05, 0, sub {
+ undef $item_timer;
+ $finish->();
+ });
+ return sub { undef $item_timer; };
+ },
+ on_done => sub {
+ ($timed_out) = @_;
+ $cv->send($timed_out);
+ },
+ );
+ },
+ 2,
+ );
+ is($res, 0, 'pool did not time out early when started with stale AE::now');
+};
+
+subtest 're-entrant limiter slot release inside wake_limiter_waiters does not strand waiters' => sub {
+ my $lim = PVE::APIClient::AnyEvent::Pool::create_limiter(1);
+ my $a_finish;
+ my ($b_started, $c_started, $c_done) = (0, 0, 0);
+
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'a1' }],
+ limiter => $lim,
+ start_item => sub {
+ my (undef, $finish) = @_;
+ $a_finish = $finish;
+ return undef;
+ },
+ on_done => sub { },
+ );
+
+ my $cv_c = AE::cv;
+ # Pool B waits on the cap-1 limiter; when woken, its start_item queues Pool C while holding
+ # the slot and then completes synchronously (re-entering wake_limiter_waiters).
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'b1' }],
+ limiter => $lim,
+ start_item => sub {
+ my (undef, $finish) = @_;
+ $b_started++;
+ PVE::APIClient::AnyEvent::Pool::start(
+ items => [{ id => 'c1' }],
+ limiter => $lim,
+ start_item => sub {
+ my (undef, $c_finish) = @_;
+ $c_started++;
+ $c_finish->();
+ return undef;
+ },
+ on_done => sub {
+ $c_done = 1;
+ $cv_c->send(1);
+ },
+ );
+ $finish->();
+ return undef;
+ },
+ on_done => sub { },
+ );
+
+ $a_finish->();
+
+ my $guard = AE::timer(2, 0, sub { $cv_c->croak('re-entrant limiter waiter C stranded'); });
+ is($cv_c->recv(), 1, 'newly queued pool C woke after re-entrant synchronous release');
+ is($b_started, 1, 'pool B ran once');
+ is($c_started, 1, 'pool C ran once');
+ is($c_done, 1, 'pool C completed');
+ is($lim->{active}, 0, 'limiter active count returned to 0');
+ is(scalar(@{ $lim->{waiters} }), 0, 'no waiters left stranded in limiter');
+};
+
+done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
` (4 preceding siblings ...)
2026-12-01 10:19 ` [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
@ 2026-12-01 10:19 ` Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
` (2 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:19 UTC (permalink / raw)
To: pve-devel
Cluster-wide GET /cluster/metrics/export runs inside the pveproxy
worker handling the request and is primarily driven by Proxmox
Datacenter Manager (PDM) scraping /api2/extjs/cluster/metrics/export
alongside external /api2/json/ and pvesh consumers. Previously,
synchronous per-node LWP fetches serialized peer latency across the
cluster and blocked the worker event loop for all unrelated requests.
Add PVE::PullMetricExport with a single export() entry point backed by
PVE::APIClient::AnyEvent and PVE::APIClient::AnyEvent::Pool, and wire
MetricServer::export() to delegate remote fan-out to it. Inside
pveproxy it returns an AsyncResponse via PVE::APIServer::AnyEvent
(dispatched by pve-http-server directly from $res->{data}); outside an
async HTTP request (such as CLI/pvesh) it runs the same bounded fan-out
via an AnyEvent CondVar.
Each export can fetch up to 16 peers at once; overlapping exports share
32 slots per worker via Pool's shared limiter and a 128 MiB dispatch
admission threshold on completed retained wire bodies (not a hard RSS
bound, with the oldest all-peers export exempt so overlapping scrapes
cannot deadlock). Waiting for a worker slot counts toward the 60-second
fan-out timeout. The timer pauses when downstream backpressure prevents
a queued request from starting. Peer calls use non-persistent HTTPS
sockets, SHA-256 leaf fingerprint pinning, PVEDisableProxy: true,
Accept-Encoding: gzip, IPv6 host bracketing, a 20s per-peer timeout,
and immediate disconnect cancellation. Add an opt-in fail-on-error
parameter (default 0, omitted from remote local-only=1 calls) so
cursor-based scrapers can require all online target nodes to succeed
while preserving best-effort partial results by default. A strict peer
timeout or overall fan-out timeout produces API status 504; other
strict peer fetch or read failures produce 502. /api2/json uses that
HTTP status, while /api2/extjs returns HTTP 200
with success: 0 and the error code in status. Decoded peer entries
enforce signed 64-bit JSON integer timestamps before merging, and
finalization errors are forwarded to reject().
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Enforce the worker-wide 32-peer cap through Pool's shared
create_limiter() instead of separate manual waiter queues so busy-
worker waits count toward the 60s overall timeout.
- Add a deadlock-free 128 MiB worker-wide dispatch admission threshold
on completed retained peer wire bodies across overlapping exports
(exempting the oldest all-peers export while holding newer exports in
Pool's queue).
- Stop initial Pool::start() dispatch immediately if a strict peer
failure marks the export done synchronously before start() returns.
- Add opt-in fail-on-error=1 (default 0, never forwarded to local-only=1
peers) so scrapers can fail on online peer fetch/read errors, import
PVE::Exception explicitly, and map only actual timeouts (504 or
timed-out reason) to API status 504 and other peer failures (including
non-timeout 596 TLS errors) to 502.
- Refine fail-on-error parameter and endpoint descriptions.
PVE/API2/Cluster/MetricServer.pm | 119 ++++++---
PVE/Makefile | 1 +
PVE/PullMetricExport.pm | 426 +++++++++++++++++++++++++++++++
3 files changed, 506 insertions(+), 40 deletions(-)
create mode 100644 PVE/PullMetricExport.pm
diff --git a/PVE/API2/Cluster/MetricServer.pm b/PVE/API2/Cluster/MetricServer.pm
index e494c27f9..14f065fd6 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -3,9 +3,9 @@ package PVE::API2::Cluster::MetricServer;
use warnings;
use strict;
-use PVE::APIClient::LWP;
use PVE::AccessControl;
use PVE::Cluster;
+use PVE::Exception ();
use PVE::INotify;
use PVE::RPCEnvironment;
use PVE::SafeSyslog;
@@ -13,9 +13,15 @@ use PVE::Tools qw(extract_param extract_sensitive_params);
use PVE::ExtMetric;
use PVE::PullMetric;
+use PVE::PullMetricExport;
use base qw(PVE::RESTHandler);
+our $REMOTE_PORT = 8006;
+our $REMOTE_REQUEST_TIMEOUT = 20;
+our $FANOUT_OVERALL_TIMEOUT = 60;
+our $MAX_CONCURRENT_REQUESTS = 16;
+
__PACKAGE__->register_method({
name => 'index',
path => '',
@@ -311,7 +317,14 @@ __PACKAGE__->register_method({
path => 'export',
method => 'GET',
expose_credentials => 1,
- description => "Retrieve metrics of the cluster.",
+ description =>
+ "Retrieve metrics of the cluster. By default, remote peer failures are logged"
+ . " and skipped (best-effort across reachable nodes); set fail-on-error=1 to fail the"
+ . " export if any online target node cannot be fetched or fails validation. If a"
+ . " cluster-wide fan-out exceeds its overall timeout (or fails with fail-on-error=1)"
+ . " before response headers are sent, /api2/json returns HTTP 504/502 and /api2/extjs"
+ . " returns HTTP 200 with success: 0 and status: 504/502. Cursor-based scrapers should"
+ . " retry with the same start-time on error or timeout rather than advancing it.",
permissions => {
check => ['perm', '/', ['Sys.Audit']],
},
@@ -343,6 +356,13 @@ __PACKAGE__->register_method({
optional => 1,
default => 0,
},
+ 'fail-on-error' => {
+ type => 'boolean',
+ description => 'Fail instead of skipping an online target that cannot be fetched'
+ . ' or whose metric response cannot be read.',
+ optional => 1,
+ default => 0,
+ },
},
},
returns => {
@@ -392,6 +412,7 @@ __PACKAGE__->register_method({
my $local_only = $param->{'local-only'} // 0;
my $start = $param->{'start-time'};
my $history = $param->{'history'} // 0;
+ my $fail_on_error = $param->{'fail-on-error'} // 0;
my $now = time();
@@ -411,6 +432,10 @@ __PACKAGE__->register_method({
my @node_list =
$param->{'node-list'} ? PVE::Tools::split_list($param->{'node-list'}) : ();
+ if (@node_list) {
+ my %seen;
+ @node_list = grep { !$seen{$_}++ } @node_list;
+ }
my $nodename = PVE::INotify::nodename();
my $include_local_metrics =
@@ -418,31 +443,29 @@ __PACKAGE__->register_method({
my @metrics;
if ($include_local_metrics) {
- @metrics = @{ PVE::PullMetric::get_local_metrics($generations) };
-
+ my $local_metrics = PVE::PullMetric::get_local_metrics($generations);
if (defined($start)) {
@metrics = grep {
- $_->{timestamp} > ($start)
- } @metrics;
+ $_->{timestamp} > $start
+ } $local_metrics->@*;
+ } else {
+ @metrics = $local_metrics->@*;
}
}
# Fan out to cluster members
# Do NOT remove this check
+ my @targets;
if (!$local_only || @node_list) {
my $members = PVE::Cluster::get_members();
- @node_list = keys $members->%* if !@node_list;
+ @node_list = sort keys $members->%* if !@node_list;
if (my @unknown_nodes = grep { !exists($members->{$_}) } @node_list) {
die "Requested node-list contains unknown nodes - "
. join(', ', @unknown_nodes) . "\n";
}
- my $rpcenv = PVE::RPCEnvironment::get();
- my $authuser = $rpcenv->get_user();
- my $credentials = $rpcenv->get_credentials();
-
for my $name (@node_list) {
if ($name eq $nodename) {
# Skip own node, for that one we already have the metrics
@@ -453,46 +476,62 @@ __PACKAGE__->register_method({
next;
}
- my $status = eval {
+ my $target = eval {
my $fingerprint = PVE::Cluster::get_node_fingerprint($name);
+ die "unable to get certificate fingerprint for node '$name'\n"
+ if !$fingerprint;
my $ip = scalar(PVE::Cluster::remote_node_ip($name));
-
- my $conn_args = {
- protocol => 'https',
- host => $ip,
- port => 8006,
- ticket => $credentials->{ticket},
- api_token => $credentials->{api_token},
- timeout => 20,
+ die "unable to get remote IP address for node '$name'\n"
+ if !$ip;
+ return {
+ name => $name,
+ ip => $ip,
+ fingerprint => $fingerprint,
};
-
- $conn_args->{cached_fingerprints} = { $fingerprint => 1 };
-
- my $api_client = PVE::APIClient::LWP->new(%$conn_args);
-
- my $params = {
- # Do NOT remove 'local-only' - potential for request recursion!
- 'local-only' => 1,
- history => $history,
- };
- $params->{'start-time'} = $start if defined($start);
-
- $api_client->get('/cluster/metrics/export', $params);
};
-
- if ($@) {
- syslog('warning', "could not fetch metrics from $name: $@");
+ if (my $err = $@) {
+ syslog('warning', "could not fetch metrics from $name: $err");
+ if ($fail_on_error) {
+ die PVE::Exception->new(
+ "could not fetch metrics from $name: $err",
+ code => 502,
+ );
+ }
} else {
- push @metrics, $status->{data}->@*;
+ push @targets, $target;
}
}
}
- my @sorted = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+ if (!@targets) {
+ # In-place sort avoids allocating a second copy of large metric arrays.
+ @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+ return {
+ data => \@metrics,
+ };
+ }
- return {
- data => \@sorted,
+ my $rpcenv = PVE::RPCEnvironment::get();
+ my $credentials = $rpcenv->get_credentials() // {};
+
+ my $remote_params = {
+ # Do NOT remove 'local-only' - potential for request recursion!
+ 'local-only' => 1,
+ history => $history,
};
+ $remote_params->{'start-time'} = $start if defined($start);
+
+ return PVE::PullMetricExport::export(
+ targets => \@targets,
+ params => $remote_params,
+ credentials => $credentials,
+ metrics => \@metrics,
+ fail_on_error => $fail_on_error,
+ port => $REMOTE_PORT,
+ request_timeout => $REMOTE_REQUEST_TIMEOUT,
+ overall_timeout => $FANOUT_OVERALL_TIMEOUT,
+ max_concurrent => $MAX_CONCURRENT_REQUESTS,
+ );
},
});
diff --git a/PVE/Makefile b/PVE/Makefile
index f7691fe7e..81a42f8d0 100644
--- a/PVE/Makefile
+++ b/PVE/Makefile
@@ -15,6 +15,7 @@ PERLSOURCE = \
MultipathNotification.pm \
NodeConfig.pm \
PullMetric.pm \
+ PullMetricExport.pm \
Report.pm \
VZDump.pm
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
new file mode 100644
index 000000000..867909977
--- /dev/null
+++ b/PVE/PullMetricExport.pm
@@ -0,0 +1,426 @@
+package PVE::PullMetricExport;
+
+# Asynchronous cluster-wide pull-metric fan-out for GET /cluster/metrics/export.
+# export() fetches remote nodes concurrently (capped via PVE::APIClient::AnyEvent::Pool),
+# returning a deferred PVE::APIServer::AnyEvent::AsyncResponse inside pveproxy or blocking on an
+# AnyEvent CondVar for CLI/pvesh callers.
+
+use v5.36;
+
+use AnyEvent;
+use B;
+
+use PVE::APIClient::AnyEvent;
+use PVE::APIClient::AnyEvent::Pool;
+use PVE::APIServer::AnyEvent;
+use PVE::Exception;
+use PVE::SafeSyslog ();
+
+our $MAX_WORKER_CONCURRENT_PEERS = 32;
+# Dispatch admission threshold on completed retained wire bodies across overlapping exports (not a
+# hard worker RSS bound: in-flight responses are charged on completion, buffered mode retains
+# decoded hashes, and the oldest all-peers export may exceed it to avoid self-deadlock).
+our $MAX_WORKER_RETAINED_BYTES = 128 * 1024 * 1024;
+
+my $WORKER_RETAINED_BYTES = 0;
+my @WORKER_ALL_PEERS_HOLDERS;
+my @WORKER_BYTE_WAITERS;
+my $WORKER_BYTE_WAKE_SCHEDULED = 0;
+
+my sub log_peer_error($name, $err) {
+ PVE::SafeSyslog::syslog('warning', "could not fetch metrics from $name: $err");
+}
+
+my sub peer_error_code($err, $status = undef) {
+ return 504 if defined($status) && $status == 504;
+ return 504 if defined($err) && "$err" =~ /timed?\s*out/i;
+ return 502;
+}
+
+my sub worker_peer_limit() {
+ my $limit = int($MAX_WORKER_CONCURRENT_PEERS // 32);
+ return $limit < 1 ? 1 : $limit;
+}
+
+my sub worker_byte_limit() {
+ my $limit = int($MAX_WORKER_RETAINED_BYTES // (128 * 1024 * 1024));
+ return $limit < 1 ? 1 : $limit;
+}
+
+my sub wake_byte_waiters() {
+ my $remaining = scalar(@WORKER_BYTE_WAITERS);
+ while ($remaining-- > 0 && @WORKER_BYTE_WAITERS) {
+ my $state = shift @WORKER_BYTE_WAITERS;
+ $state->{byte_wait_queued} = 0;
+ next if $state->{done};
+ if (my $fanout = $state->{fanout}) {
+ $fanout->{dispatch}->();
+ }
+ }
+}
+
+my sub schedule_wake_byte_waiters() {
+ return if $WORKER_BYTE_WAKE_SCHEDULED || !@WORKER_BYTE_WAITERS;
+ $WORKER_BYTE_WAKE_SCHEDULED = 1;
+ AE::postpone(sub {
+ $WORKER_BYTE_WAKE_SCHEDULED = 0;
+ wake_byte_waiters();
+ });
+}
+
+my sub retain_peer_bytes($state, $bytes) {
+ return if !$bytes || $bytes <= 0;
+ $state->{retained_bytes} += $bytes;
+ $WORKER_RETAINED_BYTES += $bytes;
+ if ($state->{needs_all_peers} && !$state->{all_peers_holder}) {
+ $state->{all_peers_holder} = 1;
+ push @WORKER_ALL_PEERS_HOLDERS, $state;
+ }
+}
+
+my sub release_peer_bytes($state, $bytes) {
+ return if !$bytes || $bytes <= 0;
+ my $held = $state->{retained_bytes} // 0;
+ my $drop = $bytes > $held ? $held : $bytes;
+ return if $drop <= 0;
+ $state->{retained_bytes} -= $drop;
+ $WORKER_RETAINED_BYTES -= $drop;
+ $WORKER_RETAINED_BYTES = 0 if $WORKER_RETAINED_BYTES < 0;
+ if ($state->{retained_bytes} == 0 && $state->{all_peers_holder}) {
+ $state->{all_peers_holder} = 0;
+ @WORKER_ALL_PEERS_HOLDERS = grep { $_ != $state } @WORKER_ALL_PEERS_HOLDERS;
+ }
+ schedule_wake_byte_waiters();
+}
+
+my sub release_all_peer_bytes($state) {
+ if ($state->{byte_wait_queued}) {
+ $state->{byte_wait_queued} = 0;
+ @WORKER_BYTE_WAITERS = grep { $_ != $state } @WORKER_BYTE_WAITERS;
+ }
+ if ($state->{all_peers_holder}) {
+ $state->{all_peers_holder} = 0;
+ @WORKER_ALL_PEERS_HOLDERS = grep { $_ != $state } @WORKER_ALL_PEERS_HOLDERS;
+ }
+ if (my $held = delete $state->{retained_bytes}) {
+ $WORKER_RETAINED_BYTES -= $held;
+ $WORKER_RETAINED_BYTES = 0 if $WORKER_RETAINED_BYTES < 0;
+ }
+ schedule_wake_byte_waiters();
+}
+
+my sub can_admit_bytes($state) {
+ return 1 if $WORKER_RETAINED_BYTES < worker_byte_limit();
+ # Allow only the oldest active export that must collect all peers before draining (buffered or
+ # sorted k-way merge) to finish fetching so overlapping exports cannot deadlock each other.
+ if (
+ $state->{needs_all_peers}
+ && @WORKER_ALL_PEERS_HOLDERS
+ && $WORKER_ALL_PEERS_HOLDERS[0] == $state
+ ) {
+ return 1;
+ }
+ if (!$state->{byte_wait_queued} && !$state->{done}) {
+ $state->{byte_wait_queued} = 1;
+ push @WORKER_BYTE_WAITERS, $state;
+ }
+ return 0;
+}
+
+my $WORKER_LIMITER = PVE::APIClient::AnyEvent::Pool::create_limiter(\&worker_peer_limit);
+
+my sub start_metric_fanout(%opts) {
+ my @items = map { { id => $_->{name}, %$_ } } @{ $opts{targets} // [] };
+ my $credentials = $opts{credentials} // {};
+ my $port = $opts{port} // 8006;
+ my $request_timeout = $opts{request_timeout} // 20;
+ my $overall_timeout = $opts{overall_timeout} // 60;
+ my $max_concurrent = int($opts{max_concurrent} // 16);
+ $max_concurrent = 1 if $max_concurrent < 1;
+
+ my ($params, $on_peer, $on_peer_error, $on_done, $is_done, $byte_state) =
+ @opts{ 'params', 'on_peer', 'on_peer_error', 'on_done', 'is_done', 'byte_state' };
+
+ my %auth_args;
+ if (defined($credentials->{api_token})) {
+ $auth_args{api_token} = $credentials->{api_token};
+ } elsif (defined($credentials->{ticket})) {
+ $auth_args{ticket} = $credentials->{ticket};
+ }
+
+ my $can_admit;
+ if ($is_done || $byte_state) {
+ $can_admit = sub {
+ return 0 if $is_done && $is_done->();
+ return $byte_state ? can_admit_bytes($byte_state) : 1;
+ };
+ }
+
+ return PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => $max_concurrent,
+ overall_timeout => $overall_timeout,
+ can_dispatch => $opts{can_dispatch},
+ can_admit => $can_admit,
+ limiter => $WORKER_LIMITER,
+ on_start_error => sub {
+ my ($name, $err) = @_;
+ log_peer_error($name, $err);
+ $on_peer_error->($name, $err, peer_error_code($err)) if $on_peer_error;
+ },
+ start_item => sub {
+ my ($target, $finish_item) = @_;
+
+ my ($name, $ip, $fingerprint) = $target->@{qw(name ip fingerprint)};
+ my $done_called = 0;
+ my $cancelled = 0;
+ my $req_cancel;
+
+ my $finish_req = sub {
+ return if $done_called;
+ $done_called = 1;
+ undef $req_cancel;
+ $finish_item->();
+ };
+
+ my $client = eval {
+ PVE::APIClient::AnyEvent->new(
+ protocol => 'https',
+ host => $ip,
+ port => $port,
+ timeout => $request_timeout,
+ cached_fingerprints => { $fingerprint => 1 },
+ headers => {
+ 'Accept-Encoding' => 'gzip',
+ PVEDisableProxy => 'true',
+ },
+ %auth_args,
+ );
+ };
+ if (my $err = $@) {
+ log_peer_error($name, $err);
+ $on_peer_error->($name, $err, peer_error_code($err)) if $on_peer_error;
+ $finish_req->();
+ return undef;
+ }
+
+ my $cancel = eval {
+ $client->request_raw(
+ 'GET',
+ '/cluster/metrics/export',
+ $params,
+ on_response => sub {
+ my ($status, $body_ref, $hdr) = @_;
+
+ my $cb_err;
+ if ($status != 200) {
+ my $reason = $hdr->{Reason} // 'unknown error';
+ my $msg = "$status $reason\n";
+ log_peer_error($name, $msg);
+ eval {
+ $on_peer_error->($name, $msg, peer_error_code($msg, $status))
+ if $on_peer_error;
+ };
+ $cb_err = $@;
+ } elsif ($on_peer) {
+ my $is_gzip =
+ (($hdr->{'content-encoding'} // '') =~ /\bgzip\b/i) ? 1 : 0;
+ eval { $on_peer->($name, $body_ref, $is_gzip); };
+ $cb_err = $@;
+ }
+ $finish_req->();
+ die $cb_err if $cb_err;
+ },
+ on_error => sub {
+ my ($err) = @_;
+ log_peer_error($name, $err);
+ my $cb_err;
+ eval {
+ $on_peer_error->($name, $err, peer_error_code($err))
+ if $on_peer_error;
+ };
+ $cb_err = $@;
+ $finish_req->();
+ die $cb_err if $cb_err;
+ },
+ );
+ };
+ if (my $err = $@) {
+ log_peer_error($name, $err);
+ $on_peer_error->($name, $err, peer_error_code($err)) if $on_peer_error;
+ $finish_req->();
+ return undef;
+ }
+
+ if ($cancelled) {
+ $cancel->() if !$done_called && ref($cancel) eq 'CODE';
+ } elsif (!$done_called) {
+ $req_cancel = $cancel;
+ }
+
+ return sub {
+ return if $cancelled;
+ $cancelled = 1;
+ if (my $c = $req_cancel) {
+ undef $req_cancel;
+ $c->();
+ }
+ };
+ },
+ on_done => sub {
+ my ($timed_out, $pending_ids) = @_;
+
+ if ($timed_out) {
+ for my $peer_name (@$pending_ids) {
+ log_peer_error($peer_name, "overall fan-out timeout (${overall_timeout}s)");
+ }
+ }
+ $on_done->($timed_out, $overall_timeout) if $on_done;
+ },
+ );
+}
+
+my sub validate_integer_timestamp($val) {
+ return undef if !defined($val) || ref($val);
+ my $flags = B::svref_2object(\$val)->FLAGS;
+ return undef if ($flags & (B::SVf_POK | B::SVf_NOK | B::SVf_IVisUV)) || !($flags & B::SVf_IOK);
+ return $val + 0;
+}
+
+my sub decode_peer_metrics($body_ref, $is_gzip = 0) {
+ my $decoded = PVE::APIClient::AnyEvent::decode_json_body($body_ref, $is_gzip);
+ if (
+ ref($decoded) ne 'HASH'
+ || ref($decoded->{data}) ne 'HASH'
+ || ref($decoded->{data}->{data}) ne 'ARRAY'
+ ) {
+ die "unexpected response format\n";
+ }
+
+ my $items = $decoded->{data}->{data};
+ for my $item (@$items) {
+ if (ref($item) ne 'HASH') {
+ die "unexpected metric entry format\n";
+ }
+ my $ts = validate_integer_timestamp($item->{timestamp});
+ die "unexpected metric entry format\n" if !defined($ts);
+ $item->{timestamp} = $ts;
+ }
+
+ return $items;
+}
+
+sub build_buffered_fanout(%opts) {
+ my ($metrics, $finalize, $fail_on_error) = @opts{ 'metrics', 'finalize', 'fail_on_error' };
+ $fail_on_error = $fail_on_error ? 1 : 0;
+
+ return sub {
+ my ($resolve, $reject) = @_;
+
+ my $state = { done => 0, needs_all_peers => 1, retained_bytes => 0 };
+ my $fail_export = sub {
+ my ($name, $err, $code) = @_;
+ return if $state->{done};
+ $state->{done} = 1;
+ if (my $fanout = delete $state->{fanout}) {
+ $fanout->{cancel}->();
+ }
+ release_all_peer_bytes($state);
+ @$metrics = ();
+ $reject->(
+ PVE::Exception->new(
+ "could not fetch metrics from $name: $err", code => $code,
+ ),
+ );
+ };
+
+ my $fanout = start_metric_fanout(
+ %opts,
+ is_done => sub { return $state->{done}; },
+ byte_state => $state,
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ return if $state->{done};
+ my $raw_len = length($$body_ref // '');
+ eval {
+ my $peer_metrics = decode_peer_metrics($body_ref, $is_gzip);
+ push @$metrics, @$peer_metrics;
+ retain_peer_bytes($state, $raw_len);
+ };
+ if (my $err = $@) {
+ log_peer_error($name, $err);
+ $fail_export->($name, $err, 502) if $fail_on_error;
+ }
+ },
+ on_peer_error => $fail_on_error
+ ? sub {
+ my ($name, $err, $code) = @_;
+ $fail_export->($name, $err, $code);
+ }
+ : undef,
+ on_done => sub($timed_out, $timeout) {
+ return if $state->{done};
+ $state->{done} = 1;
+ delete $state->{fanout};
+ release_all_peer_bytes($state);
+ if ($timed_out) {
+ @$metrics = ();
+ $reject->(
+ PVE::Exception->new(
+ "cluster metric fan-out timed out after ${timeout}s\n",
+ code => 504,
+ ),
+ );
+ return;
+ }
+ my $res = eval { $finalize->() };
+ if (my $err = $@) {
+ $reject->($err);
+ return;
+ }
+ $resolve->($res);
+ },
+ );
+ if ($state->{done}) {
+ $fanout->{cancel}->();
+ } else {
+ $state->{fanout} = $fanout;
+ }
+
+ return sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ if (my $fanout = delete $state->{fanout}) {
+ $fanout->{cancel}->();
+ }
+ release_all_peer_bytes($state);
+ @$metrics = ();
+ };
+ };
+}
+
+sub export(%opts) {
+ my $metrics = $opts{metrics} // [];
+
+ my $finalize = sub {
+ # In-place sort avoids allocating a second copy of large metric arrays.
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ return {
+ data => $metrics,
+ };
+ };
+
+ if (PVE::APIServer::AnyEvent::async_supported()) {
+ return PVE::APIServer::AnyEvent::async_response(
+ build_buffered_fanout(%opts, metrics => $metrics, finalize => $finalize),
+ );
+ }
+
+ my $cv = AnyEvent->condvar();
+ build_buffered_fanout(%opts, metrics => $metrics, finalize => $finalize)->(
+ sub { $cv->send($_[0]) }, sub { $cv->croak($_[0]) },
+ );
+ return $cv->recv();
+}
+
+1;
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
` (5 preceding siblings ...)
2026-12-01 10:19 ` [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
@ 2026-12-01 10:19 ` Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 9/9] test: add pull metric export test suite Thomas Lamprecht
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:19 UTC (permalink / raw)
To: pve-devel
Even with non-blocking peer fan-out, decoding all remote metrics into
Perl hashes before sorting and gzip-compressing consumes ~950 B per
metric (~973 MiB VmHWM at 1 million metrics) and still stalls the
pveproxy worker during JSON encoding and compression.
Add PVE::PullMetricExport::Reader (an incremental gzip+JSON scanner
using 256 KiB compressed input slices and 64 KiB Compress::Raw::Zlib
inflate chunks for remote peers, or direct buffer scanning for plain
local_json), a binary min-heap, cooperative 256 KiB slice scheduling,
and build_kway_merge_stream() to PVE::PullMetricExport, and wire
PVE::PullMetricExport::export() to return an AsyncStreamResponse when
PVE::APIServer::AnyEvent::async_stream_supported() is true. The HTTP
server owns the outer json/extjs API2 envelope while PullMetricExport
emits the inner {"data":[...]} payload.
Remote peer bodies stay gzip-compressed while fetching and are merged
in global timestamp order without allocating per-metric Perl hashes.
For flat printable-ASCII objects, Reader validates the object and
extracts its signed 64-bit integer timestamp without building a Perl
hash. For escapes, UTF-8, or nested values, it locates the object end,
decodes the object, checks its signed 64-bit integer timestamp
(rejecting strings, integral floats like 1.0/1e2, and overflows), and
rejects duplicate top-level timestamp keys. Both paths enforce the
4 MiB per-object size limit. By default, a peer that fails to open or
yield its first metric is skipped with a warning. With fail-on-error=1,
a first-read error produces API status 502 before streaming starts and a
peer or fan-out timeout produces 504; a subsequent reader error or
decreasing per-peer timestamp aborts the response instead of closing
with HTTP 200. Slices are scheduled via AnyEvent->idle paired with a
clock-synced 10 ms fallback timer.
Measured on a single pveproxy worker in a mock harness (25 ms per-peer
latency, RSA-2048 TLS with SHA-256 pinning, gzip, 16-peer per-export
cap, 34 FDs; scenarios are nodes x guests, hist10 = 10 history
generations per node, TTFB = time to first byte, Buffered = async
fan-out decoding all remote metrics into Perl hashes before JSON
encoding and gzip, Max /ping HOL = maximum concurrent /ping head-of-line
latency on the same worker):
Scenario | Mode | Total | TTFB | VmHWM | Max /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | Sync LWP | 1034ms | - | 106 MiB | 1024 ms
(25,475 metrics) | K-way stream | 196ms | 114ms | 84 MiB | 5.0 ms
25x100 hist10 | Sync LWP | 2302ms | - | 338 MiB | 2354 ms
(254,750 metrics) | K-way stream | 871ms | 123ms | 99 MiB | 9.4 ms
100x100 latest | Sync LWP | 4195ms | - | 180 MiB | 4178 ms
(101,900 metrics) | K-way stream | 687ms | 399ms | 91 MiB | 7.3 ms
100x1000 | Buffered | 5.1 s | - | 973 MiB | -
(1,001,900 metrics) | K-way stream | 3296ms | 397ms | 103 MiB | 9.5 ms
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Account queued peer payloads and active heap readers against the
worker-wide retained-byte admission threshold, releasing bytes
incrementally as each peer reader exhausts or on stream cleanup, and
drop local_json from %opts once handed to the starter.
- Validate original signed 64-bit JSON integer timestamp tokens
(inclusive INT64_MIN to INT64_MAX, rejecting strings, integral floats
like 1.0/1e2, overflows, and literal/escaped duplicate keys; fast-path
<=18-char integer tokens on the flat path) and the 4 MiB per-object
size limit identically across flat Reader, fallback Reader, and
buffered decode_peer_metrics().
- Retain incremental fallback object-scanner state across 64 KiB inflate
refills so multi-chunk objects scan in linear time, and document
Reader's PVE-specific envelope scope.
- Abort k-way merge on decreasing per-peer timestamps and propagate
pre-start fail-on-error=1 failures as API status 504/502 (halting
synchronous initial dispatch on strict failure).
- Refresh benchmark numbers against the v2 implementation.
PVE/Makefile | 2 +-
PVE/PullMetricExport.pm | 400 ++++++++++++++++++++++++++++++---
PVE/PullMetricExport/Makefile | 15 ++
PVE/PullMetricExport/Reader.pm | 396 ++++++++++++++++++++++++++++++++
4 files changed, 783 insertions(+), 30 deletions(-)
create mode 100644 PVE/PullMetricExport/Makefile
create mode 100644 PVE/PullMetricExport/Reader.pm
diff --git a/PVE/Makefile b/PVE/Makefile
index 81a42f8d0..b4b1be303 100644
--- a/PVE/Makefile
+++ b/PVE/Makefile
@@ -1,6 +1,6 @@
include ../defines.mk
-SUBDIRS=API2 Status CLI Service Ceph Jobs
+SUBDIRS=API2 Status CLI Service Ceph Jobs PullMetricExport
PERLSOURCE = \
API2.pm \
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
index 867909977..272d9bb1a 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,14 +1,16 @@
package PVE::PullMetricExport;
-# Asynchronous cluster-wide pull-metric fan-out for GET /cluster/metrics/export.
-# export() fetches remote nodes concurrently (capped via PVE::APIClient::AnyEvent::Pool),
-# returning a deferred PVE::APIServer::AnyEvent::AsyncResponse inside pveproxy or blocking on an
-# AnyEvent CondVar for CLI/pvesh callers.
+# Asynchronous cluster-wide pull-metric fan-out and streaming export for GET
+# /cluster/metrics/export. export() selects between two paths:
+# - Incremental k-way merge stream (default when AsyncStream is supported): keeps remote peer
+# responses gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then
+# merges local and remote streams in global timestamp order in cooperative 256 KiB slices.
+# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers).
use v5.36;
use AnyEvent;
-use B;
+use JSON qw(decode_json encode_json);
use PVE::APIClient::AnyEvent;
use PVE::APIClient::AnyEvent::Pool;
@@ -16,11 +18,18 @@ use PVE::APIServer::AnyEvent;
use PVE::Exception;
use PVE::SafeSyslog ();
+use PVE::PullMetricExport::Reader;
+
our $MAX_WORKER_CONCURRENT_PEERS = 32;
# Dispatch admission threshold on completed retained wire bodies across overlapping exports (not a
# hard worker RSS bound: in-flight responses are charged on completion, buffered mode retains
# decoded hashes, and the oldest all-peers export may exceed it to avoid self-deadlock).
our $MAX_WORKER_RETAINED_BYTES = 128 * 1024 * 1024;
+our $STREAM_SLICE_BYTES = 262144;
+our $SLICE_FALLBACK_INTERVAL = 0.01;
+
+my $STREAM_PREFIX = '{"data":[';
+my $STREAM_SUFFIX = ']}';
my $WORKER_RETAINED_BYTES = 0;
my @WORKER_ALL_PEERS_HOLDERS;
@@ -280,34 +289,24 @@ my sub start_metric_fanout(%opts) {
);
}
-my sub validate_integer_timestamp($val) {
- return undef if !defined($val) || ref($val);
- my $flags = B::svref_2object(\$val)->FLAGS;
- return undef if ($flags & (B::SVf_POK | B::SVf_NOK | B::SVf_IVisUV)) || !($flags & B::SVf_IOK);
- return $val + 0;
-}
-
my sub decode_peer_metrics($body_ref, $is_gzip = 0) {
- my $decoded = PVE::APIClient::AnyEvent::decode_json_body($body_ref, $is_gzip);
- if (
- ref($decoded) ne 'HASH'
- || ref($decoded->{data}) ne 'HASH'
- || ref($decoded->{data}->{data}) ne 'ARRAY'
- ) {
- die "unexpected response format\n";
- }
-
- my $items = $decoded->{data}->{data};
- for my $item (@$items) {
- if (ref($item) ne 'HASH') {
- die "unexpected metric entry format\n";
+ # Validate through Reader so buffered and streaming exports enforce identical wire timestamp
+ # range, duplicate-key rejection, and per-object size limits.
+ my $reader = PVE::PullMetricExport::Reader->open(body => $$body_ref, gzip => $is_gzip);
+ my @items;
+ eval {
+ while (defined(my $obj = $reader->next())) {
+ my $entry = decode_json($obj);
+ $entry->{timestamp} = $reader->ts();
+ push @items, $entry;
}
- my $ts = validate_integer_timestamp($item->{timestamp});
- die "unexpected metric entry format\n" if !defined($ts);
- $item->{timestamp} = $ts;
+ };
+ if (my $err = $@) {
+ $reader->close();
+ die $err;
}
- return $items;
+ return \@items;
}
sub build_buffered_fanout(%opts) {
@@ -399,9 +398,352 @@ sub build_buffered_fanout(%opts) {
};
}
+my sub open_peer_reader($name, $body, $is_gzip, $fail_on_error = 0) {
+ my $reader;
+ my $first_obj = eval {
+ $reader = PVE::PullMetricExport::Reader->open(
+ body => $body,
+ gzip => $is_gzip,
+ );
+ undef $body;
+ return $reader->next();
+ };
+ if (my $err = $@) {
+ log_peer_error($name, $err);
+ $reader->close() if $reader;
+ if ($fail_on_error) {
+ die PVE::Exception->new("could not fetch metrics from $name: $err", code => 502);
+ }
+ return undef;
+ }
+
+ return undef if !defined($first_obj);
+ return {
+ name => $name,
+ reader => $reader,
+ obj => $first_obj,
+ ts => $reader->ts(),
+ };
+}
+
+my sub heap_push($heap, $entry) {
+ push @$heap, $entry;
+ my $idx = $#$heap;
+ while ($idx > 0) {
+ my $parent = int(($idx - 1) / 2);
+ last if $heap->[$parent]->{ts} <= $heap->[$idx]->{ts};
+ @{$heap}[$parent, $idx] = @{$heap}[$idx, $parent];
+ $idx = $parent;
+ }
+}
+
+my sub heap_sift_down($heap, $idx) {
+ my $size = scalar(@$heap);
+ while (1) {
+ my $left = 2 * $idx + 1;
+ last if $left >= $size;
+ my $right = $left + 1;
+ my $smallest =
+ ($right < $size && $heap->[$right]->{ts} < $heap->[$left]->{ts}) ? $right : $left;
+ last if $heap->[$idx]->{ts} <= $heap->[$smallest]->{ts};
+ @{$heap}[$idx, $smallest] = @{$heap}[$smallest, $idx];
+ $idx = $smallest;
+ }
+}
+
+# Return the second-smallest timestamp in the min-heap so kway_merge_step can drain consecutive
+# metrics from the top node without sifting down until its timestamp exceeds the next node.
+my sub heap_second_min_ts($heap) {
+ return undef if @$heap <= 1;
+ if (@$heap > 2 && $heap->[2]->{ts} < $heap->[1]->{ts}) {
+ return $heap->[2]->{ts};
+ }
+ return $heap->[1]->{ts};
+}
+
+my sub clear_slice_watchers($state) {
+ delete @{$state}{qw(slice_idle slice_timer)};
+}
+
+my sub cleanup_stream($state) {
+ clear_slice_watchers($state);
+ if (my $fanout = delete $state->{fanout}) {
+ $fanout->{cancel}->();
+ }
+ release_all_peer_bytes($state);
+ delete $state->{local_json};
+ @{ $state->{peer_payloads} } = () if $state->{peer_payloads};
+ @{ $state->{ready_peers} } = () if $state->{ready_peers};
+ if (my $heap = $state->{heap}) {
+ $_->{reader}->close() for @$heap;
+ @$heap = ();
+ }
+ if (my $active = delete $state->{active_reader}) {
+ $active->{reader}->close();
+ }
+ delete $state->{stream};
+}
+
+my sub abort_stream($state, $err = undef) {
+ return if $state->{done};
+ $state->{done} = 1;
+ my $stream = $state->{stream};
+ cleanup_stream($state);
+ $stream->abort($err) if $stream && !$stream->is_closed();
+}
+
+my sub schedule_slice($state, $cb) {
+ clear_slice_watchers($state);
+
+ my $run = sub {
+ clear_slice_watchers($state);
+ eval { $cb->(); };
+ abort_stream($state, $@) if $@;
+ };
+
+ # AnyEvent::Loop skips select() when timers are already due, while idle alone can starve under
+ # continuous competing I/O. Sync the loop clock before arming the fallback timer so its
+ # deadline stays strictly in the future and ready I/O runs first.
+ AnyEvent->now_update();
+ $state->{slice_idle} = AnyEvent->idle(cb => $run);
+ $state->{slice_timer} = AnyEvent->timer(after => $SLICE_FALLBACK_INTERVAL, cb => $run);
+}
+
+my sub finish_stream($state, $out) {
+ my $stream = $state->{stream};
+ $out .= $STREAM_SUFFIX;
+ $state->{done} = 1;
+ cleanup_stream($state);
+ return if !$stream || $stream->is_closed();
+ eval {
+ $stream->write($out);
+ $stream->finish();
+ };
+ if (my $err = $@) {
+ $stream->abort($err) if !$stream->is_closed();
+ }
+}
+
+my sub after_stream_write($state, $ok, $step_cb, $notify_pool = undef) {
+ my $stream = $state->{stream};
+ return if $state->{done} || !$stream || $stream->is_closed();
+
+ if (!$ok || $stream->is_backpressured()) {
+ clear_slice_watchers($state);
+ $state->{waiting_drain} = 1;
+ # Poke pool dispatch right as backpressure begins so the pool re-evaluates can_dispatch()
+ # and pauses its overall_timeout budget while waiting for on_drain.
+ $notify_pool->() if $notify_pool;
+ $stream->on_drain(sub {
+ $state->{waiting_drain} = 0;
+ return if $state->{done} || $stream->is_closed();
+ eval {
+ $notify_pool->() if $notify_pool;
+ $step_cb->();
+ };
+ abort_stream($state, $@) if $@;
+ });
+ } else {
+ $notify_pool->() if $notify_pool;
+ schedule_slice($state, $step_cb);
+ }
+}
+
+my sub kway_merge_step($state) {
+ my $self = __SUB__;
+ clear_slice_watchers($state);
+ my $stream = $state->{stream};
+ return if $state->{done} || !$stream || $stream->is_closed();
+
+ my $out = '';
+ if (!$state->{started_stream}) {
+ $state->{started_stream} = 1;
+ return if !$stream->start();
+ $out = $STREAM_PREFIX;
+ }
+
+ my $heap = $state->{heap};
+ while (@$heap && length($out) < $STREAM_SLICE_BYTES) {
+ my $top = $heap->[0];
+ my $reader = $top->{reader};
+ my $next_min_ts = heap_second_min_ts($heap);
+ my $exhausted = 0;
+
+ eval {
+ while (length($out) < $STREAM_SLICE_BYTES) {
+ $out .= ',' if !$state->{first_item};
+ $state->{first_item} = 0;
+ $out .= $top->{obj};
+
+ my $prev_ts = $top->{ts};
+ my $obj = $reader->next();
+ if (!defined($obj)) {
+ $exhausted = 1;
+ last;
+ }
+ my $next_ts = $reader->ts();
+ die "non-monotonic peer timestamps ($next_ts < $prev_ts)\n"
+ if $next_ts < $prev_ts;
+ $top->{obj} = $obj;
+ $top->{ts} = $next_ts;
+
+ if (defined($next_min_ts) && $top->{ts} > $next_min_ts) {
+ heap_sift_down($heap, 0);
+ last;
+ }
+ }
+ };
+ if (my $err = $@) {
+ log_peer_error($top->{name}, $err);
+ $reader->close();
+ abort_stream($state, "could not stream metrics from $top->{name}: $err");
+ return;
+ }
+
+ if ($exhausted) {
+ release_peer_bytes($state, delete $top->{retained_bytes});
+ my $last = pop @$heap;
+ if (@$heap) {
+ $heap->[0] = $last;
+ heap_sift_down($heap, 0);
+ }
+ }
+ }
+
+ if (!@$heap) {
+ finish_stream($state, $out);
+ return;
+ }
+
+ my $ok = $stream->write($out);
+ after_stream_write($state, $ok, sub { $self->($state) });
+}
+
+sub build_kway_merge_stream(%opts) {
+ my $local_json = delete $opts{local_json};
+ my $fail_on_error = $opts{fail_on_error} ? 1 : 0;
+
+ return sub {
+ my ($stream) = @_;
+
+ my $state = {
+ stream => $stream,
+ done => 0,
+ needs_all_peers => 1,
+ retained_bytes => 0,
+ local_json => $local_json,
+ peer_payloads => [],
+ heap => [],
+ started_stream => 0,
+ first_item => 1,
+ };
+ undef $local_json;
+
+ my $fanout = start_metric_fanout(
+ %opts,
+ is_done => sub { return $state->{done}; },
+ byte_state => $state,
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ return if $state->{done};
+ my $bytes = length($$body_ref // '');
+ retain_peer_bytes($state, $bytes);
+ push @{ $state->{peer_payloads} },
+ {
+ name => $name,
+ body => $$body_ref,
+ gzip => $is_gzip,
+ retained_bytes => $bytes,
+ };
+ },
+ on_peer_error => $fail_on_error
+ ? sub {
+ my ($name, $err, $code) = @_;
+ abort_stream(
+ $state,
+ PVE::Exception->new(
+ "could not fetch metrics from $name: $err",
+ code => $code,
+ ),
+ );
+ }
+ : undef,
+ on_done => sub($timed_out, $timeout) {
+ return if $state->{done} || $stream->is_closed();
+ delete $state->{fanout};
+
+ if ($timed_out) {
+ abort_stream(
+ $state,
+ PVE::Exception->new(
+ "cluster metric fan-out timed out after ${timeout}s\n",
+ code => 504,
+ ),
+ );
+ return;
+ }
+
+ eval {
+ if (defined(my $local = delete $state->{local_json})) {
+ if (my $entry = open_peer_reader('local', $local, 0, $fail_on_error)) {
+ heap_push($state->{heap}, $entry);
+ }
+ }
+
+ my $payloads = $state->{peer_payloads};
+ while (my $peer = shift @$payloads) {
+ my $bytes = $peer->{retained_bytes};
+ my $entry = open_peer_reader(
+ $peer->{name},
+ $peer->{body},
+ $peer->{gzip},
+ $fail_on_error,
+ );
+ undef $peer;
+ if ($entry) {
+ $entry->{retained_bytes} = $bytes;
+ heap_push($state->{heap}, $entry);
+ } else {
+ release_peer_bytes($state, $bytes);
+ }
+ }
+
+ kway_merge_step($state);
+ };
+ abort_stream($state, $@) if $@;
+ },
+ );
+ if ($state->{done}) {
+ $fanout->{cancel}->();
+ } else {
+ $state->{fanout} = $fanout;
+ }
+
+ return sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ cleanup_stream($state);
+ };
+ };
+}
+
sub export(%opts) {
my $metrics = $opts{metrics} // [];
+ if (PVE::APIServer::AnyEvent::async_stream_supported()) {
+ my $local_json;
+ if (@$metrics) {
+ # Encode local metrics into the same wire envelope as remote peers so the streaming
+ # reader and k-way merge heap drain local and remote sources uniformly.
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ $local_json = encode_json({ data => { data => $metrics } });
+ @$metrics = ();
+ }
+ return PVE::APIServer::AnyEvent::async_stream_response(
+ build_kway_merge_stream(%opts, local_json => $local_json),
+ );
+ }
+
my $finalize = sub {
# In-place sort avoids allocating a second copy of large metric arrays.
@$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
diff --git a/PVE/PullMetricExport/Makefile b/PVE/PullMetricExport/Makefile
new file mode 100644
index 000000000..5098a6e52
--- /dev/null
+++ b/PVE/PullMetricExport/Makefile
@@ -0,0 +1,15 @@
+include ../../defines.mk
+
+PERLSOURCE = \
+ Reader.pm
+
+all:
+
+.PHONY: clean
+clean:
+ rm -rf *~
+
+.PHONY: install
+install: $(PERLSOURCE)
+ install -d $(PERLLIBDIR)/PVE/PullMetricExport
+ install -m 0644 $(PERLSOURCE) $(PERLLIBDIR)/PVE/PullMetricExport
diff --git a/PVE/PullMetricExport/Reader.pm b/PVE/PullMetricExport/Reader.pm
new file mode 100644
index 000000000..d4ee00c4f
--- /dev/null
+++ b/PVE/PullMetricExport/Reader.pm
@@ -0,0 +1,396 @@
+package PVE::PullMetricExport::Reader;
+
+# Incremental gzip+JSON metric array reader for remote peer responses and local_json.
+# Intentionally specialized by design for PVE's local-only endpoint exact envelope
+# ({"data":{"data":[...]}}); additional envelope members are not supported.
+# Scans in bounded 256 KiB compressed input slices and 64 KiB inflate chunks (or scans plain
+# local_json directly), validating flat printable-ASCII RFC 8259 objects without allocating
+# per-metric Perl hashes (falling back to quote/brace scanning + decode_json for escapes, UTF-8,
+# or nesting, rejecting duplicate timestamp keys and non-i64 timestamps).
+# Contract: open(body => $str, gzip => $bool) validates the opening envelope; next() returns each
+# raw JSON object string (enforcing unique signed 64-bit integer timestamp and max object size,
+# updating obj()/ts()) or undef on clean EOF; dies on corrupt, malformed, oversized, truncated, or
+# trailing data (callers call close() on error).
+
+use v5.36;
+
+use B;
+use Compress::Raw::Zlib qw(WANT_GZIP Z_OK Z_STREAM_END Z_BUF_ERROR);
+use JSON qw(decode_json);
+
+our $GZIP_INPUT_CHUNK_BYTES = 262144;
+our $MAX_METRIC_OBJECT_BYTES = 4 * 1024 * 1024;
+my $INT64_MIN = -9223372036854775807 - 1;
+
+# Validate a raw JSON wire token as an unquoted signed 64-bit JSON integer in
+# [-9223372036854775808, 9223372036854775807] (rejecting strings, integral floats like 1.0/1e2,
+# booleans, nulls, and out-of-range values) and return its Perl signed IV, or undef if invalid.
+sub parse_signed_int64_token($tok) {
+ return undef if !defined($tok) || $tok !~ /\A-?(?:0|[1-9][0-9]*)\z/;
+ return $INT64_MIN if $tok eq '-9223372036854775808';
+ my $num = $tok + 0;
+ my $flags = B::svref_2object(\$num)->FLAGS;
+ return undef if ($flags & (B::SVf_NOK | B::SVf_IVisUV)) || !($flags & B::SVf_IOK);
+ return $num;
+}
+
+# Extract the raw wire token of the unique top-level key decoding to "timestamp" in a validated
+# JSON object string, dying on duplicate top-level timestamp keys (including escaped forms).
+my sub extract_unique_timestamp_token($obj) {
+ my $count = 0;
+ my $ts_tok;
+ my $depth = 0;
+ my $expect_key = 0;
+ my $expect_ts_val = 0;
+ pos($obj) = 0;
+
+ while ($obj =~ /\G[ \t\r\n]*(\{|\}|\[|\]|:|,|"(?:[^"\\]++|\\.)*+"|[^ \t\r\n\{\}\[\]:,"]+)/gc) {
+ my $tok = $1;
+ if ($expect_ts_val) {
+ next if $tok eq ':';
+ $expect_ts_val = 0;
+ $ts_tok = $tok if !defined($ts_tok);
+ }
+ if ($tok eq '{' || $tok eq '[') {
+ $depth++;
+ $expect_key = 1 if $depth == 1 && $tok eq '{';
+ } elsif ($tok eq '}' || $tok eq ']') {
+ $depth--;
+ } elsif ($depth == 1 && $tok eq ',') {
+ $expect_key = 1;
+ } elsif ($depth == 1 && $expect_key && substr($tok, 0, 1) eq '"') {
+ $expect_key = 0;
+ if ($tok eq '"timestamp"') {
+ $count++;
+ $expect_ts_val = 1;
+ } elsif (index($tok, '\\') >= 0) {
+ my $key = decode_json("[$tok]")->[0];
+ if ($key eq 'timestamp') {
+ $count++;
+ $expect_ts_val = 1;
+ }
+ }
+ }
+ }
+
+ die "duplicate timestamp key\n" if $count > 1;
+ return $count == 1 ? $ts_tok : undef;
+}
+
+# Exact RFC 8259 flat JSON object grammar restricted to printable ASCII strings without escapes.
+# Composed as strings before compiling once to avoid nested (?^:...) regex scopes in the hot loop.
+my $JSON_WS = '[ \t\r\n]*';
+my $JSON_ASCII_STR = '"[\x20\x21\x23-\x5b\x5d-\x7e]*"';
+my $JSON_NUM = '-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?';
+my $JSON_PRIM = "(?:$JSON_ASCII_STR|$JSON_NUM|true|false|null)";
+my $JSON_FLAT_PAIR = "$JSON_ASCII_STR$JSON_WS:$JSON_WS$JSON_PRIM";
+my $JSON_NON_TS_PAIR = "(?!\"timestamp\"$JSON_WS:)$JSON_FLAT_PAIR";
+my $FLAT_JSON_OBJ_RE =
+ qr/\G(\{$JSON_WS(?:$JSON_NON_TS_PAIR$JSON_WS,$JSON_WS)*+"timestamp"$JSON_WS:$JSON_WS(-?(?:0|[1-9][0-9]*))(?:$JSON_WS,$JSON_WS$JSON_NON_TS_PAIR)*+$JSON_WS\})/;
+my $ENVELOPE_OPEN_RE =
+ qr/\G$JSON_WS\{$JSON_WS"data"$JSON_WS:$JSON_WS\{$JSON_WS"data"$JSON_WS:$JSON_WS\[/;
+my $ENVELOPE_CLOSE_RE = qr/\G$JSON_WS\}$JSON_WS\}$JSON_WS\z/;
+
+# Incrementally scan a JSON object starting at $start, resuming from $scan across refills so
+# multi-chunk objects take linear work. $scan->{offset} is relative to $start (invariant across
+# refill() buffer compaction). Returns the index right after the matching '}', or undef if
+# incomplete (updating $scan in place).
+my sub find_json_object_end($buf_ref, $start, $scan, $max_bytes = $MAX_METRIC_OBJECT_BYTES) {
+ my $len = length($$buf_ref);
+ my $limit = $start + $max_bytes;
+ my $depth = $scan->{depth};
+ my $in_string = $scan->{in_string};
+ my $cur = $start + $scan->{offset};
+
+ if ($scan->{escaped}) {
+ return undef if $cur >= $len;
+ $cur += 1;
+ $scan->{escaped} = 0;
+ if ($cur > $limit) {
+ die "metric object exceeds maximum size\n";
+ }
+ }
+
+ pos($$buf_ref) = $cur;
+
+ while ($$buf_ref =~ /(["{}\\])/gc) {
+ my $after = pos($$buf_ref);
+ if ($after > $limit) {
+ die "metric object exceeds maximum size\n";
+ }
+ my $tok = $1;
+ if ($in_string) {
+ if ($tok eq '\\') {
+ if ($after >= $len) {
+ $scan->{depth} = $depth;
+ $scan->{in_string} = 1;
+ $scan->{escaped} = 1;
+ $scan->{offset} = $after - $start;
+ return undef;
+ }
+ pos($$buf_ref) = $after + 1;
+ if ($after + 1 > $limit) {
+ die "metric object exceeds maximum size\n";
+ }
+ } elsif ($tok eq '"') {
+ $in_string = 0;
+ }
+ } elsif ($tok eq '"') {
+ $in_string = 1;
+ } elsif ($tok eq '{') {
+ $depth++;
+ } elsif ($tok eq '}') {
+ $depth--;
+ if ($depth == 0) {
+ die "metric object exceeds maximum size\n" if $after - $start > $max_bytes;
+ return $after;
+ }
+ }
+ }
+
+ $scan->{depth} = $depth;
+ $scan->{in_string} = $in_string;
+ $scan->{escaped} = 0;
+ $scan->{offset} = $len - $start;
+ return undef;
+}
+
+my sub refill($self) {
+ return 0 if $self->{eof};
+
+ # Compact the already-parsed prefix before inflating the next 64 KiB chunk so buffer memory
+ # stays bounded across multi-megabyte peer payloads.
+ if ($self->{pos} > 0) {
+ substr($self->{buf}, 0, $self->{pos}, '');
+ $self->{pos} = 0;
+ }
+
+ while (1) {
+ if (!length($self->{in_chunk}) && defined($self->{input})) {
+ $self->{in_chunk} = substr($self->{input}, $self->{input_pos}, $GZIP_INPUT_CHUNK_BYTES);
+ $self->{input_pos} += length($self->{in_chunk});
+ undef $self->{input} if $self->{input_pos} >= length($self->{input});
+ }
+
+ my $prev_in = length($self->{in_chunk});
+ my $chunk = '';
+ my $status = $self->{inflater}->inflate($self->{in_chunk}, $chunk);
+ if ($status == Z_STREAM_END) {
+ if (length($self->{in_chunk}) || defined($self->{input})) {
+ die "unexpected trailing data after gzip stream\n";
+ }
+ $self->{eof} = 1;
+ undef $self->{input};
+ undef $self->{in_chunk};
+ undef $self->{inflater};
+ $self->{buf} .= $chunk;
+ return length($chunk) > 0 ? 1 : 0;
+ } elsif ($status == Z_BUF_ERROR) {
+ if (length($chunk) > 0) {
+ $self->{buf} .= $chunk;
+ return 1;
+ }
+ next if defined($self->{input});
+ die "truncated gzip stream\n";
+ } elsif ($status != Z_OK) {
+ die "failed to gunzip stream (zlib status $status)\n";
+ }
+
+ if (length($chunk) > 0) {
+ $self->{buf} .= $chunk;
+ return 1;
+ }
+ next if defined($self->{input}) || length($self->{in_chunk}) < $prev_in;
+ die "truncated gzip stream\n";
+ }
+}
+
+sub open($class, %opts) {
+ my $is_gzip = $opts{gzip} ? 1 : 0;
+
+ my $inflater;
+ if ($is_gzip) {
+ my $status;
+ ($inflater, $status) = Compress::Raw::Zlib::Inflate->new(
+ -WindowBits => WANT_GZIP,
+ -Bufsize => 65536,
+ -LimitOutput => 1,
+ );
+ die "failed to initialize gzip inflater (status $status)\n" if $status != Z_OK;
+ }
+
+ # Plain payloads (such as local_json) are scanned directly in buf without chunk copying.
+ my $self = bless {
+ ts => 0,
+ obj => undef,
+ buf => $is_gzip ? '' : ($opts{body} // ''),
+ pos => 0,
+ input => $is_gzip ? $opts{body} : undef,
+ input_pos => 0,
+ in_chunk => '',
+ inflater => $inflater,
+ eof => $is_gzip ? 0 : 1,
+ closed => 0,
+ need_comma => 0,
+ }, $class;
+ delete $opts{body};
+
+ eval {
+ my $matched = 0;
+ while (1) {
+ pos($self->{buf}) = 0;
+ if ($self->{buf} =~ m/$ENVELOPE_OPEN_RE/gc) {
+ $self->{pos} = pos($self->{buf});
+ $matched = 1;
+ last;
+ }
+ last if length($self->{buf}) >= 4096;
+ last if !refill($self);
+ }
+ die "unexpected response format\n" if !$matched;
+ };
+ if (my $err = $@) {
+ $self->close();
+ die $err;
+ }
+
+ return $self;
+}
+
+sub next($self) {
+ return undef if $self->{closed};
+
+ while (1) {
+ # Compact PVE metric JSON uses ',{' between objects; skipping whitespace regexes on this
+ # common separator and matching flat ASCII objects avoids per-metric hash allocations,
+ # while escapes, UTF-8, nested values, or syntax errors fall back to decode_json.
+ my $pos = $self->{pos};
+ if (!defined($self->{scan_state})) {
+ if ($self->{need_comma} == 1 && substr($self->{buf}, $pos, 2) eq ',{') {
+ $pos++;
+ $self->{pos} = $pos;
+ $self->{need_comma} = 2;
+ } else {
+ pos($self->{buf}) = $pos;
+ $self->{buf} =~ /\G[ \t\r\n]*/gc;
+ $pos = pos($self->{buf});
+
+ if ($pos >= length($self->{buf})) {
+ $self->{pos} = $pos;
+ next if refill($self);
+ die "truncated metrics array\n";
+ }
+
+ my $ch = substr($self->{buf}, $pos, 1);
+ if ($ch eq ']') {
+ die "unexpected token in metrics array\n" if $self->{need_comma} == 2;
+ $self->{pos} = $pos + 1;
+ while (!$self->{eof}) {
+ die "unexpected trailing data\n"
+ if length($self->{buf}) - $self->{pos} > 4096;
+ last if !refill($self);
+ }
+ die "unexpected trailing data\n" if length($self->{buf}) - $self->{pos} > 4096;
+ pos($self->{buf}) = $self->{pos};
+ if ($self->{buf} !~ m/$ENVELOPE_CLOSE_RE/gc) {
+ die "unexpected trailing data\n";
+ }
+ $self->close();
+ return undef;
+ }
+
+ if ($self->{need_comma} == 1) {
+ die "unexpected token in metrics array\n" if $ch ne ',';
+ $self->{need_comma} = 2;
+ pos($self->{buf}) = $pos + 1;
+ $self->{buf} =~ /\G[ \t\r\n]*/gc;
+ $pos = pos($self->{buf});
+ if ($pos >= length($self->{buf})) {
+ $self->{pos} = $pos;
+ next if refill($self);
+ die "truncated metrics array\n";
+ }
+ $ch = substr($self->{buf}, $pos, 1);
+ }
+
+ die "unexpected token in metrics array\n" if $ch ne '{';
+ $self->{pos} = $pos;
+ }
+ }
+
+ # Fast path: flat printable-ASCII RFC 8259 object with a unique integer timestamp,
+ # validated and captured in a single non-backtracking pass without Perl hash allocation.
+ # Skip once an incomplete object has already entered the incremental fallback scanner.
+ if (!defined($self->{scan_state})) {
+ pos($self->{buf}) = $pos;
+ if ($self->{buf} =~ m/$FLAT_JSON_OBJ_RE/gc) {
+ my $end = pos($self->{buf});
+ if ($end - $pos > $MAX_METRIC_OBJECT_BYTES) {
+ die "metric object exceeds maximum size\n";
+ }
+ my ($obj, $ts_tok) = ($1, $2);
+ # Any <=18-char integer token (|x| < 10^18) fits in signed int64 without invoking
+ # B::svref_2object; only 19+ char tokens near INT64 bounds need full range checking.
+ my $num =
+ length($ts_tok) <= 18
+ ? ($ts_tok + 0)
+ : parse_signed_int64_token($ts_tok);
+ die "missing integer timestamp\n" if !defined($num);
+ $self->{ts} = $num;
+ $self->{pos} = $end;
+ $self->{need_comma} = 1;
+ $self->{obj} = $obj;
+ return $obj;
+ }
+ $self->{scan_state} = {
+ offset => 0,
+ depth => 0,
+ in_string => 0,
+ escaped => 0,
+ };
+ }
+
+ # Fallback: incremental bounded object scan + strict decode_json for escapes, UTF-8,
+ # nesting, or syntax errors (validating the original wire timestamp token and rejecting
+ # duplicates).
+ my $end = find_json_object_end(
+ \$self->{buf}, $pos, $self->{scan_state}, $MAX_METRIC_OBJECT_BYTES,
+ );
+ if (defined($end)) {
+ undef $self->{scan_state};
+ my $obj = substr($self->{buf}, $pos, $end - $pos);
+ my $decoded = decode_json($obj);
+ die "unexpected metric object\n" if ref($decoded) ne 'HASH';
+ my $ts_tok = extract_unique_timestamp_token($obj);
+ my $ts = parse_signed_int64_token($ts_tok);
+ die "missing integer timestamp\n" if !defined($ts);
+ $self->{ts} = $ts;
+ $self->{pos} = $end;
+ $self->{need_comma} = 1;
+ $self->{obj} = $obj;
+ return $obj;
+ }
+
+ if (length($self->{buf}) - $self->{pos} > $MAX_METRIC_OBJECT_BYTES) {
+ die "metric object exceeds maximum size\n";
+ }
+ next if refill($self);
+ die "truncated metric object\n";
+ }
+}
+
+sub obj($self) {
+ return $self->{obj};
+}
+
+sub ts($self) {
+ return $self->{ts};
+}
+
+sub close($self) {
+ return if !$self || $self->{closed};
+ $self->{closed} = 1;
+ delete @{$self}{qw(input in_chunk inflater buf obj scan_state)};
+}
+
+1;
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
` (6 preceding siblings ...)
2026-12-01 10:19 ` [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
@ 2026-12-01 10:19 ` Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 9/9] test: add pull metric export test suite Thomas Lamprecht
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:19 UTC (permalink / raw)
To: pve-devel
Sorted streaming waits for peer collection before sending its first
byte and retains all compressed peer bodies until the final peer
arrives.
Add an optional boolean `unsorted` parameter to GET
/cluster/metrics/export and build_passthrough_stream() to
PVE::PullMetricExport. An unsorted streaming cluster request writes its
first slice of pre-encoded local metrics before fetching peers, then
reads completed peer bodies in slices through
PVE::PullMetricExport::Reader, pausing queued peer dispatch (via Pool's
can_dispatch backpressure gate ahead of the shared worker limiter)
whenever the downstream socket is backpressured. CLI, buffered
formatters, and requests without remote targets do not gain incremental
delivery from unsorted=1. By default, a peer that fails to open or
yield its first metric is skipped with a warning (or aborts the stream
when fail-on-error=1); overall fan-out timeouts or subsequent reader
errors abort the in-progress stream (TCP RST) so consumers retry rather
than advancing their cursor past missing samples.
Carrying a second streaming state machine and can_dispatch backpressure
gating adds complexity. The trade-off keeps backwards-compatible global
sorting by default while reducing first-byte and total time for callers
that handle ordering themselves; omit unsorted when querying older
nodes, which reject the unknown parameter.
Measured on the same single-worker mock harness (25 ms/peer, 16-peer
per-export cap, 36 FDs; scenarios are nodes x guests, hist10 = 10
history generations per node; Max /ping HOL = maximum concurrent /ping
head-of-line latency on the same worker):
Scenario | Mode | Total | TTFB | VmHWM | Max /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | K-way stream | 196ms | 114ms | 84 MiB | 5.0 ms
(25,475 metrics) | Pass-through | 147ms | 2.0ms | 82 MiB | 8.0 ms
25x100 hist10 | K-way stream | 871ms | 123ms | 99 MiB | 9.4 ms
(254,750 metrics) | Pass-through | 761ms | 6.2ms | 93 MiB | 6.0 ms
100x100 latest | K-way stream | 687ms | 399ms | 91 MiB | 7.3 ms
(101,900 metrics) | Pass-through | 445ms | 2.1ms | 82 MiB | 9.5 ms
100x1000 | K-way stream | 3296ms | 397ms | 103 MiB | 9.5 ms
(1,001,900 metrics) | Pass-through | 2955ms | 5.3ms | 94 MiB | 8.6 ms
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
Changes in v2:
- Account queued ready_peers and active readers against the worker-wide
retained-byte admission threshold (pausing further peer fetches until
queued bodies drain), drop local_json from %opts on starter entry, and
wire fail-on-error=1 and synchronous strict-failure dispatch stopping
into pass-through streaming.
- Clarify endpoint and unsorted cursor descriptions (API 504 vs 502
mapping, non-snapshot semantics of fail-on-error=1, per-node or
overlap+dedup cursor guidance, and post-start incomplete-response
rules) and refresh commit message trade-off prose and benchmark
numbers.
PVE/API2/Cluster/MetricServer.pm | 36 +++--
PVE/PullMetricExport.pm | 268 +++++++++++++++++++++++++++++--
2 files changed, 284 insertions(+), 20 deletions(-)
diff --git a/PVE/API2/Cluster/MetricServer.pm b/PVE/API2/Cluster/MetricServer.pm
index 14f065fd6..0a9d7b838 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -319,12 +319,18 @@ __PACKAGE__->register_method({
expose_credentials => 1,
description =>
"Retrieve metrics of the cluster. By default, remote peer failures are logged"
- . " and skipped (best-effort across reachable nodes); set fail-on-error=1 to fail the"
- . " export if any online target node cannot be fetched or fails validation. If a"
- . " cluster-wide fan-out exceeds its overall timeout (or fails with fail-on-error=1)"
- . " before response headers are sent, /api2/json returns HTTP 504/502 and /api2/extjs"
- . " returns HTTP 200 with success: 0 and status: 504/502. Cursor-based scrapers should"
- . " retry with the same start-time on error or timeout rather than advancing it.",
+ . " and skipped (best-effort across reachable nodes). Setting fail-on-error=1 detects"
+ . " fetch and read errors on online target nodes; it does not provide a cluster-wide"
+ . " snapshot, as a node can publish another sample after it has answered. Before"
+ . " response headers are sent, an overall timeout or a strict peer timeout returns"
+ . " 504, and other strict peer failures return 502 (as the HTTP status on /api2/json,"
+ . " or HTTP 200 with success: 0 and the error code in status on /api2/extjs). Invalid"
+ . " peer data discovered after sending starts can leave the response incomplete, and"
+ . " with unsorted=1 this can also happen on an overall timeout or a strict peer"
+ . " failure. Cursor-based scrapers should retry errors and incomplete responses with"
+ . " the same start-time; loss-sensitive scrapers should track per-node cursors or"
+ . " overlap with deduplication rather than relying solely on the maximum returned"
+ . " timestamp.",
permissions => {
check => ['perm', '/', ['Sys.Audit']],
},
@@ -363,6 +369,15 @@ __PACKAGE__->register_method({
optional => 1,
default => 0,
},
+ 'unsorted' => {
+ type => 'boolean',
+ description =>
+ 'Do not sort metrics by timestamp. No global order is guaranteed;'
+ . ' callers must not assume the last record carries the response maximum'
+ . ' timestamp.',
+ optional => 1,
+ default => 0,
+ },
},
},
returns => {
@@ -371,8 +386,8 @@ __PACKAGE__->register_method({
properties => {
data => {
type => 'array',
- description =>
- 'Array of system metrics. Metrics are sorted by their timestamp.',
+ description => 'Array of system metrics. Sorted by timestamp unless unsorted is'
+ . ' set; no global order is guaranteed in unsorted mode.',
items => {
type => 'object',
additionalProperties => 0,
@@ -413,6 +428,7 @@ __PACKAGE__->register_method({
my $start = $param->{'start-time'};
my $history = $param->{'history'} // 0;
my $fail_on_error = $param->{'fail-on-error'} // 0;
+ my $unsorted = $param->{'unsorted'} // 0;
my $now = time();
@@ -505,7 +521,7 @@ __PACKAGE__->register_method({
if (!@targets) {
# In-place sort avoids allocating a second copy of large metric arrays.
- @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+ @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics if !$unsorted;
return {
data => \@metrics,
};
@@ -516,6 +532,7 @@ __PACKAGE__->register_method({
my $remote_params = {
# Do NOT remove 'local-only' - potential for request recursion!
+ # Intentionally omit 'unsorted' so mixed-version peers never reject the unknown parameter.
'local-only' => 1,
history => $history,
};
@@ -527,6 +544,7 @@ __PACKAGE__->register_method({
credentials => $credentials,
metrics => \@metrics,
fail_on_error => $fail_on_error,
+ unsorted => $unsorted,
port => $REMOTE_PORT,
request_timeout => $REMOTE_REQUEST_TIMEOUT,
overall_timeout => $FANOUT_OVERALL_TIMEOUT,
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
index 272d9bb1a..fd05eca72 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,10 +1,13 @@
package PVE::PullMetricExport;
# Asynchronous cluster-wide pull-metric fan-out and streaming export for GET
-# /cluster/metrics/export. export() selects between two paths:
-# - Incremental k-way merge stream (default when AsyncStream is supported): keeps remote peer
-# responses gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then
-# merges local and remote streams in global timestamp order in cooperative 256 KiB slices.
+# /cluster/metrics/export. export() selects between three paths:
+# - Default k-way merge stream (when AsyncStream is supported): keeps remote peer bodies
+# gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then merges local
+# and remote streams in global timestamp order in cooperative 256 KiB slices.
+# - Opt-in unsorted=1 pass-through stream: writes its first slice of pre-encoded local metrics
+# before fetching peers, then drains completed peer bodies in slices with can_dispatch
+# backpressure gating.
# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers).
use v5.36;
@@ -727,26 +730,269 @@ sub build_kway_merge_stream(%opts) {
};
}
+my sub passthrough_drain_reader($state, $max_bytes) {
+ my $out = '';
+ my $entry = $state->{active_reader};
+ return $out if !$entry;
+
+ my $reader = $entry->{reader};
+ my $exhausted = 0;
+
+ eval {
+ while (length($out) < $max_bytes) {
+ $out .= ',' if !$state->{first_item};
+ $state->{first_item} = 0;
+ $out .= $entry->{obj};
+
+ my $obj = $reader->next();
+ if (!defined($obj)) {
+ $exhausted = 1;
+ last;
+ }
+ $entry->{obj} = $obj;
+ }
+ };
+ if (my $err = $@) {
+ log_peer_error($entry->{name}, $err);
+ $reader->close();
+ delete $state->{active_reader};
+ abort_stream($state, "could not stream metrics from $entry->{name}: $err");
+ return undef;
+ }
+
+ if ($exhausted) {
+ release_peer_bytes($state, delete $entry->{retained_bytes});
+ delete $state->{active_reader};
+ }
+ return $out;
+}
+
+my sub passthrough_emit_step($state) {
+ my $self = __SUB__;
+ clear_slice_watchers($state);
+ my $stream = $state->{stream};
+ return if $state->{done} || !$stream || $stream->is_closed();
+
+ my $out = '';
+ my $ready = $state->{ready_peers};
+ while (length($out) < $STREAM_SLICE_BYTES) {
+ if (!defined($state->{active_reader})) {
+ last if !@$ready;
+ my $peer = shift @$ready;
+ my $bytes = $peer->{retained_bytes};
+ my $entry = eval {
+ open_peer_reader(
+ $peer->{name},
+ $peer->{body},
+ $peer->{gzip},
+ $state->{fail_on_error},
+ );
+ };
+ my $err = $@;
+ undef $peer;
+ if ($err) {
+ release_peer_bytes($state, $bytes);
+ abort_stream($state, $err);
+ return;
+ }
+ if (!$entry) {
+ release_peer_bytes($state, $bytes);
+ next;
+ }
+ $entry->{retained_bytes} = $bytes;
+ $state->{active_reader} = $entry;
+ }
+ my $chunk = passthrough_drain_reader($state, $STREAM_SLICE_BYTES - length($out));
+ return if $state->{done} || !defined($chunk);
+ $out .= $chunk;
+ }
+
+ if (!length($out)) {
+ if ($state->{fetch_done}) {
+ finish_stream($state, '');
+ return;
+ }
+ $state->{fanout}->{dispatch}->() if $state->{fanout};
+ return;
+ }
+
+ if (!defined($state->{active_reader}) && !@$ready && $state->{fetch_done}) {
+ finish_stream($state, $out);
+ return;
+ }
+
+ my $ok = $stream->write($out);
+ after_stream_write(
+ $state,
+ $ok,
+ sub { $self->($state) },
+ sub { $state->{fanout}->{dispatch}->() if $state->{fanout} },
+ );
+}
+
+my sub passthrough_schedule_emit($state) {
+ my $stream = $state->{stream};
+ if (
+ $state->{done}
+ || $state->{waiting_drain}
+ || defined($state->{slice_idle})
+ || defined($state->{slice_timer})
+ || !$stream
+ || $stream->is_closed()
+ ) {
+ return;
+ }
+ schedule_slice($state, sub { passthrough_emit_step($state) });
+}
+
+sub build_passthrough_stream(%opts) {
+ my $local_json = delete $opts{local_json};
+ my $fail_on_error = $opts{fail_on_error} ? 1 : 0;
+ my $max_concurrent = int($opts{max_concurrent} // 16);
+ $max_concurrent = 1 if $max_concurrent < 1;
+
+ return sub {
+ my ($stream) = @_;
+
+ my $state = {
+ stream => $stream,
+ done => 0,
+ needs_all_peers => 0,
+ retained_bytes => 0,
+ fetch_done => 0,
+ waiting_drain => 0,
+ fail_on_error => $fail_on_error,
+ ready_peers => [],
+ active_reader => undef,
+ first_item => 1,
+ };
+
+ my $cancel = sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ cleanup_stream($state);
+ };
+
+ # Emit wrapper + first local slice immediately for minimal TTFB.
+ return $cancel if !$stream->start();
+ my $out = $STREAM_PREFIX;
+ if (defined($local_json)) {
+ my $local_entry =
+ eval { open_peer_reader('local', $local_json, 0, $fail_on_error) };
+ my $err = $@;
+ undef $local_json;
+ if ($err) {
+ abort_stream($state, $err);
+ return $cancel;
+ }
+ if ($local_entry) {
+ $state->{active_reader} = $local_entry;
+ my $chunk = passthrough_drain_reader($state, $STREAM_SLICE_BYTES);
+ return $cancel if $state->{done} || !defined($chunk);
+ $out .= $chunk;
+ }
+ }
+
+ my $ok = $stream->write($out);
+ if (!$state->{done} && !$stream->is_closed()) {
+ $ok = $stream->flush() if $ok;
+ }
+ return $cancel if $state->{done} || $stream->is_closed();
+
+ my $fanout = start_metric_fanout(
+ %opts,
+ is_done => sub { return $state->{done}; },
+ byte_state => $state,
+ # Bound queued ready_peers alongside socket backpressure so slow consumers cap buffered
+ # peer payloads while the pool suspends its overall_timeout countdown.
+ can_dispatch => sub {
+ return
+ !$state->{waiting_drain}
+ && !$stream->is_backpressured()
+ && !$stream->is_closed()
+ && scalar(@{ $state->{ready_peers} }) < $max_concurrent;
+ },
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ return if $state->{done};
+ my $bytes = length($$body_ref // '');
+ retain_peer_bytes($state, $bytes);
+ push @{ $state->{ready_peers} },
+ {
+ name => $name,
+ body => $$body_ref,
+ gzip => $is_gzip,
+ retained_bytes => $bytes,
+ };
+ passthrough_schedule_emit($state);
+ },
+ on_peer_error => $fail_on_error
+ ? sub {
+ my ($name, $err, $code) = @_;
+ abort_stream(
+ $state,
+ PVE::Exception->new(
+ "could not fetch metrics from $name: $err",
+ code => $code,
+ ),
+ );
+ }
+ : undef,
+ on_done => sub($timed_out, $timeout) {
+ return if $state->{done} || $stream->is_closed();
+ $state->{fetch_done} = 1;
+ delete $state->{fanout};
+ if ($timed_out) {
+ abort_stream($state,
+ "cluster metric fan-out timed out after ${timeout}s\n");
+ return;
+ }
+ eval { passthrough_schedule_emit($state); };
+ abort_stream($state, $@) if $@;
+ },
+ );
+ if ($state->{done}) {
+ $fanout->{cancel}->();
+ } elsif (!$state->{fetch_done}) {
+ $state->{fanout} = $fanout;
+ }
+
+ if (!$ok || $stream->is_backpressured() || defined($state->{active_reader})) {
+ after_stream_write(
+ $state,
+ $ok,
+ sub { passthrough_emit_step($state) },
+ sub { $state->{fanout}->{dispatch}->() if $state->{fanout} },
+ );
+ }
+
+ return $cancel;
+ };
+}
+
sub export(%opts) {
my $metrics = $opts{metrics} // [];
+ my $unsorted = $opts{unsorted} ? 1 : 0;
if (PVE::APIServer::AnyEvent::async_stream_supported()) {
my $local_json;
if (@$metrics) {
- # Encode local metrics into the same wire envelope as remote peers so the streaming
- # reader and k-way merge heap drain local and remote sources uniformly.
- @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ # Encode local metrics into the same wire envelope as remote peers so both streaming
+ # modes drain local and remote sources through Reader uniformly.
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics if !$unsorted;
$local_json = encode_json({ data => { data => $metrics } });
@$metrics = ();
}
- return PVE::APIServer::AnyEvent::async_stream_response(
- build_kway_merge_stream(%opts, local_json => $local_json),
- );
+ my $starter =
+ $unsorted
+ ? build_passthrough_stream(%opts, local_json => $local_json)
+ : build_kway_merge_stream(%opts, local_json => $local_json);
+ return PVE::APIServer::AnyEvent::async_stream_response($starter);
}
my $finalize = sub {
# In-place sort avoids allocating a second copy of large metric arrays.
- @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics if !$unsorted;
return {
data => $metrics,
};
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread
* [PATCH manager v2 9/9] test: add pull metric export test suite
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
` (7 preceding siblings ...)
2026-12-01 10:19 ` [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
@ 2026-12-01 10:19 ` Thomas Lamprecht
8 siblings, 0 replies; 10+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:19 UTC (permalink / raw)
To: pve-devel
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 <t.lamprecht@proxmox.com>
---
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
^ permalink raw reply related [flat|nested] 10+ messages in thread
end of thread, other threads:[~2026-12-01 10:45 UTC | newest]
Thread overview: 10+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client Thomas Lamprecht
2026-12-01 10:19 ` [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 9/9] test: add pull metric export test suite Thomas Lamprecht
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.