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