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