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