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