]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
205b5b92cf71d4b1755a93dc7635a12767c9ab95
[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 { Net::SSLeay::randomize() };
107                 eval { PublicInbox::DS->Reset };
108                 delete @$self{qw(-wq_s1 -wq_s2 -wq_workers -wq_ppid)};
109                 $w_req = $r_res = undef;
110                 $w_res->autoflush(1);
111                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
112                 local $0 = $ident;
113                 # ensure we properly exit even if warn() dies:
114                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
115                 eval {
116                         $fields //= {};
117                         local @$self{keys %$fields} = values(%$fields);
118                         my $on_destroy = $self->ipc_atfork_child;
119                         local @SIG{keys %SIG} = values %SIG;
120                         PublicInbox::DS::sig_setmask($sigset);
121                         ipc_worker_loop($self, $r_req, $w_res);
122                 };
123                 warn "worker $ident PID:$$ died: $@\n" if $@;
124                 undef $end; # trigger exit
125         }
126         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
127         $r_req = $w_res = undef;
128         $w_req->autoflush(1);
129         $self->{-ipc_req} = $w_req;
130         $self->{-ipc_res} = $r_res;
131         $self->{-ipc_ppid} = $$;
132         $self->{-ipc_pid} = $pid;
133 }
134
135 sub ipc_worker_reap { # dwaitpid callback
136         my ($args, $pid) = @_;
137         return if !$?;
138         # TERM(15) is our default exit signal, PIPE(13) is likely w/ pager
139         my $s = $? & 127;
140         warn "PID:$pid died with \$?=$?\n" if $s != 15 && $s != 13;
141 }
142
143 sub wq_wait_old {
144         my ($self, $cb, @args) = @_;
145         my $pids = delete $self->{"-wq_old_pids.$$"} or return;
146         dwaitpid($_, $cb // \&ipc_worker_reap, [$self, @args]) for @$pids;
147 }
148
149 # for base class, override in sub classes
150 sub ipc_atfork_prepare {}
151
152 sub wq_atexit_child {}
153
154 sub ipc_atfork_child {
155         my ($self) = @_;
156         my $io = delete($self->{-ipc_atfork_child_close}) or return;
157         close($_) for @$io;
158         undef;
159 }
160
161 # idempotent, can be called regardless of whether worker is active or not
162 sub ipc_worker_stop {
163         my ($self, $args) = @_;
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, $args]);
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         $f // die 'BUG: no filename given';
182         require PublicInbox::Lock;
183         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
184 }
185
186 sub _wait_return ($$) {
187         my ($r_res, $sub) = @_;
188         my $ret = _get_rec($r_res) // die "no response on $sub";
189         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
190         wantarray ? @$ret : $$ret;
191 }
192
193 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
194 sub ipc_do {
195         my ($self, $sub, @args) = @_;
196         if (my $w_req = $self->{-ipc_req}) { # run in worker
197                 my $ipc_lock = $self->{-ipc_lock};
198                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
199                 if (defined(wantarray)) {
200                         my $r_res = $self->{-ipc_res} or die 'no ipc_res';
201                         _send_rec($w_req, [ wantarray, $sub, @args ]);
202                         _wait_return($r_res, $sub);
203                 } else { # likely, fire-and-forget into pipe
204                         _send_rec($w_req, [ undef , $sub, @args ]);
205                 }
206         } else { # run locally
207                 $self->$sub(@args);
208         }
209 }
210
211 # needed when there's multiple IPC workers and the parent forking
212 # causes newer siblings to inherit older siblings sockets
213 sub ipc_sibling_atfork_child {
214         my ($self) = @_;
215         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
216         delete(@$self{qw(-ipc_req -ipc_res)});
217         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
218 }
219
220 sub recv_and_run {
221         my ($self, $s2, $len, $full_stream) = @_;
222         my @fds = $recv_cmd->($s2, my $buf, $len // $MY_MAX_ARG_STRLEN);
223         return if scalar(@fds) && !defined($fds[0]);
224         my $n = length($buf) or return 0;
225         my $nfd = 0;
226         for my $fd (@fds) {
227                 if (open(my $cmdfh, '+<&=', $fd)) {
228                         $self->{$nfd++} = $cmdfh;
229                         $cmdfh->autoflush(1);
230                 } else {
231                         die "$$ open(+<&=$fd) (FD:$nfd): $!";
232                 }
233         }
234         while ($full_stream && $n < $len) {
235                 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
236                 croak "read EOF after $n/$len bytes" if $r == 0;
237                 $n = length($buf);
238         }
239         # Sereal dies on truncated data, Storable returns undef
240         my $args = ipc_thaw($buf) // die "thaw error on buffer of size: $n";
241         undef $buf;
242         my $sub = shift @$args;
243         eval { $self->$sub(@$args) };
244         warn "$$ $0 wq_worker: $@" if $@;
245         delete @$self{0..($nfd-1)};
246         $n;
247 }
248
249 sub wq_worker_loop ($$) {
250         my ($self, $bcast2) = @_;
251         my $wqw = PublicInbox::WQWorker->new($self, $self->{-wq_s2});
252         PublicInbox::WQWorker->new($self, $bcast2) if $bcast2;
253         PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
254         PublicInbox::DS->EventLoop;
255         PublicInbox::DS->Reset;
256 }
257
258 sub do_sock_stream { # via wq_io_do, for big requests
259         my ($self, $len) = @_;
260         recv_and_run($self, my $s2 = delete $self->{0}, $len, 1);
261 }
262
263 sub wq_broadcast {
264         my ($self, $sub, @args) = @_;
265         if (my $wkr = $self->{-wq_workers}) {
266                 my $buf = ipc_freeze([$sub, @args]);
267                 for my $bcast1 (values %$wkr) {
268                         my $sock = $bcast1 // $self->{-wq_s1} // next;
269                         send($sock, $buf, MSG_EOR) // croak "send: $!";
270                         # XXX shouldn't have to deal with EMSGSIZE here...
271                 }
272         } else {
273                 eval { $self->$sub(@args) };
274                 warn "wq_broadcast: $@" if $@;
275         }
276 }
277
278 sub stream_in_full ($$$) {
279         my ($s1, $fds, $buf) = @_;
280         socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
281                 croak "socketpair: $!";
282         my $n = $send_cmd->($s1, [ fileno($r) ],
283                         ipc_freeze(['do_sock_stream', length($buf)]),
284                         MSG_EOR) // croak "sendmsg: $!";
285         undef $r;
286         $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
287         while ($n < length($buf)) {
288                 my $x = syswrite($w, $buf, length($buf) - $n, $n) //
289                                 croak "syswrite: $!";
290                 croak "syswrite wrote 0 bytes" if $x == 0;
291                 $n += $x;
292         }
293 }
294
295 sub wq_io_do { # always async
296         my ($self, $sub, $ios, @args) = @_;
297         if (my $s1 = $self->{-wq_s1}) { # run in worker
298                 my $fds = [ map { fileno($_) } @$ios ];
299                 my $buf = ipc_freeze([$sub, @args]);
300                 if (length($buf) > $MY_MAX_ARG_STRLEN) {
301                         stream_in_full($s1, $fds, $buf);
302                 } else {
303                         my $n = $send_cmd->($s1, $fds, $buf, MSG_EOR);
304                         return if defined($n); # likely
305                         $!{ETOOMANYREFS} and
306                                 croak "sendmsg: $! (check RLIMIT_NOFILE)";
307                         $!{EMSGSIZE} ? stream_in_full($s1, $fds, $buf) :
308                                 croak("sendmsg: $!");
309                 }
310         } else {
311                 @$self{0..$#$ios} = @$ios;
312                 eval { $self->$sub(@args) };
313                 warn "wq_io_do: $@" if $@;
314                 delete @$self{0..$#$ios}; # don't close
315         }
316 }
317
318 sub wq_sync_run {
319         my ($self, $wantarray, $sub, @args) = @_;
320         if ($wantarray) {
321                 my @ret = eval { $self->$sub(@args) };
322                 ipc_return($self->{0}, \@ret, $@);
323         } else { # '' => wantscalar
324                 my $ret = eval { $self->$sub(@args) };
325                 ipc_return($self->{0}, \$ret, $@);
326         }
327 }
328
329 sub wq_do {
330         my ($self, $sub, @args) = @_;
331         if (defined(wantarray)) {
332                 pipe(my ($r, $w)) or die "pipe: $!";
333                 wq_io_do($self, 'wq_sync_run', [ $w ], wantarray, $sub, @args);
334                 undef $w;
335                 _wait_return($r, $sub);
336         } else {
337                 wq_io_do($self, $sub, [], @args);
338         }
339 }
340
341 sub _wq_worker_start ($$$$) {
342         my ($self, $oldset, $fields, $one) = @_;
343         my ($bcast1, $bcast2);
344         $one or socketpair($bcast1, $bcast2, AF_UNIX, $SEQPACKET, 0) or
345                                                         die "socketpair: $!";
346         my $seed = rand(0xffffffff);
347         my $pid = fork // die "fork: $!";
348         if ($pid == 0) {
349                 srand($seed);
350                 eval { Net::SSLeay::randomize() };
351                 undef $bcast1;
352                 eval { PublicInbox::DS->Reset };
353                 delete @$self{qw(-wq_s1 -wq_ppid)};
354                 $self->{-wq_worker_nr} =
355                                 keys %{delete($self->{-wq_workers}) // {}};
356                 $SIG{$_} = 'IGNORE' for (qw(PIPE));
357                 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
358                 local $0 = $one ? $self->{-wq_ident} :
359                         "$self->{-wq_ident} $self->{-wq_worker_nr}";
360                 # ensure we properly exit even if warn() dies:
361                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
362                 eval {
363                         $fields //= {};
364                         local @$self{keys %$fields} = values(%$fields);
365                         my $on_destroy = $self->ipc_atfork_child;
366                         local @SIG{keys %SIG} = values %SIG;
367                         PublicInbox::DS::sig_setmask($oldset);
368                         wq_worker_loop($self, $bcast2);
369                 };
370                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
371                 undef $end; # trigger exit
372         } else {
373                 $self->{-wq_workers}->{$pid} = $bcast1;
374         }
375 }
376
377 # starts workqueue workers if Sereal or Storable is installed
378 sub wq_workers_start {
379         my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
380         ($send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
381         return if $self->{-wq_s1}; # idempotent
382         $self->{-wq_s1} = $self->{-wq_s2} = undef;
383         socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
384                 die "socketpair: $!";
385         $self->ipc_atfork_prepare;
386         $nr_workers //= $self->{-wq_nr_workers}; # was set earlier
387         my $sigset = $oldset // PublicInbox::DS::block_signals();
388         $self->{-wq_workers} = {};
389         $self->{-wq_ident} = $ident;
390         my $one = $nr_workers == 1;
391         $self->{-wq_nr_workers} = $nr_workers;
392         _wq_worker_start($self, $sigset, $fields, $one) for (1..$nr_workers);
393         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
394         $self->{-wq_ppid} = $$;
395 }
396
397 sub wq_close {
398         my ($self, $nohang, $cb, @args) = @_;
399         delete @$self{qw(-wq_s1 -wq_s2)} or return;
400         my $ppid = delete $self->{-wq_ppid} or return;
401         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
402         return if $ppid != $$; # can't reap siblings or parents
403         my @pids = map { $_ + 0 } keys %$workers;
404         if ($nohang) {
405                 push @{$self->{"-wq_old_pids.$$"}}, @pids;
406         } else {
407                 $cb //= \&ipc_worker_reap;
408                 unshift @args, $self;
409                 dwaitpid($_, $cb, \@args) for @pids;
410         }
411 }
412
413 sub wq_kill_old {
414         my ($self, $sig) = @_;
415         my $pids = $self->{"-wq_old_pids.$$"} or return;
416         kill($sig // 'TERM', @$pids);
417 }
418
419 sub wq_kill {
420         my ($self, $sig) = @_;
421         my $workers = $self->{-wq_workers} or return;
422         kill($sig // 'TERM', keys %$workers);
423 }
424
425 sub DESTROY {
426         my ($self) = @_;
427         my $ppid = $self->{-wq_ppid};
428         wq_kill($self) if $ppid && $ppid == $$;
429         my $err = $?;
430         wq_close($self);
431         wq_wait_old($self);
432         ipc_worker_stop($self);
433         $? = $err if $err;
434 }
435
436 sub detect_nproc () {
437         # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
438         return POSIX::sysconf(84) if $^O eq 'linux';
439         return POSIX::sysconf(58) if $^O eq 'freebsd';
440         # TODO: more OSes
441
442         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
443         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
444                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
445         }
446         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
447                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
448         }
449
450         # should we bother with `sysctl hw.ncpu`?  Those only give
451         # us total processor count, not online processor count.
452         undef
453 }
454
455 1;