]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Qspawn.pm
qspawn: {quiet} only affects normal command exit
[public-inbox.git] / lib / PublicInbox / Qspawn.pm
1 # Copyright (C) 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 the PublicInbox::DS::event_loop or any
16 # other external scheduling mechanism, you just need to call
17 # start() and finish() appropriately. However, public-inbox-httpd
18 # (which uses PublicInbox::DS)  will be able to schedule this
19 # based on readability of stdout from the spawned process.
20 # See GitHTTPBackend.pm and SolverGit.pm for usage examples.
21 # It does not depend on any form of threading.
22 #
23 # This is useful for scheduling CGI execution of both long-lived
24 # git-http-backend(1) process (for "git clone") as well as short-lived
25 # processes such as git-apply(1).
26
27 package PublicInbox::Qspawn;
28 use v5.12;
29 use PublicInbox::Spawn qw(popen_rd);
30 use PublicInbox::GzipFilter;
31 use PublicInbox::DS qw(awaitpid);
32 use Scalar::Util qw(blessed);
33
34 # n.b.: we get EAGAIN with public-inbox-httpd, and EINTR on other PSGI servers
35 use Errno qw(EAGAIN EINTR);
36
37 my $def_limiter;
38
39 # declares a command to spawn (but does not spawn it).
40 # $cmd is the command to spawn
41 # $cmd_env is the environ for the child process (not PSGI env)
42 # $opt can include redirects and perhaps other process spawning options
43 # {qsp_err} is an optional error buffer callers may access themselves
44 sub new {
45         my ($class, $cmd, $cmd_env, $opt) = @_;
46         bless { args => [ $cmd, $cmd_env, $opt ] }, $class;
47 }
48
49 sub _do_spawn {
50         my ($self, $start_cb, $limiter) = @_;
51         my $err;
52         my ($cmd, $cmd_env, $opt) = @{delete $self->{args}};
53         my %o = %{$opt || {}};
54         $self->{limiter} = $limiter;
55         foreach my $k (@PublicInbox::Spawn::RLIMITS) {
56                 if (defined(my $rlimit = $limiter->{$k})) {
57                         $o{$k} = $rlimit;
58                 }
59         }
60         $self->{cmd} = $cmd;
61         $self->{-quiet} = 1 if $o{quiet};
62         $o{cb_arg} = [ \&waitpid_err, $self ];
63         eval {
64                 # popen_rd may die on EMFILE, ENFILE
65                 $self->{rpipe} = popen_rd($cmd, $cmd_env, \%o) // die "E: $!";
66                 $limiter->{running}++;
67                 $start_cb->($self); # EPOLL_CTL_ADD may ENOSPC/ENOMEM
68         };
69         finish($self, $@) if $@;
70 }
71
72 sub finalize ($) {
73         my ($self) = @_;
74
75         # process is done, spawn whatever's in the queue
76         my $limiter = delete $self->{limiter} or return;
77         my $running = --$limiter->{running};
78
79         if ($running < $limiter->{max}) {
80                 if (my $next = shift(@{$limiter->{run_queue}})) {
81                         _do_spawn(@$next, $limiter);
82                 }
83         }
84         if (my $err = $self->{_err}) { # set by finish or waitpid_err
85                 utf8::decode($err);
86                 if (my $dst = $self->{qsp_err}) {
87                         $$dst .= $$dst ? " $err" : "; $err";
88                 }
89                 warn "@{$self->{cmd}}: $err" if !$self->{-quiet};
90         }
91
92         my ($env, $qx_cb, $qx_arg, $qx_buf) =
93                 delete @$self{qw(psgi_env qx_cb qx_arg qx_buf)};
94         if ($qx_cb) {
95                 eval { $qx_cb->($qx_buf, $qx_arg) };
96                 return unless $@;
97                 warn "E: $@"; # hope qspawn.wcb can handle it
98         }
99         return if $self->{passed}; # another command chained it
100         if (my $wcb = delete $env->{'qspawn.wcb'}) {
101                 # have we started writing, yet?
102                 my $code = delete $env->{'qspawn.fallback'} // 500;
103                 require PublicInbox::WwwStatic;
104                 $wcb->(PublicInbox::WwwStatic::r($code));
105         }
106 }
107
108 sub DESTROY { finalize($_[0]) } # ->finalize is idempotent
109
110 sub waitpid_err { # callback for awaitpid
111         my (undef, $self) = @_; # $_[0]: pid
112         $self->{_err} = ''; # for defined check in ->finish
113         if ($?) {
114                 my $status = $? >> 8;
115                 my $sig = $? & 127;
116                 $self->{_err} .= "exit status=$status";
117                 $self->{_err} .= " signal=$sig" if $sig;
118         }
119         finalize($self) if !$self->{rpipe};
120 }
121
122 sub finish ($;$) {
123         my ($self, $err) = @_;
124         $self->{_err} //= $err; # only for $@
125
126         # we can safely finalize if pipe was closed before, or if
127         # {_err} is defined by waitpid_err.  Deleting {rpipe} will
128         # trigger PublicInbox::ProcessPipe::DESTROY -> waitpid_err,
129         # but it may not fire right away if inside the event loop.
130         my $closed_before = !delete($self->{rpipe});
131         finalize($self) if $closed_before || defined($self->{_err});
132 }
133
134 sub start ($$$) {
135         my ($self, $limiter, $start_cb) = @_;
136         if ($limiter->{running} < $limiter->{max}) {
137                 _do_spawn($self, $start_cb, $limiter);
138         } else {
139                 push @{$limiter->{run_queue}}, [ $self, $start_cb ];
140         }
141 }
142
143 sub psgi_qx_init_cb { # this may be PublicInbox::HTTPD::Async {cb}
144         my ($self) = @_;
145         my $async = delete $self->{async}; # PublicInbox::HTTPD::Async
146         my ($r, $buf);
147         my $qx_fh = $self->{qx_fh};
148 reread:
149         $r = sysread($self->{rpipe}, $buf, 65536);
150         if ($async) {
151                 $async->async_pass($self->{psgi_env}->{'psgix.io'},
152                                         $qx_fh, \$buf);
153         } elsif (defined $r) {
154                 $r ? (print $qx_fh $buf) : event_step($self, undef);
155         } else {
156                 return if $! == EAGAIN; # try again when notified
157                 goto reread if $! == EINTR;
158                 event_step($self, $!);
159         }
160 }
161
162 sub psgi_qx_start {
163         my ($self) = @_;
164         if (my $async = $self->{psgi_env}->{'pi-httpd.async'}) {
165                 # PublicInbox::HTTPD::Async->new(rpipe, $cb, cb_arg, $end_obj)
166                 $self->{async} = $async->($self->{rpipe},
167                                         \&psgi_qx_init_cb, $self, $self);
168                 # init_cb will call ->async_pass or ->close
169         } else { # generic PSGI
170                 psgi_qx_init_cb($self) while $self->{qx_fh};
171         }
172 }
173
174 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
175 # the stdout of the given command when done; but respects the given limiter
176 # $env is the PSGI env.  As with ``/qx; only use this when output is small
177 # and safe to slurp.
178 sub psgi_qx {
179         my ($self, $env, $limiter, $qx_cb, $qx_arg) = @_;
180         $self->{psgi_env} = $env;
181         my $qx_buf = '';
182         open(my $qx_fh, '+>', \$qx_buf) or die; # PerlIO::scalar
183         $self->{qx_cb} = $qx_cb;
184         $self->{qx_arg} = $qx_arg;
185         $self->{qx_fh} = $qx_fh;
186         $self->{qx_buf} = \$qx_buf;
187         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
188         start($self, $limiter, \&psgi_qx_start);
189 }
190
191 # this is called on pipe EOF to reap the process, may be called
192 # via PublicInbox::DS event loop OR via GetlineBody for generic
193 # PSGI servers.
194 sub event_step {
195         my ($self, $err) = @_; # $err: $!
196         warn "psgi_{return,qx} $err" if defined($err);
197         finish($self);
198         my ($fh, $qx_fh) = delete(@$self{qw(qfh qx_fh)});
199         $fh->close if $fh; # async-only (psgi_return)
200 }
201
202 sub rd_hdr ($) {
203         my ($self) = @_;
204         # typically used for reading CGI headers
205         # We also need to check EINTR for generic PSGI servers.
206         my $ret;
207         my $total_rd = 0;
208         my $hdr_buf = $self->{hdr_buf};
209         my ($ph_cb, $ph_arg) = @{$self->{parse_hdr}};
210         until (defined($ret)) {
211                 my $r = sysread($self->{rpipe}, $$hdr_buf, 4096,
212                                 length($$hdr_buf));
213                 if (defined($r)) {
214                         $total_rd += $r;
215                         eval { $ret = $ph_cb->($total_rd, $hdr_buf, $ph_arg) };
216                         if ($@) {
217                                 warn "parse_hdr: $@";
218                                 $ret = [ 500, [], [ "Internal error\n" ] ];
219                         } elsif (!defined($ret) && !$r) {
220                                 warn <<EOM;
221 EOF parsing headers from @{$self->{cmd}} ($self->{psgi_env}->{REQUEST_URI})
222 EOM
223                                 $ret = [ 500, [], [ "Internal error\n" ] ];
224                         }
225                 } else {
226                         # caller should notify us when it's ready:
227                         return if $! == EAGAIN;
228                         next if $! == EINTR; # immediate retry
229                         warn "error reading header: $!";
230                         $ret = [ 500, [], [ "Internal error\n" ] ];
231                 }
232         }
233         delete $self->{parse_hdr}; # done parsing headers
234         $ret;
235 }
236
237 sub psgi_return_init_cb { # this may be PublicInbox::HTTPD::Async {cb}
238         my ($self) = @_;
239         my $r = rd_hdr($self) or return;
240         my $env = $self->{psgi_env};
241         my $filter;
242
243         # this is for RepoAtom since that can fire after parse_cgi_headers
244         if (ref($r) eq 'ARRAY' && blessed($r->[2]) && $r->[2]->can('attach')) {
245                 $filter = pop @$r;
246         }
247         $filter //= delete($env->{'qspawn.filter'}) // (ref($r) eq 'ARRAY' ?
248                 PublicInbox::GzipFilter::qsp_maybe($r->[1], $env) : undef);
249
250         my $wcb = delete $env->{'qspawn.wcb'};
251         my $async = delete $self->{async}; # PublicInbox::HTTPD::Async
252         if (ref($r) ne 'ARRAY' || scalar(@$r) == 3) { # error
253                 if ($async) { # calls rpipe->close && ->event_step
254                         $async->close; # PublicInbox::HTTPD::Async::close
255                 } else { # generic PSGI, use PublicInbox::ProcessPipe::CLOSE
256                         delete($self->{rpipe})->close;
257                         event_step($self);
258                 }
259                 if (ref($r) eq 'ARRAY') { # error
260                         $wcb->($r)
261                 } elsif (ref($r) eq 'CODE') { # chain another command
262                         $r->($wcb);
263                         $self->{passed} = 1;
264                 }
265                 # else do nothing
266         } elsif ($async) {
267                 # done reading headers, handoff to read body
268                 my $fh = $wcb->($r); # scalar @$r == 2
269                 $fh = $filter->attach($fh) if $filter;
270                 $self->{qfh} = $fh;
271                 $async->async_pass($env->{'psgix.io'}, $fh,
272                                         delete($self->{hdr_buf}));
273         } else { # for synchronous PSGI servers
274                 require PublicInbox::GetlineBody;
275                 my $buf = delete $self->{hdr_buf};
276                 $r->[2] = PublicInbox::GetlineBody->new($self->{rpipe},
277                                         \&event_step, $self, $$buf, $filter);
278                 $wcb->($r);
279         }
280 }
281
282 sub psgi_return_start { # may run later, much later...
283         my ($self) = @_;
284         if (my $cb = $self->{psgi_env}->{'pi-httpd.async'}) {
285                 # PublicInbox::HTTPD::Async->new(rpipe, $cb, $cb_arg, $end_obj)
286                 $self->{async} = $cb->($self->{rpipe},
287                                         \&psgi_return_init_cb, $self, $self);
288         } else { # generic PSGI
289                 psgi_return_init_cb($self) while $self->{parse_hdr};
290         }
291 }
292
293 # Used for streaming the stdout of one process as a PSGI response.
294 #
295 # $env is the PSGI env.
296 # optional keys in $env:
297 #   $env->{'qspawn.wcb'} - the write callback from the PSGI server
298 #                          optional, use this if you've already
299 #                          captured it elsewhere.  If not given,
300 #                          psgi_return will return an anonymous
301 #                          sub for the PSGI server to call
302 #
303 #   $env->{'qspawn.filter'} - filter object, responds to ->attach for
304 #                             pi-httpd.async and ->translate for generic
305 #                             PSGI servers
306 #
307 # $limiter - the Limiter object to use (uses the def_limiter if not given)
308 #
309 # $parse_hdr - Initial read function; often for parsing CGI header output.
310 #              It will be given the return value of sysread from the pipe
311 #              and a string ref of the current buffer.  Returns an arrayref
312 #              for PSGI responses.  2-element arrays in PSGI mean the
313 #              body will be streamed, later, via writes (push-based) to
314 #              psgix.io.  3-element arrays means the body is available
315 #              immediately (or streamed via ->getline (pull-based)).
316 sub psgi_return {
317         my ($self, $env, $limiter, $parse_hdr, $hdr_arg) = @_;
318         $self->{psgi_env} = $env;
319         $self->{hdr_buf} = \(my $hdr_buf = '');
320         $self->{parse_hdr} = [ $parse_hdr, $hdr_arg ];
321         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
322
323         # the caller already captured the PSGI write callback from
324         # the PSGI server, so we can call ->start, here:
325         $env->{'qspawn.wcb'} and
326                 return start($self, $limiter, \&psgi_return_start);
327
328         # the caller will return this sub to the PSGI server, so
329         # it can set the response callback (that is, for
330         # PublicInbox::HTTP, the chunked_wcb or identity_wcb callback),
331         # but other HTTP servers are supported:
332         sub {
333                 $env->{'qspawn.wcb'} = $_[0];
334                 start($self, $limiter, \&psgi_return_start);
335         }
336 }
337
338 package PublicInbox::Qspawn::Limiter;
339 use v5.12;
340
341 sub new {
342         my ($class, $max) = @_;
343         bless {
344                 # 32 is same as the git-daemon connection limit
345                 max => $max || 32,
346                 running => 0,
347                 run_queue => [],
348                 # RLIMIT_CPU => undef,
349                 # RLIMIT_DATA => undef,
350                 # RLIMIT_CORE => undef,
351         }, $class;
352 }
353
354 sub setup_rlimit {
355         my ($self, $name, $cfg) = @_;
356         foreach my $rlim (@PublicInbox::Spawn::RLIMITS) {
357                 my $k = lc($rlim);
358                 $k =~ tr/_//d;
359                 $k = "publicinboxlimiter.$name.$k";
360                 defined(my $v = $cfg->{$k}) or next;
361                 my @rlimit = split(/\s*,\s*/, $v);
362                 if (scalar(@rlimit) == 1) {
363                         push @rlimit, $rlimit[0];
364                 } elsif (scalar(@rlimit) != 2) {
365                         warn "could not parse $k: $v\n";
366                 }
367                 eval { require BSD::Resource };
368                 if ($@) {
369                         warn "BSD::Resource missing for $rlim";
370                         next;
371                 }
372                 foreach my $i (0..$#rlimit) {
373                         next if $rlimit[$i] ne 'INFINITY';
374                         $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
375                 }
376                 $self->{$rlim} = \@rlimit;
377         }
378 }
379
380 1;