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);
30 use POSIX qw(WNOHANG);
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 # $env is the environ for the child process
41 # $opt can include redirects and perhaps other process spawning options
43 my ($class, $cmd, $env, $opt) = @_;
44 bless { args => [ $cmd, $env, $opt ] }, $class;
50 my ($cmd, $env, $opts) = @{$self->{args}};
51 my %opts = %{$opts || {}};
52 my $limiter = $self->{limiter};
53 foreach my $k (PublicInbox::Spawn::RLIMITS()) {
54 if (defined(my $rlimit = $limiter->{$k})) {
59 ($self->{rpipe}, $self->{pid}) = popen_rd($cmd, $env, \%opts);
60 if (defined $self->{pid}) {
61 $limiter->{running}++;
65 $cb->($self->{rpipe});
69 my ($child_error) = @_; # typically $?
70 my $exitstatus = ($child_error >> 8) or return;
71 my $sig = $child_error & 127;
72 my $msg = "exit status=$exitstatus";
73 $msg .= " signal=$sig" if $sig;
77 # callback for dwaitpid
78 sub waitpid_err ($$) {
79 my ($self, $pid) = @_;
80 my $xpid = delete $self->{pid};
82 if ($pid > 0) { # success!
84 } elsif ($pid < 0) { # ??? does this happen in our case?
85 $err = "W: waitpid($xpid, 0) => $pid: $!";
86 } # else should not be called with pid == 0
88 # done, spawn whatever's in the queue
89 my $limiter = $self->{limiter};
90 my $running = --$limiter->{running};
92 # limiter->{max} may change dynamically
93 if (($running || $limiter->{running}) < $limiter->{max}) {
94 if (my $next = shift @{$limiter->{run_queue}}) {
101 my $env = $self->{env} or return;
102 if (!$env->{'qspawn.quiet'}) {
103 $err = join(' ', @{$self->{args}->[0]}).": $err\n";
104 $env->{'psgi.errors'}->print($err);
108 sub do_waitpid ($;$) {
109 my ($self, $env) = @_;
110 my $pid = $self->{pid};
111 eval { # PublicInbox::DS may not be loaded
112 PublicInbox::DS::dwaitpid($pid, \&waitpid_err, $self);
115 # done if we're running in PublicInbox::DS::EventLoop
117 # non public-inbox-{httpd,nntpd} callers may block:
118 my $ret = waitpid($pid, 0);
119 waitpid_err($self, $ret);
124 my ($self, $env) = @_;
125 if (delete $self->{rpipe}) {
126 do_waitpid($self, $env);
129 # limiter->{max} may change dynamically
130 my $limiter = $self->{limiter};
131 if ($limiter->{running} < $limiter->{max}) {
132 if (my $next = shift @{$limiter->{run_queue}}) {
136 $self->{err}; # may be meaningless if non-blocking
140 my ($self, $limiter, $cb) = @_;
141 $self->{limiter} = $limiter;
143 if ($limiter->{running} < $limiter->{max}) {
144 _do_spawn($self, $cb);
146 push @{$limiter->{run_queue}}, [ $self, $cb ];
150 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
151 # the stdout of the given command when done; but respects the given limiter
152 # $env is the PSGI env. As with ``/qx; only use this when output is small
155 my ($self, $env, $limiter, $qx_cb) = @_;
157 open(my $qx, '+>', \$scalar) or die; # PerlIO::scalar
160 eval { $qx_cb->(\$scalar) };
161 $qx = $scalar = undef;
163 my $rpipe; # comes from popen_rd
164 my $async = $env->{'pi-httpd.async'};
166 my $r = sysread($rpipe, my $buf, 65536);
168 $async->async_pass($env->{'psgix.io'}, $qx, \$buf);
169 } elsif (defined $r) {
170 $r ? $qx->write($buf) : $end->();
172 return if $! == EAGAIN || $! == EINTR; # loop again
176 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
177 $self->start($limiter, sub { # may run later, much later...
178 ($rpipe) = @_; # popen_rd result
180 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
181 $async = $async->($rpipe, $cb, $end);
182 } else { # generic PSGI
188 # create a filter for "push"-based streaming PSGI writes used by HTTPD::Async
190 my ($fh, $filter) = @_;
191 Plack::Util::inline_object(
193 $fh->write($filter->(undef));
197 $fh->write($filter->($_[0]));
201 # Used for streaming the stdout of one process as a PSGI response.
203 # $env is the PSGI env.
204 # optional keys in $env:
205 # $env->{'qspawn.wcb'} - the write callback from the PSGI server
206 # optional, use this if you've already
207 # captured it elsewhere. If not given,
208 # psgi_return will return an anonymous
209 # sub for the PSGI server to call
211 # $env->{'qspawn.filter'} - filter callback, receives a string as input,
214 # $limiter - the Limiter object to use (uses the def_limiter if not given)
216 # $parse_hdr - Initial read function; often for parsing CGI header output.
217 # It will be given the return value of sysread from the pipe
218 # and a string ref of the current buffer. Returns an arrayref
219 # for PSGI responses. 2-element arrays in PSGI mean the
220 # body will be streamed, later, via writes (push-based) to
221 # psgix.io. 3-element arrays means the body is available
222 # immediately (or streamed via ->getline (pull-based)).
224 my ($self, $env, $limiter, $parse_hdr) = @_;
228 $fh->close if $fh; # async-only
233 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
234 # We also need to check EINTR for generic PSGI servers.
238 my $r = sysread($rpipe, $buf, 4096, length($buf));
239 return if !defined($r) && $! == EAGAIN || $! == EINTR;
241 # $r may be undef, here:
243 $ret = $parse_hdr->($r ? $n : $r, \$buf);
244 } until (defined $ret);
248 my $wcb = delete $env->{'qspawn.wcb'};
249 my $async = $env->{'pi-httpd.async'};
252 my $r = $rd_hdr->() or return;
254 my $filter = delete $env->{'qspawn.filter'};
255 if (scalar(@$r) == 3) { # error
257 $async->close; # calls rpipe->close and $end
264 $fh = $wcb->($r); # scalar @$r == 2
265 $fh = filter_fh($fh, $filter) if $filter;
266 $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
267 } else { # for synchronous PSGI servers
268 require PublicInbox::GetlineBody;
269 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
274 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
275 my $start_cb = sub { # may run later, much later...
278 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
279 $async = $async->($rpipe, $cb, $end);
280 } else { # generic PSGI
281 $cb->() while $rd_hdr;
285 # the caller already captured the PSGI write callback from
286 # the PSGI server, so we can call ->start, here:
287 return $self->start($limiter, $start_cb) if $wcb;
289 # the caller will return this sub to the PSGI server, so
290 # it can set the response callback (that is, for PublicInbox::HTTP,
291 # the chunked_wcb or identity_wcb callback), but other HTTP servers
295 $self->start($limiter, $start_cb);
299 package PublicInbox::Qspawn::Limiter;
304 my ($class, $max) = @_;
306 # 32 is same as the git-daemon connection limit
310 # RLIMIT_CPU => undef,
311 # RLIMIT_DATA => undef,
312 # RLIMIT_CORE => undef,
317 my ($self, $name, $config) = @_;
318 foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
321 $k = "publicinboxlimiter.$name.$k";
322 defined(my $v = $config->{$k}) or next;
323 my @rlimit = split(/\s*,\s*/, $v);
324 if (scalar(@rlimit) == 1) {
325 push @rlimit, $rlimit[0];
326 } elsif (scalar(@rlimit) != 2) {
327 warn "could not parse $k: $v\n";
329 eval { require BSD::Resource };
331 warn "BSD::Resource missing for $rlim";
334 foreach my $i (0..$#rlimit) {
335 next if $rlimit[$i] ne 'INFINITY';
336 $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
338 $self->{$rlim} = \@rlimit;