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