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