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