1 # Copyright (C) 2016-2019 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 PublicInbox::DS or any other external
16 # scheduling mechanism, you just need to call start() and finish()
17 # appropriately. However, public-inbox-httpd (which uses PublicInbox::DS)
18 # will be able to schedule this based on readability of stdout from
19 # the spawned process. See GitHTTPBackend.pm and SolverGit.pm for
20 # usage examples. It does not depend on any form of threading.
22 # This is useful for scheduling CGI execution of both long-lived
23 # git-http-backend(1) process (for "git clone") as well as short-lived
24 # processes such as git-apply(1).
26 package PublicInbox::Qspawn;
29 use PublicInbox::Spawn qw(popen_rd);
32 # n.b.: we get EAGAIN with public-inbox-httpd, and EINTR on other PSGI servers
33 use Errno qw(EAGAIN EINTR);
37 # declares a command to spawn (but does not spawn it).
38 # $cmd is the command to spawn
39 # $cmd_env is the environ for the child process (not PSGI env)
40 # $opt can include redirects and perhaps other process spawning options
42 my ($class, $cmd, $cmd_env, $opt) = @_;
43 bless { args => [ $cmd, $cmd_env, $opt ] }, $class;
47 my ($self, $start_cb, $limiter) = @_;
49 my ($cmd, $cmd_env, $opts) = @{$self->{args}};
50 my %opts = %{$opts || {}};
51 $self->{limiter} = $limiter;
52 foreach my $k (PublicInbox::Spawn::RLIMITS()) {
53 if (defined(my $rlimit = $limiter->{$k})) {
58 ($self->{rpipe}, $self->{pid}) = popen_rd($cmd, $cmd_env, \%opts);
60 # drop any IO handles opt was holding open via $opt->{hold}
61 # No need to hold onto the descriptor once the child process has it.
62 $self->{args} = $cmd; # keep this around for logging
64 if (defined $self->{pid}) {
65 $limiter->{running}++;
69 $start_cb->($self->{rpipe});
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;
83 $env->{'psgi.errors'}->print($msg, "\n");
86 # callback for dwaitpid
87 sub waitpid_err ($$) {
88 my ($self, $pid) = @_;
89 my $xpid = delete $self->{pid};
91 if ($pid > 0) { # success!
93 } elsif ($pid < 0) { # ??? does this happen in our case?
94 $err = "W: waitpid($xpid, 0) => $pid: $!";
95 } # else should not be called with pid == 0
97 my ($env, $qx_cb, $qx_arg, $qx_buf) =
98 delete @$self{qw(psgi_env qx_cb qx_arg qx_buf)};
100 # done, spawn whatever's in the queue
101 my $limiter = $self->{limiter};
102 my $running = --$limiter->{running};
104 if ($running < $limiter->{max}) {
105 if (my $next = shift(@{$limiter->{run_queue}})) {
106 _do_spawn(@$next, $limiter);
112 if ($env && !$env->{'qspawn.quiet'}) {
113 log_err($env, join(' ', @{$self->{args}}) . ": $err");
116 eval { $qx_cb->($qx_buf, $qx_arg) } if $qx_cb;
121 my $pid = $self->{pid};
122 # PublicInbox::DS may not be loaded
123 eval { PublicInbox::DS::dwaitpid($pid, \&waitpid_err, $self) };
124 # done if we're running in PublicInbox::DS::EventLoop
126 # non public-inbox-{httpd,nntpd} callers may block:
127 my $ret = waitpid($pid, 0);
128 waitpid_err($self, $ret);
134 if (delete $self->{rpipe}) {
137 my ($env, $qx_cb, $qx_arg, $qx_buf) =
138 delete @$self{qw(psgi_env qx_cb qx_arg qx_buf)};
139 eval { $qx_cb->($qx_buf, $qx_arg) } if $qx_cb;
144 my ($self, $limiter, $start_cb) = @_;
145 if ($limiter->{running} < $limiter->{max}) {
146 _do_spawn($self, $start_cb, $limiter);
148 push @{$limiter->{run_queue}}, [ $self, $start_cb ];
152 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
153 # the stdout of the given command when done; but respects the given limiter
154 # $env is the PSGI env. As with ``/qx; only use this when output is small
157 my ($self, $env, $limiter, $qx_cb, $qx_arg) = @_;
158 $self->{psgi_env} = $env;
160 open(my $qx_fh, '+>', \$qx_buf) or die; # PerlIO::scalar
161 $self->{qx_cb} = $qx_cb;
162 $self->{qx_arg} = $qx_arg;
163 $self->{qx_fh} = $qx_fh;
164 $self->{qx_buf} = \$qx_buf;
165 my $rpipe; # comes from popen_rd
166 my $async = $env->{'pi-httpd.async'};
170 $r = sysread($rpipe, $buf, 65536);
172 $async->async_pass($env->{'psgix.io'}, $qx_fh, \$buf);
173 } elsif (defined $r) {
174 $r ? $qx_fh->write($buf) : event_step($self, undef);
176 return if $! == EAGAIN; # try again when notified
177 goto reread if $! == EINTR;
178 event_step($self, $!);
181 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
182 $self->start($limiter, sub { # start_cb, may run later, much later...
183 ($rpipe) = @_; # popen_rd result
185 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end_obj)
186 $async = $async->($rpipe, $cb, undef, $self);
187 # $cb will call ->async_pass or ->close
188 } else { # generic PSGI
189 $cb->() while $self->{qx_fh};
194 # create a filter for "push"-based streaming PSGI writes used by HTTPD::Async
196 my ($fh, $filter) = @_;
197 Plack::Util::inline_object(
199 $fh->write($filter->(undef));
203 $fh->write($filter->($_[0]));
207 # this is called on pipe EOF to reap the process, may be called
208 # via PublicInbox::DS event loop OR via GetlineBody for generic
211 my ($self, $err) = @_; # $err: $!
212 log_err($self->{psgi_env}, "psgi_{return,qx} $err") if defined($err);
214 my ($fh, $qx_fh) = delete(@$self{qw(fh qx_fh)});
215 $fh->close if $fh; # async-only (psgi_return)
218 # Used for streaming the stdout of one process as a PSGI response.
220 # $env is the PSGI env.
221 # optional keys in $env:
222 # $env->{'qspawn.wcb'} - the write callback from the PSGI server
223 # optional, use this if you've already
224 # captured it elsewhere. If not given,
225 # psgi_return will return an anonymous
226 # sub for the PSGI server to call
228 # $env->{'qspawn.filter'} - filter callback, receives a string as input,
231 # $limiter - the Limiter object to use (uses the def_limiter if not given)
233 # $parse_hdr - Initial read function; often for parsing CGI header output.
234 # It will be given the return value of sysread from the pipe
235 # and a string ref of the current buffer. Returns an arrayref
236 # for PSGI responses. 2-element arrays in PSGI mean the
237 # body will be streamed, later, via writes (push-based) to
238 # psgix.io. 3-element arrays means the body is available
239 # immediately (or streamed via ->getline (pull-based)).
241 my ($self, $env, $limiter, $parse_hdr) = @_;
242 $self->{psgi_env} = $env;
246 # typically used for reading CGI headers
247 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
248 # We also need to check EINTR for generic PSGI servers.
252 my $r = sysread($rpipe, $buf, 4096, length($buf));
255 $ret = $parse_hdr->($r ? $total_rd : 0, \$buf);
257 # caller should notify us when it's ready:
258 return if $! == EAGAIN;
259 next if $! == EINTR; # immediate retry
260 log_err($env, "error reading header: $!");
261 $ret = [ 500, [], [ "Internal error\n" ] ];
263 } until (defined $ret);
267 my $wcb = delete $env->{'qspawn.wcb'}; # or PSGI server supplies it
268 my $async = $env->{'pi-httpd.async'};
271 my $r = $rd_hdr->() or return;
272 $rd_hdr = undef; # done reading headers
273 my $filter = delete $env->{'qspawn.filter'};
274 if (scalar(@$r) == 3) { # error
276 # calls rpipe->close && ->event_step
284 # done reading headers, handoff to read body
285 my $fh = $wcb->($r); # scalar @$r == 2
286 $fh = filter_fh($fh, $filter) if $filter;
288 $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
289 } else { # for synchronous PSGI servers
290 require PublicInbox::GetlineBody;
291 $r->[2] = PublicInbox::GetlineBody->new($rpipe,
297 # Workaround a leak under Perl 5.16.3 when combined with
298 # Plack::Middleware::Deflater:
301 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
302 my $start_cb = sub { # may run later, much later...
305 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $cb_arg,
307 $async = $async->($rpipe, $cb, undef, $self);
308 # $cb will call ->async_pass or ->close
309 } else { # generic PSGI
310 $cb->() while $rd_hdr;
314 # the caller already captured the PSGI write callback from
315 # the PSGI server, so we can call ->start, here:
316 return $self->start($limiter, $start_cb) if $wcb;
318 # the caller will return this sub to the PSGI server, so
319 # it can set the response callback (that is, for PublicInbox::HTTP,
320 # the chunked_wcb or identity_wcb callback), but other HTTP servers
324 $self->start($limiter, $start_cb);
328 package PublicInbox::Qspawn::Limiter;
333 my ($class, $max) = @_;
335 # 32 is same as the git-daemon connection limit
339 # RLIMIT_CPU => undef,
340 # RLIMIT_DATA => undef,
341 # RLIMIT_CORE => undef,
346 my ($self, $name, $config) = @_;
347 foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
350 $k = "publicinboxlimiter.$name.$k";
351 defined(my $v = $config->{$k}) or next;
352 my @rlimit = split(/\s*,\s*/, $v);
353 if (scalar(@rlimit) == 1) {
354 push @rlimit, $rlimit[0];
355 } elsif (scalar(@rlimit) != 2) {
356 warn "could not parse $k: $v\n";
358 eval { require BSD::Resource };
360 warn "BSD::Resource missing for $rlim";
363 foreach my $i (0..$#rlimit) {
364 next if $rlimit[$i] ne 'INFINITY';
365 $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
367 $self->{$rlim} = \@rlimit;