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(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;
19 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
20 # and eliminate method call overhead
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);
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 };
35 eval { # some distros have Storable as a separate package from Perl
37 Storable->import(qw(freeze thaw));
39 } // warn("Storable (part of Perl) missing: $@\n");
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');
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";
60 my $buf = freeze($ref);
61 length($buf) . "\n" . $buf;
66 print $w _pack_rec($ref) or croak "print: $!";
69 sub ipc_return ($$$) {
70 my ($w, $ret, $exc) = @_;
71 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
74 sub ipc_worker_loop ($$$) {
75 my ($self, $r_req, $w_res) = @_;
76 my ($rec, $wantarray, $sub, @args);
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, $@);
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: $!";
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));
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 $@;
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;
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;
138 my $pids = delete $self->{"-wq_old_pids.$$"} or return;
139 dwaitpid($_, \&ipc_worker_reap, $self) for @$pids;
142 # for base class, override in sub classes
143 sub ipc_atfork_prepare {}
145 sub ipc_atfork_child {
147 my $io = delete($self->{-ipc_atfork_child_close}) or return;
152 # idempotent, can be called regardless of whether worker is active or not
153 sub ipc_worker_stop {
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;
161 die 'no PID with IPC pipes' unless $pid;
162 $w_req = $r_res = undef;
164 return if $$ != $ppid;
165 dwaitpid($pid, \&ipc_worker_reap, $self);
168 # use this if we have multiple readers reading curl or "pigz -dc"
169 # and writing to the same store
172 require PublicInbox::Lock;
173 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
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;
185 eval { $cb->($cb_arg, $ret) };
186 warn "E: $sub callback error: $@\n" if $@;
187 return if --$max == 0;
191 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
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 ]);
207 } else { # run locally
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);
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;
227 my $ret = [ eval { $self->$sub(@$sub_args) } ];
229 $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
231 eval { $cb->($cb_arg, $ret) };
232 warn "E: $sub callback error: $@\n" if $@;
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 {
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";
246 my ($self, $s2, $len, $full_stream) = @_;
247 my @fds = $recv_cmd->($s2, my $buf, $len);
248 my $n = length($buf // '') or return;
251 if (open(my $cmdfh, '+<&=', $fd)) {
252 $self->{$nfd++} = $cmdfh;
253 $cmdfh->autoflush(1);
255 die "$$ open(+<&=$fd) (FD:$nfd): $!";
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;
263 # Sereal dies on truncated data, Storable returns undef
264 my $args = thaw($buf) // die "thaw error on buffer of size: $n";
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)};
273 sub wq_worker_loop ($) {
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));
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);
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: $!";
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;
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
314 sub _wq_worker_start ($$$) {
315 my ($self, $oldset, $fields) = @_;
316 my $seed = rand(0xffffffff);
317 my $pid = fork // die "fork: $!";
320 eval { PublicInbox::DS->Reset };
321 delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
322 @$self{keys %$fields} = values(%$fields) if $fields;
323 $SIG{$_} = 'IGNORE' for (qw(PIPE TTOU TTIN));
324 $SIG{$_} = 'DEFAULT' for (qw(TERM QUIT INT CHLD));
325 local $0 = $self->{-wq_ident};
326 PublicInbox::DS::sig_setmask($oldset);
327 # ensure we properly exit even if warn() dies:
328 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
329 my $on_destroy = $self->ipc_atfork_child;
330 eval { wq_worker_loop($self) };
331 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
333 undef $end; # trigger exit
335 $self->{-wq_workers}->{$pid} = \undef;
339 # starts workqueue workers if Sereal or Storable is installed
340 sub wq_workers_start {
341 my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
342 ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
343 return if $self->{-wq_s1}; # idempotent
344 $self->{-wq_s1} = $self->{-wq_s2} = undef;
345 socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
346 die "socketpair: $!";
347 $self->ipc_atfork_prepare;
349 $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
350 my $sigset = $oldset // PublicInbox::DS::block_signals();
351 $self->{-wq_workers} = {};
352 $self->{-wq_ident} = $ident;
353 _wq_worker_start($self, $sigset, $fields) for (1..$nr_workers);
354 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
355 $self->{-wq_ppid} = $$;
358 sub wq_worker_incr { # SIGTTIN handler
359 my ($self, $oldset, $fields) = @_;
360 $self->{-wq_s2} or return;
361 return if wq_workers($self) >= $WQ_MAX_WORKERS;
362 $self->ipc_atfork_prepare;
363 my $sigset = $oldset // PublicInbox::DS::block_signals();
364 _wq_worker_start($self, $sigset, $fields);
365 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
368 sub wq_exit { # wakes up wq_worker_decr_wait
369 send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
373 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
375 return unless wq_workers($self);
376 my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
377 $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
378 # caller must call wq_worker_decr_wait in main loop
381 sub wq_worker_decr_wait {
382 my ($self, $timeout) = @_;
383 return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
384 my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
385 vec(my $rin = '', fileno($s1), 1) = 1;
386 select(my $rout = $rin, undef, undef, $timeout) or
387 croak 'timed out waiting for wq_exit';
388 recv($s1, my $pid, 64, 0) // croak "recv: $!";
389 my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
390 delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
391 dwaitpid($pid, \&ipc_worker_reap, $self);
394 # set or retrieve number of workers
396 my ($self, $nr) = @_;
397 my $cur = $self->{-wq_workers} or return;
399 while (scalar(keys(%$cur)) > $nr) {
400 $self->wq_worker_decr;
401 $self->wq_worker_decr_wait;
403 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
409 my ($self, $nohang) = @_;
410 delete @$self{qw(-wq_s1 -wq_s2)} or return;
411 my $ppid = delete $self->{-wq_ppid} or return;
412 my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
413 return if $ppid != $$; # can't reap siblings or parents
414 my @pids = map { $_ + 0 } keys %$workers;
416 push @{$self->{"-wq_old_pids.$$"}}, @pids;
418 dwaitpid($_, \&ipc_worker_reap, $self) for @pids;
424 my $pids = $self->{"-wq_old_pids.$$"} or return;
429 my ($self, $sig) = @_;
430 my $workers = $self->{-wq_workers} or return;
431 kill($sig // 'TERM', keys %$workers);
434 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
438 my $ppid = $self->{-wq_ppid};
439 wq_kill($self) if $ppid && $ppid == $$;
442 ipc_worker_stop($self);
445 # Sereal doesn't have dclone
446 sub deep_clone { thaw(freeze($_[-1])) }