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