]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
ipc: fix IO::FDPass use with a worker limit of 1
[public-inbox.git] / lib / PublicInbox / IPC.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # base class for remote IPC calls and workqueues, requires Storable or Sereal
5 package PublicInbox::IPC;
6 use strict;
7 use v5.10.1;
8 use Carp qw(confess croak);
9 use PublicInbox::DS qw(dwaitpid);
10 use PublicInbox::Spawn;
11 use POSIX qw(WNOHANG);
12 use Socket qw(AF_UNIX MSG_EOR);
13 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
14 use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
15 my $WQ_MAX_WORKERS = 4096;
16 my ($enc, $dec);
17 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
18 # and eliminate method call overhead
19 BEGIN {
20         eval {
21                 require Sereal::Encoder;
22                 require Sereal::Decoder;
23                 Sereal::Encoder->import('sereal_encode_with_object');
24                 Sereal::Decoder->import('sereal_decode_with_object');
25                 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
26         };
27 };
28
29 if ($enc && $dec) { # should be custom ops
30         *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
31         *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
32 } else {
33         eval { # some distros have Storable as a separate package from Perl
34                 require Storable;
35                 Storable->import(qw(freeze thaw));
36                 $enc = 1;
37         } // warn("Storable (part of Perl) missing: $@\n");
38 }
39
40 my $recv_cmd1; # PublicInbox::CmdIPC1::recv_cmd1;
41 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
42 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
43         require PublicInbox::CmdIPC4;
44         $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
45         PublicInbox::CmdIPC4->can('send_cmd4');
46 } // do {
47         # IO::FDPass only allows sending a single FD at-a-time, which
48         # means we can't guarantee all packets end up on the same worker,
49         # so we cap WQ_MAX_WORKERS
50         require PublicInbox::CmdIPC1;
51         $recv_cmd1 = PublicInbox::CmdIPC1->can('recv_cmd1');
52         $WQ_MAX_WORKERS = 1 if $recv_cmd1;
53         wq_set_recv_fds(3);
54         PublicInbox::CmdIPC1->can('send_cmd1');
55 };
56
57 # needed to tell recv_cmd1 how many times to loop IO::FDPass::recv
58 sub wq_set_recv_fds {
59         return unless $recv_cmd1;
60         my $nfds = pop;
61         my $sub = sub {
62                 my ($sock, $fds, undef, $flags) = @_;
63                 $recv_cmd1->($sock, $fds, $_[2], $flags, $nfds);
64         };
65         my $self = pop;
66         if (ref $self) {
67                 $self->{-wq_recv_cmd} = $sub;
68         } else {
69                 $recv_cmd = $sub;
70         }
71 }
72
73 sub _get_rec ($) {
74         my ($r) = @_;
75         defined(my $len = <$r>) or return;
76         chop($len) eq "\n" or croak "no LF byte in $len";
77         defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
78         $n == $len or croak "short read: $n != $len";
79         thaw($buf);
80 }
81
82 sub _pack_rec ($) {
83         my ($ref) = @_;
84         my $buf = freeze($ref);
85         length($buf) . "\n" . $buf;
86 }
87
88 sub _send_rec ($$) {
89         my ($w, $ref) = @_;
90         print $w _pack_rec($ref) or croak "print: $!";
91 }
92
93 sub ipc_return ($$$) {
94         my ($w, $ret, $exc) = @_;
95         _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
96 }
97
98 sub ipc_worker_loop ($$$) {
99         my ($self, $r_req, $w_res) = @_;
100         my ($rec, $wantarray, $sub, @args);
101         local $/ = "\n";
102         while ($rec = _get_rec($r_req)) {
103                 ($wantarray, $sub, @args) = @$rec;
104                 # no waiting if client doesn't care,
105                 # this is the overwhelmingly likely case
106                 if (!defined($wantarray)) {
107                         eval { $self->$sub(@args) };
108                         warn "$$ die: $@ (from nowait $sub)\n" if $@;
109                 } elsif ($wantarray) {
110                         my @ret = eval { $self->$sub(@args) };
111                         ipc_return($w_res, \@ret, $@);
112                 } else { # '' => wantscalar
113                         my $ret = eval { $self->$sub(@args) };
114                         ipc_return($w_res, \$ret, $@);
115                 }
116         }
117 }
118
119 # starts a worker if Sereal or Storable is installed
120 sub ipc_worker_spawn {
121         my ($self, $ident, $oldset) = @_;
122         return unless $enc; # no Sereal or Storable
123         return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
124         delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
125         pipe(my ($r_req, $w_req)) or die "pipe: $!";
126         pipe(my ($r_res, $w_res)) or die "pipe: $!";
127         my $sigset = $oldset // PublicInbox::DS::block_signals();
128         my $parent = $$;
129         $self->ipc_atfork_parent;
130         defined(my $pid = fork) or die "fork: $!";
131         if ($pid == 0) {
132                 eval { PublicInbox::DS->Reset };
133                 $w_req = $r_res = undef;
134                 $w_res->autoflush(1);
135                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
136                 local $0 = $ident;
137                 PublicInbox::DS::sig_setmask($sigset);
138                 my $on_destroy = $self->ipc_atfork_child;
139                 eval { ipc_worker_loop($self, $r_req, $w_res) };
140                 die "worker $ident PID:$$ died: $@\n" if $@;
141                 exit;
142         }
143         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
144         $r_req = $w_res = undef;
145         $w_req->autoflush(1);
146         $self->{-ipc_req} = $w_req;
147         $self->{-ipc_res} = $r_res;
148         $self->{-ipc_ppid} = $$;
149         $self->{-ipc_pid} = $pid;
150 }
151
152 sub ipc_worker_reap { # dwaitpid callback
153         my ($self, $pid) = @_;
154         warn "PID:$pid died with \$?=$?\n" if $?;
155 }
156
157 # for base class, override in sub classes
158 sub ipc_atfork_parent {}
159 sub ipc_atfork_child {}
160
161 # idempotent, can be called regardless of whether worker is active or not
162 sub ipc_worker_stop {
163         my ($self) = @_;
164         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
165         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
166         if (!$w_req && !$r_res) {
167                 die "unexpected PID:$pid without IPC pipes" if $pid;
168                 return; # idempotent
169         }
170         die 'no PID with IPC pipes' unless $pid;
171         $w_req = $r_res = undef;
172
173         return if $$ != $ppid;
174         dwaitpid($pid, \&ipc_worker_reap, $self);
175 }
176
177 # use this if we have multiple readers reading curl or "pigz -dc"
178 # and writing to the same store
179 sub ipc_lock_init {
180         my ($self, $f) = @_;
181         require PublicInbox::Lock;
182         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
183 }
184
185 sub ipc_async_wait ($$) {
186         my ($self, $max) = @_; # max == -1 to wait for all
187         my $aif = $self->{-async_inflight} or return;
188         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
189         while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
190                 my $ret = _get_rec($r_res) //
191                         die "no response on $sub (req.size=$bytes)";
192                 $self->{-async_inflight_bytes} -= $bytes;
193
194                 eval { $cb->($cb_arg, $ret) };
195                 warn "E: $sub callback error: $@\n" if $@;
196                 return if --$max == 0;
197         }
198 }
199
200 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
201 sub ipc_do {
202         my ($self, $sub, @args) = @_;
203         if (my $w_req = $self->{-ipc_req}) { # run in worker
204                 my $ipc_lock = $self->{-ipc_lock};
205                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
206                 if (defined(wantarray)) {
207                         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
208                         ipc_async_wait($self, -1);
209                         _send_rec($w_req, [ wantarray, $sub, @args ]);
210                         my $ret = _get_rec($r_res) // die "no response on $sub";
211                         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
212                         wantarray ? @$ret : $$ret;
213                 } else { # likely, fire-and-forget into pipe
214                         _send_rec($w_req, [ undef , $sub, @args ]);
215                 }
216         } else { # run locally
217                 $self->$sub(@args);
218         }
219 }
220
221 sub ipc_async {
222         my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
223         if (my $w_req = $self->{-ipc_req}) { # run in worker
224                 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
225                 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
226                 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
227                         ipc_async_wait($self, 1);
228                 }
229                 my $ipc_lock = $self->{-ipc_lock};
230                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
231                 print $w_req $rec or croak "print: $!";
232                 $$cur_bytes += length($rec);
233                 push @{$self->{-async_inflight}},
234                                 $sub, length($rec), $cb, $cb_arg;
235         } else {
236                 my $ret = [ eval { $self->$sub(@$sub_args) } ];
237                 if (my $exc = $@) {
238                         $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
239                 }
240                 eval { $cb->($cb_arg, $ret) };
241                 warn "E: $sub callback error: $@\n" if $@;
242         }
243 }
244
245 # needed when there's multiple IPC workers and the parent forking
246 # causes newer siblings to inherit older siblings sockets
247 sub ipc_sibling_atfork_child {
248         my ($self) = @_;
249         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
250         delete(@$self{qw(-ipc_req -ipc_res)});
251         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
252 }
253
254 sub wq_worker_loop ($) {
255         my ($self) = @_;
256         my $buf;
257         my $len = $self->{wq_req_len} // (4096 * 33);
258         my ($rec, $sub, @args);
259         my $s2 = $self->{-wq_s2} // die 'BUG: no -wq_s2';
260         local $SIG{PIPE} = sub {
261                 die(bless(\"$_[0]", __PACKAGE__.'::PIPE')) if $sub;
262         };
263         my $rcv = $self->{-wq_recv_cmd} // $recv_cmd;
264         until ($self->{-wq_quit}) {
265                 my (@fds) = $rcv->($s2, $buf, $len) or return; # EOF
266                 my $i = 0;
267                 my @m = @{$self->{wq_open_modes} // [qw( +<&= >&= >&= )]};
268                 for my $fd (@fds) {
269                         my $mode = shift(@m);
270                         if (open(my $fh, $mode, $fd)) {
271                                 $self->{$i++} = $fh;
272                                 $fh->autoflush(1);
273                         } else {
274                                 die "$$ open($mode$fd) (FD:$i): $!";
275                         }
276                 }
277                 # Sereal dies, Storable returns undef
278                 $rec = thaw($buf) //
279                         die "thaw error on buffer of size:".length($buf);
280                 ($sub, @args) = @$rec;
281                 eval { $self->$sub(@args) };
282                 warn "$$ wq_worker: $@" if $@ && ref $@ ne __PACKAGE__.'::PIPE';
283                 undef $sub; # quiet SIG{PIPE} handler
284                 # need to close explicitly to avoid warnings after SIGPIPE
285                 close($_) for (delete(@$self{0..2}));
286         }
287 }
288
289 sub wq_do { # always async
290         my ($self, $sub, $ios, @args) = @_;
291         if (my $s1 = $self->{-wq_s1}) { # run in worker
292                 my $fds = [ map { fileno($_) } @$ios ];
293                 $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
294         } else {
295                 @$self{0..$#$ios} = @$ios;
296                 eval { $self->$sub(@args) };
297                 warn "wq_do: $@" if $@;
298                 delete @$self{0..$#$ios};
299         }
300 }
301
302 sub _wq_worker_start ($$) {
303         my ($self, $oldset) = @_;
304         my $pid = fork // die "fork: $!";
305         if ($pid == 0) {
306                 eval { PublicInbox::DS->Reset };
307                 close(delete $self->{-wq_s1});
308                 delete $self->{qw(-wq_workers -wq_quit -wq_ppid)};
309                 my $quit = sub { $self->{-wq_quit} = 1 };
310                 $SIG{$_} = $quit for (qw(TERM INT QUIT));
311                 $SIG{$_} = 'IGNORE' for (qw(TTOU TTIN));
312                 local $0 = $self->{-wq_ident};
313                 PublicInbox::DS::sig_setmask($oldset);
314                 my $on_destroy = $self->ipc_atfork_child;
315                 eval { wq_worker_loop($self) };
316                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
317                 exit($@ ? 1 : 0);
318         } else {
319                 $self->{-wq_workers}->{$pid} = \undef;
320         }
321 }
322
323 # starts workqueue workers if Sereal or Storable is installed
324 sub wq_workers_start {
325         my ($self, $ident, $nr_workers, $oldset) = @_;
326         ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
327         return if $self->{-wq_s1}; # idempotent
328         my ($s1, $s2);
329         socketpair($s1, $s2, AF_UNIX, $SEQPACKET, 0) or die "socketpair: $!";
330         $self->ipc_atfork_parent;
331         $nr_workers //= 4;
332         $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
333         my $sigset = $oldset // PublicInbox::DS::block_signals();
334         $self->{-wq_workers} = {};
335         $self->{-wq_ident} = $ident;
336         $self->{-wq_s1} = $s1;
337         $self->{-wq_s2} = $s2;
338         _wq_worker_start($self, $sigset) for (1..$nr_workers);
339         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
340         $self->{-wq_ppid} = $$;
341 }
342
343 sub wq_worker_incr { # SIGTTIN handler
344         my ($self, $oldset) = @_;
345         $self->{-wq_s2} or return;
346         return if wq_workers($self) >= $WQ_MAX_WORKERS;
347         $self->ipc_atfork_parent;
348         my $sigset = $oldset // PublicInbox::DS::block_signals();
349         _wq_worker_start($self, $sigset);
350         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
351 }
352
353 sub wq_exit { # wakes up wq_worker_decr_wait
354         send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
355         exit;
356 }
357
358 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
359         my ($self) = @_;
360         return unless wq_workers($self);
361         my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
362         $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
363         $self->{-wq_exit_pending}++;
364         # caller must call wq_worker_decr_wait in main loop
365 }
366
367 sub wq_worker_decr_wait {
368         my ($self, $timeout) = @_;
369         return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
370         my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
371         vec(my $rin = '', fileno($s1), 1) = 1;
372         select(my $rout = $rin, undef, undef, $timeout) or
373                 croak 'timed out waiting for wq_exit';
374         recv($s1, my $pid, 64, 0) // croak "recv: $!";
375         my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
376         delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
377         $self->{-wq_exit_pending}--;
378         dwaitpid($pid, \&ipc_worker_reap, $self);
379 }
380
381 # set or retrieve number of workers
382 sub wq_workers {
383         my ($self, $nr) = @_;
384         my $cur = $self->{-wq_workers} or return;
385         if (defined $nr) {
386                 while (scalar(keys(%$cur)) > $nr) {
387                         $self->wq_worker_decr;
388                         $self->wq_worker_decr_wait;
389                 }
390                 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
391         }
392         scalar(keys(%$cur));
393 }
394
395 sub wq_close {
396         my ($self) = @_;
397         delete @$self{qw(-wq_s1 -wq_s2)} or return;
398         my $ppid = delete $self->{-wq_ppid} or return;
399         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
400         return if $ppid != $$; # can't reap siblings or parents
401         for my $pid (keys %$workers) {
402                 dwaitpid($pid, \&ipc_worker_reap, $self);
403         }
404 }
405
406 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
407
408 sub DESTROY {
409         wq_close($_[0]);
410         ipc_worker_stop($_[0]);
411 }
412
413 1;