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