]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Qspawn.pm
qspawn: shorten lifetime of circular references
[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, $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         $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, $cb) = @_;
139         if ($limiter->{running} < $limiter->{max}) {
140                 _do_spawn($self, $cb, $limiter);
141         } else {
142                 push @{$limiter->{run_queue}}, [ $self, $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 { # 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                 } else { # generic PSGI
184                         $cb->() while $qx;
185                 }
186         });
187 }
188
189 # create a filter for "push"-based streaming PSGI writes used by HTTPD::Async
190 sub filter_fh ($$) {
191         my ($fh, $filter) = @_;
192         Plack::Util::inline_object(
193                 close => sub {
194                         $fh->write($filter->(undef));
195                         $fh->close;
196                 },
197                 write => sub {
198                         $fh->write($filter->($_[0]));
199                 });
200 }
201
202 # Used for streaming the stdout of one process as a PSGI response.
203 #
204 # $env is the PSGI env.
205 # optional keys in $env:
206 #   $env->{'qspawn.wcb'} - the write callback from the PSGI server
207 #                          optional, use this if you've already
208 #                          captured it elsewhere.  If not given,
209 #                          psgi_return will return an anonymous
210 #                          sub for the PSGI server to call
211 #
212 #   $env->{'qspawn.filter'} - filter callback, receives a string as input,
213 #                             undef on EOF
214 #
215 # $limiter - the Limiter object to use (uses the def_limiter if not given)
216 #
217 # $parse_hdr - Initial read function; often for parsing CGI header output.
218 #              It will be given the return value of sysread from the pipe
219 #              and a string ref of the current buffer.  Returns an arrayref
220 #              for PSGI responses.  2-element arrays in PSGI mean the
221 #              body will be streamed, later, via writes (push-based) to
222 #              psgix.io.  3-element arrays means the body is available
223 #              immediately (or streamed via ->getline (pull-based)).
224 sub psgi_return {
225         my ($self, $env, $limiter, $parse_hdr) = @_;
226         my ($fh, $rpipe);
227         my $end = sub {
228                 my $err = $_[0]; # $!
229                 log_err($env, "psgi_return: $err") if defined($err);
230                 finish($self, $env);
231                 $fh->close if $fh; # async-only
232         };
233
234         my $buf = '';
235         my $rd_hdr = sub {
236                 # typically used for reading CGI headers
237                 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
238                 # We also need to check EINTR for generic PSGI servers.
239                 my $ret;
240                 my $total_rd = 0;
241                 do {
242                         my $r = sysread($rpipe, $buf, 4096, length($buf));
243                         if (defined($r)) {
244                                 $total_rd += $r;
245                                 $ret = $parse_hdr->($r ? $total_rd : 0, \$buf);
246                         } else {
247                                 # caller should notify us when it's ready:
248                                 return if $! == EAGAIN;
249                                 next if $! == EINTR; # immediate retry
250                                 log_err($env, "error reading header: $!");
251                                 $ret = [ 500, [], [ "Internal error\n" ] ];
252                         }
253                 } until (defined $ret);
254                 $ret;
255         };
256
257         my $wcb = delete $env->{'qspawn.wcb'};
258         my $async = $env->{'pi-httpd.async'};
259
260         my $cb = sub {
261                 my $r = $rd_hdr->() or return;
262                 $rd_hdr = undef; # done reading headers
263                 my $filter = delete $env->{'qspawn.filter'};
264                 if (scalar(@$r) == 3) { # error
265                         if ($async) {
266                                 $async->close; # calls rpipe->close and $end
267                         } else {
268                                 $rpipe->close;
269                                 $end->();
270                         }
271                         $wcb->($r);
272                 } elsif ($async) {
273                         # done reading headers, handoff to read body
274                         $fh = $wcb->($r); # scalar @$r == 2
275                         $fh = filter_fh($fh, $filter) if $filter;
276                         $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
277                 } else { # for synchronous PSGI servers
278                         require PublicInbox::GetlineBody;
279                         $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
280                                                                 $buf, $filter);
281                         $wcb->($r);
282                 }
283         };
284         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
285         my $start_cb = sub { # may run later, much later...
286                 ($rpipe) = @_;
287                 if ($async) {
288                         # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
289                         $async = $async->($rpipe, $cb, $end);
290                 } else { # generic PSGI
291                         $cb->() while $rd_hdr;
292                 }
293         };
294
295         # the caller already captured the PSGI write callback from
296         # the PSGI server, so we can call ->start, here:
297         return $self->start($limiter, $start_cb) if $wcb;
298
299         # the caller will return this sub to the PSGI server, so
300         # it can set the response callback (that is, for PublicInbox::HTTP,
301         # the chunked_wcb or identity_wcb callback), but other HTTP servers
302         # are supported:
303         sub {
304                 ($wcb) = @_;
305                 $self->start($limiter, $start_cb);
306         };
307 }
308
309 package PublicInbox::Qspawn::Limiter;
310 use strict;
311 use warnings;
312
313 sub new {
314         my ($class, $max) = @_;
315         bless {
316                 # 32 is same as the git-daemon connection limit
317                 max => $max || 32,
318                 running => 0,
319                 run_queue => [],
320                 # RLIMIT_CPU => undef,
321                 # RLIMIT_DATA => undef,
322                 # RLIMIT_CORE => undef,
323         }, $class;
324 }
325
326 sub setup_rlimit {
327         my ($self, $name, $config) = @_;
328         foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
329                 my $k = lc($rlim);
330                 $k =~ tr/_//d;
331                 $k = "publicinboxlimiter.$name.$k";
332                 defined(my $v = $config->{$k}) or next;
333                 my @rlimit = split(/\s*,\s*/, $v);
334                 if (scalar(@rlimit) == 1) {
335                         push @rlimit, $rlimit[0];
336                 } elsif (scalar(@rlimit) != 2) {
337                         warn "could not parse $k: $v\n";
338                 }
339                 eval { require BSD::Resource };
340                 if ($@) {
341                         warn "BSD::Resource missing for $rlim";
342                         next;
343                 }
344                 foreach my $i (0..$#rlimit) {
345                         next if $rlimit[$i] ne 'INFINITY';
346                         $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
347                 }
348                 $self->{$rlim} = \@rlimit;
349         }
350 }
351
352 1;