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>
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;
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 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;
23 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
24 # and eliminate method call overhead
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);
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 };
39 eval { # some distros have Storable as a separate package from Perl
41 Storable->import(qw(freeze thaw));
43 } // warn("Storable (part of Perl) missing: $@\n");
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');
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";
64 my $buf = freeze($ref);
65 length($buf) . "\n" . $buf;
70 print $w _pack_rec($ref) or croak "print: $!";
73 sub ipc_return ($$$) {
74 my ($w, $ret, $exc) = @_;
75 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
78 sub ipc_worker_loop ($$$) {
79 my ($self, $r_req, $w_res) = @_;
80 my ($rec, $wantarray, $sub, @args);
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, $@);
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: $!";
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));
119 PublicInbox::DS::sig_setmask($sigset);
120 # ensure we properly exit even if warn() dies:
121 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
123 my $on_destroy = $self->ipc_atfork_child;
125 ipc_worker_loop($self, $r_req, $w_res);
127 die "worker $ident PID:$$ died: $@\n" if $@;
128 undef $end; # trigger exit
130 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
131 $r_req = $w_res = undef;
132 $w_req->autoflush(1);
133 $self->{-ipc_req} = $w_req;
134 $self->{-ipc_res} = $r_res;
135 $self->{-ipc_ppid} = $$;
136 $self->{-ipc_pid} = $pid;
139 sub ipc_worker_reap { # dwaitpid callback
140 my ($self, $pid) = @_;
142 # TERM(15) is our default exit signal, PIPE(13) is likely w/ pager
144 warn "PID:$pid died with \$?=$?\n" if $s != 15 && $s != 13;
149 my $pids = delete $self->{"-wq_old_pids.$$"} or return;
150 dwaitpid($_, \&ipc_worker_reap, $self) for @$pids;
153 # for base class, override in sub classes
154 sub ipc_atfork_prepare {}
156 sub wq_atexit_child {}
158 sub ipc_atfork_child {
160 my $io = delete($self->{-ipc_atfork_child_close}) or return;
165 # idempotent, can be called regardless of whether worker is active or not
166 sub ipc_worker_stop {
168 my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
169 my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
170 if (!$w_req && !$r_res) {
171 die "unexpected PID:$pid without IPC pipes" if $pid;
174 die 'no PID with IPC pipes' unless $pid;
175 $w_req = $r_res = undef;
177 return if $$ != $ppid;
178 dwaitpid($pid, \&ipc_worker_reap, $self);
181 # use this if we have multiple readers reading curl or "pigz -dc"
182 # and writing to the same store
185 require PublicInbox::Lock;
186 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
189 sub ipc_async_wait ($$) {
190 my ($self, $max) = @_; # max == -1 to wait for all
191 my $aif = $self->{-async_inflight} or return;
192 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
193 while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
194 my $ret = _get_rec($r_res) //
195 die "no response on $sub (req.size=$bytes)";
196 $self->{-async_inflight_bytes} -= $bytes;
198 eval { $cb->($cb_arg, $ret) };
199 warn "E: $sub callback error: $@\n" if $@;
200 return if --$max == 0;
204 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
206 my ($self, $sub, @args) = @_;
207 if (my $w_req = $self->{-ipc_req}) { # run in worker
208 my $ipc_lock = $self->{-ipc_lock};
209 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
210 if (defined(wantarray)) {
211 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
212 ipc_async_wait($self, -1);
213 _send_rec($w_req, [ wantarray, $sub, @args ]);
214 my $ret = _get_rec($r_res) // die "no response on $sub";
215 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
216 wantarray ? @$ret : $$ret;
217 } else { # likely, fire-and-forget into pipe
218 _send_rec($w_req, [ undef , $sub, @args ]);
220 } else { # run locally
226 my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
227 if (my $w_req = $self->{-ipc_req}) { # run in worker
228 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
229 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
230 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
231 ipc_async_wait($self, 1);
233 my $ipc_lock = $self->{-ipc_lock};
234 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
235 print $w_req $rec or croak "print: $!";
236 $$cur_bytes += length($rec);
237 push @{$self->{-async_inflight}},
238 $sub, length($rec), $cb, $cb_arg;
240 my $ret = [ eval { $self->$sub(@$sub_args) } ];
242 $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
244 eval { $cb->($cb_arg, $ret) };
245 warn "E: $sub callback error: $@\n" if $@;
249 # needed when there's multiple IPC workers and the parent forking
250 # causes newer siblings to inherit older siblings sockets
251 sub ipc_sibling_atfork_child {
253 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
254 delete(@$self{qw(-ipc_req -ipc_res)});
255 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
259 my ($self, $s2, $len, $full_stream) = @_;
260 my @fds = $recv_cmd->($s2, my $buf, $len);
261 return if scalar(@fds) && !defined($fds[0]);
262 my $n = length($buf) or return 0;
265 if (open(my $cmdfh, '+<&=', $fd)) {
266 $self->{$nfd++} = $cmdfh;
267 $cmdfh->autoflush(1);
269 die "$$ open(+<&=$fd) (FD:$nfd): $!";
272 while ($full_stream && $n < $len) {
273 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
274 croak "read EOF after $n/$len bytes" if $r == 0;
277 # Sereal dies on truncated data, Storable returns undef
278 my $args = thaw($buf) // die "thaw error on buffer of size: $n";
280 my $sub = shift @$args;
281 eval { $self->$sub(@$args) };
282 warn "$$ wq_worker: $@" if $@;
283 delete @$self{0..($nfd-1)};
287 sub wq_worker_loop ($) {
289 my $wqw = PublicInbox::WQWorker->new($self);
290 PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
291 PublicInbox::DS->EventLoop;
292 PublicInbox::DS->Reset;
295 sub do_sock_stream { # via wq_do, for big requests
296 my ($self, $len) = @_;
297 recv_and_run($self, delete $self->{0}, $len, 1);
300 sub wq_do { # always async
301 my ($self, $sub, $ios, @args) = @_;
302 if (my $s1 = $self->{-wq_s1}) { # run in worker
303 my $fds = [ map { fileno($_) } @$ios ];
304 my $n = $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
305 return if defined($n); # likely
306 croak "sendmsg: $! (check RLIMIT_NOFILE)" if $!{ETOOMANYREFS};
307 croak "sendmsg: $!" 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: $!";
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;
323 @$self{0..$#$ios} = @$ios;
324 eval { $self->$sub(@args) };
325 warn "wq_do: $@" if $@;
326 delete @$self{0..$#$ios}; # don't close
330 sub _wq_worker_start ($$$) {
331 my ($self, $oldset, $fields) = @_;
332 my $seed = rand(0xffffffff);
333 my $pid = fork // die "fork: $!";
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(!!$@) });
346 my $on_destroy = $self->ipc_atfork_child;
348 wq_worker_loop($self);
350 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
351 undef $end; # trigger exit
353 $self->{-wq_workers}->{$pid} = \undef;
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;
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} = $$;
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;
386 sub wq_exit { # wakes up wq_worker_decr_wait
387 send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
391 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
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
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);
412 # set or retrieve number of workers
414 my ($self, $nr) = @_;
415 my $cur = $self->{-wq_workers} or return;
417 while (scalar(keys(%$cur)) > $nr) {
418 $self->wq_worker_decr;
419 $self->wq_worker_decr_wait;
421 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
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;
434 push @{$self->{"-wq_old_pids.$$"}}, @pids;
436 dwaitpid($_, \&ipc_worker_reap, $self) for @pids;
442 my $pids = $self->{"-wq_old_pids.$$"} or return;
447 my ($self, $sig) = @_;
448 my $workers = $self->{-wq_workers} or return;
449 kill($sig // 'TERM', keys %$workers);
452 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
456 my $ppid = $self->{-wq_ppid};
457 wq_kill($self) if $ppid && $ppid == $$;
460 ipc_worker_stop($self);
463 # Sereal doesn't have dclone
464 sub deep_clone { thaw(freeze($_[-1])) }