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;
29 use PublicInbox::Spawn qw(popen_rd);
30 use PublicInbox::GzipFilter;
31 use PublicInbox::DS qw(awaitpid);
32 use Scalar::Util qw(blessed);
34 # n.b.: we get EAGAIN with public-inbox-httpd, and EINTR on other PSGI servers
35 use Errno qw(EAGAIN EINTR);
39 # declares a command to spawn (but does not spawn it).
40 # $cmd is the command to spawn
41 # $cmd_env is the environ for the child process (not PSGI env)
42 # $opt can include redirects and perhaps other process spawning options
43 # {qsp_err} is an optional error buffer callers may access themselves
45 my ($class, $cmd, $cmd_env, $opt) = @_;
46 bless { args => [ $cmd, $cmd_env, $opt ] }, $class;
50 my ($self, $start_cb, $limiter) = @_;
52 my ($cmd, $cmd_env, $opt) = @{delete $self->{args}};
53 my %o = %{$opt || {}};
54 $self->{limiter} = $limiter;
55 foreach my $k (@PublicInbox::Spawn::RLIMITS) {
56 if (defined(my $rlimit = $limiter->{$k})) {
60 $self->{cmd} = $o{quiet} ? undef : $cmd;
61 $o{cb_arg} = [ \&waitpid_err, $self ];
63 # popen_rd may die on EMFILE, ENFILE
64 $self->{rpipe} = popen_rd($cmd, $cmd_env, \%o) // die "E: $!";
65 $limiter->{running}++;
66 $start_cb->($self); # EPOLL_CTL_ADD may ENOSPC/ENOMEM
68 finish($self, $@) if $@;
74 # process is done, spawn whatever's in the queue
75 my $limiter = delete $self->{limiter} or return;
76 my $running = --$limiter->{running};
78 if ($running < $limiter->{max}) {
79 if (my $next = shift(@{$limiter->{run_queue}})) {
80 _do_spawn(@$next, $limiter);
83 if (my $err = $self->{_err}) { # set by finish or waitpid_err
85 if (my $dst = $self->{qsp_err}) {
86 $$dst .= $$dst ? " $err" : "; $err";
88 warn "@{$self->{cmd}}: $err" if $self->{cmd};
91 my ($env, $qx_cb, $qx_arg, $qx_buf) =
92 delete @$self{qw(psgi_env qx_cb qx_arg qx_buf)};
94 eval { $qx_cb->($qx_buf, $qx_arg) };
96 warn "E: $@"; # hope qspawn.wcb can handle it
98 return if $self->{passed}; # another command chained it
99 if (my $wcb = delete $env->{'qspawn.wcb'}) {
100 # have we started writing, yet?
101 my $code = delete $env->{'qspawn.fallback'} // 500;
102 require PublicInbox::WwwStatic;
103 $wcb->(PublicInbox::WwwStatic::r($code));
107 sub waitpid_err { # callback for awaitpid
108 my (undef, $self) = @_; # $_[0]: pid
109 $self->{_err} = ''; # for defined check in ->finish
111 my $status = $? >> 8;
113 $self->{_err} .= "exit status=$status";
114 $self->{_err} .= " signal=$sig" if $sig;
116 finalize($self) if !$self->{rpipe};
120 my ($self, $err) = @_;
121 $self->{_err} //= $err; # only for $@
123 # we can safely finalize if pipe was closed before, or if
124 # {_err} is defined by waitpid_err. Deleting {rpipe} will
125 # trigger PublicInbox::ProcessPipe::DESTROY -> waitpid_err,
126 # but it may not fire right away if inside the event loop.
127 my $closed_before = !delete($self->{rpipe});
128 finalize($self) if $closed_before || defined($self->{_err});
132 my ($self, $limiter, $start_cb) = @_;
133 if ($limiter->{running} < $limiter->{max}) {
134 _do_spawn($self, $start_cb, $limiter);
136 push @{$limiter->{run_queue}}, [ $self, $start_cb ];
140 sub psgi_qx_init_cb { # this may be PublicInbox::HTTPD::Async {cb}
142 my $async = delete $self->{async}; # PublicInbox::HTTPD::Async
144 my $qx_fh = $self->{qx_fh};
146 $r = sysread($self->{rpipe}, $buf, 65536);
148 $async->async_pass($self->{psgi_env}->{'psgix.io'},
150 } elsif (defined $r) {
151 $r ? (print $qx_fh $buf) : event_step($self, undef);
153 return if $! == EAGAIN; # try again when notified
154 goto reread if $! == EINTR;
155 event_step($self, $!);
161 if (my $async = $self->{psgi_env}->{'pi-httpd.async'}) {
162 # PublicInbox::HTTPD::Async->new(rpipe, $cb, cb_arg, $end_obj)
163 $self->{async} = $async->($self->{rpipe},
164 \&psgi_qx_init_cb, $self, $self);
165 # init_cb will call ->async_pass or ->close
166 } else { # generic PSGI
167 psgi_qx_init_cb($self) while $self->{qx_fh};
171 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
172 # the stdout of the given command when done; but respects the given limiter
173 # $env is the PSGI env. As with ``/qx; only use this when output is small
176 my ($self, $env, $limiter, $qx_cb, $qx_arg) = @_;
177 $self->{psgi_env} = $env;
179 open(my $qx_fh, '+>', \$qx_buf) or die; # PerlIO::scalar
180 $self->{qx_cb} = $qx_cb;
181 $self->{qx_arg} = $qx_arg;
182 $self->{qx_fh} = $qx_fh;
183 $self->{qx_buf} = \$qx_buf;
184 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
185 start($self, $limiter, \&psgi_qx_start);
188 # this is called on pipe EOF to reap the process, may be called
189 # via PublicInbox::DS event loop OR via GetlineBody for generic
192 my ($self, $err) = @_; # $err: $!
193 warn "psgi_{return,qx} $err" if defined($err);
195 my ($fh, $qx_fh) = delete(@$self{qw(qfh qx_fh)});
196 $fh->close if $fh; # async-only (psgi_return)
201 # typically used for reading CGI headers
202 # We also need to check EINTR for generic PSGI servers.
205 my $hdr_buf = $self->{hdr_buf};
206 my ($ph_cb, $ph_arg) = @{$self->{parse_hdr}};
207 until (defined($ret)) {
208 my $r = sysread($self->{rpipe}, $$hdr_buf, 4096,
212 eval { $ret = $ph_cb->($total_rd, $hdr_buf, $ph_arg) };
214 warn "parse_hdr: $@";
215 $ret = [ 500, [], [ "Internal error\n" ] ];
216 } elsif (!defined($ret) && !$r) {
217 my $cmd = $self->{cmd} // [ '(?)' ];
219 EOF parsing headers from @$cmd ($self->{psgi_env}->{REQUEST_URI})
221 $ret = [ 500, [], [ "Internal error\n" ] ];
224 # caller should notify us when it's ready:
225 return if $! == EAGAIN;
226 next if $! == EINTR; # immediate retry
227 warn "error reading header: $!";
228 $ret = [ 500, [], [ "Internal error\n" ] ];
231 delete $self->{parse_hdr}; # done parsing headers
235 sub psgi_return_init_cb { # this may be PublicInbox::HTTPD::Async {cb}
237 my $r = rd_hdr($self) or return;
238 my $env = $self->{psgi_env};
241 # this is for RepoAtom since that can fire after parse_cgi_headers
242 if (ref($r) eq 'ARRAY' && blessed($r->[2]) && $r->[2]->can('attach')) {
245 $filter //= delete($env->{'qspawn.filter'}) // (ref($r) eq 'ARRAY' ?
246 PublicInbox::GzipFilter::qsp_maybe($r->[1], $env) : undef);
248 my $wcb = delete $env->{'qspawn.wcb'};
249 my $async = delete $self->{async}; # PublicInbox::HTTPD::Async
250 if (ref($r) ne 'ARRAY' || scalar(@$r) == 3) { # error
251 if ($async) { # calls rpipe->close && ->event_step
252 $async->close; # PublicInbox::HTTPD::Async::close
253 } else { # generic PSGI, use PublicInbox::ProcessPipe::CLOSE
254 delete($self->{rpipe})->close;
257 if (ref($r) eq 'ARRAY') { # error
259 } elsif (ref($r) eq 'CODE') { # chain another command
265 # done reading headers, handoff to read body
266 my $fh = $wcb->($r); # scalar @$r == 2
267 $fh = $filter->attach($fh) if $filter;
269 $async->async_pass($env->{'psgix.io'}, $fh,
270 delete($self->{hdr_buf}));
271 } else { # for synchronous PSGI servers
272 require PublicInbox::GetlineBody;
273 my $buf = delete $self->{hdr_buf};
274 $r->[2] = PublicInbox::GetlineBody->new($self->{rpipe},
275 \&event_step, $self, $$buf, $filter);
280 sub psgi_return_start { # may run later, much later...
282 if (my $cb = $self->{psgi_env}->{'pi-httpd.async'}) {
283 # PublicInbox::HTTPD::Async->new(rpipe, $cb, $cb_arg, $end_obj)
284 $self->{async} = $cb->($self->{rpipe},
285 \&psgi_return_init_cb, $self, $self);
286 } else { # generic PSGI
287 psgi_return_init_cb($self) while $self->{parse_hdr};
291 # Used for streaming the stdout of one process as a PSGI response.
293 # $env is the PSGI env.
294 # optional keys in $env:
295 # $env->{'qspawn.wcb'} - the write callback from the PSGI server
296 # optional, use this if you've already
297 # captured it elsewhere. If not given,
298 # psgi_return will return an anonymous
299 # sub for the PSGI server to call
301 # $env->{'qspawn.filter'} - filter object, responds to ->attach for
302 # pi-httpd.async and ->translate for generic
305 # $limiter - the Limiter object to use (uses the def_limiter if not given)
307 # $parse_hdr - Initial read function; often for parsing CGI header output.
308 # It will be given the return value of sysread from the pipe
309 # and a string ref of the current buffer. Returns an arrayref
310 # for PSGI responses. 2-element arrays in PSGI mean the
311 # body will be streamed, later, via writes (push-based) to
312 # psgix.io. 3-element arrays means the body is available
313 # immediately (or streamed via ->getline (pull-based)).
315 my ($self, $env, $limiter, $parse_hdr, $hdr_arg) = @_;
316 $self->{psgi_env} = $env;
317 $self->{hdr_buf} = \(my $hdr_buf = '');
318 $self->{parse_hdr} = [ $parse_hdr, $hdr_arg ];
319 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
321 # the caller already captured the PSGI write callback from
322 # the PSGI server, so we can call ->start, here:
323 $env->{'qspawn.wcb'} and
324 return start($self, $limiter, \&psgi_return_start);
326 # the caller will return this sub to the PSGI server, so
327 # it can set the response callback (that is, for
328 # PublicInbox::HTTP, the chunked_wcb or identity_wcb callback),
329 # but other HTTP servers are supported:
331 $env->{'qspawn.wcb'} = $_[0];
332 start($self, $limiter, \&psgi_return_start);
336 package PublicInbox::Qspawn::Limiter;
340 my ($class, $max) = @_;
342 # 32 is same as the git-daemon connection limit
346 # RLIMIT_CPU => undef,
347 # RLIMIT_DATA => undef,
348 # RLIMIT_CORE => undef,
353 my ($self, $name, $cfg) = @_;
354 foreach my $rlim (@PublicInbox::Spawn::RLIMITS) {
357 $k = "publicinboxlimiter.$name.$k";
358 defined(my $v = $cfg->{$k}) or next;
359 my @rlimit = split(/\s*,\s*/, $v);
360 if (scalar(@rlimit) == 1) {
361 push @rlimit, $rlimit[0];
362 } elsif (scalar(@rlimit) != 2) {
363 warn "could not parse $k: $v\n";
365 eval { require BSD::Resource };
367 warn "BSD::Resource missing for $rlim";
370 foreach my $i (0..$#rlimit) {
371 next if $rlimit[$i] ne 'INFINITY';
372 $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
374 $self->{$rlim} = \@rlimit;