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