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 package PublicInbox::IPC;
8 use Carp qw(confess croak);
9 use PublicInbox::DS qw(dwaitpid);
10 use PublicInbox::Spawn;
11 use POSIX qw(WNOHANG);
12 use Socket qw(AF_UNIX MSG_EOR);
13 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
14 use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
15 my $WQ_MAX_WORKERS = 4096;
17 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
18 # and eliminate method call overhead
21 require Sereal::Encoder;
22 require Sereal::Decoder;
23 Sereal::Encoder->import('sereal_encode_with_object');
24 Sereal::Decoder->import('sereal_decode_with_object');
25 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
29 if ($enc && $dec) { # should be custom ops
30 *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
31 *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
33 eval { # some distros have Storable as a separate package from Perl
35 Storable->import(qw(freeze thaw));
37 } // warn("Storable (part of Perl) missing: $@\n");
40 my $recv_cmd1; # PublicInbox::CmdIPC1::recv_cmd1;
41 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
42 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
43 require PublicInbox::CmdIPC4;
44 $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
45 PublicInbox::CmdIPC4->can('send_cmd4');
47 # IO::FDPass only allows sending a single FD at-a-time, which
48 # means we can't guarantee all packets end up on the same worker,
49 # so we cap WQ_MAX_WORKERS
50 require PublicInbox::CmdIPC1;
51 $recv_cmd1 = PublicInbox::CmdIPC1->can('recv_cmd1');
52 $WQ_MAX_WORKERS = 1 if $recv_cmd1;
54 PublicInbox::CmdIPC1->can('send_cmd1');
57 # needed to tell recv_cmd1 how many times to loop IO::FDPass::recv
59 return unless $recv_cmd1;
62 my ($sock, $fds, undef, $flags) = @_;
63 $recv_cmd1->($sock, $fds, $_[2], $flags, $nfds);
67 $self->{-wq_recv_cmd} = $sub;
75 defined(my $len = <$r>) or return;
76 chop($len) eq "\n" or croak "no LF byte in $len";
77 defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
78 $n == $len or croak "short read: $n != $len";
84 my $buf = freeze($ref);
85 length($buf) . "\n" . $buf;
90 print $w _pack_rec($ref) or croak "print: $!";
93 sub ipc_return ($$$) {
94 my ($w, $ret, $exc) = @_;
95 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
98 sub ipc_worker_loop ($$$) {
99 my ($self, $r_req, $w_res) = @_;
100 my ($rec, $wantarray, $sub, @args);
102 while ($rec = _get_rec($r_req)) {
103 ($wantarray, $sub, @args) = @$rec;
104 # no waiting if client doesn't care,
105 # this is the overwhelmingly likely case
106 if (!defined($wantarray)) {
107 eval { $self->$sub(@args) };
108 warn "$$ die: $@ (from nowait $sub)\n" if $@;
109 } elsif ($wantarray) {
110 my @ret = eval { $self->$sub(@args) };
111 ipc_return($w_res, \@ret, $@);
112 } else { # '' => wantscalar
113 my $ret = eval { $self->$sub(@args) };
114 ipc_return($w_res, \$ret, $@);
119 # starts a worker if Sereal or Storable is installed
120 sub ipc_worker_spawn {
121 my ($self, $ident, $oldset) = @_;
122 return unless $enc; # no Sereal or Storable
123 return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
124 delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
125 pipe(my ($r_req, $w_req)) or die "pipe: $!";
126 pipe(my ($r_res, $w_res)) or die "pipe: $!";
127 my $sigset = $oldset // PublicInbox::DS::block_signals();
129 $self->ipc_atfork_prepare;
130 defined(my $pid = fork) or die "fork: $!";
132 eval { PublicInbox::DS->Reset };
133 $w_req = $r_res = undef;
134 $w_res->autoflush(1);
135 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
137 PublicInbox::DS::sig_setmask($sigset);
138 my $on_destroy = $self->ipc_atfork_child;
139 eval { ipc_worker_loop($self, $r_req, $w_res) };
140 die "worker $ident PID:$$ died: $@\n" if $@;
143 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
144 $r_req = $w_res = undef;
145 $w_req->autoflush(1);
146 $self->{-ipc_req} = $w_req;
147 $self->{-ipc_res} = $r_res;
148 $self->{-ipc_ppid} = $$;
149 $self->{-ipc_pid} = $pid;
152 sub ipc_worker_reap { # dwaitpid callback
153 my ($self, $pid) = @_;
154 warn "PID:$pid died with \$?=$?\n" if $?;
157 # for base class, override in sub classes
158 sub ipc_atfork_prepare {}
160 sub ipc_atfork_child {
162 my $io = delete($self->{-ipc_atfork_child_close}) or return;
167 # idempotent, can be called regardless of whether worker is active or not
168 sub ipc_worker_stop {
170 my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
171 my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
172 if (!$w_req && !$r_res) {
173 die "unexpected PID:$pid without IPC pipes" if $pid;
176 die 'no PID with IPC pipes' unless $pid;
177 $w_req = $r_res = undef;
179 return if $$ != $ppid;
180 dwaitpid($pid, \&ipc_worker_reap, $self);
183 # use this if we have multiple readers reading curl or "pigz -dc"
184 # and writing to the same store
187 require PublicInbox::Lock;
188 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
191 sub ipc_async_wait ($$) {
192 my ($self, $max) = @_; # max == -1 to wait for all
193 my $aif = $self->{-async_inflight} or return;
194 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
195 while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
196 my $ret = _get_rec($r_res) //
197 die "no response on $sub (req.size=$bytes)";
198 $self->{-async_inflight_bytes} -= $bytes;
200 eval { $cb->($cb_arg, $ret) };
201 warn "E: $sub callback error: $@\n" if $@;
202 return if --$max == 0;
206 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
208 my ($self, $sub, @args) = @_;
209 if (my $w_req = $self->{-ipc_req}) { # run in worker
210 my $ipc_lock = $self->{-ipc_lock};
211 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
212 if (defined(wantarray)) {
213 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
214 ipc_async_wait($self, -1);
215 _send_rec($w_req, [ wantarray, $sub, @args ]);
216 my $ret = _get_rec($r_res) // die "no response on $sub";
217 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
218 wantarray ? @$ret : $$ret;
219 } else { # likely, fire-and-forget into pipe
220 _send_rec($w_req, [ undef , $sub, @args ]);
222 } else { # run locally
228 my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
229 if (my $w_req = $self->{-ipc_req}) { # run in worker
230 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
231 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
232 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
233 ipc_async_wait($self, 1);
235 my $ipc_lock = $self->{-ipc_lock};
236 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
237 print $w_req $rec or croak "print: $!";
238 $$cur_bytes += length($rec);
239 push @{$self->{-async_inflight}},
240 $sub, length($rec), $cb, $cb_arg;
242 my $ret = [ eval { $self->$sub(@$sub_args) } ];
244 $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
246 eval { $cb->($cb_arg, $ret) };
247 warn "E: $sub callback error: $@\n" if $@;
251 # needed when there's multiple IPC workers and the parent forking
252 # causes newer siblings to inherit older siblings sockets
253 sub ipc_sibling_atfork_child {
255 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
256 delete(@$self{qw(-ipc_req -ipc_res)});
257 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
260 sub _close_recvd ($) {
262 close($_) for (grep { defined } (delete @$self{0..2}));
265 sub wq_worker_loop ($) {
268 my $len = $self->{wq_req_len} // (4096 * 33);
270 my $s2 = $self->{-wq_s2} // die 'BUG: no -wq_s2';
271 local $SIG{PIPE} = sub {
274 die(bless(\$cur_sub, __PACKAGE__.'::PIPE')) if $cur_sub;
276 my $rcv = $self->{-wq_recv_cmd} // $recv_cmd;
278 my (@fds) = $rcv->($s2, $buf, $len) or return; # EOF
280 my @m = @{$self->{wq_open_modes} // [qw( +<&= >&= >&= )]};
282 my $mode = shift(@m);
283 if (open(my $cmdfh, $mode, $fd)) {
284 $self->{$i++} = $cmdfh;
285 $cmdfh->autoflush(1);
287 die "$$ open($mode$fd) (FD:$i): $!";
290 # Sereal dies on truncated data, Storable returns undef
291 $args = thaw($buf) //
292 die "thaw error on buffer of size:".length($buf);
295 eval { $self->$sub(@$args) };
296 undef $sub; # quiet SIG{PIPE} handler
299 warn "$$ wq_worker: $@" if $@ && ref $@ ne __PACKAGE__.'::PIPE';
300 # need to close explicitly to avoid warnings after SIGPIPE
305 sub wq_do { # always async
306 my ($self, $sub, $ios, @args) = @_;
307 if (my $s1 = $self->{-wq_s1}) { # run in worker
308 my $fds = [ map { fileno($_) } @$ios ];
309 $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
311 @$self{0..$#$ios} = @$ios;
312 eval { $self->$sub(@args) };
313 warn "wq_do: $@" if $@;
314 delete @$self{0..$#$ios};
318 sub _wq_worker_start ($$) {
319 my ($self, $oldset) = @_;
320 my $pid = fork // die "fork: $!";
322 eval { PublicInbox::DS->Reset };
323 close(delete $self->{-wq_s1});
324 delete $self->{qw(-wq_workers -wq_ppid)};
325 $SIG{$_} = 'IGNORE' for (qw(PIPE TTOU TTIN));
326 $SIG{$_} = 'DEFAULT' for (qw(TERM QUIT INT CHLD));
327 local $0 = $self->{-wq_ident};
328 PublicInbox::DS::sig_setmask($oldset);
329 # ensure we properly exit even if warn() dies:
330 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
331 my $on_destroy = $self->ipc_atfork_child;
332 eval { wq_worker_loop($self) };
333 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
335 undef $end; # trigger exit
337 $self->{-wq_workers}->{$pid} = \undef;
341 # starts workqueue workers if Sereal or Storable is installed
342 sub wq_workers_start {
343 my ($self, $ident, $nr_workers, $oldset) = @_;
344 ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
345 return if $self->{-wq_s1}; # idempotent
347 socketpair($s1, $s2, AF_UNIX, $SEQPACKET, 0) or die "socketpair: $!";
348 $self->ipc_atfork_prepare;
350 $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
351 my $sigset = $oldset // PublicInbox::DS::block_signals();
352 $self->{-wq_workers} = {};
353 $self->{-wq_ident} = $ident;
354 $self->{-wq_s1} = $s1;
355 $self->{-wq_s2} = $s2;
356 _wq_worker_start($self, $sigset) for (1..$nr_workers);
357 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
358 $self->{-wq_ppid} = $$;
361 sub wq_worker_incr { # SIGTTIN handler
362 my ($self, $oldset) = @_;
363 $self->{-wq_s2} or return;
364 return if wq_workers($self) >= $WQ_MAX_WORKERS;
365 $self->ipc_atfork_prepare;
366 my $sigset = $oldset // PublicInbox::DS::block_signals();
367 _wq_worker_start($self, $sigset);
368 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
371 sub wq_exit { # wakes up wq_worker_decr_wait
372 send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
376 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
378 return unless wq_workers($self);
379 my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
380 $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
381 # caller must call wq_worker_decr_wait in main loop
384 sub wq_worker_decr_wait {
385 my ($self, $timeout) = @_;
386 return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
387 my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
388 vec(my $rin = '', fileno($s1), 1) = 1;
389 select(my $rout = $rin, undef, undef, $timeout) or
390 croak 'timed out waiting for wq_exit';
391 recv($s1, my $pid, 64, 0) // croak "recv: $!";
392 my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
393 delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
394 dwaitpid($pid, \&ipc_worker_reap, $self);
397 # set or retrieve number of workers
399 my ($self, $nr) = @_;
400 my $cur = $self->{-wq_workers} or return;
402 while (scalar(keys(%$cur)) > $nr) {
403 $self->wq_worker_decr;
404 $self->wq_worker_decr_wait;
406 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
413 delete @$self{qw(-wq_s1 -wq_s2)} or return;
414 my $ppid = delete $self->{-wq_ppid} or return;
415 my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
416 return if $ppid != $$; # can't reap siblings or parents
417 for my $pid (keys %$workers) {
418 dwaitpid($pid, \&ipc_worker_reap, $self);
422 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
426 ipc_worker_stop($_[0]);