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