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