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_io_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_io_do when your work can be done on any idle worker
10 package PublicInbox::IPC;
13 use parent qw(Exporter);
15 use PublicInbox::DS qw(dwaitpid);
16 use PublicInbox::Spawn;
17 use PublicInbox::OnDestroy;
18 use PublicInbox::WQWorker;
19 use Socket qw(AF_UNIX MSG_EOR SOCK_STREAM);
20 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
21 our @EXPORT_OK = qw(ipc_freeze ipc_thaw);
22 my $WQ_MAX_WORKERS = 4096;
24 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
25 # and eliminate method call overhead
28 require Sereal::Encoder;
29 require Sereal::Decoder;
30 Sereal::Encoder->import('sereal_encode_with_object');
31 Sereal::Decoder->import('sereal_decode_with_object');
32 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
36 if ($enc && $dec) { # should be custom ops
37 *ipc_freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
38 *ipc_thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
41 *ipc_freeze = \&Storable::freeze;
42 *ipc_thaw = \&Storable::thaw;
45 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
46 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
47 require PublicInbox::CmdIPC4;
48 $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
49 PublicInbox::CmdIPC4->can('send_cmd4');
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 = ipc_freeze($ref);
64 print $w length($buf), "\n", $buf or croak "print: $!";
67 sub ipc_return ($$$) {
68 my ($w, $ret, $exc) = @_;
69 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
72 sub ipc_worker_loop ($$$) {
73 my ($self, $r_req, $w_res) = @_;
74 my ($rec, $wantarray, $sub, @args);
76 while ($rec = _get_rec($r_req)) {
77 ($wantarray, $sub, @args) = @$rec;
78 # no waiting if client doesn't care,
79 # this is the overwhelmingly likely case
80 if (!defined($wantarray)) {
81 eval { $self->$sub(@args) };
82 warn "$$ die: $@ (from nowait $sub)\n" if $@;
83 } elsif ($wantarray) {
84 my @ret = eval { $self->$sub(@args) };
85 ipc_return($w_res, \@ret, $@);
86 } else { # '' => wantscalar
87 my $ret = eval { $self->$sub(@args) };
88 ipc_return($w_res, \$ret, $@);
93 # starts a worker if Sereal or Storable is installed
94 sub ipc_worker_spawn {
95 my ($self, $ident, $oldset, $fields) = @_;
96 return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
97 delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
98 pipe(my ($r_req, $w_req)) or die "pipe: $!";
99 pipe(my ($r_res, $w_res)) or die "pipe: $!";
100 my $sigset = $oldset // PublicInbox::DS::block_signals();
101 $self->ipc_atfork_prepare;
102 my $seed = rand(0xffffffff);
103 my $pid = fork // die "fork: $!";
106 eval { PublicInbox::DS->Reset };
107 delete @$self{qw(-wq_s1 -wq_s2 -wq_workers -wq_ppid)};
108 $w_req = $r_res = undef;
109 $w_res->autoflush(1);
110 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
112 # ensure we properly exit even if warn() dies:
113 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
116 local @$self{keys %$fields} = values(%$fields);
117 my $on_destroy = $self->ipc_atfork_child;
119 PublicInbox::DS::sig_setmask($sigset);
120 ipc_worker_loop($self, $r_req, $w_res);
122 warn "worker $ident PID:$$ died: $@\n" if $@;
123 undef $end; # trigger exit
125 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
126 $r_req = $w_res = undef;
127 $w_req->autoflush(1);
128 $self->{-ipc_req} = $w_req;
129 $self->{-ipc_res} = $r_res;
130 $self->{-ipc_ppid} = $$;
131 $self->{-ipc_pid} = $pid;
134 sub ipc_worker_reap { # dwaitpid callback
135 my ($args, $pid) = @_;
137 # TERM(15) is our default exit signal, PIPE(13) is likely w/ pager
139 warn "PID:$pid died with \$?=$?\n" if $s != 15 && $s != 13;
143 my ($self, $cb, @args) = @_;
144 my $pids = delete $self->{"-wq_old_pids.$$"} or return;
145 dwaitpid($_, $cb // \&ipc_worker_reap, [$self, @args]) for @$pids;
148 # for base class, override in sub classes
149 sub ipc_atfork_prepare {}
151 sub wq_atexit_child {}
153 sub ipc_atfork_child {
155 my $io = delete($self->{-ipc_atfork_child_close}) or return;
160 # idempotent, can be called regardless of whether worker is active or not
161 sub ipc_worker_stop {
162 my ($self, $args) = @_;
163 my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
164 my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
165 if (!$w_req && !$r_res) {
166 die "unexpected PID:$pid without IPC pipes" if $pid;
169 die 'no PID with IPC pipes' unless $pid;
170 $w_req = $r_res = undef;
172 return if $$ != $ppid;
173 dwaitpid($pid, \&ipc_worker_reap, [$self, $args]);
176 # use this if we have multiple readers reading curl or "pigz -dc"
177 # and writing to the same store
180 $f // die 'BUG: no filename given';
181 require PublicInbox::Lock;
182 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
185 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
187 my ($self, $sub, @args) = @_;
188 if (my $w_req = $self->{-ipc_req}) { # run in worker
189 my $ipc_lock = $self->{-ipc_lock};
190 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
191 if (defined(wantarray)) {
192 my $r_res = $self->{-ipc_res} or die 'no ipc_res';
193 _send_rec($w_req, [ wantarray, $sub, @args ]);
194 my $ret = _get_rec($r_res) // die "no response on $sub";
195 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
196 wantarray ? @$ret : $$ret;
197 } else { # likely, fire-and-forget into pipe
198 _send_rec($w_req, [ undef , $sub, @args ]);
200 } else { # run locally
205 # needed when there's multiple IPC workers and the parent forking
206 # causes newer siblings to inherit older siblings sockets
207 sub ipc_sibling_atfork_child {
209 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
210 delete(@$self{qw(-ipc_req -ipc_res)});
211 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
215 my ($self, $s2, $len, $full_stream) = @_;
216 my @fds = $recv_cmd->($s2, my $buf, $len);
217 return if scalar(@fds) && !defined($fds[0]);
218 my $n = length($buf) or return 0;
221 if (open(my $cmdfh, '+<&=', $fd)) {
222 $self->{$nfd++} = $cmdfh;
223 $cmdfh->autoflush(1);
225 die "$$ open(+<&=$fd) (FD:$nfd): $!";
228 while ($full_stream && $n < $len) {
229 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
230 croak "read EOF after $n/$len bytes" if $r == 0;
233 # Sereal dies on truncated data, Storable returns undef
234 my $args = ipc_thaw($buf) // die "thaw error on buffer of size: $n";
236 my $sub = shift @$args;
237 eval { $self->$sub(@$args) };
238 warn "$$ wq_worker: $@" if $@;
239 delete @$self{0..($nfd-1)};
243 sub wq_worker_loop ($) {
244 my ($self, $bcast_a) = @_;
245 my $wqw = PublicInbox::WQWorker->new($self);
246 PublicInbox::WQWorker->new($self, '-wq_bcast2');
247 PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
248 PublicInbox::DS->EventLoop;
249 PublicInbox::DS->Reset;
252 sub do_sock_stream { # via wq_io_do, for big requests
253 my ($self, $len) = @_;
254 recv_and_run($self, delete $self->{0}, $len, 1);
258 my ($self, $sub, @args) = @_;
259 if (my $wkr = $self->{-wq_workers}) {
260 for my $bcast1 (values %$wkr) {
261 my $buf = ipc_freeze([$sub, @args]);
262 send($bcast1, $buf, MSG_EOR) // croak "send: $!";
263 # XXX shouldn't have to deal with EMSGSIZE here...
266 eval { $self->$sub(@args) };
267 warn "wq_broadcast: $@" if $@;
271 sub wq_io_do { # always async
272 my ($self, $sub, $ios, @args) = @_;
273 if (my $s1 = $self->{-wq_s1}) { # run in worker
274 my $fds = [ map { fileno($_) } @$ios ];
275 my $buf = ipc_freeze([$sub, @args]);
276 my $n = $send_cmd->($s1, $fds, $buf, MSG_EOR);
277 return if defined($n); # likely
278 croak "sendmsg: $! (check RLIMIT_NOFILE)" if $!{ETOOMANYREFS};
279 croak "sendmsg: $!" if !$!{EMSGSIZE};
280 socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
281 croak "socketpair: $!";
282 $n = $send_cmd->($s1, [ fileno($r) ],
283 ipc_freeze(['do_sock_stream', length($buf)]),
284 MSG_EOR) // croak "sendmsg: $!";
286 $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
287 while ($n < length($buf)) {
288 my $x = syswrite($w, $buf, length($buf) - $n, $n) //
289 croak "syswrite: $!";
290 croak "syswrite wrote 0 bytes" if $x == 0;
294 @$self{0..$#$ios} = @$ios;
295 eval { $self->$sub(@args) };
296 warn "wq_io_do: $@" if $@;
297 delete @$self{0..$#$ios}; # don't close
301 sub _wq_worker_start ($$$) {
302 my ($self, $oldset, $fields) = @_;
303 my ($bcast1, $bcast2);
304 socketpair($bcast1, $bcast2, AF_UNIX, $SEQPACKET, 0) or
305 die "socketpair: $!";
306 my $seed = rand(0xffffffff);
307 my $pid = fork // die "fork: $!";
311 eval { PublicInbox::DS->Reset };
312 delete @$self{qw(-wq_s1 -wq_ppid)};
313 $self->{-wq_worker_nr} =
314 keys %{delete($self->{-wq_workers}) // {}};
315 $SIG{$_} = 'IGNORE' for (qw(PIPE));
316 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
317 local $0 = "$self->{-wq_ident} $self->{-wq_worker_nr}";
318 # ensure we properly exit even if warn() dies:
319 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
322 local @$self{keys %$fields} = values(%$fields);
323 my $on_destroy = $self->ipc_atfork_child;
325 PublicInbox::DS::sig_setmask($oldset);
326 $self->{-wq_bcast2} = $bcast2;
327 wq_worker_loop($self);
329 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
330 undef $end; # trigger exit
332 $self->{-wq_workers}->{$pid} = $bcast1;
336 # starts workqueue workers if Sereal or Storable is installed
337 sub wq_workers_start {
338 my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
339 ($send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
340 return if $self->{-wq_s1}; # idempotent
341 $self->{-wq_s1} = $self->{-wq_s2} = undef;
342 socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
343 die "socketpair: $!";
344 $self->ipc_atfork_prepare;
345 $nr_workers //= $self->{-wq_nr_workers};
346 $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
347 my $sigset = $oldset // PublicInbox::DS::block_signals();
348 $self->{-wq_workers} = {};
349 $self->{-wq_ident} = $ident;
350 _wq_worker_start($self, $sigset, $fields) for (1..$nr_workers);
351 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
352 $self->{-wq_ppid} = $$;
355 sub wq_worker_incr { # SIGTTIN handler
356 my ($self, $oldset, $fields) = @_;
357 $self->{-wq_s2} or return;
358 die "-wq_nr_workers locked" if defined $self->{-wq_nr_workers};
359 return if wq_workers($self) >= $WQ_MAX_WORKERS;
360 $self->ipc_atfork_prepare;
361 my $sigset = $oldset // PublicInbox::DS::block_signals();
362 _wq_worker_start($self, $sigset, $fields);
363 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
366 sub wq_exit { # wakes up wq_worker_decr_wait
367 send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
371 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
373 return unless wq_workers($self);
374 die "-wq_nr_workers locked" if defined $self->{-wq_nr_workers};
375 $self->wq_io_do('wq_exit');
376 # caller must call wq_worker_decr_wait in main loop
379 sub wq_worker_decr_wait {
380 my ($self, $timeout, $cb, @args) = @_;
381 return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
382 die "-wq_nr_workers locked" if defined $self->{-wq_nr_workers};
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, $cb // \&ipc_worker_reap, [ $self, @args ]);
393 # set or retrieve number of workers
395 my ($self, $nr, $cb, @args) = @_;
396 my $cur = $self->{-wq_workers} or return;
398 while (scalar(keys(%$cur)) > $nr) {
399 $self->wq_worker_decr;
400 $self->wq_worker_decr_wait(undef, $cb, @args);
402 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
408 my ($self, $nohang, $cb, @args) = @_;
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;
415 push @{$self->{"-wq_old_pids.$$"}}, @pids;
417 $cb //= \&ipc_worker_reap;
418 unshift @args, $self;
419 dwaitpid($_, $cb, \@args) for @pids;
424 my ($self, $sig) = @_;
425 my $pids = $self->{"-wq_old_pids.$$"} or return;
426 kill($sig // 'TERM', @$pids);
430 my ($self, $sig) = @_;
431 my $workers = $self->{-wq_workers} or return;
432 kill($sig // 'TERM', keys %$workers);
435 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
439 my $ppid = $self->{-wq_ppid};
440 wq_kill($self) if $ppid && $ppid == $$;
444 ipc_worker_stop($self);
448 sub detect_nproc () {
449 # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
450 return POSIX::sysconf(84) if $^O eq 'linux';
451 return POSIX::sysconf(58) if $^O eq 'freebsd';
454 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
455 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
456 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
458 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
459 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
462 # should we bother with `sysctl hw.ncpu`? Those only give
463 # us total processor count, not online processor count.