]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Qspawn.pm
844d50f7cdeedb6775df8183df8a2d3f9bb83c18
[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, $cb) = @_;
48         my $err;
49         my ($cmd, $env, $opts) = @{$self->{args}};
50         my %opts = %{$opts || {}};
51         my $limiter = $self->{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         $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         # done, spawn whatever's in the queue
98         my $limiter = $self->{limiter};
99         my $running = --$limiter->{running};
100
101         # limiter->{max} may change dynamically
102         if (($running || $limiter->{running}) < $limiter->{max}) {
103                 if (my $next = shift @{$limiter->{run_queue}}) {
104                         _do_spawn(@$next);
105                 }
106         }
107
108         return unless $err;
109         $self->{err} = $err;
110         my $env = $self->{env} or return;
111         if (!$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         # limiter->{max} may change dynamically
137         my $limiter = $self->{limiter};
138         if ($limiter->{running} < $limiter->{max}) {
139                 if (my $next = shift @{$limiter->{run_queue}}) {
140                         _do_spawn(@$next);
141                 }
142         }
143 }
144
145 sub start {
146         my ($self, $limiter, $cb) = @_;
147         $self->{limiter} = $limiter;
148
149         if ($limiter->{running} < $limiter->{max}) {
150                 _do_spawn($self, $cb);
151         } else {
152                 push @{$limiter->{run_queue}}, [ $self, $cb ];
153         }
154 }
155
156 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
157 # the stdout of the given command when done; but respects the given limiter
158 # $env is the PSGI env.  As with ``/qx; only use this when output is small
159 # and safe to slurp.
160 sub psgi_qx {
161         my ($self, $env, $limiter, $qx_cb) = @_;
162         my $scalar = '';
163         open(my $qx, '+>', \$scalar) or die; # PerlIO::scalar
164         my $end = sub {
165                 my $err = $_[0]; # $!
166                 log_err($env, "psgi_qx: $err") if defined($err);
167                 finish($self, $env);
168                 eval { $qx_cb->(\$scalar) };
169                 $qx = $scalar = undef;
170         };
171         my $rpipe; # comes from popen_rd
172         my $async = $env->{'pi-httpd.async'};
173         my $cb = sub {
174                 my ($r, $buf);
175 reread:
176                 $r = sysread($rpipe, $buf, 65536);
177                 if ($async) {
178                         $async->async_pass($env->{'psgix.io'}, $qx, \$buf);
179                 } elsif (defined $r) {
180                         $r ? $qx->write($buf) : $end->();
181                 } else {
182                         return if $! == EAGAIN; # try again when notified
183                         goto reread if $! == EINTR;
184                         $end->($!);
185                 }
186         };
187         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
188         $self->start($limiter, sub { # may run later, much later...
189                 ($rpipe) = @_; # popen_rd result
190                 if ($async) {
191                 # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
192                         $async = $async->($rpipe, $cb, $end);
193                 } else { # generic PSGI
194                         $cb->() while $qx;
195                 }
196         });
197 }
198
199 # create a filter for "push"-based streaming PSGI writes used by HTTPD::Async
200 sub filter_fh ($$) {
201         my ($fh, $filter) = @_;
202         Plack::Util::inline_object(
203                 close => sub {
204                         $fh->write($filter->(undef));
205                         $fh->close;
206                 },
207                 write => sub {
208                         $fh->write($filter->($_[0]));
209                 });
210 }
211
212 # Used for streaming the stdout of one process as a PSGI response.
213 #
214 # $env is the PSGI env.
215 # optional keys in $env:
216 #   $env->{'qspawn.wcb'} - the write callback from the PSGI server
217 #                          optional, use this if you've already
218 #                          captured it elsewhere.  If not given,
219 #                          psgi_return will return an anonymous
220 #                          sub for the PSGI server to call
221 #
222 #   $env->{'qspawn.filter'} - filter callback, receives a string as input,
223 #                             undef on EOF
224 #
225 # $limiter - the Limiter object to use (uses the def_limiter if not given)
226 #
227 # $parse_hdr - Initial read function; often for parsing CGI header output.
228 #              It will be given the return value of sysread from the pipe
229 #              and a string ref of the current buffer.  Returns an arrayref
230 #              for PSGI responses.  2-element arrays in PSGI mean the
231 #              body will be streamed, later, via writes (push-based) to
232 #              psgix.io.  3-element arrays means the body is available
233 #              immediately (or streamed via ->getline (pull-based)).
234 sub psgi_return {
235         my ($self, $env, $limiter, $parse_hdr) = @_;
236         my ($fh, $rpipe);
237         my $end = sub {
238                 my $err = $_[0]; # $!
239                 log_err($env, "psgi_return: $err") if defined($err);
240                 finish($self, $env);
241                 $fh->close if $fh; # async-only
242         };
243
244         my $buf = '';
245         my $rd_hdr = sub {
246                 # typically used for reading CGI headers
247                 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
248                 # We also need to check EINTR for generic PSGI servers.
249                 my $ret;
250                 my $total_rd = 0;
251                 do {
252                         my $r = sysread($rpipe, $buf, 4096, length($buf));
253                         if (defined($r)) {
254                                 $total_rd += $r;
255                                 $ret = $parse_hdr->($r ? $total_rd : 0, \$buf);
256                         } else {
257                                 # caller should notify us when it's ready:
258                                 return if $! == EAGAIN;
259                                 next if $! == EINTR; # immediate retry
260                                 log_err($env, "error reading header: $!");
261                                 $ret = [ 500, [], [ "Internal error\n" ] ];
262                         }
263                 } until (defined $ret);
264                 $ret;
265         };
266
267         my $wcb = delete $env->{'qspawn.wcb'};
268         my $async = $env->{'pi-httpd.async'};
269
270         my $cb = sub {
271                 my $r = $rd_hdr->() or return;
272                 $rd_hdr = undef; # done reading headers
273                 my $filter = delete $env->{'qspawn.filter'};
274                 if (scalar(@$r) == 3) { # error
275                         if ($async) {
276                                 $async->close; # calls rpipe->close and $end
277                         } else {
278                                 $rpipe->close;
279                                 $end->();
280                         }
281                         $wcb->($r);
282                 } elsif ($async) {
283                         # done reading headers, handoff to read body
284                         $fh = $wcb->($r); # scalar @$r == 2
285                         $fh = filter_fh($fh, $filter) if $filter;
286                         $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
287                 } else { # for synchronous PSGI servers
288                         require PublicInbox::GetlineBody;
289                         $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
290                                                                 $buf, $filter);
291                         $wcb->($r);
292                 }
293         };
294         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
295         my $start_cb = sub { # may run later, much later...
296                 ($rpipe) = @_;
297                 if ($async) {
298                         # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
299                         $async = $async->($rpipe, $cb, $end);
300                 } else { # generic PSGI
301                         $cb->() while $rd_hdr;
302                 }
303         };
304
305         # the caller already captured the PSGI write callback from
306         # the PSGI server, so we can call ->start, here:
307         return $self->start($limiter, $start_cb) if $wcb;
308
309         # the caller will return this sub to the PSGI server, so
310         # it can set the response callback (that is, for PublicInbox::HTTP,
311         # the chunked_wcb or identity_wcb callback), but other HTTP servers
312         # are supported:
313         sub {
314                 ($wcb) = @_;
315                 $self->start($limiter, $start_cb);
316         };
317 }
318
319 package PublicInbox::Qspawn::Limiter;
320 use strict;
321 use warnings;
322
323 sub new {
324         my ($class, $max) = @_;
325         bless {
326                 # 32 is same as the git-daemon connection limit
327                 max => $max || 32,
328                 running => 0,
329                 run_queue => [],
330                 # RLIMIT_CPU => undef,
331                 # RLIMIT_DATA => undef,
332                 # RLIMIT_CORE => undef,
333         }, $class;
334 }
335
336 sub setup_rlimit {
337         my ($self, $name, $config) = @_;
338         foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
339                 my $k = lc($rlim);
340                 $k =~ tr/_//d;
341                 $k = "publicinboxlimiter.$name.$k";
342                 defined(my $v = $config->{$k}) or next;
343                 my @rlimit = split(/\s*,\s*/, $v);
344                 if (scalar(@rlimit) == 1) {
345                         push @rlimit, $rlimit[0];
346                 } elsif (scalar(@rlimit) != 2) {
347                         warn "could not parse $k: $v\n";
348                 }
349                 eval { require BSD::Resource };
350                 if ($@) {
351                         warn "BSD::Resource missing for $rlim";
352                         next;
353                 }
354                 foreach my $i (0..$#rlimit) {
355                         next if $rlimit[$i] ne 'INFINITY';
356                         $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
357                 }
358                 $self->{$rlim} = \@rlimit;
359         }
360 }
361
362 1;