]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Qspawn.pm
qspawn: remove unused WNOHANG import
[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         if (defined $self->{pid}) {
60                 $limiter->{running}++;
61         } else {
62                 $self->{err} = $!;
63         }
64         $cb->($self->{rpipe});
65 }
66
67 sub child_err ($) {
68         my ($child_error) = @_; # typically $?
69         my $exitstatus = ($child_error >> 8) or return;
70         my $sig = $child_error & 127;
71         my $msg = "exit status=$exitstatus";
72         $msg .= " signal=$sig" if $sig;
73         $msg;
74 }
75
76 # callback for dwaitpid
77 sub waitpid_err ($$) {
78         my ($self, $pid) = @_;
79         my $xpid = delete $self->{pid};
80         my $err;
81         if ($pid > 0) { # success!
82                 $err = child_err($?);
83         } elsif ($pid < 0) { # ??? does this happen in our case?
84                 $err = "W: waitpid($xpid, 0) => $pid: $!";
85         } # else should not be called with pid == 0
86
87         # done, spawn whatever's in the queue
88         my $limiter = $self->{limiter};
89         my $running = --$limiter->{running};
90
91         # limiter->{max} may change dynamically
92         if (($running || $limiter->{running}) < $limiter->{max}) {
93                 if (my $next = shift @{$limiter->{run_queue}}) {
94                         _do_spawn(@$next);
95                 }
96         }
97
98         return unless $err;
99         $self->{err} = $err;
100         my $env = $self->{env} or return;
101         if (!$env->{'qspawn.quiet'}) {
102                 $err = join(' ', @{$self->{args}->[0]}).": $err\n";
103                 $env->{'psgi.errors'}->print($err);
104         }
105 }
106
107 sub do_waitpid ($;$) {
108         my ($self, $env) = @_;
109         my $pid = $self->{pid};
110         eval { # PublicInbox::DS may not be loaded
111                 PublicInbox::DS::dwaitpid($pid, \&waitpid_err, $self);
112                 $self->{env} = $env;
113         };
114         # done if we're running in PublicInbox::DS::EventLoop
115         if ($@) {
116                 # non public-inbox-{httpd,nntpd} callers may block:
117                 my $ret = waitpid($pid, 0);
118                 waitpid_err($self, $ret);
119         }
120 }
121
122 sub finish ($;$) {
123         my ($self, $env) = @_;
124         if (delete $self->{rpipe}) {
125                 do_waitpid($self, $env);
126         }
127
128         # limiter->{max} may change dynamically
129         my $limiter = $self->{limiter};
130         if ($limiter->{running} < $limiter->{max}) {
131                 if (my $next = shift @{$limiter->{run_queue}}) {
132                         _do_spawn(@$next);
133                 }
134         }
135         $self->{err}; # may be meaningless if non-blocking
136 }
137
138 sub start {
139         my ($self, $limiter, $cb) = @_;
140         $self->{limiter} = $limiter;
141
142         if ($limiter->{running} < $limiter->{max}) {
143                 _do_spawn($self, $cb);
144         } else {
145                 push @{$limiter->{run_queue}}, [ $self, $cb ];
146         }
147 }
148
149 # Similar to `backtick` or "qx" ("perldoc -f qx"), it calls $qx_cb with
150 # the stdout of the given command when done; but respects the given limiter
151 # $env is the PSGI env.  As with ``/qx; only use this when output is small
152 # and safe to slurp.
153 sub psgi_qx {
154         my ($self, $env, $limiter, $qx_cb) = @_;
155         my $scalar = '';
156         open(my $qx, '+>', \$scalar) or die; # PerlIO::scalar
157         my $end = sub {
158                 finish($self, $env);
159                 eval { $qx_cb->(\$scalar) };
160                 $qx = $scalar = 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                 # typically used for reading CGI headers
233                 # we must loop until EAGAIN for EPOLLET in HTTPD/Async.pm
234                 # We also need to check EINTR for generic PSGI servers.
235                 my $ret;
236                 my $n = 0;
237                 do {
238                         my $r = sysread($rpipe, $buf, 4096, length($buf));
239                         return if !defined($r) && $! == EAGAIN || $! == EINTR;
240
241                         # $r may be undef, here:
242                         $n += $r if $r;
243                         $ret = $parse_hdr->($r ? $n : $r, \$buf);
244                 } until (defined $ret);
245                 $ret;
246         };
247
248         my $wcb = delete $env->{'qspawn.wcb'};
249         my $async = $env->{'pi-httpd.async'};
250
251         my $cb = sub {
252                 my $r = $rd_hdr->() or return;
253                 $rd_hdr = undef; # done reading headers
254                 my $filter = delete $env->{'qspawn.filter'};
255                 if (scalar(@$r) == 3) { # error
256                         if ($async) {
257                                 $async->close; # calls rpipe->close and $end
258                         } else {
259                                 $rpipe->close;
260                                 $end->();
261                         }
262                         $wcb->($r);
263                 } elsif ($async) {
264                         # done reading headers, handoff to read body
265                         $fh = $wcb->($r); # scalar @$r == 2
266                         $fh = filter_fh($fh, $filter) if $filter;
267                         $async->async_pass($env->{'psgix.io'}, $fh, \$buf);
268                 } else { # for synchronous PSGI servers
269                         require PublicInbox::GetlineBody;
270                         $r->[2] = PublicInbox::GetlineBody->new($rpipe, $end,
271                                                                 $buf, $filter);
272                         $wcb->($r);
273                 }
274         };
275         $limiter ||= $def_limiter ||= PublicInbox::Qspawn::Limiter->new(32);
276         my $start_cb = sub { # may run later, much later...
277                 ($rpipe) = @_;
278                 if ($async) {
279                         # PublicInbox::HTTPD::Async->new($rpipe, $cb, $end)
280                         $async = $async->($rpipe, $cb, $end);
281                 } else { # generic PSGI
282                         $cb->() while $rd_hdr;
283                 }
284         };
285
286         # the caller already captured the PSGI write callback from
287         # the PSGI server, so we can call ->start, here:
288         return $self->start($limiter, $start_cb) if $wcb;
289
290         # the caller will return this sub to the PSGI server, so
291         # it can set the response callback (that is, for PublicInbox::HTTP,
292         # the chunked_wcb or identity_wcb callback), but other HTTP servers
293         # are supported:
294         sub {
295                 ($wcb) = @_;
296                 $self->start($limiter, $start_cb);
297         };
298 }
299
300 package PublicInbox::Qspawn::Limiter;
301 use strict;
302 use warnings;
303
304 sub new {
305         my ($class, $max) = @_;
306         bless {
307                 # 32 is same as the git-daemon connection limit
308                 max => $max || 32,
309                 running => 0,
310                 run_queue => [],
311                 # RLIMIT_CPU => undef,
312                 # RLIMIT_DATA => undef,
313                 # RLIMIT_CORE => undef,
314         }, $class;
315 }
316
317 sub setup_rlimit {
318         my ($self, $name, $config) = @_;
319         foreach my $rlim (PublicInbox::Spawn::RLIMITS()) {
320                 my $k = lc($rlim);
321                 $k =~ tr/_//d;
322                 $k = "publicinboxlimiter.$name.$k";
323                 defined(my $v = $config->{$k}) or next;
324                 my @rlimit = split(/\s*,\s*/, $v);
325                 if (scalar(@rlimit) == 1) {
326                         push @rlimit, $rlimit[0];
327                 } elsif (scalar(@rlimit) != 2) {
328                         warn "could not parse $k: $v\n";
329                 }
330                 eval { require BSD::Resource };
331                 if ($@) {
332                         warn "BSD::Resource missing for $rlim";
333                         next;
334                 }
335                 foreach my $i (0..$#rlimit) {
336                         next if $rlimit[$i] ne 'INFINITY';
337                         $rlimit[$i] = BSD::Resource::RLIM_INFINITY();
338                 }
339                 $self->{$rlim} = \@rlimit;
340         }
341 }
342
343 1;