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