]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
ipc: do not die inside wq_worker child process
[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 # - ipc_do and ipc_worker_* is for a single worker/producer and uses pipes
6 # - wq_do and wq_worker* is for a single producer and multiple workers,
7 #   using SOCK_SEQPACKET for work distribution
8 # use ipc_do when you need work done on a certain process
9 # use wq_do when your work can be done on any idle worker
10 package PublicInbox::IPC;
11 use strict;
12 use v5.10.1;
13 use parent qw(Exporter);
14 use Carp qw(croak);
15 use PublicInbox::DS qw(dwaitpid);
16 use PublicInbox::Spawn;
17 use PublicInbox::OnDestroy;
18 use PublicInbox::WQWorker;
19 use Socket qw(AF_UNIX MSG_EOR SOCK_STREAM);
20 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
21 use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
22 our @EXPORT_OK = qw(ipc_freeze ipc_thaw);
23 my $WQ_MAX_WORKERS = 4096;
24 my ($enc, $dec);
25 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
26 # and eliminate method call overhead
27 BEGIN {
28         eval {
29                 require Sereal::Encoder;
30                 require Sereal::Decoder;
31                 Sereal::Encoder->import('sereal_encode_with_object');
32                 Sereal::Decoder->import('sereal_decode_with_object');
33                 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
34         };
35 };
36
37 if ($enc && $dec) { # should be custom ops
38         *ipc_freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
39         *ipc_thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
40 } else {
41         eval { # some distros have Storable as a separate package from Perl
42                 require Storable;
43                 *ipc_freeze = \&Storable::freeze;
44                 *ipc_thaw = \&Storable::thaw;
45                 $enc = 1;
46         } // warn("Storable (part of Perl) missing: $@\n");
47 }
48
49 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
50 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
51         require PublicInbox::CmdIPC4;
52         $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
53         PublicInbox::CmdIPC4->can('send_cmd4');
54 };
55
56 sub _get_rec ($) {
57         my ($r) = @_;
58         defined(my $len = <$r>) or return;
59         chop($len) eq "\n" or croak "no LF byte in $len";
60         defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
61         $n == $len or croak "short read: $n != $len";
62         ipc_thaw($buf);
63 }
64
65 sub _pack_rec ($) {
66         my ($ref) = @_;
67         my $buf = ipc_freeze($ref);
68         length($buf) . "\n" . $buf;
69 }
70
71 sub _send_rec ($$) {
72         my ($w, $ref) = @_;
73         print $w _pack_rec($ref) or croak "print: $!";
74 }
75
76 sub ipc_return ($$$) {
77         my ($w, $ret, $exc) = @_;
78         _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
79 }
80
81 sub ipc_worker_loop ($$$) {
82         my ($self, $r_req, $w_res) = @_;
83         my ($rec, $wantarray, $sub, @args);
84         local $/ = "\n";
85         while ($rec = _get_rec($r_req)) {
86                 ($wantarray, $sub, @args) = @$rec;
87                 # no waiting if client doesn't care,
88                 # this is the overwhelmingly likely case
89                 if (!defined($wantarray)) {
90                         eval { $self->$sub(@args) };
91                         warn "$$ die: $@ (from nowait $sub)\n" if $@;
92                 } elsif ($wantarray) {
93                         my @ret = eval { $self->$sub(@args) };
94                         ipc_return($w_res, \@ret, $@);
95                 } else { # '' => wantscalar
96                         my $ret = eval { $self->$sub(@args) };
97                         ipc_return($w_res, \$ret, $@);
98                 }
99         }
100 }
101
102 # starts a worker if Sereal or Storable is installed
103 sub ipc_worker_spawn {
104         my ($self, $ident, $oldset, $fields) = @_;
105         return unless $enc; # no Sereal or Storable
106         return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
107         delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
108         pipe(my ($r_req, $w_req)) or die "pipe: $!";
109         pipe(my ($r_res, $w_res)) or die "pipe: $!";
110         my $sigset = $oldset // PublicInbox::DS::block_signals();
111         $self->ipc_atfork_prepare;
112         my $seed = rand(0xffffffff);
113         my $pid = fork // die "fork: $!";
114         if ($pid == 0) {
115                 srand($seed);
116                 eval { PublicInbox::DS->Reset };
117                 delete @$self{qw(-wq_s1 -wq_s2 -wq_workers -wq_ppid)};
118                 $w_req = $r_res = undef;
119                 $w_res->autoflush(1);
120                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
121                 local $0 = $ident;
122                 PublicInbox::DS::sig_setmask($sigset);
123                 # ensure we properly exit even if warn() dies:
124                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
125                 eval {
126                         $fields //= {};
127                         local @$self{keys %$fields} = values(%$fields);
128                         my $on_destroy = $self->ipc_atfork_child;
129                         local %SIG = %SIG;
130                         ipc_worker_loop($self, $r_req, $w_res);
131                 };
132                 warn "worker $ident PID:$$ died: $@\n" if $@;
133                 undef $end; # trigger exit
134         }
135         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
136         $r_req = $w_res = undef;
137         $w_req->autoflush(1);
138         $self->{-ipc_req} = $w_req;
139         $self->{-ipc_res} = $r_res;
140         $self->{-ipc_ppid} = $$;
141         $self->{-ipc_pid} = $pid;
142 }
143
144 sub ipc_worker_reap { # dwaitpid callback
145         my ($args, $pid) = @_;
146         return if !$?;
147         # TERM(15) is our default exit signal, PIPE(13) is likely w/ pager
148         my $s = $? & 127;
149         warn "PID:$pid died with \$?=$?\n" if $s != 15 && $s != 13;
150 }
151
152 sub wq_wait_old {
153         my ($self, @args) = @_;
154         my $cb = ref($args[0]) eq 'CODE' ? shift(@args) : \&ipc_worker_reap;
155         my $pids = delete $self->{"-wq_old_pids.$$"} or return;
156         dwaitpid($_, $cb, [$self, @args]) for @$pids;
157 }
158
159 # for base class, override in sub classes
160 sub ipc_atfork_prepare {}
161
162 sub wq_atexit_child {}
163
164 sub ipc_atfork_child {
165         my ($self) = @_;
166         my $io = delete($self->{-ipc_atfork_child_close}) or return;
167         close($_) for @$io;
168         undef;
169 }
170
171 # idempotent, can be called regardless of whether worker is active or not
172 sub ipc_worker_stop {
173         my ($self, $args) = @_;
174         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
175         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
176         if (!$w_req && !$r_res) {
177                 die "unexpected PID:$pid without IPC pipes" if $pid;
178                 return; # idempotent
179         }
180         die 'no PID with IPC pipes' unless $pid;
181         $w_req = $r_res = undef;
182
183         return if $$ != $ppid;
184         dwaitpid($pid, \&ipc_worker_reap, [$self, $args]);
185 }
186
187 # use this if we have multiple readers reading curl or "pigz -dc"
188 # and writing to the same store
189 sub ipc_lock_init {
190         my ($self, $f) = @_;
191         require PublicInbox::Lock;
192         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
193 }
194
195 sub ipc_async_wait ($$) {
196         my ($self, $max) = @_; # max == -1 to wait for all
197         my $aif = $self->{-async_inflight} or return;
198         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
199         while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
200                 my $ret = _get_rec($r_res) //
201                         die "no response on $sub (req.size=$bytes)";
202                 $self->{-async_inflight_bytes} -= $bytes;
203
204                 eval { $cb->($cb_arg, $ret) };
205                 warn "E: $sub callback error: $@\n" if $@;
206                 return if --$max == 0;
207         }
208 }
209
210 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
211 sub ipc_do {
212         my ($self, $sub, @args) = @_;
213         if (my $w_req = $self->{-ipc_req}) { # run in worker
214                 my $ipc_lock = $self->{-ipc_lock};
215                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
216                 if (defined(wantarray)) {
217                         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
218                         ipc_async_wait($self, -1);
219                         _send_rec($w_req, [ wantarray, $sub, @args ]);
220                         my $ret = _get_rec($r_res) // die "no response on $sub";
221                         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
222                         wantarray ? @$ret : $$ret;
223                 } else { # likely, fire-and-forget into pipe
224                         _send_rec($w_req, [ undef , $sub, @args ]);
225                 }
226         } else { # run locally
227                 $self->$sub(@args);
228         }
229 }
230
231 sub ipc_async {
232         my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
233         if (my $w_req = $self->{-ipc_req}) { # run in worker
234                 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
235                 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
236                 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
237                         ipc_async_wait($self, 1);
238                 }
239                 my $ipc_lock = $self->{-ipc_lock};
240                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
241                 print $w_req $rec or croak "print: $!";
242                 $$cur_bytes += length($rec);
243                 push @{$self->{-async_inflight}},
244                                 $sub, length($rec), $cb, $cb_arg;
245         } else {
246                 my $ret = [ eval { $self->$sub(@$sub_args) } ];
247                 if (my $exc = $@) {
248                         $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
249                 }
250                 eval { $cb->($cb_arg, $ret) };
251                 warn "E: $sub callback error: $@\n" if $@;
252         }
253 }
254
255 # needed when there's multiple IPC workers and the parent forking
256 # causes newer siblings to inherit older siblings sockets
257 sub ipc_sibling_atfork_child {
258         my ($self) = @_;
259         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
260         delete(@$self{qw(-ipc_req -ipc_res)});
261         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
262 }
263
264 sub recv_and_run {
265         my ($self, $s2, $len, $full_stream) = @_;
266         my @fds = $recv_cmd->($s2, my $buf, $len);
267         return if scalar(@fds) && !defined($fds[0]);
268         my $n = length($buf) or return 0;
269         my $nfd = 0;
270         for my $fd (@fds) {
271                 if (open(my $cmdfh, '+<&=', $fd)) {
272                         $self->{$nfd++} = $cmdfh;
273                         $cmdfh->autoflush(1);
274                 } else {
275                         die "$$ open(+<&=$fd) (FD:$nfd): $!";
276                 }
277         }
278         while ($full_stream && $n < $len) {
279                 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
280                 croak "read EOF after $n/$len bytes" if $r == 0;
281                 $n = length($buf);
282         }
283         # Sereal dies on truncated data, Storable returns undef
284         my $args = ipc_thaw($buf) // die "thaw error on buffer of size: $n";
285         undef $buf;
286         my $sub = shift @$args;
287         eval { $self->$sub(@$args) };
288         warn "$$ wq_worker: $@" if $@;
289         delete @$self{0..($nfd-1)};
290         $n;
291 }
292
293 sub wq_worker_loop ($) {
294         my ($self) = @_;
295         my $wqw = PublicInbox::WQWorker->new($self);
296         PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
297         PublicInbox::DS->EventLoop;
298         PublicInbox::DS->Reset;
299 }
300
301 sub do_sock_stream { # via wq_do, for big requests
302         my ($self, $len) = @_;
303         recv_and_run($self, delete $self->{0}, $len, 1);
304 }
305
306 sub wq_do { # always async
307         my ($self, $sub, $ios, @args) = @_;
308         if (my $s1 = $self->{-wq_s1}) { # run in worker
309                 my $fds = [ map { fileno($_) } @$ios ];
310                 my $buf = ipc_freeze([$sub, @args]);
311                 my $n = $send_cmd->($s1, $fds, $buf, MSG_EOR);
312                 return if defined($n); # likely
313                 croak "sendmsg: $! (check RLIMIT_NOFILE)" if $!{ETOOMANYREFS};
314                 croak "sendmsg: $!" if !$!{EMSGSIZE};
315                 socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
316                         croak "socketpair: $!";
317                 $n = $send_cmd->($s1, [ fileno($r) ],
318                                 ipc_freeze(['do_sock_stream', length($buf)]),
319                                 MSG_EOR) // croak "sendmsg: $!";
320                 undef $r;
321                 $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
322                 while ($n < length($buf)) {
323                         my $x = syswrite($w, $buf, length($buf) - $n, $n) //
324                                         croak "syswrite: $!";
325                         croak "syswrite wrote 0 bytes" if $x == 0;
326                         $n += $x;
327                 }
328         } else {
329                 @$self{0..$#$ios} = @$ios;
330                 eval { $self->$sub(@args) };
331                 warn "wq_do: $@" if $@;
332                 delete @$self{0..$#$ios}; # don't close
333         }
334 }
335
336 sub _wq_worker_start ($$$) {
337         my ($self, $oldset, $fields) = @_;
338         my $seed = rand(0xffffffff);
339         my $pid = fork // die "fork: $!";
340         if ($pid == 0) {
341                 srand($seed);
342                 eval { PublicInbox::DS->Reset };
343                 delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
344                 $SIG{$_} = 'IGNORE' for (qw(PIPE));
345                 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
346                 local $0 = $self->{-wq_ident};
347                 PublicInbox::DS::sig_setmask($oldset);
348                 # ensure we properly exit even if warn() dies:
349                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
350                 eval {
351                         $fields //= {};
352                         local @$self{keys %$fields} = values(%$fields);
353                         my $on_destroy = $self->ipc_atfork_child;
354                         local %SIG = %SIG;
355                         wq_worker_loop($self);
356                 };
357                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
358                 undef $end; # trigger exit
359         } else {
360                 $self->{-wq_workers}->{$pid} = \undef;
361         }
362 }
363
364 # starts workqueue workers if Sereal or Storable is installed
365 sub wq_workers_start {
366         my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
367         ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
368         return if $self->{-wq_s1}; # idempotent
369         $self->{-wq_s1} = $self->{-wq_s2} = undef;
370         socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
371                 die "socketpair: $!";
372         $self->ipc_atfork_prepare;
373         $nr_workers //= 4;
374         $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
375         my $sigset = $oldset // PublicInbox::DS::block_signals();
376         $self->{-wq_workers} = {};
377         $self->{-wq_ident} = $ident;
378         _wq_worker_start($self, $sigset, $fields) for (1..$nr_workers);
379         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
380         $self->{-wq_ppid} = $$;
381 }
382
383 sub wq_worker_incr { # SIGTTIN handler
384         my ($self, $oldset, $fields) = @_;
385         $self->{-wq_s2} or return;
386         return if wq_workers($self) >= $WQ_MAX_WORKERS;
387         $self->ipc_atfork_prepare;
388         my $sigset = $oldset // PublicInbox::DS::block_signals();
389         _wq_worker_start($self, $sigset, $fields);
390         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
391 }
392
393 sub wq_exit { # wakes up wq_worker_decr_wait
394         send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
395         exit;
396 }
397
398 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
399         my ($self) = @_;
400         return unless wq_workers($self);
401         my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
402         $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
403         # caller must call wq_worker_decr_wait in main loop
404 }
405
406 sub wq_worker_decr_wait {
407         my ($self, $timeout) = @_;
408         return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
409         my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
410         vec(my $rin = '', fileno($s1), 1) = 1;
411         select(my $rout = $rin, undef, undef, $timeout) or
412                 croak 'timed out waiting for wq_exit';
413         recv($s1, my $pid, 64, 0) // croak "recv: $!";
414         my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
415         delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
416         dwaitpid($pid, \&ipc_worker_reap, $self);
417 }
418
419 # set or retrieve number of workers
420 sub wq_workers {
421         my ($self, $nr) = @_;
422         my $cur = $self->{-wq_workers} or return;
423         if (defined $nr) {
424                 while (scalar(keys(%$cur)) > $nr) {
425                         $self->wq_worker_decr;
426                         $self->wq_worker_decr_wait;
427                 }
428                 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
429         }
430         scalar(keys(%$cur));
431 }
432
433 sub wq_close {
434         my ($self, $nohang) = @_;
435         delete @$self{qw(-wq_s1 -wq_s2)} or return;
436         my $ppid = delete $self->{-wq_ppid} or return;
437         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
438         return if $ppid != $$; # can't reap siblings or parents
439         my @pids = map { $_ + 0 } keys %$workers;
440         if ($nohang) {
441                 push @{$self->{"-wq_old_pids.$$"}}, @pids;
442         } else {
443                 dwaitpid($_, \&ipc_worker_reap, $self) for @pids;
444         }
445 }
446
447 sub wq_kill_old {
448         my ($self) = @_;
449         my $pids = $self->{"-wq_old_pids.$$"} or return;
450         kill 'TERM', @$pids;
451 }
452
453 sub wq_kill {
454         my ($self, $sig) = @_;
455         my $workers = $self->{-wq_workers} or return;
456         kill($sig // 'TERM', keys %$workers);
457 }
458
459 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
460
461 sub DESTROY {
462         my ($self) = @_;
463         my $ppid = $self->{-wq_ppid};
464         wq_kill($self) if $ppid && $ppid == $$;
465         wq_close($self);
466         wq_wait_old($self);
467         ipc_worker_stop($self);
468 }
469
470 sub detect_nproc () {
471         # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
472         return POSIX::sysconf(84) if $^O eq 'linux';
473         return POSIX::sysconf(58) if $^O eq 'freebsd';
474         # TODO: more OSes
475
476         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
477         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
478                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
479         }
480         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
481                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
482         }
483
484         # should we bother with `sysctl hw.ncpu`?  Those only give
485         # us total processor count, not online processor count.
486         undef
487 }
488
489 1;