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