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