* [PATCH http-server 01/09] response: support deferred async API2 responses
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH http-server 02/09] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
` (9 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 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
one of the three pveproxy workers 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>
---
src/PVE/APIServer/AnyEvent.pm | 254 +++++++++++++++++++++++++++++-----
1 file changed, 221 insertions(+), 33 deletions(-)
diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm
index b4d3f21..7bbd586 100644
--- a/src/PVE/APIServer/AnyEvent.pm
+++ b/src/PVE/APIServer/AnyEvent.pm
@@ -54,6 +54,19 @@ 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.
+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 +160,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 +1045,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 +1256,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 +1323,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 +2623,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] 12+ messages in thread* [PATCH http-server 02/09] proxy: strip chunked framing headers from decoded responses
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
2026-11-30 0:58 ` [PATCH http-server 01/09] response: support deferred async API2 responses Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH http-server 03/09] response: support incremental streaming API2 responses Thomas Lamprecht
` (8 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 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, and frame
non-stream responses whenever the status permits a body and $content
is defined (keeping 1xx, 204, 304, and streamed responses without
Content-Length or body). 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>
---
src/PVE/APIServer/AnyEvent.pm | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm
index 7bbd586..36ad253 100644
--- a/src/PVE/APIServer/AnyEvent.pm
+++ b/src/PVE/APIServer/AnyEvent.pm
@@ -406,7 +406,8 @@ sub response {
$content = '';
}
- if ($code =~ /^(1\d\d|[23]04)$/) {
+ my $no_body = $code =~ /^(1[0-9][0-9]|[23]04)$/;
+ if ($no_body) {
# make sure informational, no content and not modified response send no content
$content = "";
}
@@ -432,7 +433,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);
@@ -467,7 +468,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});
@@ -957,6 +958,9 @@ sub proxy_request {
my $stream = delete $hdr->{pvestreamfile};
delete $hdr->{URL};
delete $hdr->{HTTPVersion};
+ # AnyEvent::HTTP already decoded a chunked body but keeps the framing headers.
+ delete $hdr->{'transfer-encoding'};
+ delete $hdr->{trailer};
my $header = HTTP::Headers->new(%$hdr);
if (my $location = $header->header('Location')) {
$location =~ s|^http://localhost:85||;
--
2.47.3
^ permalink raw reply related [flat|nested] 12+ messages in thread* [PATCH http-server 03/09] response: support incremental streaming API2 responses
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
2026-11-30 0:58 ` [PATCH http-server 01/09] response: support deferred async API2 responses Thomas Lamprecht
2026-11-30 0:58 ` [PATCH http-server 02/09] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH apiclient 04/09] add non-blocking AnyEvent API client Thomas Lamprecht
` (7 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 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>
---
src/Makefile | 1 +
src/PVE/APIServer/AnyEvent.pm | 76 ++++++-
src/PVE/APIServer/AsyncStream.pm | 375 +++++++++++++++++++++++++++++++
3 files changed, 451 insertions(+), 1 deletion(-)
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 36ad253..c0d2397 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,11 +56,17 @@ my $limit_max_post = 512 * 1024;
my $limit_max_request_line = 64 * 1024;
my $ASYNC_SUPPORTED = 0;
+my $ASYNC_FORMAT;
sub async_supported {
return $ASYNC_SUPPORTED;
}
+sub async_stream_supported {
+ return 0 if !$ASYNC_SUPPORTED || !defined($ASYNC_FORMAT);
+ return ($ASYNC_FORMAT eq 'json' || $ASYNC_FORMAT eq 'extjs') ? 1 : 0;
+}
+
# Wrap a deferred API2 response starter: sub ($resolve, $reject) -> optional cancel coderef.
sub async_response {
my ($starter) = @_;
@@ -67,6 +74,13 @@ sub async_response {
return bless { start => $starter }, 'PVE::APIServer::AnyEvent::AsyncResponse';
}
+# Wrap a deferred streaming API2 response starter: sub ($stream) -> optional cancel coderef.
+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,
@@ -1227,6 +1241,45 @@ my sub start_async_response {
);
}
+my sub start_async_stream {
+ my ($self, $reqstate, $async_stream, $res, $finish, $format) = @_;
+
+ if (
+ ref($async_stream) ne 'PVE::APIServer::AnyEvent::AsyncStreamResponse'
+ || ref($async_stream->{start}) ne 'CODE'
+ ) {
+ die "invalid async stream response\n";
+ }
+
+ if (!defined($format) || ($format ne 'json' && $format ne 'extjs')) {
+ 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) = @_;
@@ -1262,8 +1315,13 @@ sub handle_api2_request {
my $res = do {
my $prev_async = $ASYNC_SUPPORTED;
- my $guard = guard { $ASYNC_SUPPORTED = $prev_async };
+ my $prev_format = $ASYNC_FORMAT;
+ my $guard = guard {
+ $ASYNC_SUPPORTED = $prev_async;
+ $ASYNC_FORMAT = $prev_format;
+ };
$ASYNC_SUPPORTED = 1;
+ $ASYNC_FORMAT = $format;
$self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
};
@@ -1272,6 +1330,15 @@ 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);
+ return;
+ }
+
if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncResponse') {
my $async = delete $res->{data};
my $finish = sub {
@@ -2634,6 +2701,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..1a190ce
--- /dev/null
+++ b/src/PVE/APIServer/AsyncStream.pm
@@ -0,0 +1,375 @@
+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;
+# pause further writes and resume via on_drain()).
+# 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() - 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;
+ 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()) {
+ die "failed to initialize gzip compressor: $st\n";
+ }
+ $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()) {
+ die "failed to initialize deflate compressor: $st\n";
+ }
+ $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) {
+ $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;
+ }
+
+ $self->{finished} = 1;
+ delete $reqstate->{on_disconnect};
+
+ if ($reqstate->{hdl} && $chunked) {
+ Net::SSLeay::ERR_clear_error();
+ $hdl->push_write("0\015\012\015\012");
+ }
+
+ if ($reqstate->{hdl}) {
+ $reqstate->{log}->{content_length} = $self->{bytes_written};
+ $server->log_request($reqstate, $reqstate->{request});
+
+ AnyEvent->now_update();
+ if ($reqstate->{hdl}) {
+ $hdl->timeout_reset();
+ $hdl->timeout($server->{timeout});
+ }
+
+ # 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();
+ $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] 12+ messages in thread* [PATCH apiclient 04/09] add non-blocking AnyEvent API client
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (2 preceding siblings ...)
2026-11-30 0:58 ` [PATCH http-server 03/09] response: support incremental streaming API2 responses Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH apiclient 05/09] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
` (6 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 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>
---
Makefile | 4 +
debian/control | 12 +-
src/Makefile | 7 +-
src/PVE/APIClient/AnyEvent.pm | 496 ++++++++++
src/test/anyevent_client.t | 1653 +++++++++++++++++++++++++++++++++
5 files changed, 2170 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..0b29ab7
--- /dev/null
+++ b/src/PVE/APIClient/AnyEvent.pm
@@ -0,0 +1,496 @@
+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 (verify_hostname defaults to 0 only with cached_fingerprints).
+# - 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 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 $explicit_verify_hostname =
+ defined($ssl_opts{verify_hostname}) ? ($ssl_opts{verify_hostname} ? 1 : 0) : undef;
+ my $verify_hostname;
+ if (defined($explicit_verify_hostname)) {
+ $verify_hostname = $explicit_verify_hostname;
+ } else {
+ # Match LWP.pm: purely trust configured cached fingerprints by default, otherwise enforce
+ # hostname verification (falling back to verify_fingerprint_cb for untrusted certs).
+ $verify_hostname = $has_cached_fp ? 0 : 1;
+ }
+ delete $ssl_opts{verify_hostname};
+
+ if (
+ $explicit_verify_hostname
+ && defined($ssl_opts{verify_peername})
+ && $ssl_opts{verify_peername} eq 'none'
+ ) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: verify_hostname => 1 with verify_peername => 'none'\n");
+ }
+
+ my %tls_args = (
+ method => 'any',
+ sslv2 => 0,
+ sslv3 => 0,
+ verify => 1,
+ dh => undef,
+ %ssl_opts,
+ );
+
+ 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';
+ }
+
+ $tls_args{verify_peername} //= $verify_hostname ? 'https' : 'none';
+
+ if (!$has_fp_pinning && !$tls_args{verify_cb} && $tls_args{verify_peername} eq 'none') {
+ 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_hostname && !$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_hostname && $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 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});
+ my $auth_header = $api_token;
+ if ($auth_header !~ /^\w+(?:=| )/) {
+ $auth_header = "${api_token_name}=${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 exactly one terminal callback (and none after $cancel->()):
+# - 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.
+# Thrown setup errors are deferred via AE::postpone so on_error never fires before $cancel is
+# returned (invalid callback/body+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 !~ /^(?:GET|POST|PUT|DELETE|HEAD)$/) {
+ 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';
+
+ my $headers = normalize_headers($opts{headers});
+ if (!exists($headers->{'accept-encoding'}) && !exists($self->{headers}->{'accept-encoding'})) {
+ $headers->{'accept-encoding'} = 'gzip';
+ }
+ $opts{headers} = $headers;
+
+ 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' || !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..a74939d
--- /dev/null
+++ b/src/test/anyevent_client.t
@@ -0,0 +1,1653 @@
+#!/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/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@pam!tok=secret-val',
+ 'bare api_token gets default PVEAPIToken= prefix',
+ );
+ is($r1->{headers}->{pvedisableproxy}, '1', 'custom default header sent');
+
+ 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@pam!tok=from-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',
+ );
+ is($unpinned_conns, 0, 'no TCP connections opened for verify => 0 or conflicting ssl_opts');
+ undef $unpinned_guard;
+
+ 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");
+ }
+
+ is($hdr_conns, 0, 'no TCP connections opened for rejected per-request headers');
+ undef $hdr_guard;
+};
+
+undef $server_guard;
+%active_server_handles = ();
+
+done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 12+ messages in thread* [PATCH apiclient 05/09] add bounded AnyEvent request pool with backpressure and timeout
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (3 preceding siblings ...)
2026-11-30 0:58 ` [PATCH apiclient 04/09] add non-blocking AnyEvent API client Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH manager 06/09] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
` (5 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 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>
---
src/Makefile | 3 +-
src/PVE/APIClient/AnyEvent/Pool.pm | 272 ++++++++++++
src/test/anyevent_pool.t | 690 +++++++++++++++++++++++++++++
3 files changed, 964 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..518b998
--- /dev/null
+++ b/src/PVE/APIClient/AnyEvent/Pool.pm
@@ -0,0 +1,272 @@
+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;
+
+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;
+}
+
+my sub cleanup_state($state) {
+ my @cancels = grep { ref($_) eq 'CODE' } values %{ $state->{active} };
+ # 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 on_start_error)};
+
+ for my $cancel (@cancels) {
+ invoke_callback($cancel);
+ }
+}
+
+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});
+
+ AnyEvent->now_update();
+ my $elapsed = AnyEvent->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});
+
+ AnyEvent->now_update();
+ $state->{timeout_started_at} = AnyEvent->time;
+ $state->{timeout_watcher} = AE::timer(
+ $state->{remaining_timeout},
+ 0,
+ sub {
+ 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});
+
+ AnyEvent->now_update();
+ my $elapsed = AnyEvent->time - $state->{timeout_started_at};
+ $elapsed = 0 if $elapsed < 0;
+ return $elapsed >= $state->{remaining_timeout} ? 1 : 0;
+}
+
+my sub check_can_dispatch($state) {
+ my $can_dispatch = $state->{can_dispatch};
+ return 1 if !$can_dispatch;
+
+ my $ok = eval { $can_dispatch->() };
+ 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_can_dispatch($state);
+ 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};
+
+ resume_timeout($state);
+ if (timeout_expired($state)) {
+ $timed_out = 1;
+ last;
+ }
+
+ my $item = shift @{ $state->{queue} };
+ my $id = $item->{id};
+ my $item_done = 0;
+
+ $state->{active}->{$id} = undef;
+
+ my $finish_item = sub {
+ return if $item_done;
+ $item_done = 1;
+ return if $state->{done};
+
+ delete $state->{active}->{$id};
+ $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};
+ }
+ 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 && ref($cancel) eq 'CODE') {
+ invoke_callback($cancel);
+ }
+ } elsif (!$item_done) {
+ $state->{active}->{$id} = 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 using `can_dispatch` must invoke `$pool->{dispatch}->()` when backpressure starts or
+# clears: `overall_timeout` suspends while queued items are held back by `can_dispatch` (once the
+# queue is empty, active items stay subject to the deadline), and a backpressured pool with no
+# active items stays paused until `dispatch()` is called. A throwing `can_dispatch` warns and stops
+# dispatch without pausing `overall_timeout` (without a timeout, queued items stay paused until a
+# later `dispatch()` succeeds or `cancel()` runs). 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, $on_start_error) =
+ @opts{ 'items', 'start_item', 'on_done', 'can_dispatch', 'on_start_error' };
+ 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($on_start_error) && ref($on_start_error) ne 'CODE') {
+ croak "on_start_error must be a CODE ref";
+ }
+
+ my $max_concurrent = $opts{max_concurrent} // 16;
+ if (ref($max_concurrent) || $max_concurrent !~ /^[0-9]+$/ || $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]+)$/
+ || $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,
+ on_start_error => $on_start_error,
+ max_concurrent => $max_concurrent,
+ };
+
+ 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..30657f7
--- /dev/null
+++ b/src/test/anyevent_pool.t
@@ -0,0 +1,690 @@
+#!/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');
+};
+
+done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 12+ messages in thread* [PATCH manager 06/09] api: metrics export: fetch remote nodes asynchronously
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (4 preceding siblings ...)
2026-11-30 0:58 ` [PATCH apiclient 05/09] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH manager 07/09] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
` (4 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 UTC (permalink / raw)
To: pve-devel
Cluster-wide GET /cluster/metrics/export runs inside pveproxy's 3
AnyEvent workers 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.
Concurrent peer fetches are capped at 16 per export and 32 worker-wide
across overlapping exports (FIFO-queued without pausing overall
timeouts) with non-persistent HTTPS sockets, SHA-256 leaf fingerprint
pinning, PVEDisableProxy: true, Accept-Encoding: gzip, IPv6 host
bracketing, an overall timeout, and immediate disconnect cancellation.
Non-persistent sockets and the worker-wide peer cap keep open FDs flat
well below AnyEvent::Impl::Perl's select() 1024 limit at the trade-off
of one fresh TLS handshake per peer per scrape. Decoded peer entries
are validated per peer before merging, and finalization errors are
forwarded to reject().
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
PVE/API2/Cluster/MetricServer.pm | 100 ++++++----
PVE/Makefile | 1 +
PVE/PullMetricExport.pm | 324 +++++++++++++++++++++++++++++++
3 files changed, 385 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..8dc8db7b0 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -3,7 +3,6 @@ package PVE::API2::Cluster::MetricServer;
use warnings;
use strict;
-use PVE::APIClient::LWP;
use PVE::AccessControl;
use PVE::Cluster;
use PVE::INotify;
@@ -13,9 +12,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 +316,11 @@ __PACKAGE__->register_method({
path => 'export',
method => 'GET',
expose_credentials => 1,
- description => "Retrieve metrics of the cluster.",
+ description => "Retrieve metrics of the cluster. If a cluster-wide fan-out exceeds the"
+ . " overall timeout before completing, the request fails with HTTP 504 on /api2/json"
+ . " (or HTTP 200 with success: 0 and status: 504 on /api2/extjs). Cursor-based"
+ . " scrapers should retry from their previous start-time on error or timeout rather"
+ . " than advancing it.",
permissions => {
check => ['perm', '/', ['Sys.Audit']],
},
@@ -411,6 +420,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 +431,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 +464,55 @@ __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");
} 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,
+ 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..f657a1c34
--- /dev/null
+++ b/PVE/PullMetricExport.pm
@@ -0,0 +1,324 @@
+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 PVE::APIClient::AnyEvent;
+use PVE::APIClient::AnyEvent::Pool;
+use PVE::APIServer::AnyEvent;
+use PVE::Exception;
+use PVE::SafeSyslog ();
+
+our $MAX_WORKER_CONCURRENT_PEERS = 32;
+
+my $WORKER_ACTIVE_PEERS = 0;
+my @WORKER_WAIT_QUEUE;
+my $WORKER_DRAINING = 0;
+my $WORKER_DRAIN_SCHEDULED = 0;
+
+my sub log_peer_error($name, $err) {
+ PVE::SafeSyslog::syslog('warning', "could not fetch metrics from $name: $err");
+}
+
+my sub worker_peer_limit() {
+ my $limit = int($MAX_WORKER_CONCURRENT_PEERS // 32);
+ return $limit < 1 ? 1 : $limit;
+}
+
+my sub drain_worker_waiters() {
+ return if $WORKER_DRAINING;
+ $WORKER_DRAINING = 1;
+ eval {
+ while (@WORKER_WAIT_QUEUE && $WORKER_ACTIVE_PEERS < worker_peer_limit()) {
+ my $waiter = shift @WORKER_WAIT_QUEUE;
+ next if $waiter->{cancelled};
+ $WORKER_ACTIVE_PEERS++;
+ $waiter->{granted} = 1;
+ my $start_cb = delete $waiter->{start};
+ $start_cb->();
+ }
+ };
+ my $err = $@;
+ $WORKER_DRAINING = 0;
+ die $err if $err;
+}
+
+my sub schedule_drain_worker_waiters() {
+ return if $WORKER_DRAIN_SCHEDULED || !@WORKER_WAIT_QUEUE;
+ $WORKER_DRAIN_SCHEDULED = 1;
+ AE::postpone(sub {
+ $WORKER_DRAIN_SCHEDULED = 0;
+ drain_worker_waiters();
+ });
+}
+
+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_done) = @opts{ 'params', 'on_peer', 'on_done' };
+
+ my %auth_args;
+ if (defined($credentials->{api_token})) {
+ $auth_args{api_token} = $credentials->{api_token};
+ } elsif (defined($credentials->{ticket})) {
+ $auth_args{ticket} = $credentials->{ticket};
+ }
+
+ return PVE::APIClient::AnyEvent::Pool::start(
+ items => \@items,
+ max_concurrent => $max_concurrent,
+ overall_timeout => $overall_timeout,
+ can_dispatch => $opts{can_dispatch},
+ on_start_error => sub {
+ my ($name, $err) = @_;
+ log_peer_error($name, $err);
+ },
+ start_item => sub {
+ my ($target, $finish_item) = @_;
+
+ my ($name, $ip, $fingerprint) = $target->@{qw(name ip fingerprint)};
+ my $released = 0;
+ my $req_cancel;
+ my $waiter;
+
+ my $release_slot = sub {
+ my ($defer_drain) = @_;
+ return if $released;
+ $released = 1;
+ $WORKER_ACTIVE_PEERS-- if $WORKER_ACTIVE_PEERS > 0;
+ if ($defer_drain) {
+ schedule_drain_worker_waiters();
+ } else {
+ drain_worker_waiters();
+ }
+ };
+
+ my $start_request = sub {
+ my $done_called = 0;
+ my $finish_with_release = sub {
+ return if $done_called;
+ $done_called = 1;
+ undef $req_cancel;
+ $release_slot->();
+ $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);
+ $finish_with_release->();
+ return;
+ }
+
+ 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';
+ log_peer_error($name, "$status $reason");
+ } 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_with_release->();
+ die $cb_err if $cb_err;
+ },
+ on_error => sub {
+ my ($err) = @_;
+ log_peer_error($name, $err);
+ $finish_with_release->();
+ },
+ );
+ };
+ if (my $err = $@) {
+ log_peer_error($name, $err);
+ $finish_with_release->();
+ return;
+ }
+
+ if ($waiter->{cancelled}) {
+ $cancel->() if !$done_called && ref($cancel) eq 'CODE';
+ } elsif (!$done_called) {
+ $req_cancel = $cancel;
+ }
+ };
+
+ $waiter = {
+ granted => 0,
+ cancelled => 0,
+ start => $start_request,
+ };
+
+ if ($WORKER_ACTIVE_PEERS < worker_peer_limit()) {
+ $WORKER_ACTIVE_PEERS++;
+ $waiter->{granted} = 1;
+ delete $waiter->{start};
+ $start_request->();
+ } else {
+ push @WORKER_WAIT_QUEUE, $waiter;
+ }
+
+ return sub {
+ return if $waiter->{cancelled};
+ $waiter->{cancelled} = 1;
+ delete $waiter->{start};
+ if (!$waiter->{granted}) {
+ @WORKER_WAIT_QUEUE = grep { $_ != $waiter } @WORKER_WAIT_QUEUE;
+ return;
+ }
+ if (my $cancel = $req_cancel) {
+ undef $req_cancel;
+ $cancel->();
+ }
+ # Defer draining queued waiters until all items in a cancelling or timing-out pool
+ # have run their cancel callbacks so another waiter from the same pool is not started.
+ $release_slot->(1);
+ };
+ },
+ 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 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'
+ || !defined($item->{timestamp})
+ || ref($item->{timestamp})
+ || $item->{timestamp} !~ /^-?(?:0|[1-9][0-9]*)$/
+ ) {
+ die "unexpected metric entry format\n";
+ }
+ }
+
+ return $items;
+}
+
+sub build_buffered_fanout(%opts) {
+ my ($metrics, $finalize) = @opts{ 'metrics', 'finalize' };
+
+ return sub {
+ my ($resolve, $reject) = @_;
+
+ my $state = { done => 0 };
+ $state->{fanout} = start_metric_fanout(
+ %opts,
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ eval {
+ my $peer_metrics = decode_peer_metrics($body_ref, $is_gzip);
+ push @$metrics, @$peer_metrics;
+ };
+ log_peer_error($name, $@) if $@;
+ },
+ on_done => sub($timed_out, $timeout) {
+ return if $state->{done};
+ $state->{done} = 1;
+ delete $state->{fanout};
+ 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);
+ },
+ );
+
+ return sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ if (my $fanout = delete $state->{fanout}) {
+ $fanout->{cancel}->();
+ }
+ @$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] 12+ messages in thread* [PATCH manager 07/09] api: metrics export: stream sorted metrics via incremental k-way merge
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (5 preceding siblings ...)
2026-11-30 0:58 ` [PATCH manager 06/09] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
` (3 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 UTC (permalink / raw)
To: pve-devel
Decoding every remote node's metrics into Perl hashes and sorting the
combined array in memory allocates roughly 950 B per metric (~973 MiB
VmHWM at 1,001,900 metrics) and stalls the worker event loop during
decode, sort, and single-shot JSON encoding.
Add PVE::PullMetricExport::Reader and build_kway_merge_stream(), and
route PVE::PullMetricExport::export() through
PVE::APIServer::AnyEvent::async_stream_response() whenever streaming is
supported. Remote payloads stay gzip-compressed while fetching; once
all peers arrive, local and remote streams are incrementally inflated
in bounded 256 KiB compressed / 64 KiB output chunks (compacting
whitespace between objects across chunk boundaries) and merged in
global timestamp order via a min-heap in cooperative 256 KiB slices
without allocating per-metric Perl hashes.
Reader validates flat printable-ASCII RFC 8259 objects and captures the
required integer timestamp in a single non-backtracking pass, falling
back to a quote/brace-aware object scan and JSON::decode_json for
escapes, UTF-8, nesting, duplicate timestamp keys, or syntax errors,
and dies on corrupt, truncated, or trailing input. Pre-emission peer
failures still log a warning and skip the peer, while a late Reader
error after records have been emitted aborts the stream (TCP RST) so
scrapers do not advance start-time past partial data. Slices are
scheduled via AnyEvent->idle paired with a clock-synced 10 ms fallback
timer; overall fan-out timeouts abort pre-start with HTTP 504, and
unexpected callback or finish_stream() exceptions abort cleanly.
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 cap, 34 FDs;
scenarios are nodes x guests with latest or 10 history generations, and
/ping HOL is max head-of-line delay for a concurrent /ping request):
Scenario | Mode | Total | TTFB | VmHWM | Max /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | Sync LWP | 980ms | - | 105 MiB | 952 ms
(25,475 metrics) | K-way stream | 188ms | 118ms | 83 MiB | 7.9 ms
25x100 hist10 | Sync LWP | 2146ms | - | 337 MiB | 2194 ms
(254,750 metrics) | K-way stream | 827ms | 129ms | 98 MiB | 5.3 ms
100x100 latest | Sync LWP | 4445ms | - | 180 MiB | 4128 ms
(101,900 metrics) | K-way stream | 644ms | 401ms | 90 MiB | 13.3 ms
100x1000 | Buffered | 5.1 s | - | 973 MiB | -
(1,001,900 metrics) | K-way stream | 2969ms | 360ms | 103 MiB | 10.5 ms
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
PVE/Makefile | 2 +-
PVE/PullMetricExport.pm | 315 ++++++++++++++++++++++++++++++++-
PVE/PullMetricExport/Makefile | 15 ++
PVE/PullMetricExport/Reader.pm | 276 +++++++++++++++++++++++++++++
4 files changed, 603 insertions(+), 5 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 f657a1c34..9464246c2 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,21 +1,30 @@
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 JSON qw(encode_json);
use PVE::APIClient::AnyEvent;
use PVE::APIClient::AnyEvent::Pool;
use PVE::APIServer::AnyEvent;
use PVE::Exception;
+use PVE::PullMetricExport::Reader;
use PVE::SafeSyslog ();
our $MAX_WORKER_CONCURRENT_PEERS = 32;
+our $STREAM_SLICE_BYTES = 262144;
+our $SLICE_FALLBACK_INTERVAL = 0.01;
+
+my $STREAM_PREFIX = '{"data":[';
+my $STREAM_SUFFIX = ']}';
my $WORKER_ACTIVE_PEERS = 0;
my @WORKER_WAIT_QUEUE;
@@ -297,9 +306,307 @@ sub build_buffered_fanout(%opts) {
};
}
+my sub open_peer_reader($name, $body, $is_gzip) {
+ 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;
+ 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}->();
+ }
+ 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;
+ $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 $obj = $reader->next();
+ if (!defined($obj)) {
+ $exhausted = 1;
+ last;
+ }
+ $top->{obj} = $obj;
+ $top->{ts} = $reader->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) {
+ 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 = $opts{local_json};
+
+ return sub {
+ my ($stream) = @_;
+
+ my $state = {
+ stream => $stream,
+ done => 0,
+ local_json => $local_json,
+ peer_payloads => [],
+ heap => [],
+ started_stream => 0,
+ first_item => 1,
+ };
+ undef $local_json;
+
+ $state->{fanout} = start_metric_fanout(
+ %opts,
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ push @{ $state->{peer_payloads} },
+ {
+ name => $name,
+ body => $$body_ref,
+ gzip => $is_gzip,
+ };
+ },
+ 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)) {
+ heap_push($state->{heap}, $entry);
+ }
+ }
+
+ my $payloads = $state->{peer_payloads};
+ while (my $peer = shift @$payloads) {
+ my $entry =
+ open_peer_reader($peer->{name}, $peer->{body}, $peer->{gzip});
+ undef $peer;
+ heap_push($state->{heap}, $entry) if $entry;
+ }
+
+ kway_merge_step($state);
+ };
+ abort_stream($state, $@) if $@;
+ },
+ );
+
+ 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..cdeeffa71
--- /dev/null
+++ b/PVE/PullMetricExport/Reader.pm
@@ -0,0 +1,276 @@
+package PVE::PullMetricExport::Reader;
+
+# Incremental gzip+JSON metric array reader for remote peer responses and local_json.
+# Scans {"data":{"data":[...]}} in bounded 256 KiB compressed input slices and 64 KiB inflate
+# chunks, 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).
+# Contract: open(body => $str, gzip => $bool) validates the opening envelope; next() returns each
+# raw JSON object string (enforcing integer timestamp and updating obj()/ts()) or undef on clean
+# EOF; dies on corrupt, malformed, truncated, or trailing data (callers call close() on error).
+
+use v5.36;
+
+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;
+
+# 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/;
+
+# Scan a complete JSON object starting at $start, tracking string quotes, escapes, and brace
+# depth. Returns the index right after the matching '}', or undef if the buffer is incomplete.
+my sub find_json_object_end($buf_ref, $start) {
+ my $depth = 0;
+ my $in_string = 0;
+ my $len = length($$buf_ref);
+ pos($$buf_ref) = $start;
+
+ while ($$buf_ref =~ /(["{}\\])/gc) {
+ my $tok = $1;
+ if ($in_string) {
+ if ($tok eq '\\') {
+ return undef if pos($$buf_ref) >= $len;
+ pos($$buf_ref) += 1;
+ } elsif ($tok eq '"') {
+ $in_string = 0;
+ }
+ } elsif ($tok eq '"') {
+ $in_string = 1;
+ } elsif ($tok eq '{') {
+ $depth++;
+ } elsif ($tok eq '}') {
+ $depth--;
+ return pos($$buf_ref) if $depth == 0;
+ }
+ }
+
+ 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 ($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.
+ pos($self->{buf}) = $pos;
+ if ($self->{buf} =~ m/$FLAT_JSON_OBJ_RE/gc) {
+ my ($obj, $ts) = ($1, $2);
+ $self->{ts} = $ts + 0;
+ $self->{pos} = pos($self->{buf});
+ $self->{need_comma} = 1;
+ $self->{obj} = $obj;
+ return $obj;
+ }
+
+ # Fallback: full object scan + strict decode_json for escapes, UTF-8, nesting, or errors.
+ my $end = find_json_object_end(\$self->{buf}, $pos);
+ if (defined($end)) {
+ my $obj = substr($self->{buf}, $pos, $end - $pos);
+ my $decoded = decode_json($obj);
+ die "unexpected metric object\n" if ref($decoded) ne 'HASH';
+ if (
+ !defined($decoded->{timestamp})
+ || ref($decoded->{timestamp})
+ || $decoded->{timestamp} !~ /^-?[0-9]+$/
+ ) {
+ die "missing integer timestamp\n";
+ }
+ $self->{ts} = $decoded->{timestamp} + 0;
+ $self->{pos} = $end;
+ $self->{need_comma} = 1;
+ $self->{obj} = $obj;
+ return $obj;
+ }
+
+ if (length($self->{buf}) - $self->{pos} > 4 * 1024 * 1024) {
+ 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)};
+}
+
+1;
--
2.47.3
^ permalink raw reply related [flat|nested] 12+ messages in thread* [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (6 preceding siblings ...)
2026-11-30 0:58 ` [PATCH manager 07/09] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-11-30 0:58 ` [PATCH manager 09/09] test: add pull metric export test suite Thomas Lamprecht
` (2 subsequent siblings)
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 UTC (permalink / raw)
To: pve-devel
The default k-way merge preserves global cross-node timestamp ordering
for existing clients with zero migration effort, but must wait for all
peers before TTFB and hold all compressed peer bodies until the final
peer arrives.
Add an optional boolean `unsorted` parameter to GET
/cluster/metrics/export and build_passthrough_stream() to
PVE::PullMetricExport. When unsorted=1 is requested, the local node
slice is flushed immediately for minimal TTFB without sorting and each
remote peer is drained incrementally through
PVE::PullMetricExport::Reader as it arrives, pausing queued peer
dispatch (and suspending the pool's overall timeout budget) via
can_dispatch whenever the downstream socket is backpressured. Overall
fan-out timeouts and late mid-stream Reader errors abort the
in-progress stream (TCP RST) so consumers retry rather than advancing
their cursor past uncontacted or truncated nodes.
Carrying a second streaming state machine and can_dispatch backpressure
gating adds complexity, traded for keeping backwards-compatible global
sorting by default while cutting TTFB across all tested scenarios
(25x100 latest: 118 -> 2.3 ms, ~51x; 25x100 hist10: 129 -> 6.7 ms,
~19x; 100x100 latest: 401 -> 2.8 ms, ~143x; 100x1000: 360 -> 7.5 ms,
~48x), lowering peak RAM by ~10%, and reducing total time by ~10-25%
for opt-in clients that sort before RRD ingestion (older PVE nodes
reject the unknown unsorted parameter with HTTP 400; cluster fan-out
always forwards local-only=1 without unsorted to peers).
Measured on the same single-worker mock harness (25 ms/peer, 16-peer
cap, 34 FDs; scenarios are nodes x guests with latest or 10 history
generations, and /ping HOL is head-of-line delay for a concurrent
/ping request reported as max or median across samples):
Scenario | Mode | Total | TTFB | VmHWM | /ping HOL
--------------------+---------------+--------+-------+----------+--------------
25x100 latest | K-way stream | 188ms | 118ms | 83 MiB | 7.9 ms (max)
(25,475 metrics) | Pass-through | 154ms | 2.3ms | 81 MiB | 6.6 ms (max)
25x100 hist10 | K-way stream | 827ms | 129ms | 98 MiB | 5.3 ms (max)
(254,750 metrics) | Pass-through | 744ms | 6.7ms | 92 MiB | 5.3 ms (med)
100x100 latest | K-way stream | 644ms | 401ms | 90 MiB | 13.3 ms (max)
(101,900 metrics) | Pass-through | 463ms | 2.8ms | 81 MiB | 13.7 ms (max)
100x1000 | K-way stream | 2969ms | 360ms | 103 MiB | 10.5 ms (max)
(1,001,900 metrics) | Pass-through | 2790ms | 7.5ms | 93 MiB | 5.5 ms (med)
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
PVE/API2/Cluster/MetricServer.pm | 19 ++-
PVE/PullMetricExport.pm | 213 +++++++++++++++++++++++++++++--
2 files changed, 218 insertions(+), 14 deletions(-)
diff --git a/PVE/API2/Cluster/MetricServer.pm b/PVE/API2/Cluster/MetricServer.pm
index 8dc8db7b0..f1b6e62b6 100644
--- a/PVE/API2/Cluster/MetricServer.pm
+++ b/PVE/API2/Cluster/MetricServer.pm
@@ -352,6 +352,17 @@ __PACKAGE__->register_method({
optional => 1,
default => 0,
},
+ 'unsorted' => {
+ type => 'boolean',
+ description => 'Do not sort metrics by timestamp. Skips cross-node sorting and'
+ . ' permits incremental streaming on supported HTTP endpoints (buffered and'
+ . ' CLI paths still return the full response once complete). When streaming'
+ . ' has already started, a fan-out timeout terminates the response'
+ . ' incompletely instead of returning HTTP 504. Cluster fan-out forwards'
+ . ' local-only=1 without unsorted to remote nodes.',
+ optional => 1,
+ default => 0,
+ },
},
},
returns => {
@@ -360,8 +371,8 @@ __PACKAGE__->register_method({
properties => {
data => {
type => 'array',
- description =>
- 'Array of system metrics. Metrics are sorted by their timestamp.',
+ description => 'Array of system metrics. Sorted by timestamp by default'
+ . ' (unsorted=0), or in arrival order when unsorted is set.',
items => {
type => 'object',
additionalProperties => 0,
@@ -401,6 +412,7 @@ __PACKAGE__->register_method({
my $local_only = $param->{'local-only'} // 0;
my $start = $param->{'start-time'};
my $history = $param->{'history'} // 0;
+ my $unsorted = $param->{'unsorted'} // 0;
my $now = time();
@@ -487,7 +499,7 @@ __PACKAGE__->register_method({
if (!@targets) {
# In-place sort avoids allocating a second copy of large metric arrays.
- @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics;
+ @metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @metrics if !$unsorted;
return {
data => \@metrics,
};
@@ -508,6 +520,7 @@ __PACKAGE__->register_method({
params => $remote_params,
credentials => $credentials,
metrics => \@metrics,
+ unsorted => $unsorted,
port => $REMOTE_PORT,
request_timeout => $REMOTE_REQUEST_TIMEOUT,
overall_timeout => $FANOUT_OVERALL_TIMEOUT,
diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm
index 9464246c2..869bd6f99 100644
--- a/PVE/PullMetricExport.pm
+++ b/PVE/PullMetricExport.pm
@@ -1,10 +1,12 @@
package PVE::PullMetricExport;
# Asynchronous cluster-wide pull-metric fan-out and streaming export for GET
-# /cluster/metrics/export. export() selects between two paths:
-# - Incremental k-way merge stream (default when AsyncStream is supported): keeps remote peer
-# responses gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then
-# merges local and remote streams in global timestamp order in cooperative 256 KiB slices.
+# /cluster/metrics/export. export() selects between three paths:
+# - Default k-way merge stream (when AsyncStream is supported): keeps remote peer bodies
+# gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then merges local
+# and remote streams in global timestamp order in cooperative 256 KiB slices.
+# - Opt-in unsorted=1 pass-through stream: flushes local metrics immediately for minimal TTFB and
+# drains remote peers as they arrive with can_dispatch backpressure gating.
# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers).
use v5.36;
@@ -590,26 +592,215 @@ sub build_kway_merge_stream(%opts) {
};
}
+my sub passthrough_drain_reader($state, $max_bytes) {
+ my $out = '';
+ my $entry = $state->{active_reader};
+ return $out if !$entry;
+
+ my $reader = $entry->{reader};
+ my $exhausted = 0;
+
+ eval {
+ while (length($out) < $max_bytes) {
+ $out .= ',' if !$state->{first_item};
+ $state->{first_item} = 0;
+ $out .= $entry->{obj};
+
+ my $obj = $reader->next();
+ if (!defined($obj)) {
+ $exhausted = 1;
+ last;
+ }
+ $entry->{obj} = $obj;
+ }
+ };
+ if (my $err = $@) {
+ log_peer_error($entry->{name}, $err);
+ $reader->close();
+ delete $state->{active_reader};
+ abort_stream($state, "could not stream metrics from $entry->{name}: $err");
+ return undef;
+ }
+
+ delete $state->{active_reader} if $exhausted;
+ return $out;
+}
+
+my sub passthrough_emit_step($state) {
+ my $self = __SUB__;
+ clear_slice_watchers($state);
+ my $stream = $state->{stream};
+ return if $state->{done} || !$stream || $stream->is_closed();
+
+ my $out = '';
+ my $ready = $state->{ready_peers};
+ while (length($out) < $STREAM_SLICE_BYTES) {
+ if (!defined($state->{active_reader})) {
+ last if !@$ready;
+ my $peer = shift @$ready;
+ my $entry = open_peer_reader($peer->{name}, $peer->{body}, $peer->{gzip});
+ undef $peer;
+ next if !$entry;
+ $state->{active_reader} = $entry;
+ }
+ my $chunk = passthrough_drain_reader($state, $STREAM_SLICE_BYTES - length($out));
+ return if $state->{done} || !defined($chunk);
+ $out .= $chunk;
+ }
+
+ if (!length($out)) {
+ if ($state->{fetch_done}) {
+ finish_stream($state, '');
+ return;
+ }
+ $state->{fanout}->{dispatch}->() if $state->{fanout};
+ return;
+ }
+
+ if (!defined($state->{active_reader}) && !@$ready && $state->{fetch_done}) {
+ finish_stream($state, $out);
+ return;
+ }
+
+ my $ok = $stream->write($out);
+ after_stream_write(
+ $state,
+ $ok,
+ sub { $self->($state) },
+ sub { $state->{fanout}->{dispatch}->() if $state->{fanout} },
+ );
+}
+
+my sub passthrough_schedule_emit($state) {
+ my $stream = $state->{stream};
+ if (
+ $state->{done}
+ || $state->{waiting_drain}
+ || defined($state->{slice_idle})
+ || defined($state->{slice_timer})
+ || !$stream
+ || $stream->is_closed()
+ ) {
+ return;
+ }
+ schedule_slice($state, sub { passthrough_emit_step($state) });
+}
+
+sub build_passthrough_stream(%opts) {
+ my $local_json = $opts{local_json};
+ my $max_concurrent = int($opts{max_concurrent} // 16);
+ $max_concurrent = 1 if $max_concurrent < 1;
+
+ return sub {
+ my ($stream) = @_;
+
+ my $state = {
+ stream => $stream,
+ done => 0,
+ fetch_done => 0,
+ waiting_drain => 0,
+ ready_peers => [],
+ active_reader => undef,
+ first_item => 1,
+ };
+
+ my $cancel = sub {
+ return if $state->{done};
+ $state->{done} = 1;
+ cleanup_stream($state);
+ };
+
+ # Emit wrapper + first local slice immediately for minimal TTFB.
+ $stream->start();
+ my $out = $STREAM_PREFIX;
+ if (defined($local_json)) {
+ my $local_entry = open_peer_reader('local', $local_json, 0);
+ undef $local_json;
+ if ($local_entry) {
+ $state->{active_reader} = $local_entry;
+ my $chunk = passthrough_drain_reader($state, $STREAM_SLICE_BYTES);
+ return $cancel if $state->{done} || !defined($chunk);
+ $out .= $chunk;
+ }
+ }
+
+ my $ok = $stream->write($out);
+ if (!$state->{done} && !$stream->is_closed()) {
+ $ok = $stream->flush() if $ok;
+ }
+ return $cancel if $state->{done} || $stream->is_closed();
+
+ $state->{fanout} = start_metric_fanout(
+ %opts,
+ # Bound queued ready_peers alongside socket backpressure so slow consumers cap buffered
+ # peer payloads while the pool suspends its overall_timeout countdown.
+ can_dispatch => sub {
+ return
+ !$state->{waiting_drain}
+ && !$stream->is_backpressured()
+ && !$stream->is_closed()
+ && scalar(@{ $state->{ready_peers} }) < $max_concurrent;
+ },
+ on_peer => sub {
+ my ($name, $body_ref, $is_gzip) = @_;
+ push @{ $state->{ready_peers} },
+ {
+ name => $name,
+ body => $$body_ref,
+ gzip => $is_gzip,
+ };
+ passthrough_schedule_emit($state);
+ },
+ on_done => sub($timed_out, $timeout) {
+ return if $state->{done} || $stream->is_closed();
+ $state->{fetch_done} = 1;
+ delete $state->{fanout};
+ if ($timed_out) {
+ abort_stream($state,
+ "cluster metric fan-out timed out after ${timeout}s\n");
+ return;
+ }
+ eval { passthrough_schedule_emit($state); };
+ abort_stream($state, $@) if $@;
+ },
+ );
+
+ if (!$ok || $stream->is_backpressured() || defined($state->{active_reader})) {
+ after_stream_write(
+ $state,
+ $ok,
+ sub { passthrough_emit_step($state) },
+ sub { $state->{fanout}->{dispatch}->() if $state->{fanout} },
+ );
+ }
+
+ return $cancel;
+ };
+}
+
sub export(%opts) {
my $metrics = $opts{metrics} // [];
+ my $unsorted = $opts{unsorted} ? 1 : 0;
if (PVE::APIServer::AnyEvent::async_stream_supported()) {
my $local_json;
if (@$metrics) {
- # Encode local metrics into the same wire envelope as remote peers so the streaming
- # reader and k-way merge heap drain local and remote sources uniformly.
- @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ # Encode local metrics into the same wire envelope as remote peers so both streaming
+ # modes drain local and remote sources through Reader uniformly.
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics if !$unsorted;
$local_json = encode_json({ data => { data => $metrics } });
@$metrics = ();
}
- return PVE::APIServer::AnyEvent::async_stream_response(
- build_kway_merge_stream(%opts, local_json => $local_json),
- );
+ my $starter =
+ $unsorted
+ ? build_passthrough_stream(%opts, local_json => $local_json)
+ : build_kway_merge_stream(%opts, local_json => $local_json);
+ return PVE::APIServer::AnyEvent::async_stream_response($starter);
}
my $finalize = sub {
# In-place sort avoids allocating a second copy of large metric arrays.
- @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics;
+ @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics if !$unsorted;
return {
data => $metrics,
};
--
2.47.3
^ permalink raw reply related [flat|nested] 12+ messages in thread* [PATCH manager 09/09] test: add pull metric export test suite
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (7 preceding siblings ...)
2026-11-30 0:58 ` [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
@ 2026-11-30 0:58 ` Thomas Lamprecht
2026-12-01 10:13 ` [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Jonas Theisen
2026-12-01 10:22 ` superseded: " Thomas Lamprecht
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-11-30 0:58 UTC (permalink / raw)
To: pve-devel
Add test/PullMetricExport_test.pl and wire it into test/Makefile
covering:
- Buffered async fan-out: 16-peer concurrency cap, non-persistent
sockets, disabled redirects, IPv6 URI bracketing, synchronous
callback safety, duplicate node-list deduplication, invalid entry
rejection, finalize error forwarding to reject(), CondVar mode
outside async HTTP handlers, single-peer timeout isolation, and
overall timeout HTTP 504 rejection.
- K-way merge and pass-through streaming: inner {"data":[...]} payload
composition with server-owned json/extjs envelopes, global sorting,
escaped JSON strings, multi-chunk gzip inflation across input-chunk
and 64 KiB inflate boundaries (zero whole-body memGunzip),
pre-emission corrupt-peer isolation vs late mid-stream Reader error
stream abort, strict malformed JSON rejection, fallback to buffered
AsyncResponse for unsupported formats, and stock HTTPServer returning
AsyncResponse/AsyncStreamResponse handles under data while clearing
rpcenv credentials.
- Resilience, lifecycle, worker-wide concurrency, real AsyncStream, and
direct Reader tests: forward progress under continuously ready
competing I/O, slow-consumer backpressure pausing overall_timeout,
on_done/schedule_slice/finish_stream exception abort isolation,
disconnect cancellation, weakened-ref destruction checks, worker-wide
concurrency cap and waiter cancellation across overlapping exports,
end-to-end gzip + /api2/extjs/ verification against real
PVE::APIServer::AsyncStream (chunked 0-terminator, Z_STREAM_END,
envelope), and direct PVE::PullMetricExport::Reader unit tests
including >128 KiB inter-object whitespace compaction and trailing
comma rejection.
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---
test/Makefile | 6 +-
test/PullMetricExport_test.pl | 2082 +++++++++++++++++++++++++++++++++
2 files changed, 2087 insertions(+), 1 deletion(-)
create mode 100755 test/PullMetricExport_test.pl
diff --git a/test/Makefile b/test/Makefile
index bb9aba282..72edbf6a9 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -5,7 +5,11 @@ all:
export PERLLIB=..
.PHONY: check
-check: test-replication test-balloon test-vzdump test-osd test-ceph-health test-ceph-releases test-ceph-services test-ceph-auth test-ceph-key-migration test-ceph-lockbox-migration test-custom-cpu-models test-pvesh test-report test-access-log test-cluster-resources test-cluster-status test-bulk-migrate test-multipath-notification
+check: test-replication test-balloon test-vzdump test-osd test-ceph-health test-ceph-releases test-ceph-services test-ceph-auth test-ceph-key-migration test-ceph-lockbox-migration test-custom-cpu-models test-pvesh test-report test-access-log test-cluster-resources test-cluster-status test-bulk-migrate test-multipath-notification test-pull-metric-export
+
+.PHONY: test-pull-metric-export
+test-pull-metric-export:
+ ./PullMetricExport_test.pl
.PHONY: test-multipath-notification
test-multipath-notification:
diff --git a/test/PullMetricExport_test.pl b/test/PullMetricExport_test.pl
new file mode 100755
index 000000000..ac82f1218
--- /dev/null
+++ b/test/PullMetricExport_test.pl
@@ -0,0 +1,2082 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use lib ('.', '..');
+
+use AnyEvent;
+use AnyEvent::Util;
+use Compress::Raw::Zlib qw(WANT_GZIP Z_STREAM_END);
+use Compress::Zlib qw(memGzip);
+use JSON qw(decode_json encode_json);
+use Scalar::Util qw(weaken);
+use Test::MockModule;
+use Test::More;
+
+use PVE::API2::Cluster::MetricServer;
+use PVE::APIServer::AsyncStream;
+use PVE::HTTPServer;
+use PVE::PullMetricExport;
+use PVE::PullMetricExport::Reader;
+
+{
+
+ package MockStream;
+
+ sub new {
+ my ($class, %opts) = @_;
+ my ($prefix, $suffix) = ('', '');
+ if (defined($opts{format})) {
+ if ($opts{format} eq 'json') {
+ ($prefix, $suffix) = ('{"data":', '}');
+ } elsif ($opts{format} eq 'extjs') {
+ ($prefix, $suffix) = ('{"data":', ',"success":1}');
+ }
+ }
+ return bless {
+ started => 0,
+ finished => 0,
+ closed => 0,
+ flushed => 0,
+ backpressured => 0,
+ aborted_err => undef,
+ prefix => $prefix,
+ suffix => $suffix,
+ buf => '',
+ drain_cb => undef,
+ on_finish => $opts{on_finish},
+ on_abort => $opts{on_abort},
+ on_write => $opts{on_write},
+ bp_after_bytes => $opts{bp_after_bytes},
+ }, $class;
+ }
+
+ sub start {
+ my ($self) = @_;
+ return 0 if $self->{closed};
+ if (!$self->{started}) {
+ $self->{started} = 1;
+ $self->{buf} .= $self->{prefix};
+ }
+ return 1;
+ }
+
+ sub is_backpressured { return $_[0]->{backpressured}; }
+ sub is_closed { return $_[0]->{closed}; }
+ sub on_drain { $_[0]->{drain_cb} = $_[1]; }
+
+ sub write {
+ my ($self, $data) = @_;
+ return 0 if $self->{closed};
+ $self->start() if !$self->{started};
+ $self->{buf} .= $data;
+ if (defined($self->{bp_after_bytes}) && length($self->{buf}) >= $self->{bp_after_bytes}) {
+ $self->{backpressured} = 1;
+ }
+ $self->{on_write}->($self, $data) if $self->{on_write};
+ return $self->{backpressured} ? 0 : 1;
+ }
+
+ sub flush {
+ my ($self) = @_;
+ return 0 if $self->{closed};
+ $self->{flushed}++;
+ return $self->{backpressured} ? 0 : 1;
+ }
+
+ sub trigger_drain {
+ my ($self) = @_;
+ $self->{backpressured} = 0;
+ if (my $cb = delete $self->{drain_cb}) {
+ $cb->();
+ }
+ }
+
+ sub finish {
+ my ($self) = @_;
+ return if $self->{closed};
+ $self->start() if !$self->{started};
+ $self->{buf} .= $self->{suffix};
+ $self->{finished} = 1;
+ $self->{closed} = 1;
+ undef $self->{drain_cb};
+ $self->{on_finish}->($self) if $self->{on_finish};
+ }
+
+ sub disconnect {
+ my ($self, $cancel) = @_;
+ $self->{closed} = 1;
+ undef $self->{drain_cb};
+ $cancel->() if $cancel;
+ }
+
+ sub abort {
+ my ($self, $err) = @_;
+ return if $self->{closed};
+ $self->{aborted_err} = $err;
+ $self->{closed} = 1;
+ undef $self->{drain_cb};
+ $self->{on_abort}->($self, $err) if $self->{on_abort};
+ }
+}
+
+{
+
+ package MockRPCEnv;
+
+ sub get_credentials { return $_[0]->{credentials}; }
+ sub set_credentials { $_[0]->{credentials} = $_[1]; }
+ sub get_user { return $_[0]->{user}; }
+ sub set_user { $_[0]->{user} = $_[1]; }
+ sub get_result_attrib { return $_[0]->{result_attributes}->{ $_[1] }; }
+ sub check_api2_permissions { return 1; }
+}
+
+my (%members, %ips, %fps, @syslogs);
+my $local_metrics = [];
+my $mock_rpcenv = bless {
+ type => 'pub',
+ user => 'root@pam',
+ credentials => { api_token => 'root@pam!test=secret' },
+ result_attributes => {},
+ },
+ 'MockRPCEnv';
+
+our $async_flag = 1;
+our $stream_format = 'json';
+
+my $inotify_mock = Test::MockModule->new('PVE::INotify');
+$inotify_mock->redefine(nodename => sub { return 'node0'; });
+
+my $cluster_mock = Test::MockModule->new('PVE::Cluster');
+$cluster_mock->redefine(
+ get_members => sub { return \%members; },
+ remote_node_ip => sub { return $ips{ $_[0] }; },
+ get_node_fingerprint => sub { return $fps{ $_[0] }; },
+);
+
+my $pull_mock = Test::MockModule->new('PVE::PullMetric');
+$pull_mock->redefine(get_local_metrics => sub { return [@$local_metrics]; });
+
+my $rpc_mock = Test::MockModule->new('PVE::RPCEnvironment');
+$rpc_mock->redefine(get => sub { return $mock_rpcenv; });
+
+my $syslog_mock = Test::MockModule->new('PVE::SafeSyslog');
+$syslog_mock->redefine(syslog => sub { push @syslogs, "[$_[0]] $_[1]"; });
+
+my $ae_mock = Test::MockModule->new('PVE::APIServer::AnyEvent');
+$ae_mock->mock(
+ async_supported => sub { return $async_flag; },
+ async_response => sub {
+ return bless { start => $_[0] }, 'PVE::APIServer::AnyEvent::AsyncResponse';
+ },
+ async_stream_supported => sub {
+ return 0 if !$async_flag || !defined($stream_format);
+ return ($stream_format eq 'json' || $stream_format eq 'extjs') ? 1 : 0;
+ },
+ async_stream_response => sub {
+ return bless { start => $_[0] }, 'PVE::APIServer::AnyEvent::AsyncStreamResponse';
+ },
+);
+
+my sub make_metric {
+ my ($ts, $id, $metric, $value, $type) = @_;
+ return {
+ timestamp => $ts,
+ id => $id,
+ metric => $metric // 'cpu',
+ value => $value // 0.5,
+ type => $type // 'gauge',
+ };
+}
+
+my sub make_payload {
+ my ($metrics, $gzip) = @_;
+ my $json = encode_json({ data => { data => $metrics } });
+ return $gzip ? memGzip($json) : $json;
+}
+
+my sub setup_cluster {
+ my ($n, %opts) = @_;
+ %members = (node0 => { online => 1 });
+ %ips = ();
+ %fps = ();
+ @syslogs = ();
+ $local_metrics = [
+ make_metric(105, 'node/node0', 'uptime', 10),
+ make_metric(101, 'node/node0', 'cpu', 0.5),
+ ];
+ for my $i (1 .. $n) {
+ my $name = sprintf("node%03d", $i);
+ $members{$name} = { online => 1 };
+ $ips{$name} = $opts{ipv6} && $i == 1 ? '2001:db8::1' : "10.0.0.$i";
+ $fps{$name} = sprintf("%064X", $i);
+ }
+}
+
+my sub with_http_mock {
+ my ($handler, $code) = @_;
+ my $tls_mock = Test::MockModule->new('AnyEvent::TLS');
+ $tls_mock->redefine(new => sub { return bless {}, 'MockTLS'; });
+ my $http_mock = Test::MockModule->new('AnyEvent::HTTP');
+ $http_mock->redefine(
+ http_request => sub {
+ my $cb = pop @_;
+ my ($method, $url, %opts) = @_;
+ return $handler->($method, $url, \%opts, $cb);
+ },
+ );
+ return $code->();
+}
+
+my sub is_sorted_by_ts {
+ my ($arr) = @_;
+ for my $i (1 .. $#$arr) {
+ return 0 if $arr->[$i - 1]->{timestamp} > $arr->[$i]->{timestamp};
+ }
+ return 1;
+}
+
+subtest 'buffered async fan-out: concurrency cap, sync callbacks, IPv6, dedup, and CondVar mode' =>
+ sub {
+ setup_cluster(50, ipv6 => 1);
+ local $stream_format = undef;
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 16;
+
+ my ($in_flight, $peak, $started, $ipv6_seen) = (0, 0, 0, 0);
+ my ($result, $weak_cancel);
+ {
+ my $cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my ($method, $url, $opts, $cb) = @_;
+ my $idx = ++$started;
+ $in_flight++;
+ $peak = $in_flight if $in_flight > $peak;
+ $ipv6_seen = 1 if $url =~ m{^https://\[2001:db8::1\]:8006/};
+ if ($idx == 1) {
+ is($opts->{persistent}, 0, 'non-persistent peer sockets');
+ is($opts->{recurse}, 0, 'redirects disabled');
+ }
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ $in_flight--;
+ if ($idx == 10) {
+ $cb->(undef, { Status => 595, Reason => 'Connection refused' });
+ return;
+ }
+ $cb->(
+ make_payload([make_metric(200 - $idx, "node/p$idx", 'm', $idx)], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ isa_ok($async, 'PVE::APIServer::AnyEvent::AsyncResponse');
+ my $cancel = $async->{start}->(
+ sub { $result = $_[0]; $cv->send; }, sub { $cv->croak($_[0]); },
+ );
+ $weak_cancel = $cancel;
+ weaken($weak_cancel);
+ $cv->recv;
+ },
+ );
+ }
+
+ is($started, 50, 'all 50 peers fetched');
+ is($peak, 16, 'peak in-flight capped at 16');
+ is($ipv6_seen, 1, 'IPv6 host bracketed in URI');
+ is(scalar(@{ $result->{data} }), 51, '2 local + 49 remote metrics (1 failed)');
+ ok(is_sorted_by_ts($result->{data}), 'buffered metrics sorted by timestamp');
+ is($weak_cancel, undef, 'buffered cancel closure freed without cycle');
+
+ # Synchronous http_request callbacks across 150 peers must not recurse.
+ setup_cluster(150);
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, @_; };
+ my $sync_started = 0;
+ my $sync_res;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $sync_started++;
+ $cb->(
+ make_payload([make_metric(300, "node/s$sync_started", 'm', 1)]),
+ { Status => 200 },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(sub { $sync_res = $_[0]; }, sub { die $_[0]; });
+ },
+ );
+ is($sync_started, 150, '150 synchronous callbacks completed');
+ is(scalar(@warnings), 0, 'no recursion warnings on 150 sync callbacks');
+
+ # Duplicate node-list entries deduplicated.
+ setup_cluster(3);
+ my $dedup_calls = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $dedup_calls++;
+ $cb->('{"data":{"data":[]}}', { Status => 200 });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({
+ 'node-list' => 'node001,node001,node002',
+ });
+ $async->{start}->(sub { }, sub { die $_[0]; });
+ },
+ );
+ is($dedup_calls, 2, 'duplicate node-list entries deduplicated');
+
+ # Reject invalid buffered peer entries (including boolean timestamps) and forward finalize errors.
+ setup_cluster(4);
+ $local_metrics = [];
+ @syslogs = ();
+ my @buf_payloads = (
+ make_payload([make_metric(10, 'node/good')]),
+ '{"data":{"data":["oops"]}}',
+ '{"data":{"data":[{"id":"node/missing-ts","value":1}]}}',
+ '{"data":{"data":[{"timestamp":true,"id":"node/bool-ts","value":1}]}}',
+ );
+ my $bidx = 0;
+ my $buf_res;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->(
+ memGzip($buf_payloads[$bidx++]),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(sub { $buf_res = $_[0]; }, sub { die $_[0]; });
+ },
+ );
+ is(scalar(@{ $buf_res->{data} }), 1, 'buffered fan-out skipped malformed peer entries');
+ is($buf_res->{data}->[0]->{id}, 'node/good', 'buffered fan-out preserved valid peer entry');
+ is(scalar(@syslogs), 3, 'buffered fan-out logged all three invalid entry payloads');
+
+ for my $mode (qw(sync async)) {
+ my ($resolved, $rejected_err);
+ my $cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $body = '{"data":{"data":[]}}';
+ if ($mode eq 'sync') {
+ $cb->($body, { Status => 200 });
+ return AnyEvent::Util::guard {};
+ }
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($body, { Status => 200 });
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $starter = PVE::PullMetricExport::build_buffered_fanout(
+ targets => [{ name => 'node1', ip => '10.0.0.1', fingerprint => 'AA:BB' }],
+ params => { 'local-only' => 1 },
+ credentials => {},
+ metrics => [],
+ finalize => sub { die "finalize boom ($mode)\n"; },
+ );
+ $starter->(
+ sub { $resolved = 1; $cv->send; },
+ sub { $rejected_err = $_[0]; $cv->send; },
+ );
+ $cv->recv;
+ },
+ );
+ ok(!$resolved, "buffered fan-out did not resolve on throwing finalize ($mode)");
+ like(
+ $rejected_err // '',
+ qr/finalize boom \($mode\)/,
+ "buffered fan-out invoked reject on throwing finalize ($mode)",
+ );
+ }
+
+ # CondVar mode outside an async HTTP handler (e.g. CLI/pvesh).
+ setup_cluster(4);
+ local $async_flag = 0;
+ local $mock_rpcenv->{type} = 'cli';
+ my $cli_res = with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ $cb->(
+ make_payload([make_metric(42, 'node/cli', 'm', 1)]),
+ { Status => 200 },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub { return PVE::API2::Cluster::MetricServer->export({}); },
+ );
+ is(scalar(@{ $cli_res->{data} }), 6, 'CLI CondVar mode returns 2 local + 4 remote metrics');
+
+ # Single hanging peer hitting request_timeout logs warning while healthy peers return 200.
+ setup_cluster(3);
+ local $async_flag = 1;
+ local $stream_format = undef;
+ @syslogs = ();
+ my $req_to_idx = 0;
+ my $req_to_res;
+ my $req_to_cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $i = ++$req_to_idx;
+ if ($i == 2) {
+ $cb->(undef, { Status => 596, Reason => 'Request timed out' });
+ return AnyEvent::Util::guard {};
+ }
+ $cb->(
+ make_payload([make_metric(50 + $i, "node/ok$i", 'm', 1)], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(
+ sub { $req_to_res = $_[0]; $req_to_cv->send; },
+ sub { $req_to_cv->croak($_[0]); },
+ );
+ $req_to_cv->recv;
+ },
+ );
+ is(
+ scalar(@{ $req_to_res->{data} }),
+ 4,
+ 'single-peer request_timeout still returns 2 local + 2 healthy peer metrics',
+ );
+ ok(
+ scalar(grep { /Request timed out/ } @syslogs) == 1,
+ 'single-peer request_timeout logged warning',
+ );
+
+ # Buffered overall_timeout rejects with HTTP 504 instead of partial 200 OK.
+ setup_cluster(4);
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.08;
+ @syslogs = ();
+ my ($buf_to_resolved, $buf_to_err);
+ my $buf_to_cv = AnyEvent->condvar;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ return AnyEvent::Util::guard { undef $cb; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->(
+ sub { $buf_to_resolved = 1; $buf_to_cv->send; },
+ sub { $buf_to_err = $_[0]; $buf_to_cv->send; },
+ );
+ $buf_to_cv->recv;
+ },
+ );
+ ok(!$buf_to_resolved, 'buffered overall_timeout did not resolve with partial 200');
+ isa_ok($buf_to_err, 'PVE::Exception');
+ is($buf_to_err->{code}, 504, 'buffered overall_timeout rejects with HTTP 504');
+ like("$buf_to_err", qr/timed out/, 'buffered overall_timeout exception mentions timeout');
+ };
+
+subtest
+ 'k-way merge stream: sort, escapes, multi-chunk, corrupt peers, extjs, backpressure and timeout'
+ => sub {
+ setup_cluster(12);
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 512;
+
+ my ($in_flight, $peak, $idx) = (0, 0, 0);
+ my $cv = AnyEvent->condvar;
+ my $stream = MockStream->new(on_finish => sub { $cv->send; });
+ my $weak_cancel;
+
+ {
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $my_idx = ++$idx;
+ $in_flight++;
+ $peak = $in_flight if $in_flight > $peak;
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ $in_flight--;
+ if ($my_idx == 1) {
+ $cb->(
+ memGzip('{"data":{"data":[ ]}}'),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ if ($my_idx == 2) {
+ my $body = make_payload(
+ [
+ make_metric(
+ 102,
+ 'node/a"b{c}d\\"timestamp":999',
+ 'escaped',
+ 1,
+ ),
+ make_metric(104, 'node/bare}brace', 'brace', 2),
+ ],
+ 1,
+ );
+ $cb->($body, { Status => 200, 'content-encoding' => 'gzip' });
+ return;
+ }
+ if ($my_idx == 3) {
+ $cb->(
+ "\x1f\x8b\x08\x00corrupt-gzip",
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ if ($my_idx == 4) {
+ $cb->('{"bad":1}', { Status => 200 });
+ return;
+ }
+ if ($my_idx == 5) {
+ $cb->('error',
+ { Status => 500, Reason => 'Internal Server Error' });
+ return;
+ }
+ my $ts_base = 90 + ($my_idx * 2);
+ my $is_gz = $my_idx % 2 == 0;
+ my $body = make_payload(
+ [
+ make_metric($ts_base, "node/p$my_idx", 'm1', 1),
+ make_metric($ts_base + 5, "node/p$my_idx", 'm2', 2),
+ ],
+ $is_gz,
+ );
+ $cb->(
+ $body,
+ { Status => 200, $is_gz ? ('content-encoding' => 'gzip') : () },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ isa_ok($async, 'PVE::APIServer::AnyEvent::AsyncStreamResponse');
+ my $cancel = $async->{start}->($stream);
+ $weak_cancel = $cancel;
+ weaken($weak_cancel);
+ $cv->recv;
+ },
+ );
+ }
+
+ is($peak, 4, 'k-way merge capped concurrency at 4');
+ my $parsed = eval { decode_json($stream->{buf}) };
+ ok(!$@ && ref($parsed) eq 'HASH', 'k-way merge output is valid JSON despite corrupt peers');
+ # PullMetricExport emits the inner {"data":[...]} payload; AsyncStream owns the outer envelope.
+ my $arr = $parsed->{data};
+ # 2 local + 0 (p1) + 2 (p2) + 0 (p3) + 0 (p4 bad envelope) + 0 (p5) + 7*2 (p6..p12) = 18
+ is(scalar(@$arr), 18, 'k-way merge emitted exact 18 metrics');
+ ok(is_sorted_by_ts($arr), 'k-way merge output strictly sorted by timestamp');
+ my ($esc) = grep { $_->{metric} eq 'escaped' } @$arr;
+ is($esc->{timestamp}, 102, 'k-way merge extracted real timestamp outside escaped string');
+ is($weak_cancel, undef, 'k-way merge cancel closure freed without cycle');
+
+ # Late mid-stream Reader error aborts k-way merge stream instead of finishing with 200.
+ setup_cluster(2);
+ $local_metrics = [];
+ @syslogs = ();
+ my $cv_trunc = AnyEvent->condvar;
+ my $s_trunc = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_trunc->send; },
+ on_finish => sub { $cv_trunc->send; },
+ );
+ my $trunc_idx = 0;
+ my @trunc_bodies = (
+ make_payload([make_metric(105, 'node/ok')]),
+ '{"data":{"data":[{"timestamp":100,"id":"partial/ok","metric":"m","value":1,"type":"gauge"},{"timestamp":109,"id":"trunc',
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->($trunc_bodies[$trunc_idx++], { Status => 200 });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s_trunc);
+ $cv_trunc->recv;
+ },
+ );
+ ok($s_trunc->{started}, 'k-way merge late Reader error occurred after stream started');
+ ok(!$s_trunc->{finished}, 'k-way merge late Reader error did not finish with 200');
+ like(
+ $s_trunc->{aborted_err} // '',
+ qr/could not stream metrics from node002/,
+ 'k-way merge late Reader error aborted stream with peer context',
+ );
+ ok($s_trunc->is_closed(), 'k-way merge late Reader error closed stream');
+ ok(
+ scalar(grep { /could not fetch metrics from node002/ } @syslogs) >= 1,
+ 'k-way merge late Reader error logged peer warning',
+ );
+
+ # Multi-chunk (~180 KiB uncompressed) across 64 KiB inflate and input-chunk boundaries + extjs.
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'extjs';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 16384;
+ local $PVE::PullMetricExport::Reader::GZIP_INPUT_CHUNK_BYTES = 1024;
+ my $cv2 = AnyEvent->condvar;
+ my $s2 = MockStream->new(format => 'extjs', on_finish => sub { $cv2->send; });
+ my $pno = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $p = ++$pno;
+ my @m = map {
+ make_metric(
+ 1000 + $_ * 2 + $p,
+ ($_ % 97 == 0) ? "qemu/$p\\\"$_\\{x}" : "qemu/$p/$_",
+ )
+ } (1 .. 1500);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s2);
+ $cv2->recv;
+ },
+ );
+ my $p2 = eval { decode_json($s2->{buf}) };
+ ok(!$@ && $p2->{success} == 1, 'k-way merge extjs multi-chunk output has success:1');
+ is(scalar(@{ $p2->{data}->{data} }), 3000, 'k-way merge merged all 3,000 metrics');
+ ok(is_sorted_by_ts($p2->{data}->{data}), 'k-way merge 3,000 metrics strictly sorted');
+
+ # Backpressure resume via on_drain.
+ setup_cluster(2);
+ local $stream_format = 'json';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+
+ my ($bp_idx, $bp_hits) = (0, 0);
+ my $cv_bp = AnyEvent->condvar;
+ my $s_bp = MockStream->new(
+ format => 'json',
+ bp_after_bytes => 200,
+ on_write => sub {
+ my ($s) = @_;
+ if ($s->{backpressured}) {
+ $bp_hits++;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.01,
+ cb => sub {
+ undef $t;
+ $s->{bp_after_bytes} = 10_000_000;
+ $s->trigger_drain();
+ },
+ );
+ }
+ },
+ on_finish => sub { $cv_bp->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $i = ++$bp_idx;
+ my @m = map { make_metric(50 + $_, "node/ok$i/$_", 'm', 1) } (1 .. 4);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s_bp);
+ $cv_bp->recv;
+ },
+ );
+ ok($bp_hits >= 1, 'k-way merge paused on backpressure and resumed via on_drain');
+ is(
+ scalar(@{ decode_json($s_bp->{buf})->{data}->{data} }),
+ 10,
+ 'k-way merge emitted 2 local + 8 fast metrics after backpressure drain',
+ );
+
+ # Overall timeout cancels in-flight guards and aborts stream pre-start with HTTP 504.
+ setup_cluster(8);
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.10;
+ my ($started_to, $cancelled_to) = (0, 0);
+ my $cv_to = AnyEvent->condvar;
+ my $s_to = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_to->send; },
+ on_finish => sub { $cv_to->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $started_to++;
+ if ($started_to <= 2) {
+ my @m = map { make_metric(50 + $_, "node/ok$started_to/$_", 'm', 1) } (1 .. 4);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ }
+ return AnyEvent::Util::guard { undef $cb; $cancelled_to++; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($s_to);
+ $cv_to->recv;
+ },
+ );
+ is($cancelled_to, 4, 'k-way merge overall timeout cancelled 4 in-flight guards');
+ is(
+ scalar(grep { /overall fan-out timeout/ } @syslogs),
+ 6,
+ 'k-way merge logged all 6 unfinished peers',
+ );
+ ok(!$s_to->{started}, 'k-way merge overall timeout aborted pre-start');
+ ok(!$s_to->{finished}, 'k-way merge overall timeout did not finish with 200');
+ isa_ok($s_to->{aborted_err}, 'PVE::Exception');
+ is($s_to->{aborted_err}->{code}, 504, 'k-way merge overall timeout aborts with HTTP 504');
+ };
+
+subtest
+ 'pass-through stream: TTFB flush, incremental inflate, corrupt safety, extjs and backpressure'
+ => sub {
+ setup_cluster(8);
+ local $stream_format = 'extjs';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 256;
+
+ my ($started_before, $flushed_before, $idx) = (0, 0, 0);
+ my ($local_only_ok, $unsorted_leaked) = (0, 0);
+ my $cv = AnyEvent->condvar;
+ my $stream = MockStream->new(format => 'extjs', on_finish => sub { $cv->send; });
+ my $weak_cancel;
+
+ {
+ with_http_mock(
+ sub {
+ my (undef, $url, undef, $cb) = @_;
+ $local_only_ok++ if $url =~ /[?&]local-only=1(?:&|$)/;
+ $unsorted_leaked++ if $url =~ /[?&]unsorted=/;
+ my $my_idx = ++$idx;
+ if ($my_idx == 1) {
+ $started_before = $stream->{started};
+ $flushed_before = $stream->{flushed};
+ }
+ my $t;
+ $t = AnyEvent->timer(
+ after => 0.001,
+ cb => sub {
+ undef $t;
+ if ($my_idx == 1) {
+ $cb->(
+ memGzip('{"data":{"data":[]}}'),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ if ($my_idx == 2) {
+ $cb->('{"data":{"data":[{not_valid_json}]}}', { Status => 200 });
+ return;
+ }
+ if ($my_idx == 3) {
+ $cb->(
+ make_payload([make_metric(50, 'node/esc"}{quote', 'm', 1)], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return;
+ }
+ $cb->(
+ make_payload(
+ [make_metric(200 - $my_idx, "node/b$my_idx", 'm', 1)], 1,
+ ),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ isa_ok($async, 'PVE::APIServer::AnyEvent::AsyncStreamResponse');
+ my $cancel = $async->{start}->($stream);
+ $weak_cancel = $cancel;
+ weaken($weak_cancel);
+ $cv->recv;
+ },
+ );
+ }
+
+ is($started_before, 1, 'pass-through started stream before peers completed');
+ is($flushed_before, 1, 'pass-through flushed initial local slice for minimal TTFB');
+ is($local_only_ok, 8, 'remote peer requests always set local-only=1');
+ is($unsorted_leaked, 0, 'remote peer requests never forward unsorted parameter');
+ my $parsed = eval { decode_json($stream->{buf}) };
+ ok(!$@ && $parsed->{success} == 1,
+ 'pass-through extjs output is valid JSON with success:1');
+ # 2 local + 0 (p1 empty) + 0 (p2 corrupt) + 1 (p3 escaped) + 5 (p4..p8) = 8
+ is(scalar(@{ $parsed->{data}->{data} }), 8, 'pass-through emitted exact 8 metrics');
+ is_deeply(
+ [map { $_->{timestamp} } @{ $parsed->{data}->{data} }[0, 1]],
+ [105, 101],
+ 'pass-through emitted both local metrics first without sorting',
+ );
+ is($weak_cancel, undef, 'pass-through cancel closure freed without cycle');
+
+ # Incremental slicing (zero memGunzip) + pre-emission corrupt peer isolation.
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+ @syslogs = ();
+
+ my $gunzip_calls = 0;
+ my $zlib_mock = Test::MockModule->new('Compress::Zlib');
+ my $orig_memgunzip = \&Compress::Zlib::memGunzip;
+ $zlib_mock->redefine(
+ memGunzip => sub {
+ $gunzip_calls++;
+ return $orig_memgunzip->(@_);
+ },
+ );
+
+ my $writes = 0;
+ my $cv_inc = AnyEvent->condvar;
+ my $inc_stream = MockStream->new(
+ format => 'json',
+ on_write => sub { $writes++; },
+ on_finish => sub { $cv_inc->send; },
+ );
+ my $inc_idx = 0;
+ my @m200 = map { make_metric(500 + $_, "qemu/1/$_", 'cpu', 0.25) } (1 .. 200);
+ my @inc_bodies = (
+ make_payload(\@m200, 1), memGzip('{"data":{"data":[{"timestamp":11,"value":BROKEN}]}}'),
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->($inc_bodies[$inc_idx++], { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($inc_stream);
+ $cv_inc->recv;
+ },
+ );
+ undef $zlib_mock;
+
+ is($gunzip_calls, 0, 'pass-through incremental reader never calls whole-body memGunzip');
+ ok($writes > 5, "pass-through drained multi-chunk peer across multiple slices ($writes)");
+ my $inc_parsed = eval { decode_json($inc_stream->{buf}) };
+ ok(
+ !$@ && ref($inc_parsed) eq 'HASH',
+ 'pass-through output is valid JSON after skipping pre-emission corrupt peer',
+ );
+ is(
+ scalar(@{ $inc_parsed->{data}->{data} }),
+ 200,
+ 'pass-through kept all 200 healthy metrics',
+ );
+ is(scalar(@syslogs), 1, 'pass-through logged pre-emission corrupt peer warning');
+
+ # Late mid-array Reader error aborts pass-through stream instead of finishing with 200.
+ setup_cluster(2);
+ $local_metrics = [];
+ @syslogs = ();
+ my $cv_mid = AnyEvent->condvar;
+ my $mid_stream = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_mid->send; },
+ on_finish => sub { $cv_mid->send; },
+ );
+ my $mid_idx = 0;
+ my @mid_bodies = (
+ make_payload([make_metric(10, 'node/ok')], 1),
+ memGzip(
+ '{"data":{"data":[{"timestamp":10,"id":"node/valid1","metric":"cpu","value":1,"type":"gauge"},'
+ . '{"timestamp":11,"value":BROKEN}]}}'
+ ),
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->($mid_bodies[$mid_idx++], { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($mid_stream);
+ $cv_mid->recv;
+ },
+ );
+ ok($mid_stream->{started}, 'pass-through late Reader error occurred after stream started');
+ ok(!$mid_stream->{finished}, 'pass-through late Reader error did not finish with 200');
+ like(
+ $mid_stream->{aborted_err} // '',
+ qr/could not stream metrics from node002/,
+ 'pass-through late Reader error aborted stream with peer context',
+ );
+ ok($mid_stream->is_closed(), 'pass-through late Reader error closed stream');
+ ok(
+ scalar(grep { /could not fetch metrics from node002/ } @syslogs) >= 1,
+ 'pass-through late Reader error logged peer warning',
+ );
+
+ # Backpressure pauses peer dispatch; drain resumes; disconnect cancels guards.
+ setup_cluster(16);
+ local $stream_format = 'json';
+ my ($dispatched, $cancelled_bp) = (0, 0);
+ my $bp_stream = MockStream->new(bp_after_bytes => 10);
+ my $weak_bp;
+ {
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $dispatched++;
+ return AnyEvent::Util::guard { undef $cb; $cancelled_bp++; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ my $cancel = $async->{start}->($bp_stream);
+ $weak_bp = $cancel;
+ weaken($weak_bp);
+ is($dispatched, 0, 'pass-through paused peer dispatch while backpressured');
+ $bp_stream->{bp_after_bytes} = 10_000_000;
+ $bp_stream->trigger_drain();
+ is($dispatched, 4, 'pass-through resumed peer dispatch on drain (capped at 4)');
+ $bp_stream->disconnect($cancel);
+ is($cancelled_bp, 4, 'pass-through cancelled active guards on disconnect');
+ },
+ );
+ }
+ is($weak_bp, undef, 'pass-through disconnect freed cancel closure');
+
+ # Pass-through rejects peer metric objects missing integer timestamp.
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ @syslogs = ();
+ my $pt_ts_cv = AnyEvent->condvar;
+ my $pt_ts_stream = MockStream->new(format => 'json', on_finish => sub { $pt_ts_cv->send; });
+ my @pt_ts_bodies = (
+ make_payload([make_metric(10, 'node/good')]),
+ '{"data":{"data":[{"id":"node/missing-ts","value":1}]}}',
+ );
+ my $pt_ts_idx = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ $cb->(
+ memGzip($pt_ts_bodies[$pt_ts_idx++]),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($pt_ts_stream);
+ $pt_ts_cv->recv;
+ },
+ );
+ my $pt_ts_parsed = eval { decode_json($pt_ts_stream->{buf}) };
+ is_deeply(
+ [map { $_->{id} } @{ $pt_ts_parsed->{data}->{data} }],
+ ['node/good'],
+ 'unsorted=1 rejected peer metric object missing timestamp',
+ );
+ ok(
+ scalar(grep { /missing integer timestamp/ } @syslogs) == 1,
+ 'unsorted=1 logged missing integer timestamp warning',
+ );
+
+ # Pass-through overall_timeout aborts post-start stream instead of finishing with 200.
+ setup_cluster(2);
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.08;
+ my $pt_to_cv = AnyEvent->condvar;
+ my $pt_to_stream = MockStream->new(
+ format => 'json',
+ on_abort => sub { $pt_to_cv->send; },
+ on_finish => sub { $pt_to_cv->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ return AnyEvent::Util::guard { undef $cb; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($pt_to_stream);
+ $pt_to_cv->recv;
+ },
+ );
+ ok($pt_to_stream->{started}, 'pass-through overall_timeout had already started stream');
+ ok(!$pt_to_stream->{finished}, 'pass-through overall_timeout did not finish stream');
+ like(
+ $pt_to_stream->{aborted_err} // '',
+ qr/timed out/,
+ 'pass-through overall_timeout aborted stream on timeout',
+ );
+
+ # Unsupported stream formats fall back to buffered AsyncResponse.
+ local $stream_format = 'htmljs';
+ isa_ok(
+ PVE::API2::Cluster::MetricServer->export({ unsorted => 1 }),
+ 'PVE::APIServer::AnyEvent::AsyncResponse',
+ 'htmljs format falls back to buffered AsyncResponse',
+ );
+ };
+
+subtest 'stock HTTPServer returns AsyncResponse/AsyncStreamResponse under data and clears auth' =>
+ sub {
+ my $server = bless { rpcenv => $mock_rpcenv }, 'PVE::HTTPServer';
+ my $api2_mock = Test::MockModule->new('PVE::API2');
+
+ for my $case (
+ [
+ 'AsyncResponse',
+ PVE::APIServer::AnyEvent::async_response(sub {
+ return sub { };
+ }),
+ ],
+ [
+ 'AsyncStreamResponse',
+ PVE::APIServer::AnyEvent::async_stream_response(sub {
+ return sub { };
+ }),
+ ],
+ ) {
+ my ($label, $obj) = @$case;
+ $mock_rpcenv->set_user('root@pam');
+ $mock_rpcenv->set_credentials({ ticket => 'PVE:secret' });
+
+ my $handler = bless { obj => $obj }, 'TestAsyncHandler';
+ {
+ no warnings qw(redefine once);
+ *TestAsyncHandler::handle = sub { return $_[0]->{obj}; };
+ }
+ $api2_mock->redefine(
+ find_handler => sub {
+ return (
+ $handler,
+ {
+ allowtoken => 1,
+ expose_credentials => 1,
+ permissions => { user => 'all' },
+ },
+ );
+ },
+ );
+
+ my $resp = $server->rest_handler(
+ '127.0.0.1',
+ 'GET',
+ '/cluster/metrics/export',
+ { userid => 'root@pam', ticket => 'PVE:secret' },
+ {},
+ );
+ is($resp->{status}, 200, "HTTPServer returns 200 for $label");
+ is($resp->{data}, $obj, "stock HTTPServer returns $label handle under data");
+ is($mock_rpcenv->get_user(), undef, "rpcenv user cleared before yielding ($label)");
+ is(
+ $mock_rpcenv->get_credentials(),
+ undef,
+ "rpcenv credentials cleared before yielding ($label)",
+ );
+ }
+ };
+
+subtest
+ 'streaming resilience: competing I/O, slow-consumer deadline pause, malformed JSON and cleanup'
+ => sub {
+ # 1. Continuously ready competing I/O must not starve either streaming mode.
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+ local $PVE::PullMetricExport::SLICE_FALLBACK_INTERVAL = 0.005;
+
+ pipe(my $r_fh, my $w_fh) or die "pipe failed: $!\n";
+ syswrite($w_fh, 'x');
+ my $io_hits = 0;
+ my $io_w = AnyEvent->io(fh => $r_fh, poll => 'r', cb => sub { $io_hits++; });
+
+ my $cv = AnyEvent->condvar;
+ my $timed_out = 0;
+ AnyEvent->now_update;
+ my $guard_t = AnyEvent->timer(after => 5, cb => sub { $timed_out = 1; $cv->send; });
+
+ my $stream = MockStream->new(format => 'json', on_finish => sub { $cv->send; });
+ my $pno = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $p = ++$pno;
+ my @m = map { make_metric(1000 + $_ * 2 + $p, "qemu/$p/$_") } (1 .. 40);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($stream);
+ $cv->recv;
+ },
+ );
+ undef $io_w;
+ undef $guard_t;
+ close($r_fh);
+ close($w_fh);
+
+ ok(!$timed_out, "$label finished under continuously ready competing I/O");
+ ok($io_hits > 0, "$label yielded to competing I/O ($io_hits events)");
+ my $parsed = eval { decode_json($stream->{buf}) };
+ ok(!$@ && ref($parsed) eq 'HASH', "$label output under competing I/O is valid JSON");
+ is(
+ scalar(@{ $parsed->{data}->{data} }),
+ 80,
+ "$label emitted all 80 metrics under competing I/O",
+ );
+ }
+
+ # 2. Slow-consumer backpressure pauses overall_timeout budget so queued peers are not dropped.
+ setup_cluster(6);
+ local $stream_format = 'json';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 2;
+ local $PVE::API2::Cluster::MetricServer::FANOUT_OVERALL_TIMEOUT = 0.15;
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 1024;
+ @syslogs = ();
+
+ my $cv_bp = AnyEvent->condvar;
+ my $bp_stream = MockStream->new(
+ format => 'json',
+ bp_after_bytes => 10,
+ on_finish => sub { $cv_bp->send; },
+ );
+ my ($bp_dispatched, $mid_paused) = (0, 0);
+ my @resume_timers;
+
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $idx = ++$bp_dispatched;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.01,
+ cb => sub {
+ undef $t;
+ if ($idx == 2 && !$mid_paused) {
+ $mid_paused = 1;
+ $bp_stream->{bp_after_bytes} = length($bp_stream->{buf}) + 1;
+ AnyEvent->now_update;
+ push @resume_timers, AnyEvent->timer(
+ after => 0.25,
+ cb => sub {
+ $bp_stream->{bp_after_bytes} = 10_000_000;
+ $bp_stream->trigger_drain();
+ },
+ );
+ }
+ $cb->(
+ make_payload([make_metric(200 + $idx, "node/bp$idx")], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ AnyEvent->now_update;
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => 1 });
+ $async->{start}->($bp_stream);
+ AnyEvent->now_update;
+ push @resume_timers, AnyEvent->timer(
+ after => 0.25,
+ cb => sub {
+ $bp_stream->{bp_after_bytes} = 10_000_000;
+ $bp_stream->trigger_drain();
+ },
+ );
+ $cv_bp->recv;
+ },
+ );
+ @resume_timers = ();
+
+ my $bp_parsed = eval { decode_json($bp_stream->{buf}) };
+ ok(!$@ && ref($bp_parsed) eq 'HASH', 'slow-consumer pass-through produced valid JSON');
+ is(
+ scalar(@{ $bp_parsed->{data}->{data} }),
+ 8,
+ 'slow-consumer pass-through delivered all 2 local + 6 queued peers',
+ );
+ is(
+ scalar(@syslogs), 0, 'slow-consumer backpressure caused zero overall_timeout warnings',
+ );
+
+ # 3. Malformed peer JSON rejected strictly by both streaming modes (no backtracking stall).
+ my $large_bad_pairs = join(',', map { "\"k$_\":$_" } (1 .. 2000));
+ my $large_bad_obj = '{"data":{"data":[{' . $large_bad_pairs . ',"value":BROKEN}]}}';
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ setup_cluster(6);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ @syslogs = ();
+
+ my @payloads = (
+ make_payload([make_metric(100, 'node/ok')]),
+ '{"data":{"data":[{"timestamp":10,"value":BROKEN}]}}',
+ '{"data":{"data":[{"timestamp":11,"value":01}]}}',
+ '{"data":{"data":[{"timestamp":12,"value":1,}]}}',
+ "{\"data\":{\"data\":[{\"timestamp\":13,\"id\":\"bad\x01ctrl\",\"value\":1}]}}",
+ $large_bad_obj,
+ );
+ my $idx = 0;
+ my $cv_bad = AnyEvent->condvar;
+ my $bad_stream = MockStream->new(format => 'json', on_finish => sub { $cv_bad->send; });
+
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $body = $payloads[$idx++];
+ $cb->(memGzip($body), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($bad_stream);
+ $cv_bad->recv;
+ },
+ );
+
+ my $parsed = eval { decode_json($bad_stream->{buf}) };
+ ok(
+ !$@ && ref($parsed) eq 'HASH',
+ "$label rejected pre-emission malformed peer JSON and produced valid output",
+ );
+ my @ids = map { $_->{id} } @{ $parsed->{data}->{data} };
+ is_deeply(
+ \@ids,
+ ['node/ok'],
+ "$label skipped pre-emission malformed objects and kept valid output",
+ );
+ is(scalar(@syslogs), 5, "$label logged errors for all 5 pre-emission malformed peers");
+
+ # Late trailing-comma syntax error after emitting a valid object aborts the stream.
+ setup_cluster(2);
+ $local_metrics = [];
+ @syslogs = ();
+ my @late_payloads = (
+ make_payload([make_metric(100, 'node/ok')]),
+ '{"data":{"data":[{"timestamp":14,"id":"node/trailing","value":1},]}}',
+ );
+ my $late_idx = 0;
+ my $cv_late = AnyEvent->condvar;
+ my $late_stream = MockStream->new(
+ format => 'json',
+ on_abort => sub { $cv_late->send; },
+ on_finish => sub { $cv_late->send; },
+ );
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $body = $late_payloads[$late_idx++];
+ $cb->(memGzip($body), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($late_stream);
+ $cv_late->recv;
+ },
+ );
+ ok(!$late_stream->{finished}, "$label aborted on late trailing-comma error");
+ like(
+ $late_stream->{aborted_err} // '',
+ qr/could not stream metrics from node002/,
+ "$label reported peer context on late trailing-comma abort",
+ );
+ ok($late_stream->is_closed(), "$label closed stream on late trailing-comma error");
+ }
+
+ # 4. Direct resource destruction: HTTP guards, gzip inflaters, and stream refs released.
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ for my $action (qw(finish cancel)) {
+ setup_cluster(2);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+
+ my (@weak_guards, @weak_inflaters, $weak_stream);
+ my $inflate_mock = Test::MockModule->new(
+ 'Compress::Raw::Zlib::Inflate', no_auto => 1,
+ );
+ my $orig_inflate_new = \&Compress::Raw::Zlib::Inflate::new;
+ $inflate_mock->redefine(
+ new => sub {
+ my ($inf, $st) = $orig_inflate_new->(@_);
+ if (defined($inf)) {
+ push @weak_inflaters, $inf;
+ weaken($weak_inflaters[-1]);
+ }
+ return ($inf, $st);
+ },
+ );
+
+ {
+ my $cv_res = AnyEvent->condvar;
+ my ($cancel, $did_cancel) = (undef, 0);
+ my $s;
+ $s = MockStream->new(
+ bp_after_bytes => ($action eq 'cancel' ? 60 : undef),
+ on_write => sub {
+ return if $action ne 'cancel' || $did_cancel || !@weak_inflaters;
+ $did_cancel = 1;
+ AE::postpone(sub {
+ $s->disconnect($cancel) if $s;
+ $cv_res->send;
+ });
+ },
+ on_finish => sub { $cv_res->send; },
+ );
+ $weak_stream = $s;
+ weaken($weak_stream);
+
+ my @payload = map { make_metric(100 + $_, "qemu/res/$_") } (1 .. 30);
+ my $gz = make_payload(\@payload, 1);
+
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($gz, { Status => 200, 'content-encoding' => 'gzip' });
+ },
+ );
+ my $g = AnyEvent::Util::guard { undef $t; undef $cb; };
+ push @weak_guards, $g;
+ weaken($weak_guards[-1]);
+ return $g;
+ },
+ sub {
+ my $export_params = { unsorted => $unsorted };
+ my $async = PVE::API2::Cluster::MetricServer->export($export_params);
+ $cancel = $async->{start}->($s);
+ AnyEvent->now_update;
+ my $guard_t = AnyEvent->timer(
+ after => 5,
+ cb => sub { $cv_res->croak("resource cleanup test timed out\n"); },
+ );
+ $cv_res->recv;
+ undef $guard_t;
+ },
+ );
+ undef $cancel;
+ undef $s;
+ }
+ undef $inflate_mock;
+
+ ok(scalar(@weak_guards) > 0, "$label ($action) tracked active HTTP guards");
+ ok(scalar(@weak_inflaters) > 0, "$label ($action) tracked active gzip inflaters");
+ is(scalar(grep { defined($_) } @weak_guards), 0, "$label ($action) freed guards");
+ is(
+ scalar(grep { defined($_) } @weak_inflaters),
+ 0,
+ "$label ($action) freed gzip inflaters",
+ );
+ is($weak_stream, undef, "$label ($action) freed stream reference");
+ }
+ }
+
+ # 5. Slice callback and on_done exceptions abort the stream cleanly without unwinding.
+ for my $case (['on_done', 1], ['schedule_slice', 2]) {
+ my ($phase, $fail_on_write) = @$case;
+ setup_cluster(1);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 128;
+
+ my $cv_ab = AnyEvent->condvar;
+ my $timed_out = 0;
+ AnyEvent->now_update;
+ my $guard_t = AnyEvent->timer(after => 5, cb => sub { $timed_out = 1; $cv_ab->send; });
+
+ my $writes = 0;
+ my $ab_stream = MockStream->new(
+ on_write => sub {
+ die "slice write boom ($phase)\n" if ++$writes == $fail_on_write;
+ },
+ on_abort => sub { $cv_ab->send; },
+ on_finish => sub { $cv_ab->send; },
+ );
+
+ my @payload = map { make_metric(100 + $_, "qemu/ab/$_") } (1 .. 30);
+ my $gz = make_payload(\@payload, 1);
+
+ my $recv_err = '';
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($gz, { Status => 200, 'content-encoding' => 'gzip' });
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($ab_stream);
+ eval { $cv_ab->recv; };
+ $recv_err = $@;
+ },
+ );
+ undef $guard_t;
+
+ is($recv_err, '', "$phase exception did not unwind out of event loop");
+ ok(!$timed_out, "$phase exception aborted stream before guard timeout");
+ like(
+ $ab_stream->{aborted_err} // '',
+ qr/slice write boom \(\Q$phase\E\)/,
+ "$phase exception passed error to stream->abort()",
+ );
+ ok($ab_stream->is_closed(), "$phase exception closed stream");
+ }
+
+ # 6. Exception inside finish_stream() aborts the stream cleanly without unwinding.
+ {
+ setup_cluster(1);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 4096;
+
+ my $cv_fin = AnyEvent->condvar;
+ my $fin_stream = MockStream->new(
+ format => 'json',
+ on_write => sub { die "finish_stream write boom\n"; },
+ on_abort => sub { $cv_fin->send; },
+ on_finish => sub { $cv_fin->send; },
+ );
+ my $gz1 = make_payload([make_metric(100, 'qemu/fin/1')], 1);
+ my $recv_err = '';
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $cb->($gz1, { Status => 200, 'content-encoding' => 'gzip' });
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({});
+ $async->{start}->($fin_stream);
+ eval { $cv_fin->recv; };
+ $recv_err = $@;
+ },
+ );
+ is($recv_err, '', 'finish_stream exception did not unwind out of event loop');
+ like(
+ $fin_stream->{aborted_err} // '',
+ qr/finish_stream write boom/,
+ 'finish_stream exception invoked stream->abort()',
+ );
+ ok($fin_stream->is_closed(), 'finish_stream exception closed stream');
+ }
+ };
+
+subtest 'PVE::PullMetricExport::Reader direct unit tests' => sub {
+ # 1. Plain and gzipped payloads with negative timestamps, escapes, and UTF-8.
+ my $plain = make_payload([
+ make_metric(-42, 'node/neg', 'cpu', 0.1),
+ make_metric(100, 'node/esc"}{\\"timestamp":999', 'escaped', 1),
+ make_metric(200, "node/utf8-\x{c3}\x{a9}", 'utf8', 2),
+ ]);
+ for my $gz (0, 1) {
+ my $body = $gz ? memGzip($plain) : $plain;
+ my $r = PVE::PullMetricExport::Reader->open(body => $body, gzip => $gz);
+ my (@ts, @objs);
+ while (defined(my $obj = $r->next())) {
+ is($obj, $r->obj(), "Reader (gzip=$gz) next() return value matches obj()");
+ push @ts, $r->ts();
+ push @objs, $obj;
+ }
+ is_deeply(\@ts, [-42, 100, 200], "Reader (gzip=$gz) extracted exact timestamps");
+ is(scalar(@objs), 3, "Reader (gzip=$gz) yielded all 3 objects");
+ is(
+ decode_json($objs[1])->{id},
+ 'node/esc"}{\\"timestamp":999',
+ "Reader (gzip=$gz) preserved escaped JSON object",
+ );
+ is($r->next(), undef, "Reader (gzip=$gz) next() after EOF returns undef");
+ $r->close(); # idempotent
+ }
+
+ # 2. Empty array with whitespace.
+ my $empty = PVE::PullMetricExport::Reader->open(
+ body => memGzip('{"data":{"data":[ ]}}'),
+ gzip => 1,
+ );
+ is($empty->next(), undef, 'empty metrics array returns undef on first next()');
+
+ # 3. Multi-chunk gzip inflation across tiny input slices and 64 KiB inflate chunks.
+ {
+ local $PVE::PullMetricExport::Reader::GZIP_INPUT_CHUNK_BYTES = 128;
+ my @m500 = map { make_metric(1000 + $_, "qemu/reader/$_", 'cpu', 0.5) } (1 .. 500);
+ my $gz500 = make_payload(\@m500, 1);
+ my $r = PVE::PullMetricExport::Reader->open(body => $gz500, gzip => 1);
+ my ($count, $first_ts, $last_ts) = (0, undef, undef);
+ while (defined($r->next())) {
+ $count++;
+ $first_ts //= $r->ts();
+ $last_ts = $r->ts();
+ }
+ is($count, 500, 'Reader inflated all 500 metrics across 128 B input slices');
+ is($first_ts, 1001, 'Reader first multi-chunk timestamp matches');
+ is($last_ts, 1500, 'Reader last multi-chunk timestamp matches');
+ }
+
+ # 3b. Multi-chunk (>128 KiB) whitespace between metrics compacts cleanly and rejects trailing comma.
+ {
+ my $ws140k = ' ' x 140_000;
+ my $ws_payload =
+ '{"data":{"data":['
+ . '{"timestamp":10,"id":"node/a","metric":"cpu","value":1,"type":"gauge"}'
+ . $ws140k . ','
+ . $ws140k
+ . '{"timestamp":20,"id":"node/b","metric":"cpu","value":2,"type":"gauge"}'
+ . $ws140k . ']}}';
+ for my $gz (0, 1) {
+ my $body = $gz ? memGzip($ws_payload) : $ws_payload;
+ my $r = PVE::PullMetricExport::Reader->open(body => $body, gzip => $gz);
+ my (@ts, $max_buf);
+ $max_buf = 0;
+ while (defined($r->next())) {
+ push @ts, $r->ts();
+ my $blen = length($r->{buf} // '');
+ $max_buf = $blen if $blen > $max_buf;
+ }
+ is_deeply(
+ \@ts,
+ [10, 20],
+ "Reader (gzip=$gz) parsed >128 KiB inter-object whitespace",
+ );
+ if ($gz) {
+ ok(
+ $max_buf <= 131_072,
+ "Reader (gzip=1) kept buffer compacted across >128 KiB whitespace ($max_buf B)",
+ );
+ }
+ }
+
+ my $trailing_ws_payload =
+ '{"data":{"data":['
+ . '{"timestamp":10,"id":"node/a","metric":"cpu","value":1,"type":"gauge"},'
+ . $ws140k . ']}}';
+ for my $gz (0, 1) {
+ my $body = $gz ? memGzip($trailing_ws_payload) : $trailing_ws_payload;
+ my $r;
+ eval {
+ $r = PVE::PullMetricExport::Reader->open(body => $body, gzip => $gz);
+ while (defined($r->next())) { }
+ };
+ my $err = $@;
+ $r->close() if $r;
+ like(
+ $err,
+ qr/unexpected token in metrics array/,
+ "Reader (gzip=$gz) rejected trailing comma after >128 KiB whitespace",
+ );
+ }
+ }
+
+ # 4. Missing integer timestamp is always rejected.
+ my $no_ts_body = '{"data":{"data":[{"id":"node/no-ts","value":1}]}}';
+ {
+ my $r_no_ts;
+ eval {
+ $r_no_ts = PVE::PullMetricExport::Reader->open(body => $no_ts_body, gzip => 0);
+ $r_no_ts->next();
+ };
+ my $err = $@;
+ $r_no_ts->close() if $r_no_ts;
+ like($err, qr/missing integer timestamp/, 'Reader always enforces integer timestamp');
+ }
+
+ # Duplicate timestamp keys fall back to decode_json for exact last-key-wins parity.
+ {
+ my $r_dup = PVE::PullMetricExport::Reader->open(
+ body => '{"data":{"data":[{"timestamp":1,"timestamp":2,"id":"x"}]}}',
+ gzip => 0,
+ );
+ ok(defined($r_dup->next()), 'duplicate integer timestamp key accepted via fallback');
+ is($r_dup->ts(), 2, 'duplicate timestamp key uses last-key-wins value (2)');
+ is($r_dup->next(), undef, 'duplicate timestamp reader reaches EOF cleanly');
+ }
+
+ # 5. Strict error cases die cleanly (callers close reader on error).
+ for my $case (
+ ['bad opening envelope', '{"bad":1}', 0, qr/unexpected response format/],
+ [
+ 'corrupt gzip',
+ "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xff\xff\xff\xffcorrupt-deflate-payload",
+ 1,
+ qr/failed to gunzip stream/,
+ ],
+ [
+ 'truncated gzip',
+ substr(memGzip($plain), 0, int(length(memGzip($plain)) / 2)),
+ 1,
+ qr/truncated gzip stream|unexpected response format/,
+ ],
+ [
+ 'truncated array', '{"data":{"data":[{"timestamp":1}', 0,
+ qr/truncated metrics array/,
+ ],
+ [
+ 'truncated object',
+ '{"data":{"data":[{"timestamp":1,"id":"abc',
+ 0,
+ qr/truncated metric object/,
+ ],
+ [
+ 'non-object element',
+ '{"data":{"data":[123]}}',
+ 0,
+ qr/unexpected token in metrics array/,
+ ],
+ [
+ 'missing comma',
+ '{"data":{"data":[{"timestamp":1}{"timestamp":2}]}}',
+ 0,
+ qr/unexpected token in metrics array/,
+ ],
+ [
+ 'trailing comma',
+ '{"data":{"data":[{"timestamp":1},]}}',
+ 0,
+ qr/unexpected token in metrics array/,
+ ],
+ ['malformed JSON', '{"data":{"data":[{"timestamp":1,"v":BROKEN}]}}', 0, qr/./],
+ ['missing timestamp', $no_ts_body, 0, qr/missing integer timestamp/],
+ [
+ 'boolean timestamp',
+ '{"data":{"data":[{"timestamp":true,"id":"x"}]}}',
+ 0,
+ qr/missing integer timestamp/,
+ ],
+ [
+ 'duplicate timestamp with non-integer value',
+ '{"data":{"data":[{"timestamp":1,"timestamp":"bad","id":"x"}]}}',
+ 0,
+ qr/missing integer timestamp/,
+ ],
+ [
+ 'non-integer timestamp',
+ '{"data":{"data":[{"timestamp":1.5,"id":"x"}]}}',
+ 0,
+ qr/missing integer timestamp/,
+ ],
+ [
+ 'trailing data after empty array',
+ '{"data":{"data":[]}}extra',
+ 0,
+ qr/unexpected trailing data/,
+ ],
+ [
+ 'trailing data after items',
+ '{"data":{"data":[{"timestamp":1}]}}extra',
+ 0,
+ qr/unexpected trailing data/,
+ ],
+ [
+ '>4 KiB trailing gzip payload after ]',
+ memGzip('{"data":{"data":[]}}' . (' ' x 8192)),
+ 1,
+ qr/unexpected trailing data/,
+ ],
+ [
+ 'trailing bytes after Z_STREAM_END',
+ memGzip('{"data":{"data":[]}}') . 'extra',
+ 1,
+ qr/unexpected trailing data after gzip stream/,
+ ],
+ ) {
+ my ($label, $body, $gz, $re) = @$case;
+ my $r;
+ eval {
+ $r = PVE::PullMetricExport::Reader->open(
+ body => $body,
+ gzip => $gz,
+ );
+ while (defined($r->next())) { }
+ };
+ my $err = $@;
+ $r->close() if $r;
+ like($err, $re, "Reader dies on $label");
+ }
+
+ # 6. Early close() releases gzip inflater reference and stops iteration.
+ my $weak_inf;
+ my $inflate_mock = Test::MockModule->new('Compress::Raw::Zlib::Inflate', no_auto => 1);
+ my $orig_new = \&Compress::Raw::Zlib::Inflate::new;
+ $inflate_mock->redefine(
+ new => sub {
+ my ($inf, $st) = $orig_new->(@_);
+ $weak_inf = $inf;
+ weaken($weak_inf) if defined($weak_inf);
+ return ($inf, $st);
+ },
+ );
+ # >64 KiB uncompressed so open() leaves the gzip inflater active until close().
+ my @m1000 = map { make_metric(10 + $_, "qemu/close/$_") } (1 .. 1000);
+ my $r_close = PVE::PullMetricExport::Reader->open(
+ body => make_payload(\@m1000, 1),
+ gzip => 1,
+ );
+ ok(defined($weak_inf), 'Reader holds live inflater while open');
+ ok(defined($r_close->next()), 'Reader yields first item before close');
+ $r_close->close();
+ is($weak_inf, undef, 'Reader->close() immediately releases gzip inflater');
+ is($r_close->next(), undef, 'Reader->next() returns undef after close()');
+ undef $inflate_mock;
+};
+
+subtest 'worker-wide peer concurrency cap across overlapping exports and cancel cleanup' => sub {
+ setup_cluster(10);
+ $local_metrics = [];
+ local $stream_format = 'json';
+ local $PVE::API2::Cluster::MetricServer::MAX_CONCURRENT_REQUESTS = 4;
+ local $PVE::PullMetricExport::MAX_WORKER_CONCURRENT_PEERS = 6;
+
+ # 1. Three overlapping exports stay <= 6 worker-wide and <= 4 per export.
+ my ($worker_active, $worker_peak, $total_started) = (0, 0, 0);
+ my (%per_export_active, %per_export_peak);
+ my $remaining = 3;
+ my $cv = AnyEvent->condvar;
+ my @streams;
+
+ with_http_mock(
+ sub {
+ my (undef, $url, undef, $cb) = @_;
+ my ($eid) = $url =~ /[?&]start-time=([0-9]+)/;
+ $total_started++;
+ $worker_active++;
+ $worker_peak = $worker_active if $worker_active > $worker_peak;
+ $per_export_active{$eid}++;
+ $per_export_peak{$eid} = $per_export_active{$eid}
+ if $per_export_active{$eid} > ($per_export_peak{$eid} // 0);
+
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.005,
+ cb => sub {
+ undef $t;
+ $worker_active--;
+ $per_export_active{$eid}--;
+ $cb->(
+ make_payload([make_metric(1000 + $eid, "node/e$eid")], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard { undef $t; };
+ },
+ sub {
+ for my $eid (1 .. 3) {
+ my $s = MockStream->new(
+ format => 'json',
+ on_finish => sub { $cv->send if --$remaining == 0; },
+ );
+ push @streams, $s;
+ my $async = PVE::API2::Cluster::MetricServer->export({ 'start-time' => $eid });
+ $async->{start}->($s);
+ }
+ $cv->recv;
+ },
+ );
+
+ is($total_started, 30, 'all 30 peer fetches across 3 overlapping exports completed');
+ is($worker_peak, 6,
+ 'worker-wide in-flight peers capped at MAX_WORKER_CONCURRENT_PEERS (6)');
+ for my $eid (1 .. 3) {
+ ok(
+ ($per_export_peak{$eid} // 0) <= 4,
+ "export $eid peak in-flight <= 4 ($per_export_peak{$eid})",
+ );
+ my $parsed = decode_json($streams[$eid - 1]->{buf});
+ is(scalar(@{ $parsed->{data}->{data} }), 10,
+ "export $eid received all 10 peer metrics");
+ }
+
+ # 2. Cancelling a queued overlapping export frees its active slots and drops queued waiters.
+ setup_cluster(6);
+ $local_metrics = [];
+ my ($c_active, $c_peak, $cancelled_e2_started) = (0, 0, 0);
+ my $c_rem = 2;
+ my $cv_c = AnyEvent->condvar;
+ my (@c_streams, @c_cancels);
+ my $e2_cancelled = 0;
+
+ with_http_mock(
+ sub {
+ my (undef, $url, undef, $cb) = @_;
+ my ($eid) = $url =~ /[?&]start-time=([0-9]+)/;
+ $cancelled_e2_started++ if $eid == 2 && $e2_cancelled;
+ $c_active++;
+ $c_peak = $c_active if $c_active > $c_peak;
+ my $done = 0;
+ my $t;
+ AnyEvent->now_update;
+ $t = AnyEvent->timer(
+ after => 0.01,
+ cb => sub {
+ undef $t;
+ return if $done;
+ $done = 1;
+ $c_active--;
+ $cb->(
+ make_payload([make_metric(2000 + $eid, "node/c$eid")], 1),
+ { Status => 200, 'content-encoding' => 'gzip' },
+ );
+ },
+ );
+ return AnyEvent::Util::guard {
+ undef $t;
+ if (!$done) {
+ $done = 1;
+ $c_active--;
+ }
+ };
+ },
+ sub {
+ for my $eid (1 .. 3) {
+ my $s = MockStream->new(
+ format => 'json',
+ on_finish => sub {
+ $cv_c->send if $eid != 2 && --$c_rem == 0;
+ },
+ );
+ push @c_streams, $s;
+ my $async = PVE::API2::Cluster::MetricServer->export({ 'start-time' => $eid });
+ push @c_cancels, $async->{start}->($s);
+ }
+ # Export 2 holds 2 active slots + 2 queued worker waiters (1 holds 4, 3 holds 4 queued).
+ $e2_cancelled = 1;
+ $c_streams[1]->disconnect($c_cancels[1]);
+ $cv_c->recv;
+ },
+ );
+
+ is($cancelled_e2_started, 0, 'queued worker waiters for cancelled export never started');
+ ok($c_peak <= 6, "worker-wide peak stayed <= 6 after cancel ($c_peak)");
+ is($c_active, 0, 'all worker peer slots cleanly released');
+ for my $idx (0, 2) {
+ my $parsed = decode_json($c_streams[$idx]->{buf});
+ is(
+ scalar(@{ $parsed->{data}->{data} }),
+ 6,
+ "surviving export $idx completed with all 6 peer metrics",
+ );
+ }
+};
+
+subtest 'end-to-end gzip + extjs against real PVE::APIServer::AsyncStream' => sub {
+ {
+
+ package RecordingHandle;
+
+ sub new { return bless { wire => '', wbuf => '', _tls_wbuf => '' }, $_[0]; }
+ sub push_write { $_[0]->{wire} .= $_[1]; }
+ sub wtimeout { }
+ sub wtimeout_reset { }
+ sub timeout { }
+ sub timeout_reset { }
+ sub on_drain { $_[1]->($_[0]) if ref($_[1]) eq 'CODE'; }
+ }
+ {
+
+ package RecordingServer;
+
+ sub new {
+ my ($class, $on_finish) = @_;
+ return bless {
+ compression => 1,
+ timeout => 30,
+ end_loop => 0,
+ logged => 0,
+ finished => 0,
+ aborted => 0,
+ on_finish => $on_finish,
+ }, $class;
+ }
+ sub log_request { $_[0]->{logged}++; }
+
+ sub finish_response {
+ $_[0]->{finished}++;
+ $_[0]->{on_finish}->() if $_[0]->{on_finish};
+ }
+ sub log_aborted_request { $_[0]->{aborted}++; }
+ sub client_do_disconnect { }
+ }
+
+ my $decode_chunked = sub {
+ my ($raw) = @_;
+ my $out = '';
+ my $pos = 0;
+ my $len = length($raw);
+ while ($pos < $len) {
+ my $crlf = index($raw, "\015\012", $pos);
+ return (undef, 'missing chunk size CRLF') if $crlf < 0;
+ my $size_hex = substr($raw, $pos, $crlf - $pos);
+ return (undef, "invalid chunk size '$size_hex'") if $size_hex !~ /^[0-9a-fA-F]+$/;
+ my $size = hex($size_hex);
+ $pos = $crlf + 2;
+ if ($size == 0) {
+ return (undef, 'missing terminating CRLF after 0-chunk')
+ if substr($raw, $pos) ne "\015\012";
+ return ($out, undef);
+ }
+ return (undef, 'truncated chunk body') if $pos + $size + 2 > $len;
+ $out .= substr($raw, $pos, $size);
+ return (undef, 'missing CRLF after chunk payload')
+ if substr($raw, $pos + $size, 2) ne "\015\012";
+ $pos += $size + 2;
+ }
+ return (undef, 'missing terminating 0-chunk');
+ };
+
+ for my $unsorted (0, 1) {
+ my $label = $unsorted ? 'pass-through' : 'k-way merge';
+ setup_cluster(3);
+ local $stream_format = 'extjs';
+ local $PVE::PullMetricExport::STREAM_SLICE_BYTES = 256;
+
+ my $cv = AnyEvent->condvar;
+ my $hdl = RecordingHandle->new();
+ my $srv = RecordingServer->new(sub { $cv->send; });
+ my $reqstate = {
+ hdl => $hdl,
+ accept_gzip => 1,
+ proto => { ver => 1001, str => 'HTTP/1.1' },
+ keep_alive => 1,
+ log => {},
+ request => {},
+ };
+ my $stream = PVE::APIServer::AsyncStream->new(
+ server => $srv,
+ reqstate => $reqstate,
+ format => 'extjs',
+ );
+
+ my $pno = 0;
+ with_http_mock(
+ sub {
+ my (undef, undef, undef, $cb) = @_;
+ my $p = ++$pno;
+ my @m = map { make_metric(200 + $_ * 3 + $p, "qemu/e2e/$p/$_") } (1 .. 10);
+ $cb->(make_payload(\@m, 1), { Status => 200, 'content-encoding' => 'gzip' });
+ return AnyEvent::Util::guard {};
+ },
+ sub {
+ my $async = PVE::API2::Cluster::MetricServer->export({ unsorted => $unsorted });
+ $async->{start}->($stream);
+ $cv->recv;
+ },
+ );
+
+ is($srv->{finished}, 1, "$label real AsyncStream called finish_response()");
+ is($srv->{aborted}, 0, "$label real AsyncStream did not abort");
+ my ($hdr_block, $body_raw) = split(/\015\012\015\012/, $hdl->{wire}, 2);
+ like($hdr_block, qr{^HTTP/1\.1 200 OK\015\012}, "$label emitted HTTP/1.1 200 OK");
+ like($hdr_block, qr{^Content-Encoding: gzip\015?$}mi,
+ "$label negotiated gzip encoding");
+ like(
+ $hdr_block,
+ qr{^Transfer-Encoding: chunked\015?$}mi,
+ "$label used HTTP/1.1 chunked framing",
+ );
+
+ my ($gz_body, $chunk_err) = $decode_chunked->($body_raw);
+ is($chunk_err, undef, "$label chunked framing terminated cleanly with 0\\r\\n\\r\\n");
+
+ my ($inf, $st) = Compress::Raw::Zlib::Inflate->new(-WindowBits => WANT_GZIP);
+ my $json_str = '';
+ my $in_copy = $gz_body;
+ my $inf_st = $inf->inflate($in_copy, $json_str);
+ cmp_ok(
+ $inf_st,
+ '==',
+ Z_STREAM_END,
+ "$label gzip stream finalized cleanly (Z_STREAM_END)",
+ );
+ is(length($in_copy), 0, "$label zero trailing bytes after gzip Z_STREAM_END");
+
+ my $parsed = eval { decode_json($json_str) };
+ ok(!$@ && ref($parsed) eq 'HASH', "$label decoded valid JSON envelope");
+ is($parsed->{success}, 1, "$label extjs envelope has success => 1");
+ is(
+ scalar(@{ $parsed->{data}->{data} }),
+ 32,
+ "$label extjs payload contains 2 local + 30 remote metrics",
+ );
+ ok(is_sorted_by_ts($parsed->{data}->{data}), "$label k-way output sorted")
+ if !$unsorted;
+ }
+};
+
+done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 12+ messages in thread* Re: [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (8 preceding siblings ...)
2026-11-30 0:58 ` [PATCH manager 09/09] test: add pull metric export test suite Thomas Lamprecht
@ 2026-12-01 10:13 ` Jonas Theisen
2026-12-01 10:22 ` superseded: " Thomas Lamprecht
10 siblings, 0 replies; 12+ messages in thread
From: Jonas Theisen @ 2026-12-01 10:13 UTC (permalink / raw)
To: Thomas Lamprecht, pve-devel
On 11/30/26 02:01, Thomas Lamprecht wrote:
> GET /cluster/metrics/export runs inside pveproxy's three AnyEvent
> workers 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).
> - pve-manager (patches 6-9): switch GET /cluster/metrics/export to
> bounded async fan-out (16 peers per export, 32 per worker), 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.
>
> 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; /ping HOL = concurrent
> /ping latency on the same worker):
>
> Scenario | Mode | Total | TTFB | VmHWM | /ping HOL
> --------------------+---------------+--------+-------+----------+--------------
> 25x100 latest | Sync LWP | 980ms | - | 105 MiB | 952 ms (max)
> (25,475 metrics) | K-way stream | 188ms | 118ms | 83 MiB | 7.9 ms (max)
> | Pass-through | 154ms | 2.3ms | 81 MiB | 6.6 ms (max)
> 25x100 hist10 | Sync LWP | 2146ms | - | 337 MiB | 2194 ms (max)
> (254,750 metrics) | K-way stream | 827ms | 129ms | 98 MiB | 5.3 ms (max)
> | Pass-through | 744ms | 6.7ms | 92 MiB | 5.3 ms (med)
> 100x100 latest | Sync LWP | 4445ms | - | 180 MiB | 4128 ms (max)
> (101,900 metrics) | K-way stream | 644ms | 401ms | 90 MiB | 13.3 ms (max)
> | Pass-through | 463ms | 2.8ms | 81 MiB | 13.7 ms (max)
> 100x1000 | Buffered | 5.1 s | - | 973 MiB | -
> (1,001,900 metrics) | K-way stream | 2969ms | 360ms | 103 MiB | 10.5 ms (max)
> | Pass-through | 2790ms | 7.5ms | 93 MiB | 5.5 ms (med)
>
> 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.
>
> <snip>
Tested this series on a 9 node cluster including varying connection
failures and blocks between hosts. Also connected to PDM.
Didn't notice anything off.
Performance was not reliably tested since the cluster does not
include a lot of metrics.
Consider this
Tested-by: Jonas Theisen <j.theisen@proxmox.com>
^ permalink raw reply [flat|nested] 12+ messages in thread* superseded: [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export
2026-11-30 0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
` (9 preceding siblings ...)
2026-12-01 10:13 ` [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Jonas Theisen
@ 2026-12-01 10:22 ` Thomas Lamprecht
10 siblings, 0 replies; 12+ messages in thread
From: Thomas Lamprecht @ 2026-12-01 10:22 UTC (permalink / raw)
To: pve-devel
Superseded-by: https://lore.proxmox.com/pve-devel/20261201101913.1885484-1-t.lamprecht@proxmox.com/
^ permalink raw reply [flat|nested] 12+ messages in thread