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