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_cmd = PublicInbox::Spawn->can('recv_cmd4');
41 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
42 require PublicInbox::CmdIPC4;
43 $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
44 PublicInbox::CmdIPC4->can('send_cmd4');
47 sub wq_set_recv_modes {
48 my ($self, @modes) = @_;
49 $self->{-wq_recv_modes} = \@modes;
54 defined(my $len = <$r>) or return;
55 chop($len) eq "\n" or croak "no LF byte in $len";
56 defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
57 $n == $len or croak "short read: $n != $len";
63 my $buf = freeze($ref);
64 length($buf) . "\n" . $buf;
69 print $w _pack_rec($ref) or croak "print: $!";
72 sub ipc_return ($$$) {
73 my ($w, $ret, $exc) = @_;
74 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
77 sub ipc_worker_loop ($$$) {
78 my ($self, $r_req, $w_res) = @_;
79 my ($rec, $wantarray, $sub, @args);
81 while ($rec = _get_rec($r_req)) {
82 ($wantarray, $sub, @args) = @$rec;
83 # no waiting if client doesn't care,
84 # this is the overwhelmingly likely case
85 if (!defined($wantarray)) {
86 eval { $self->$sub(@args) };
87 warn "$$ die: $@ (from nowait $sub)\n" if $@;
88 } elsif ($wantarray) {
89 my @ret = eval { $self->$sub(@args) };
90 ipc_return($w_res, \@ret, $@);
91 } else { # '' => wantscalar
92 my $ret = eval { $self->$sub(@args) };
93 ipc_return($w_res, \$ret, $@);
98 # starts a worker if Sereal or Storable is installed
99 sub ipc_worker_spawn {
100 my ($self, $ident, $oldset) = @_;
101 return unless $enc; # no Sereal or Storable
102 return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
103 delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
104 pipe(my ($r_req, $w_req)) or die "pipe: $!";
105 pipe(my ($r_res, $w_res)) or die "pipe: $!";
106 my $sigset = $oldset // PublicInbox::DS::block_signals();
108 $self->ipc_atfork_prepare;
109 defined(my $pid = fork) or die "fork: $!";
111 eval { PublicInbox::DS->Reset };
112 $w_req = $r_res = undef;
113 $w_res->autoflush(1);
114 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
116 PublicInbox::DS::sig_setmask($sigset);
117 my $on_destroy = $self->ipc_atfork_child;
118 eval { ipc_worker_loop($self, $r_req, $w_res) };
119 die "worker $ident PID:$$ died: $@\n" if $@;
122 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
123 $r_req = $w_res = undef;
124 $w_req->autoflush(1);
125 $self->{-ipc_req} = $w_req;
126 $self->{-ipc_res} = $r_res;
127 $self->{-ipc_ppid} = $$;
128 $self->{-ipc_pid} = $pid;
131 sub ipc_worker_reap { # dwaitpid callback
132 my ($self, $pid) = @_;
133 # SIGTERM (15) is our default exit signal
134 warn "PID:$pid died with \$?=$?\n" if $? && ($? & 127) != 15;
137 # for base class, override in sub classes
138 sub ipc_atfork_prepare {}
140 sub ipc_atfork_child {
142 my $io = delete($self->{-ipc_atfork_child_close}) or return;
147 # idempotent, can be called regardless of whether worker is active or not
148 sub ipc_worker_stop {
150 my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
151 my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
152 if (!$w_req && !$r_res) {
153 die "unexpected PID:$pid without IPC pipes" if $pid;
156 die 'no PID with IPC pipes' unless $pid;
157 $w_req = $r_res = undef;
159 return if $$ != $ppid;
160 dwaitpid($pid, \&ipc_worker_reap, $self);
163 # use this if we have multiple readers reading curl or "pigz -dc"
164 # and writing to the same store
167 require PublicInbox::Lock;
168 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
171 sub ipc_async_wait ($$) {
172 my ($self, $max) = @_; # max == -1 to wait for all
173 my $aif = $self->{-async_inflight} or return;
174 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
175 while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
176 my $ret = _get_rec($r_res) //
177 die "no response on $sub (req.size=$bytes)";
178 $self->{-async_inflight_bytes} -= $bytes;
180 eval { $cb->($cb_arg, $ret) };
181 warn "E: $sub callback error: $@\n" if $@;
182 return if --$max == 0;
186 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
188 my ($self, $sub, @args) = @_;
189 if (my $w_req = $self->{-ipc_req}) { # run in worker
190 my $ipc_lock = $self->{-ipc_lock};
191 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
192 if (defined(wantarray)) {
193 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
194 ipc_async_wait($self, -1);
195 _send_rec($w_req, [ wantarray, $sub, @args ]);
196 my $ret = _get_rec($r_res) // die "no response on $sub";
197 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
198 wantarray ? @$ret : $$ret;
199 } else { # likely, fire-and-forget into pipe
200 _send_rec($w_req, [ undef , $sub, @args ]);
202 } else { # run locally
208 my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
209 if (my $w_req = $self->{-ipc_req}) { # run in worker
210 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
211 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
212 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
213 ipc_async_wait($self, 1);
215 my $ipc_lock = $self->{-ipc_lock};
216 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
217 print $w_req $rec or croak "print: $!";
218 $$cur_bytes += length($rec);
219 push @{$self->{-async_inflight}},
220 $sub, length($rec), $cb, $cb_arg;
222 my $ret = [ eval { $self->$sub(@$sub_args) } ];
224 $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
226 eval { $cb->($cb_arg, $ret) };
227 warn "E: $sub callback error: $@\n" if $@;
231 # needed when there's multiple IPC workers and the parent forking
232 # causes newer siblings to inherit older siblings sockets
233 sub ipc_sibling_atfork_child {
235 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
236 delete(@$self{qw(-ipc_req -ipc_res)});
237 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
240 sub wq_worker_loop ($) {
242 my $len = $self->{wq_req_len} // (4096 * 33);
243 my $s2 = $self->{-wq_s2} // die 'BUG: no -wq_s2';
245 my @fds = $recv_cmd->($s2, my $buf, $len) or return; # EOF
246 my @m = @{$self->{-wq_recv_modes} // [qw( +<&= >&= >&= )]};
249 my $mode = shift(@m);
250 if (open(my $cmdfh, $mode, $fd)) {
251 $self->{$nfd++} = $cmdfh;
252 $cmdfh->autoflush(1);
254 die "$$ open($mode$fd) (FD:$nfd): $!";
257 # Sereal dies on truncated data, Storable returns undef
258 my $args = thaw($buf) //
259 die "thaw error on buffer of size:".length($buf);
260 my $sub = shift @$args;
261 eval { $self->$sub(@$args) };
262 warn "$$ wq_worker: $@" if $@ &&
263 ref($@) ne 'PublicInbox::SIGPIPE';
264 delete @$self{0..($nfd-1)};
268 sub wq_do { # always async
269 my ($self, $sub, $ios, @args) = @_;
270 if (my $s1 = $self->{-wq_s1}) { # run in worker
271 my $fds = [ map { fileno($_) } @$ios ];
272 $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
274 @$self{0..$#$ios} = @$ios;
275 eval { $self->$sub(@args) };
276 warn "wq_do: $@" if $@ && ref($@) ne 'PublicInbox::SIGPIPE';
277 delete @$self{0..$#$ios}; # don't close
281 sub _wq_worker_start ($$) {
282 my ($self, $oldset) = @_;
283 my $pid = fork // die "fork: $!";
285 eval { PublicInbox::DS->Reset };
286 close(delete $self->{-wq_s1});
287 delete $self->{qw(-wq_workers -wq_ppid)};
288 $SIG{$_} = 'IGNORE' for (qw(PIPE TTOU TTIN));
289 $SIG{$_} = 'DEFAULT' for (qw(TERM QUIT INT CHLD));
290 local $0 = $self->{-wq_ident};
291 PublicInbox::DS::sig_setmask($oldset);
292 # ensure we properly exit even if warn() dies:
293 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
294 my $on_destroy = $self->ipc_atfork_child;
295 eval { wq_worker_loop($self) };
296 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
298 undef $end; # trigger exit
300 $self->{-wq_workers}->{$pid} = \undef;
304 # starts workqueue workers if Sereal or Storable is installed
305 sub wq_workers_start {
306 my ($self, $ident, $nr_workers, $oldset) = @_;
307 ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
308 return if $self->{-wq_s1}; # idempotent
310 socketpair($s1, $s2, AF_UNIX, $SEQPACKET, 0) or die "socketpair: $!";
311 $self->ipc_atfork_prepare;
313 $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
314 my $sigset = $oldset // PublicInbox::DS::block_signals();
315 $self->{-wq_workers} = {};
316 $self->{-wq_ident} = $ident;
317 $self->{-wq_s1} = $s1;
318 $self->{-wq_s2} = $s2;
319 _wq_worker_start($self, $sigset) for (1..$nr_workers);
320 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
321 $self->{-wq_ppid} = $$;
324 sub wq_worker_incr { # SIGTTIN handler
325 my ($self, $oldset) = @_;
326 $self->{-wq_s2} or return;
327 return if wq_workers($self) >= $WQ_MAX_WORKERS;
328 $self->ipc_atfork_prepare;
329 my $sigset = $oldset // PublicInbox::DS::block_signals();
330 _wq_worker_start($self, $sigset);
331 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
334 sub wq_exit { # wakes up wq_worker_decr_wait
335 send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
339 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
341 return unless wq_workers($self);
342 my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
343 $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
344 # caller must call wq_worker_decr_wait in main loop
347 sub wq_worker_decr_wait {
348 my ($self, $timeout) = @_;
349 return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
350 my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
351 vec(my $rin = '', fileno($s1), 1) = 1;
352 select(my $rout = $rin, undef, undef, $timeout) or
353 croak 'timed out waiting for wq_exit';
354 recv($s1, my $pid, 64, 0) // croak "recv: $!";
355 my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
356 delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
357 dwaitpid($pid, \&ipc_worker_reap, $self);
360 # set or retrieve number of workers
362 my ($self, $nr) = @_;
363 my $cur = $self->{-wq_workers} or return;
365 while (scalar(keys(%$cur)) > $nr) {
366 $self->wq_worker_decr;
367 $self->wq_worker_decr_wait;
369 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
376 delete @$self{qw(-wq_s1 -wq_s2)} or return;
377 my $ppid = delete $self->{-wq_ppid} or return;
378 my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
379 return if $ppid != $$; # can't reap siblings or parents
380 for my $pid (keys %$workers) {
381 dwaitpid($pid, \&ipc_worker_reap, $self);
386 my ($self, $sig) = @_;
387 my $workers = $self->{-wq_workers} or return;
388 kill($sig // 'TERM', keys %$workers);
391 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
396 ipc_worker_stop($_[0]);