]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
treewide: replace confess with croak
[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                 die "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 $pids = delete $self->{"-wq_old_pids.$$"} or return;
155         dwaitpid($_, \&ipc_worker_reap, [$self, $args]) for @$pids;
156 }
157
158 # for base class, override in sub classes
159 sub ipc_atfork_prepare {}
160
161 sub wq_atexit_child {}
162
163 sub ipc_atfork_child {
164         my ($self) = @_;
165         my $io = delete($self->{-ipc_atfork_child_close}) or return;
166         close($_) for @$io;
167         undef;
168 }
169
170 # idempotent, can be called regardless of whether worker is active or not
171 sub ipc_worker_stop {
172         my ($self, $args) = @_;
173         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
174         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
175         if (!$w_req && !$r_res) {
176                 die "unexpected PID:$pid without IPC pipes" if $pid;
177                 return; # idempotent
178         }
179         die 'no PID with IPC pipes' unless $pid;
180         $w_req = $r_res = undef;
181
182         return if $$ != $ppid;
183         dwaitpid($pid, \&ipc_worker_reap, [$self, $args]);
184 }
185
186 # use this if we have multiple readers reading curl or "pigz -dc"
187 # and writing to the same store
188 sub ipc_lock_init {
189         my ($self, $f) = @_;
190         require PublicInbox::Lock;
191         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
192 }
193
194 sub ipc_async_wait ($$) {
195         my ($self, $max) = @_; # max == -1 to wait for all
196         my $aif = $self->{-async_inflight} or return;
197         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
198         while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
199                 my $ret = _get_rec($r_res) //
200                         die "no response on $sub (req.size=$bytes)";
201                 $self->{-async_inflight_bytes} -= $bytes;
202
203                 eval { $cb->($cb_arg, $ret) };
204                 warn "E: $sub callback error: $@\n" if $@;
205                 return if --$max == 0;
206         }
207 }
208
209 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
210 sub ipc_do {
211         my ($self, $sub, @args) = @_;
212         if (my $w_req = $self->{-ipc_req}) { # run in worker
213                 my $ipc_lock = $self->{-ipc_lock};
214                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
215                 if (defined(wantarray)) {
216                         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
217                         ipc_async_wait($self, -1);
218                         _send_rec($w_req, [ wantarray, $sub, @args ]);
219                         my $ret = _get_rec($r_res) // die "no response on $sub";
220                         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
221                         wantarray ? @$ret : $$ret;
222                 } else { # likely, fire-and-forget into pipe
223                         _send_rec($w_req, [ undef , $sub, @args ]);
224                 }
225         } else { # run locally
226                 $self->$sub(@args);
227         }
228 }
229
230 sub ipc_async {
231         my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
232         if (my $w_req = $self->{-ipc_req}) { # run in worker
233                 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
234                 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
235                 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
236                         ipc_async_wait($self, 1);
237                 }
238                 my $ipc_lock = $self->{-ipc_lock};
239                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
240                 print $w_req $rec or croak "print: $!";
241                 $$cur_bytes += length($rec);
242                 push @{$self->{-async_inflight}},
243                                 $sub, length($rec), $cb, $cb_arg;
244         } else {
245                 my $ret = [ eval { $self->$sub(@$sub_args) } ];
246                 if (my $exc = $@) {
247                         $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
248                 }
249                 eval { $cb->($cb_arg, $ret) };
250                 warn "E: $sub callback error: $@\n" if $@;
251         }
252 }
253
254 # needed when there's multiple IPC workers and the parent forking
255 # causes newer siblings to inherit older siblings sockets
256 sub ipc_sibling_atfork_child {
257         my ($self) = @_;
258         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
259         delete(@$self{qw(-ipc_req -ipc_res)});
260         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
261 }
262
263 sub recv_and_run {
264         my ($self, $s2, $len, $full_stream) = @_;
265         my @fds = $recv_cmd->($s2, my $buf, $len);
266         return if scalar(@fds) && !defined($fds[0]);
267         my $n = length($buf) or return 0;
268         my $nfd = 0;
269         for my $fd (@fds) {
270                 if (open(my $cmdfh, '+<&=', $fd)) {
271                         $self->{$nfd++} = $cmdfh;
272                         $cmdfh->autoflush(1);
273                 } else {
274                         die "$$ open(+<&=$fd) (FD:$nfd): $!";
275                 }
276         }
277         while ($full_stream && $n < $len) {
278                 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
279                 croak "read EOF after $n/$len bytes" if $r == 0;
280                 $n = length($buf);
281         }
282         # Sereal dies on truncated data, Storable returns undef
283         my $args = ipc_thaw($buf) // die "thaw error on buffer of size: $n";
284         undef $buf;
285         my $sub = shift @$args;
286         eval { $self->$sub(@$args) };
287         warn "$$ wq_worker: $@" if $@;
288         delete @$self{0..($nfd-1)};
289         $n;
290 }
291
292 sub wq_worker_loop ($) {
293         my ($self) = @_;
294         my $wqw = PublicInbox::WQWorker->new($self);
295         PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
296         PublicInbox::DS->EventLoop;
297         PublicInbox::DS->Reset;
298 }
299
300 sub do_sock_stream { # via wq_do, for big requests
301         my ($self, $len) = @_;
302         recv_and_run($self, delete $self->{0}, $len, 1);
303 }
304
305 sub wq_do { # always async
306         my ($self, $sub, $ios, @args) = @_;
307         if (my $s1 = $self->{-wq_s1}) { # run in worker
308                 my $fds = [ map { fileno($_) } @$ios ];
309                 my $buf = ipc_freeze([$sub, @args]);
310                 my $n = $send_cmd->($s1, $fds, $buf, MSG_EOR);
311                 return if defined($n); # likely
312                 croak "sendmsg: $! (check RLIMIT_NOFILE)" if $!{ETOOMANYREFS};
313                 croak "sendmsg: $!" if !$!{EMSGSIZE};
314                 socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
315                         croak "socketpair: $!";
316                 $n = $send_cmd->($s1, [ fileno($r) ],
317                                 ipc_freeze(['do_sock_stream', length($buf)]),
318                                 MSG_EOR) // croak "sendmsg: $!";
319                 undef $r;
320                 $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
321                 while ($n < length($buf)) {
322                         my $x = syswrite($w, $buf, length($buf) - $n, $n) //
323                                         croak "syswrite: $!";
324                         croak "syswrite wrote 0 bytes" if $x == 0;
325                         $n += $x;
326                 }
327         } else {
328                 @$self{0..$#$ios} = @$ios;
329                 eval { $self->$sub(@args) };
330                 warn "wq_do: $@" if $@;
331                 delete @$self{0..$#$ios}; # don't close
332         }
333 }
334
335 sub _wq_worker_start ($$$) {
336         my ($self, $oldset, $fields) = @_;
337         my $seed = rand(0xffffffff);
338         my $pid = fork // die "fork: $!";
339         if ($pid == 0) {
340                 srand($seed);
341                 eval { PublicInbox::DS->Reset };
342                 delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
343                 $SIG{$_} = 'IGNORE' for (qw(PIPE));
344                 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
345                 local $0 = $self->{-wq_ident};
346                 PublicInbox::DS::sig_setmask($oldset);
347                 # ensure we properly exit even if warn() dies:
348                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
349                 eval {
350                         $fields //= {};
351                         local @$self{keys %$fields} = values(%$fields);
352                         my $on_destroy = $self->ipc_atfork_child;
353                         local %SIG = %SIG;
354                         wq_worker_loop($self);
355                 };
356                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
357                 undef $end; # trigger exit
358         } else {
359                 $self->{-wq_workers}->{$pid} = \undef;
360         }
361 }
362
363 # starts workqueue workers if Sereal or Storable is installed
364 sub wq_workers_start {
365         my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
366         ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
367         return if $self->{-wq_s1}; # idempotent
368         $self->{-wq_s1} = $self->{-wq_s2} = undef;
369         socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
370                 die "socketpair: $!";
371         $self->ipc_atfork_prepare;
372         $nr_workers //= 4;
373         $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
374         my $sigset = $oldset // PublicInbox::DS::block_signals();
375         $self->{-wq_workers} = {};
376         $self->{-wq_ident} = $ident;
377         _wq_worker_start($self, $sigset, $fields) for (1..$nr_workers);
378         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
379         $self->{-wq_ppid} = $$;
380 }
381
382 sub wq_worker_incr { # SIGTTIN handler
383         my ($self, $oldset, $fields) = @_;
384         $self->{-wq_s2} or return;
385         return if wq_workers($self) >= $WQ_MAX_WORKERS;
386         $self->ipc_atfork_prepare;
387         my $sigset = $oldset // PublicInbox::DS::block_signals();
388         _wq_worker_start($self, $sigset, $fields);
389         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
390 }
391
392 sub wq_exit { # wakes up wq_worker_decr_wait
393         send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
394         exit;
395 }
396
397 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
398         my ($self) = @_;
399         return unless wq_workers($self);
400         my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
401         $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
402         # caller must call wq_worker_decr_wait in main loop
403 }
404
405 sub wq_worker_decr_wait {
406         my ($self, $timeout) = @_;
407         return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
408         my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
409         vec(my $rin = '', fileno($s1), 1) = 1;
410         select(my $rout = $rin, undef, undef, $timeout) or
411                 croak 'timed out waiting for wq_exit';
412         recv($s1, my $pid, 64, 0) // croak "recv: $!";
413         my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
414         delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
415         dwaitpid($pid, \&ipc_worker_reap, $self);
416 }
417
418 # set or retrieve number of workers
419 sub wq_workers {
420         my ($self, $nr) = @_;
421         my $cur = $self->{-wq_workers} or return;
422         if (defined $nr) {
423                 while (scalar(keys(%$cur)) > $nr) {
424                         $self->wq_worker_decr;
425                         $self->wq_worker_decr_wait;
426                 }
427                 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
428         }
429         scalar(keys(%$cur));
430 }
431
432 sub wq_close {
433         my ($self, $nohang) = @_;
434         delete @$self{qw(-wq_s1 -wq_s2)} or return;
435         my $ppid = delete $self->{-wq_ppid} or return;
436         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
437         return if $ppid != $$; # can't reap siblings or parents
438         my @pids = map { $_ + 0 } keys %$workers;
439         if ($nohang) {
440                 push @{$self->{"-wq_old_pids.$$"}}, @pids;
441         } else {
442                 dwaitpid($_, \&ipc_worker_reap, $self) for @pids;
443         }
444 }
445
446 sub wq_kill_old {
447         my ($self) = @_;
448         my $pids = $self->{"-wq_old_pids.$$"} or return;
449         kill 'TERM', @$pids;
450 }
451
452 sub wq_kill {
453         my ($self, $sig) = @_;
454         my $workers = $self->{-wq_workers} or return;
455         kill($sig // 'TERM', keys %$workers);
456 }
457
458 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
459
460 sub DESTROY {
461         my ($self) = @_;
462         my $ppid = $self->{-wq_ppid};
463         wq_kill($self) if $ppid && $ppid == $$;
464         wq_close($self);
465         wq_wait_old($self);
466         ipc_worker_stop($self);
467 }
468
469 sub detect_nproc () {
470         # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
471         return POSIX::sysconf(84) if $^O eq 'linux';
472         return POSIX::sysconf(58) if $^O eq 'freebsd';
473         # TODO: more OSes
474
475         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
476         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
477                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
478         }
479         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
480                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
481         }
482
483         # should we bother with `sysctl hw.ncpu`?  Those only give
484         # us total processor count, not online processor count.
485         undef
486 }
487
488 1;