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