From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 548601FF0B7 for ; Mon, 30 Nov 2026 02:02:00 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id D57AC21708; Mon, 30 Nov 2026 02:01:57 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH http-server 03/09] response: support incremental streaming API2 responses Date: Mon, 30 Nov 2026 01:58:07 +0100 Message-ID: <20261130010113.2166775-4-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com> References: <20261130010113.2166775-1-t.lamprecht@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796000480742 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.147 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: E4ZPOTE7EZ35T4ML4GQ6MYWCC6LLRMW6 X-Message-ID-Hash: E4ZPOTE7EZ35T4ML4GQ6MYWCC6LLRMW6 X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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