1 # Copyright (C) 2016-2020 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);
31 # n.b.: we get EAGAIN with public-inbox-httpd, and EINTR on other PSGI servers
32 use Errno qw(EAGAIN EINTR);
36 # declares a command to spawn (but does not spawn it).
37 # $cmd is the command to spawn
38 # $cmd_env is the environ for the child process (not PSGI env)
39 # $opt can include redirects and perhaps other process spawning options
41 my ($class, $cmd, $cmd_env, $opt) = @_;
42 bless { args => [ $cmd, $cmd_env, $opt ] }, $class;
46 my ($self, $start_cb, $limiter) = @_;
48 my ($cmd, $cmd_env, $opt) = @{$self->{args}};
49 my %o = %{$opt || {}};
50 $self->{limiter} = $limiter;
51 foreach my $k (PublicInbox::Spawn::RLIMITS()) {
52 if (defined(my $rlimit = $limiter->{$k})) {
57 # popen_rd may die on EMFILE, ENFILE
58 ($self->{rpipe}, $self->{pid}) = popen_rd($cmd, $cmd_env, \%o);
59 $self->{args} = $o{quiet} ? undef : $cmd;
61 die "E: $!" unless defined($self->{pid});
63 $limiter->{running}++;
64 $start_cb->($self); # EPOLL_CTL_ADD may ENOSPC/ENOMEM
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 $self->{err} .= "; $err";
116 if ($env && $self->{args}) {
117 log_err($env, join(' ', @{$self->{args}}) . ": $err");
120 eval { $qx_cb->($qx_buf, $qx_arg) } if $qx_cb;
125 my $pid = $self->{pid};
126 # PublicInbox::DS may not be loaded
127 eval { PublicInbox::DS::dwaitpid($pid, \&waitpid_err, $self) };
128 # done if we're running in PublicInbox::DS::EventLoop
130 # non public-inbox-{httpd,nntpd} callers may block:
131 my $ret = waitpid($pid, 0);
132 waitpid_err($self, $ret);
138 if (delete $self->{rpipe}) {
141 my ($env, $qx_cb, $qx_arg, $qx_buf) =
142 delete @$self{qw(psgi_env qx_cb qx_arg qx_buf)};
143 eval { $qx_cb->($qx_buf, $qx_arg) } if $qx_cb;
148 my ($self, $limiter, $start_cb) = @_;
149 if ($limiter->{running} < $limiter->{max}) {
150 _do_spawn($self, $start_cb, $limiter);
152 push @{$limiter->{run_queue}}, [ $self, $start_cb ];
156 sub psgi_qx_init_cb {
158 my $async = delete $self->{async};
160 my $qx_fh = $self->{qx_fh};
162 $r = sysread($self->{rpipe}, $buf, 65536);
164 $async->async_pass($self->{psgi_env}->{'psgix.io'},
166 } elsif (defined $r) {
167 $r ? (print $qx_fh $buf) : event_step($self, undef);
169 return if $! == EAGAIN; # try again when notified
170 goto reread if $! == EINTR;
171 event_step($self, $!);
177 if (my $async = $self->{psgi_env}->{'pi-httpd.async'}) {
178 # PublicInbox::HTTPD::Async->new(rpipe, $cb, cb_arg, $end_obj)
179 $self->{async} = $async->($self->{rpipe},
180 \&psgi_qx_init_cb, $self, $self);
181 # init_cb will call ->async_pass or ->close
182 } else { # generic PSGI
183 psgi_qx_init_cb($self) while $self->{qx_fh};
187 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
188 # the stdout of the given command when done; but respects the given limiter
189 # $env is the PSGI env. As with ``/qx; only use this when output is small
192 my ($self, $env, $limiter, $qx_cb, $qx_arg) = @_;
193 $self->{psgi_env} = $env;
195 open(my $qx_fh, '+>', \$qx_buf) or die; # PerlIO::scalar
196 $self->{qx_cb} = $qx_cb;
197 $self->{qx_arg} = $qx_arg;
198 $self->{qx_fh} = $qx_fh;
199 $self->{qx_buf} = \$qx_buf;
200 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
201 start($self, $limiter, \&psgi_qx_start);
204 # this is called on pipe EOF to reap the process, may be called
205 # via PublicInbox::DS event loop OR via GetlineBody for generic
208 my ($self, $err) = @_; # $err: $!
209 log_err($self->{psgi_env}, "psgi_{return,qx} $err") if defined($err);
211 my ($fh, $qx_fh) = delete(@$self{qw(fh qx_fh)});
212 $fh->close if $fh; # async-only (psgi_return)
217 # typically used for reading CGI headers
218 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
219 # We also need to check EINTR for generic PSGI servers.
222 my $hdr_buf = $self->{hdr_buf};
223 my ($ph_cb, $ph_arg) = @{$self->{parse_hdr}};
225 my $r = sysread($self->{rpipe}, $$hdr_buf, 4096,
229 $ret = $ph_cb->($total_rd, $hdr_buf, $ph_arg);
231 # caller should notify us when it's ready:
232 return if $! == EAGAIN;
233 next if $! == EINTR; # immediate retry
234 log_err($self->{psgi_env}, "error reading header: $!");
235 $ret = [ 500, [], [ "Internal error\n" ] ];
237 } until (defined $ret);
238 delete $self->{parse_hdr}; # done parsing headers
242 sub psgi_return_init_cb {
244 my $r = rd_hdr($self) or return;
245 my $env = $self->{psgi_env};
246 my $wcb = delete $env->{'qspawn.wcb'};
247 my $async = delete $self->{async};
248 if (scalar(@$r) == 3) { # error
250 # calls rpipe->close && ->event_step
253 $self->{rpipe}->close;
258 # done reading headers, handoff to read body
259 my $fh = $wcb->($r); # scalar @$r == 2
261 $async->async_pass($env->{'psgix.io'}, $fh,
262 delete($self->{hdr_buf}));
263 } else { # for synchronous PSGI servers
264 require PublicInbox::GetlineBody;
265 $r->[2] = PublicInbox::GetlineBody->new($self->{rpipe},
267 ${$self->{hdr_buf}});
271 # Workaround a leak under Perl 5.16.3 when combined with
272 # Plack::Middleware::Deflater:
276 sub psgi_return_start { # may run later, much later...
278 if (my $async = $self->{psgi_env}->{'pi-httpd.async'}) {
279 # PublicInbox::HTTPD::Async->new(rpipe, $cb, $cb_arg, $end_obj)
280 $self->{async} = $async->($self->{rpipe},
281 \&psgi_return_init_cb, $self, $self);
282 } else { # generic PSGI
283 psgi_return_init_cb($self) while $self->{parse_hdr};
287 # Used for streaming the stdout of one process as a PSGI response.
289 # $env is the PSGI env.
290 # optional keys in $env:
291 # $env->{'qspawn.wcb'} - the write callback from the PSGI server
292 # optional, use this if you've already
293 # captured it elsewhere. If not given,
294 # psgi_return will return an anonymous
295 # sub for the PSGI server to call
297 # $limiter - the Limiter object to use (uses the def_limiter if not given)
299 # $parse_hdr - Initial read function; often for parsing CGI header output.
300 # It will be given the return value of sysread from the pipe
301 # and a string ref of the current buffer. Returns an arrayref
302 # for PSGI responses. 2-element arrays in PSGI mean the
303 # body will be streamed, later, via writes (push-based) to
304 # psgix.io. 3-element arrays means the body is available
305 # immediately (or streamed via ->getline (pull-based)).
307 my ($self, $env, $limiter, $parse_hdr, $hdr_arg) = @_;
308 $self->{psgi_env} = $env;
309 $self->{hdr_buf} = \(my $hdr_buf = '');
310 $self->{parse_hdr} = [ $parse_hdr, $hdr_arg ];
311 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
313 # the caller already captured the PSGI write callback from
314 # the PSGI server, so we can call ->start, here:
315 $env->{'qspawn.wcb'} and
316 return start($self, $limiter, \&psgi_return_start);
318 # the caller will return this sub to the PSGI server, so
319 # it can set the response callback (that is, for
320 # PublicInbox::HTTP, the chunked_wcb or identity_wcb callback),
321 # but other HTTP servers are supported:
323 $env->{'qspawn.wcb'} = $_[0];
324 start($self, $limiter, \&psgi_return_start);
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;