]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Qspawn.pm
qspawn: remove return value from ->finish
[public-inbox.git] / lib / PublicInbox / Qspawn.pm
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>
3
4 # Like most Perl modules in public-inbox, this is internal and
5 # NOT subject to any stability guarantees!  It is only documented
6 # for other hackers.
7 #
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.
14 #
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.
21 #
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).
25
26 package PublicInbox::Qspawn;
27 use strict;
28 use warnings;
29 use PublicInbox::Spawn qw(popen_rd);
30 require Plack::Util;
31
32 # n.b.: we get EAGAIN with public-inbox-httpd, and EINTR on other PSGI servers
33 use Errno qw(EAGAIN EINTR);
34
35 my $def_limiter;
36
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
41 sub new ($$$;) {
42         my ($class, $cmd, $env, $opt) = @_;
43         bless { args => [ $cmd, $env, $opt ] }, $class;
44 }
45
46 sub _do_spawn {
47         my ($self, $cb) = @_;
48         my $err;
49         my ($cmd, $env, $opts) = @{$self->{args}};
50         my %opts = %{$opts || {}};
51         my $limiter = $self->{limiter};
52         foreach my $k (PublicInbox::Spawn::RLIMITS()) {
53                 if (defined(my $rlimit = $limiter->{$k})) {
54                         $opts{$k} = $rlimit;
55                 }
56         }
57
58         ($self->{rpipe}, $self->{pid}) = popen_rd($cmd, $env, \%opts);
59
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
63
64         if (defined $self->{pid}) {
65                 $limiter->{running}++;
66         } else {
67                 $self->{err} = $!;
68         }
69         $cb->($self->{rpipe});
70 }
71
72 sub child_err ($) {
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;
78         $msg;
79 }
80
81 sub log_err ($$) {
82         my ($env, $msg) = @_;
83         $env->{'psgi.errors'}->print($msg, "\n");
84 }
85
86 # callback for dwaitpid
87 sub waitpid_err ($$) {
88         my ($self, $pid) = @_;
89         my $xpid = delete $self->{pid};
90         my $err;
91         if ($pid > 0) { # success!
92                 $err = child_err($?);
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
96
97         # done, spawn whatever's in the queue
98         my $limiter = $self->{limiter};
99         my $running = --$limiter->{running};
100
101         # limiter->{max} may change dynamically
102         if (($running || $limiter->{running}) < $limiter->{max}) {
103                 if (my $next = shift @{$limiter->{run_queue}}) {
104                         _do_spawn(@$next);
105                 }
106         }
107
108         return unless $err;
109         $self->{err} = $err;
110         my $env = $self->{env} or return;
111         if (!$env->{'qspawn.quiet'}) {
112                 log_err($env, join(' ', @{$self->{args}}) . ": $err");
113         }
114 }
115
116 sub do_waitpid ($;$) {
117         my ($self, $env) = @_;
118         my $pid = $self->{pid};
119         eval { # PublicInbox::DS may not be loaded
120                 PublicInbox::DS::dwaitpid($pid, \&waitpid_err, $self);
121                 $self->{env} = $env;
122         };
123         # done if we're running in PublicInbox::DS::EventLoop
124         if ($@) {
125                 # non public-inbox-{httpd,nntpd} callers may block:
126                 my $ret = waitpid($pid, 0);
127                 waitpid_err($self, $ret);
128         }
129 }
130
131 sub finish ($;$) {
132         my ($self, $env) = @_;
133         if (delete $self->{rpipe}) {
134                 do_waitpid($self, $env);
135         }
136
137         # limiter->{max} may change dynamically
138         my $limiter = $self->{limiter};
139         if ($limiter->{running} < $limiter->{max}) {
140                 if (my $next = shift @{$limiter->{run_queue}}) {
141                         _do_spawn(@$next);
142                 }
143         }
144 }
145
146 sub start {
147         my ($self, $limiter, $cb) = @_;
148         $self->{limiter} = $limiter;
149
150         if ($limiter->{running} < $limiter->{max}) {
151                 _do_spawn($self, $cb);
152         } else {
153                 push @{$limiter->{run_queue}}, [ $self, $cb ];
154         }
155 }
156
157 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
158 # the stdout of the given command when done; but respects the given limiter
159 # $env is the PSGI env.  As with ``/qx; only use this when output is small
160 # and safe to slurp.
161 sub psgi_qx {
162         my ($self, $env, $limiter, $qx_cb) = @_;
163         my $scalar = '';
164         open(my $qx, '+>', \$scalar) or die; # PerlIO::scalar
165         my $end = sub {
166                 my $err = $_[0]; # $!
167                 log_err($env, "psgi_qx: $err") if defined($err);
168                 finish($self, $env);
169                 eval { $qx_cb->(\$scalar) };
170                 $qx = $scalar = undef;
171         };
172         my $rpipe; # comes from popen_rd
173         my $async = $env->{'pi-httpd.async'};
174         my $cb = sub {
175                 my ($r, $buf);
176 reread:
177                 $r = sysread($rpipe, $buf, 65536);
178                 if ($async) {
179                         $async->async_pass($env->{'psgix.io'}, $qx, \$buf);
180                 } elsif (defined $r) {
181                         $r ? $qx->write($buf) : $end->();
182                 } else {
183                         return if $! == EAGAIN; # try again when notified
184                         goto reread if $! == EINTR;
185                         $end->($!);
186                 }
187         };
188         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
189         $self->start($limiter, sub { # may run later, much later...
190                 ($rpipe) = @_; # popen_rd result
191                 if ($async) {
192                 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
193                         $async = $async->($rpipe, $cb, $end);
194                 } else { # generic PSGI
195                         $cb->() while $qx;
196                 }
197         });
198 }
199
200 # create a filter for "push"-based streaming PSGI writes used by HTTPD::Async
201 sub filter_fh ($$) {
202         my ($fh, $filter) = @_;
203         Plack::Util::inline_object(
204                 close => sub {
205                         $fh->write($filter->(undef));
206                         $fh->close;
207                 },
208                 write => sub {
209                         $fh->write($filter->($_[0]));
210                 });
211 }
212
213 # Used for streaming the stdout of one process as a PSGI response.
214 #
215 # $env is the PSGI env.
216 # optional keys in $env:
217 #   $env->{'qspawn.wcb'} - the write callback from the PSGI server
218 #                          optional, use this if you've already
219 #                          captured it elsewhere.  If not given,
220 #                          psgi_return will return an anonymous
221 #                          sub for the PSGI server to call
222 #
223 #   $env->{'qspawn.filter'} - filter callback, receives a string as input,
224 #                             undef on EOF
225 #
226 # $limiter - the Limiter object to use (uses the def_limiter if not given)
227 #
228 # $parse_hdr - Initial read function; often for parsing CGI header output.
229 #              It will be given the return value of sysread from the pipe
230 #              and a string ref of the current buffer.  Returns an arrayref
231 #              for PSGI responses.  2-element arrays in PSGI mean the
232 #              body will be streamed, later, via writes (push-based) to
233 #              psgix.io.  3-element arrays means the body is available
234 #              immediately (or streamed via ->getline (pull-based)).
235 sub psgi_return {
236         my ($self, $env, $limiter, $parse_hdr) = @_;
237         my ($fh, $rpipe);
238         my $end = sub {
239                 my $err = $_[0]; # $!
240                 log_err($env, "psgi_return: $err") if defined($err);
241                 finish($self, $env);
242                 $fh->close if $fh; # async-only
243         };
244
245         my $buf = '';
246         my $rd_hdr = sub {
247                 # typically used for reading CGI headers
248                 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
249                 # We also need to check EINTR for generic PSGI servers.
250                 my $ret;
251                 my $total_rd = 0;
252                 do {
253                         my $r = sysread($rpipe, $buf, 4096, length($buf));
254                         if (defined($r)) {
255                                 $total_rd += $r;
256                                 $ret = $parse_hdr->($r ? $total_rd : 0, \$buf);
257                         } else {
258                                 # caller should notify us when it's ready:
259                                 return if $! == EAGAIN;
260                                 next if $! == EINTR; # immediate retry
261                                 log_err($env, "error reading header: $!");
262                                 $ret = [ 500, [], [ "Internal error\n" ] ];
263                         }
264                 } until (defined $ret);
265                 $ret;
266         };
267
268         my $wcb = delete $env->{'qspawn.wcb'};
269         my $async = $env->{'pi-httpd.async'};
270
271         my $cb = sub {
272                 my $r = $rd_hdr->() or return;
273                 $rd_hdr = undef; # done reading headers
274                 my $filter = delete $env->{'qspawn.filter'};
275                 if (scalar(@$r) == 3) { # error
276                         if ($async) {
277                                 $async->close; # calls rpipe->close and $end
278                         } else {
279                                 $rpipe->close;
280                                 $end->();
281                         }
282                         $wcb->($r);
283                 } elsif ($async) {
284                         # done reading headers, handoff to read body
285                         $fh = $wcb->($r); # scalar @$r == 2
286                         $fh = filter_fh($fh, $filter) if $filter;
287                         $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
288                 } else { # for synchronous PSGI servers
289                         require PublicInbox::GetlineBody;
290                         $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
291                                                                 $buf, $filter);
292                         $wcb->($r);
293                 }
294         };
295         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
296         my $start_cb = sub { # may run later, much later...
297                 ($rpipe) = @_;
298                 if ($async) {
299                         # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
300                         $async = $async->($rpipe, $cb, $end);
301                 } else { # generic PSGI
302                         $cb->() while $rd_hdr;
303                 }
304         };
305
306         # the caller already captured the PSGI write callback from
307         # the PSGI server, so we can call ->start, here:
308         return $self->start($limiter, $start_cb) if $wcb;
309
310         # the caller will return this sub to the PSGI server, so
311         # it can set the response callback (that is, for PublicInbox::HTTP,
312         # the chunked_wcb or identity_wcb callback), but other HTTP servers
313         # are supported:
314         sub {
315                 ($wcb) = @_;
316                 $self->start($limiter, $start_cb);
317         };
318 }
319
320 package PublicInbox::Qspawn::Limiter;
321 use strict;
322 use warnings;
323
324 sub new {
325         my ($class, $max) = @_;
326         bless {
327                 # 32 is same as the git-daemon connection limit
328                 max => $max || 32,
329                 running => 0,
330                 run_queue => [],
331                 # RLIMIT_CPU => undef,
332                 # RLIMIT_DATA => undef,
333                 # RLIMIT_CORE => undef,
334         }, $class;
335 }
336
337 sub setup_rlimit {
338         my ($self, $name, $config) = @_;
339         foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
340                 my $k = lc($rlim);
341                 $k =~ tr/_//d;
342                 $k = "publicinboxlimiter.$name.$k";
343                 defined(my $v = $config->{$k}) or next;
344                 my @rlimit = split(/\s*,\s*/, $v);
345                 if (scalar(@rlimit) == 1) {
346                         push @rlimit, $rlimit[0];
347                 } elsif (scalar(@rlimit) != 2) {
348                         warn "could not parse $k: $v\n";
349                 }
350                 eval { require BSD::Resource };
351                 if ($@) {
352                         warn "BSD::Resource missing for $rlim";
353                         next;
354                 }
355                 foreach my $i (0..$#rlimit) {
356                         next if $rlimit[$i] ne 'INFINITY';
357                         $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
358                 }
359                 $self->{$rlim} = \@rlimit;
360         }
361 }
362
363 1;