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