1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Like most Perl modules in public-inbox, this is internal and
5 # NOT subject to any stability guarantees! It is only documented
8 # This is used to limit the number of processes spawned by the
9 # PSGI server, so it acts like a semaphore and queues up extra
10 # commands to be run if currently at the limit. Multiple "limiters"
11 # may be configured which give inboxes different channels to
12 # operate in. This can be useful to ensure smaller inboxes can
13 # be cloned while cloning of large inboxes is maxed out.
15 # This does not depend on the PublicInbox::DS::event_loop or any
16 # other external scheduling mechanism, you just need to call
17 # start() and finish() appropriately. However, public-inbox-httpd
18 # (which uses PublicInbox::DS) will be able to schedule this
19 # based on readability of stdout from the spawned process.
20 # See GitHTTPBackend.pm and SolverGit.pm for usage examples.
21 # It does not depend on any form of threading.
23 # This is useful for scheduling CGI execution of both long-lived
24 # git-http-backend(1) process (for "git clone") as well as short-lived
25 # processes such as git-apply(1).
27 package PublicInbox::Qspawn;
30 use PublicInbox::Spawn qw(popen_rd);
31 use PublicInbox::GzipFilter;
33 # n.b.: we get EAGAIN with public-inbox-httpd, and EINTR on other PSGI servers
34 use Errno qw(EAGAIN EINTR);
38 # declares a command to spawn (but does not spawn it).
39 # $cmd is the command to spawn
40 # $cmd_env is the environ for the child process (not PSGI env)
41 # $opt can include redirects and perhaps other process spawning options
42 # {qsp_err} is an optional error buffer callers may access themselves
44 my ($class, $cmd, $cmd_env, $opt) = @_;
45 bless { args => [ $cmd, $cmd_env, $opt ] }, $class;
49 my ($self, $start_cb, $limiter) = @_;
51 my ($cmd, $cmd_env, $opt) = @{delete $self->{args}};
52 my %o = %{$opt || {}};
53 $self->{limiter} = $limiter;
54 foreach my $k (@PublicInbox::Spawn::RLIMITS) {
55 if (defined(my $rlimit = $limiter->{$k})) {
59 $self->{cmd} = $o{quiet} ? undef : $cmd;
61 # popen_rd may die on EMFILE, ENFILE
62 $self->{rpipe} = popen_rd($cmd, $cmd_env, \%o);
64 die "E: $!" unless defined($self->{rpipe});
66 $limiter->{running}++;
67 $start_cb->($self); # EPOLL_CTL_ADD may ENOSPC/ENOMEM
69 finish($self, $@) if $@;
73 my ($child_error) = @_; # typically $?
74 my $exitstatus = ($child_error >> 8) or return;
75 my $sig = $child_error & 127;
76 my $msg = "exit status=$exitstatus";
77 $msg .= " signal=$sig" if $sig;
82 my ($self, $err) = @_;
84 my ($env, $qx_cb, $qx_arg, $qx_buf) =
85 delete @$self{qw(psgi_env qx_cb qx_arg qx_buf)};
87 # done, spawn whatever's in the queue
88 my $limiter = $self->{limiter};
89 my $running = --$limiter->{running};
91 if ($running < $limiter->{max}) {
92 if (my $next = shift(@{$limiter->{run_queue}})) {
93 _do_spawn(@$next, $limiter);
99 if (my $dst = $self->{qsp_err}) {
100 $$dst .= $$dst ? " $err" : "; $err";
102 warn "@{$self->{cmd}}: $err" if $self->{cmd};
105 eval { $qx_cb->($qx_buf, $qx_arg) };
107 warn "E: $@"; # hope qspawn.wcb can handle it
109 return if $self->{passed}; # another command chained it
110 if (my $wcb = delete $env->{'qspawn.wcb'}) {
111 # have we started writing, yet?
112 require PublicInbox::WwwStatic;
113 $wcb->(PublicInbox::WwwStatic::r(500));
117 # callback for dwaitpid or ProcessPipe
118 sub waitpid_err { finalize($_[0], child_err($?)) }
121 my ($self, $err) = @_;
122 my $tied_pp = delete($self->{rpipe}) or return finalize($self, $err);
123 my PublicInbox::ProcessPipe $pp = tied *$tied_pp;
124 @$pp{qw(cb arg)} = (\&waitpid_err, $self); # for ->DESTROY
128 my ($self, $limiter, $start_cb) = @_;
129 if ($limiter->{running} < $limiter->{max}) {
130 _do_spawn($self, $start_cb, $limiter);
132 push @{$limiter->{run_queue}}, [ $self, $start_cb ];
136 sub psgi_qx_init_cb {
138 my $async = delete $self->{async}; # PublicInbox::HTTPD::Async
140 my $qx_fh = $self->{qx_fh};
142 $r = sysread($self->{rpipe}, $buf, 65536);
144 $async->async_pass($self->{psgi_env}->{'psgix.io'},
146 } elsif (defined $r) {
147 $r ? (print $qx_fh $buf) : event_step($self, undef);
149 return if $! == EAGAIN; # try again when notified
150 goto reread if $! == EINTR;
151 event_step($self, $!);
157 if (my $async = $self->{psgi_env}->{'pi-httpd.async'}) {
158 # PublicInbox::HTTPD::Async->new(rpipe, $cb, cb_arg, $end_obj)
159 $self->{async} = $async->($self->{rpipe},
160 \&psgi_qx_init_cb, $self, $self);
161 # init_cb will call ->async_pass or ->close
162 } else { # generic PSGI
163 psgi_qx_init_cb($self) while $self->{qx_fh};
167 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
168 # the stdout of the given command when done; but respects the given limiter
169 # $env is the PSGI env. As with ``/qx; only use this when output is small
172 my ($self, $env, $limiter, $qx_cb, $qx_arg) = @_;
173 $self->{psgi_env} = $env;
175 open(my $qx_fh, '+>', \$qx_buf) or die; # PerlIO::scalar
176 $self->{qx_cb} = $qx_cb;
177 $self->{qx_arg} = $qx_arg;
178 $self->{qx_fh} = $qx_fh;
179 $self->{qx_buf} = \$qx_buf;
180 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
181 start($self, $limiter, \&psgi_qx_start);
184 # this is called on pipe EOF to reap the process, may be called
185 # via PublicInbox::DS event loop OR via GetlineBody for generic
188 my ($self, $err) = @_; # $err: $!
189 warn "psgi_{return,qx} $err" if defined($err);
191 my ($fh, $qx_fh) = delete(@$self{qw(qfh qx_fh)});
192 $fh->close if $fh; # async-only (psgi_return)
197 # typically used for reading CGI headers
198 # We also need to check EINTR for generic PSGI servers.
201 my $hdr_buf = $self->{hdr_buf};
202 my ($ph_cb, $ph_arg) = @{$self->{parse_hdr}};
204 my $r = sysread($self->{rpipe}, $$hdr_buf, 4096,
208 eval { $ret = $ph_cb->($total_rd, $hdr_buf, $ph_arg) };
210 warn "parse_hdr: $@";
211 $ret = [ 500, [], [ "Internal error\n" ] ];
214 # caller should notify us when it's ready:
215 return if $! == EAGAIN;
216 next if $! == EINTR; # immediate retry
217 warn "error reading header: $!";
218 $ret = [ 500, [], [ "Internal error\n" ] ];
220 } until (defined $ret);
221 delete $self->{parse_hdr}; # done parsing headers
225 sub psgi_return_init_cb {
227 my $r = rd_hdr($self) or return;
228 my $env = $self->{psgi_env};
230 if (ref($r) eq 'ARRAY' && Scalar::Util::blessed($r->[2]) &&
231 $r->[2]->can('attach')) {
234 $filter //= delete($env->{'qspawn.filter'}) // (ref($r) eq 'ARRAY' ?
235 PublicInbox::GzipFilter::qsp_maybe($r->[1], $env) : undef);
237 my $wcb = delete $env->{'qspawn.wcb'};
238 my $async = delete $self->{async}; # PublicInbox::HTTPD::Async
239 if (ref($r) ne 'ARRAY' || scalar(@$r) == 3) { # error
240 if ($async) { # calls rpipe->close && ->event_step
241 $async->close; # PublicInbox::HTTPD::Async::close
242 } else { # generic PSGI:
243 delete($self->{rpipe})->close;
247 if (ref($r) eq 'ARRAY') { # error
249 } elsif (ref($r) eq 'CODE') { # chain another command
255 # done reading headers, handoff to read body
256 my $fh = $wcb->($r); # scalar @$r == 2
257 $fh = $filter->attach($fh) if $filter;
259 $async->async_pass($env->{'psgix.io'}, $fh,
260 delete($self->{hdr_buf}));
261 } else { # for synchronous PSGI servers
262 require PublicInbox::GetlineBody;
263 my $buf = delete $self->{hdr_buf};
264 $r->[2] = PublicInbox::GetlineBody->new($self->{rpipe},
265 \&event_step, $self, $$buf, $filter);
270 sub psgi_return_start { # may run later, much later...
272 if (my $cb = $self->{psgi_env}->{'pi-httpd.async'}) {
273 # PublicInbox::HTTPD::Async->new(rpipe, $cb, $cb_arg, $end_obj)
274 $self->{async} = $cb->($self->{rpipe},
275 \&psgi_return_init_cb, $self, $self);
276 } else { # generic PSGI
277 psgi_return_init_cb($self) while $self->{parse_hdr};
281 # Used for streaming the stdout of one process as a PSGI response.
283 # $env is the PSGI env.
284 # optional keys in $env:
285 # $env->{'qspawn.wcb'} - the write callback from the PSGI server
286 # optional, use this if you've already
287 # captured it elsewhere. If not given,
288 # psgi_return will return an anonymous
289 # sub for the PSGI server to call
291 # $env->{'qspawn.filter'} - filter object, responds to ->attach for
292 # pi-httpd.async and ->translate for generic
295 # $limiter - the Limiter object to use (uses the def_limiter if not given)
297 # $parse_hdr - Initial read function; often for parsing CGI header output.
298 # It will be given the return value of sysread from the pipe
299 # and a string ref of the current buffer. Returns an arrayref
300 # for PSGI responses. 2-element arrays in PSGI mean the
301 # body will be streamed, later, via writes (push-based) to
302 # psgix.io. 3-element arrays means the body is available
303 # immediately (or streamed via ->getline (pull-based)).
305 my ($self, $env, $limiter, $parse_hdr, $hdr_arg) = @_;
306 $self->{psgi_env} = $env;
307 $self->{hdr_buf} = \(my $hdr_buf = '');
308 $self->{parse_hdr} = [ $parse_hdr, $hdr_arg ];
309 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
311 # the caller already captured the PSGI write callback from
312 # the PSGI server, so we can call ->start, here:
313 $env->{'qspawn.wcb'} and
314 return start($self, $limiter, \&psgi_return_start);
316 # the caller will return this sub to the PSGI server, so
317 # it can set the response callback (that is, for
318 # PublicInbox::HTTP, the chunked_wcb or identity_wcb callback),
319 # but other HTTP servers are supported:
321 $env->{'qspawn.wcb'} = $_[0];
322 start($self, $limiter, \&psgi_return_start);
326 package PublicInbox::Qspawn::Limiter;
331 my ($class, $max) = @_;
333 # 32 is same as the git-daemon connection limit
337 # RLIMIT_CPU => undef,
338 # RLIMIT_DATA => undef,
339 # RLIMIT_CORE => undef,
344 my ($self, $name, $cfg) = @_;
345 foreach my $rlim (@PublicInbox::Spawn::RLIMITS) {
348 $k = "publicinboxlimiter.$name.$k";
349 defined(my $v = $cfg->{$k}) or next;
350 my @rlimit = split(/\s*,\s*/, $v);
351 if (scalar(@rlimit) == 1) {
352 push @rlimit, $rlimit[0];
353 } elsif (scalar(@rlimit) != 2) {
354 warn "could not parse $k: $v\n";
356 eval { require BSD::Resource };
358 warn "BSD::Resource missing for $rlim";
361 foreach my $i (0..$#rlimit) {
362 next if $rlimit[$i] ne 'INFINITY';
363 $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
365 $self->{$rlim} = \@rlimit;