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