]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
ipc: switch wq to use the event loop
[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         # 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 wq_atexit_child {}
156
157 sub ipc_atfork_child {
158         my ($self) = @_;
159         my $io = delete($self->{-ipc_atfork_child_close}) or return;
160         close($_) for @$io;
161         undef;
162 }
163
164 # idempotent, can be called regardless of whether worker is active or not
165 sub ipc_worker_stop {
166         my ($self) = @_;
167         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
168         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
169         if (!$w_req && !$r_res) {
170                 die "unexpected PID:$pid without IPC pipes" if $pid;
171                 return; # idempotent
172         }
173         die 'no PID with IPC pipes' unless $pid;
174         $w_req = $r_res = undef;
175
176         return if $$ != $ppid;
177         dwaitpid($pid, \&ipc_worker_reap, $self);
178 }
179
180 # use this if we have multiple readers reading curl or "pigz -dc"
181 # and writing to the same store
182 sub ipc_lock_init {
183         my ($self, $f) = @_;
184         require PublicInbox::Lock;
185         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
186 }
187
188 sub ipc_async_wait ($$) {
189         my ($self, $max) = @_; # max == -1 to wait for all
190         my $aif = $self->{-async_inflight} or return;
191         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
192         while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
193                 my $ret = _get_rec($r_res) //
194                         die "no response on $sub (req.size=$bytes)";
195                 $self->{-async_inflight_bytes} -= $bytes;
196
197                 eval { $cb->($cb_arg, $ret) };
198                 warn "E: $sub callback error: $@\n" if $@;
199                 return if --$max == 0;
200         }
201 }
202
203 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
204 sub ipc_do {
205         my ($self, $sub, @args) = @_;
206         if (my $w_req = $self->{-ipc_req}) { # run in worker
207                 my $ipc_lock = $self->{-ipc_lock};
208                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
209                 if (defined(wantarray)) {
210                         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
211                         ipc_async_wait($self, -1);
212                         _send_rec($w_req, [ wantarray, $sub, @args ]);
213                         my $ret = _get_rec($r_res) // die "no response on $sub";
214                         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
215                         wantarray ? @$ret : $$ret;
216                 } else { # likely, fire-and-forget into pipe
217                         _send_rec($w_req, [ undef , $sub, @args ]);
218                 }
219         } else { # run locally
220                 $self->$sub(@args);
221         }
222 }
223
224 sub ipc_async {
225         my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
226         if (my $w_req = $self->{-ipc_req}) { # run in worker
227                 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
228                 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
229                 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
230                         ipc_async_wait($self, 1);
231                 }
232                 my $ipc_lock = $self->{-ipc_lock};
233                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
234                 print $w_req $rec or croak "print: $!";
235                 $$cur_bytes += length($rec);
236                 push @{$self->{-async_inflight}},
237                                 $sub, length($rec), $cb, $cb_arg;
238         } else {
239                 my $ret = [ eval { $self->$sub(@$sub_args) } ];
240                 if (my $exc = $@) {
241                         $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
242                 }
243                 eval { $cb->($cb_arg, $ret) };
244                 warn "E: $sub callback error: $@\n" if $@;
245         }
246 }
247
248 # needed when there's multiple IPC workers and the parent forking
249 # causes newer siblings to inherit older siblings sockets
250 sub ipc_sibling_atfork_child {
251         my ($self) = @_;
252         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
253         delete(@$self{qw(-ipc_req -ipc_res)});
254         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
255 }
256
257 sub recv_and_run {
258         my ($self, $s2, $len, $full_stream) = @_;
259         my @fds = $recv_cmd->($s2, my $buf, $len);
260         return if scalar(@fds) && !defined($fds[0]);
261         my $n = length($buf) or return 0;
262         my $nfd = 0;
263         for my $fd (@fds) {
264                 if (open(my $cmdfh, '+<&=', $fd)) {
265                         $self->{$nfd++} = $cmdfh;
266                         $cmdfh->autoflush(1);
267                 } else {
268                         die "$$ open(+<&=$fd) (FD:$nfd): $!";
269                 }
270         }
271         while ($full_stream && $n < $len) {
272                 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
273                 croak "read EOF after $n/$len bytes" if $r == 0;
274                 $n = length($buf);
275         }
276         # Sereal dies on truncated data, Storable returns undef
277         my $args = thaw($buf) // die "thaw error on buffer of size: $n";
278         undef $buf;
279         my $sub = shift @$args;
280         eval { $self->$sub(@$args) };
281         warn "$$ wq_worker: $@" if $@ && ref($@) ne 'PublicInbox::SIGPIPE';
282         delete @$self{0..($nfd-1)};
283         $n;
284 }
285
286 sub wq_worker_loop ($) {
287         my ($self) = @_;
288         my $wqw = PublicInbox::WQWorker->new($self);
289         PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
290         PublicInbox::DS->EventLoop;
291         PublicInbox::DS->Reset;
292 }
293
294 sub do_sock_stream { # via wq_do, for big requests
295         my ($self, $len) = @_;
296         recv_and_run($self, delete $self->{0}, $len, 1);
297 }
298
299 sub wq_do { # always async
300         my ($self, $sub, $ios, @args) = @_;
301         if (my $s1 = $self->{-wq_s1}) { # run in worker
302                 my $fds = [ map { fileno($_) } @$ios ];
303                 my $n = $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
304                 return if defined($n);
305                 croak "sendmsg error: $!" if $! != EMSGSIZE;
306                 socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
307                         croak "socketpair: $!";
308                 my $buf = freeze([$sub, @args]);
309                 $n = $send_cmd->($s1, [ fileno($r) ],
310                                 freeze(['do_sock_stream', length($buf)]),
311                                 MSG_EOR) // croak "sendmsg: $!";
312                 undef $r;
313                 $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
314                 while ($n < length($buf)) {
315                         my $x = syswrite($w, $buf, length($buf) - $n, $n) //
316                                         croak "syswrite: $!";
317                         croak "syswrite wrote 0 bytes" if $x == 0;
318                         $n += $x;
319                 }
320         } else {
321                 @$self{0..$#$ios} = @$ios;
322                 eval { $self->$sub(@args) };
323                 warn "wq_do: $@" if $@ && ref($@) ne 'PublicInbox::SIGPIPE';
324                 delete @$self{0..$#$ios}; # don't close
325         }
326 }
327
328 sub _wq_worker_start ($$$) {
329         my ($self, $oldset, $fields) = @_;
330         my $seed = rand(0xffffffff);
331         my $pid = fork // die "fork: $!";
332         if ($pid == 0) {
333                 srand($seed);
334                 eval { PublicInbox::DS->Reset };
335                 delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
336                 @$self{keys %$fields} = values(%$fields) if $fields;
337                 $SIG{$_} = 'IGNORE' for (qw(PIPE));
338                 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
339                 local $0 = $self->{-wq_ident};
340                 PublicInbox::DS::sig_setmask($oldset);
341                 # ensure we properly exit even if warn() dies:
342                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
343                 eval {
344                         my $on_destroy = $self->ipc_atfork_child;
345                         local %SIG = %SIG;
346                         wq_worker_loop($self);
347                 };
348                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
349                 undef $end; # trigger exit
350         } else {
351                 $self->{-wq_workers}->{$pid} = \undef;
352         }
353 }
354
355 # starts workqueue workers if Sereal or Storable is installed
356 sub wq_workers_start {
357         my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
358         ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
359         return if $self->{-wq_s1}; # idempotent
360         $self->{-wq_s1} = $self->{-wq_s2} = undef;
361         socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
362                 die "socketpair: $!";
363         $self->ipc_atfork_prepare;
364         $nr_workers //= 4;
365         $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
366         my $sigset = $oldset // PublicInbox::DS::block_signals();
367         $self->{-wq_workers} = {};
368         $self->{-wq_ident} = $ident;
369         _wq_worker_start($self, $sigset, $fields) for (1..$nr_workers);
370         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
371         $self->{-wq_ppid} = $$;
372 }
373
374 sub wq_worker_incr { # SIGTTIN handler
375         my ($self, $oldset, $fields) = @_;
376         $self->{-wq_s2} or return;
377         return if wq_workers($self) >= $WQ_MAX_WORKERS;
378         $self->ipc_atfork_prepare;
379         my $sigset = $oldset // PublicInbox::DS::block_signals();
380         _wq_worker_start($self, $sigset, $fields);
381         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
382 }
383
384 sub wq_exit { # wakes up wq_worker_decr_wait
385         send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
386         exit;
387 }
388
389 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
390         my ($self) = @_;
391         return unless wq_workers($self);
392         my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
393         $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
394         # caller must call wq_worker_decr_wait in main loop
395 }
396
397 sub wq_worker_decr_wait {
398         my ($self, $timeout) = @_;
399         return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
400         my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
401         vec(my $rin = '', fileno($s1), 1) = 1;
402         select(my $rout = $rin, undef, undef, $timeout) or
403                 croak 'timed out waiting for wq_exit';
404         recv($s1, my $pid, 64, 0) // croak "recv: $!";
405         my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
406         delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
407         dwaitpid($pid, \&ipc_worker_reap, $self);
408 }
409
410 # set or retrieve number of workers
411 sub wq_workers {
412         my ($self, $nr) = @_;
413         my $cur = $self->{-wq_workers} or return;
414         if (defined $nr) {
415                 while (scalar(keys(%$cur)) > $nr) {
416                         $self->wq_worker_decr;
417                         $self->wq_worker_decr_wait;
418                 }
419                 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
420         }
421         scalar(keys(%$cur));
422 }
423
424 sub wq_close {
425         my ($self, $nohang) = @_;
426         delete @$self{qw(-wq_s1 -wq_s2)} or return;
427         my $ppid = delete $self->{-wq_ppid} or return;
428         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
429         return if $ppid != $$; # can't reap siblings or parents
430         my @pids = map { $_ + 0 } keys %$workers;
431         if ($nohang) {
432                 push @{$self->{"-wq_old_pids.$$"}}, @pids;
433         } else {
434                 dwaitpid($_, \&ipc_worker_reap, $self) for @pids;
435         }
436 }
437
438 sub wq_kill_old {
439         my ($self) = @_;
440         my $pids = $self->{"-wq_old_pids.$$"} or return;
441         kill 'TERM', @$pids;
442 }
443
444 sub wq_kill {
445         my ($self, $sig) = @_;
446         my $workers = $self->{-wq_workers} or return;
447         kill($sig // 'TERM', keys %$workers);
448 }
449
450 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
451
452 sub DESTROY {
453         my ($self) = @_;
454         my $ppid = $self->{-wq_ppid};
455         wq_kill($self) if $ppid && $ppid == $$;
456         wq_close($self);
457         wq_wait_old($self);
458         ipc_worker_stop($self);
459 }
460
461 # Sereal doesn't have dclone
462 sub deep_clone { thaw(freeze($_[-1])) }
463
464 1;