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 # $env is the environ for the child process
40 # $opt can include redirects and perhaps other process spawning options
42 my ($class, $cmd, $env, $opt) = @_;
43 bless { args => [ $cmd, $env, $opt ] }, $class;
47 my ($self, $start_cb, $limiter) = @_;
49 my ($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, $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 = delete $self->{env};
99 # done, spawn whatever's in the queue
100 my $limiter = $self->{limiter};
101 my $running = --$limiter->{running};
103 if ($running < $limiter->{max}) {
104 if (my $next = shift(@{$limiter->{run_queue}})) {
105 _do_spawn(@$next, $limiter);
111 if ($env && !$env->{'qspawn.quiet'}) {
112 log_err($env, join(' ', @{$self->{args}}) . ": $err");
116 sub do_waitpid ($;$) {
117 my ($self, $env) = @_;
118 my $pid = $self->{pid};
120 # PublicInbox::DS may not be loaded
121 eval { PublicInbox::DS::dwaitpid($pid, \&waitpid_err, $self) };
122 # done if we're running in PublicInbox::DS::EventLoop
124 # non public-inbox-{httpd,nntpd} callers may block:
125 my $ret = waitpid($pid, 0);
126 waitpid_err($self, $ret);
131 my ($self, $env) = @_;
132 if (delete $self->{rpipe}) {
133 do_waitpid($self, $env);
138 my ($self, $limiter, $start_cb) = @_;
139 if ($limiter->{running} < $limiter->{max}) {
140 _do_spawn($self, $start_cb, $limiter);
142 push @{$limiter->{run_queue}}, [ $self, $start_cb ];
146 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
147 # the stdout of the given command when done; but respects the given limiter
148 # $env is the PSGI env. As with ``/qx; only use this when output is small
151 my ($self, $env, $limiter, $qx_cb) = @_;
153 open(my $qx, '+>', \$scalar) or die; # PerlIO::scalar
155 my $err = $_[0]; # $!
156 log_err($env, "psgi_qx: $err") if defined($err);
158 eval { $qx_cb->(\$scalar) };
159 $qx = $scalar = undef;
161 my $rpipe; # comes from popen_rd
162 my $async = $env->{'pi-httpd.async'};
166 $r = sysread($rpipe, $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; # try again when notified
173 goto reread if $! == EINTR;
177 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
178 $self->start($limiter, sub { # start_cb, may run later, much later...
179 ($rpipe) = @_; # popen_rd result
181 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
182 $async = $async->($rpipe, $cb, $end);
183 # $cb will call ->async_pass or ->close
184 } else { # generic PSGI
190 # create a filter for "push"-based streaming PSGI writes used by HTTPD::Async
192 my ($fh, $filter) = @_;
193 Plack::Util::inline_object(
195 $fh->write($filter->(undef));
199 $fh->write($filter->($_[0]));
203 # Used for streaming the stdout of one process as a PSGI response.
205 # $env is the PSGI env.
206 # optional keys in $env:
207 # $env->{'qspawn.wcb'} - the write callback from the PSGI server
208 # optional, use this if you've already
209 # captured it elsewhere. If not given,
210 # psgi_return will return an anonymous
211 # sub for the PSGI server to call
213 # $env->{'qspawn.filter'} - filter callback, receives a string as input,
216 # $limiter - the Limiter object to use (uses the def_limiter if not given)
218 # $parse_hdr - Initial read function; often for parsing CGI header output.
219 # It will be given the return value of sysread from the pipe
220 # and a string ref of the current buffer. Returns an arrayref
221 # for PSGI responses. 2-element arrays in PSGI mean the
222 # body will be streamed, later, via writes (push-based) to
223 # psgix.io. 3-element arrays means the body is available
224 # immediately (or streamed via ->getline (pull-based)).
226 my ($self, $env, $limiter, $parse_hdr) = @_;
229 my $err = $_[0]; # $!
230 log_err($env, "psgi_return: $err") if defined($err);
232 $fh->close if $fh; # async-only
237 # typically used for reading CGI headers
238 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
239 # We also need to check EINTR for generic PSGI servers.
243 my $r = sysread($rpipe, $buf, 4096, length($buf));
246 $ret = $parse_hdr->($r ? $total_rd : 0, \$buf);
248 # caller should notify us when it's ready:
249 return if $! == EAGAIN;
250 next if $! == EINTR; # immediate retry
251 log_err($env, "error reading header: $!");
252 $ret = [ 500, [], [ "Internal error\n" ] ];
254 } until (defined $ret);
258 my $wcb = delete $env->{'qspawn.wcb'}; # or PSGI server supplies it
259 my $async = $env->{'pi-httpd.async'};
262 my $r = $rd_hdr->() or return;
263 $rd_hdr = undef; # done reading headers
264 my $filter = delete $env->{'qspawn.filter'};
265 if (scalar(@$r) == 3) { # error
267 $async->close; # calls rpipe->close and $end
274 # done reading headers, handoff to read body
275 $fh = $wcb->($r); # scalar @$r == 2
276 $fh = filter_fh($fh, $filter) if $filter;
277 $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
278 } else { # for synchronous PSGI servers
279 require PublicInbox::GetlineBody;
280 $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
285 $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
286 my $start_cb = sub { # may run later, much later...
289 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
290 $async = $async->($rpipe, $cb, $end);
291 # $cb will call ->async_pass or ->close
292 } else { # generic PSGI
293 $cb->() while $rd_hdr;
297 # the caller already captured the PSGI write callback from
298 # the PSGI server, so we can call ->start, here:
299 return $self->start($limiter, $start_cb) if $wcb;
301 # the caller will return this sub to the PSGI server, so
302 # it can set the response callback (that is, for PublicInbox::HTTP,
303 # the chunked_wcb or identity_wcb callback), but other HTTP servers
307 $self->start($limiter, $start_cb);
311 package PublicInbox::Qspawn::Limiter;
316 my ($class, $max) = @_;
318 # 32 is same as the git-daemon connection limit
322 # RLIMIT_CPU => undef,
323 # RLIMIT_DATA => undef,
324 # RLIMIT_CORE => undef,
329 my ($self, $name, $config) = @_;
330 foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
333 $k = "publicinboxlimiter.$name.$k";
334 defined(my $v = $config->{$k}) or next;
335 my @rlimit = split(/\s*,\s*/, $v);
336 if (scalar(@rlimit) == 1) {
337 push @rlimit, $rlimit[0];
338 } elsif (scalar(@rlimit) != 2) {
339 warn "could not parse $k: $v\n";
341 eval { require BSD::Resource };
343 warn "BSD::Resource missing for $rlim";
346 foreach my $i (0..$#rlimit) {
347 next if $rlimit[$i] ne 'INFINITY';
348 $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
350 $self->{$rlim} = \@rlimit;