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