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 $MY_MAX_ARG_STRLEN = 4096 * 33; # extra 4K for serialization
21 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
22 our @EXPORT_OK = qw(ipc_freeze ipc_thaw);
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 { Net::SSLeay::randomize() };
107 eval { PublicInbox::DS->Reset };
108 delete @$self{qw(-wq_s1 -wq_s2 -wq_workers -wq_ppid)};
109 $w_req = $r_res = undef;
110 $w_res->autoflush(1);
111 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
113 # ensure we properly exit even if warn() dies:
114 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
117 local @$self{keys %$fields} = values(%$fields);
118 my $on_destroy = $self->ipc_atfork_child;
119 local @SIG{keys %SIG} = values %SIG;
120 PublicInbox::DS::sig_setmask($sigset);
121 ipc_worker_loop($self, $r_req, $w_res);
123 warn "worker $ident PID:$$ died: $@\n" if $@;
124 undef $end; # trigger exit
126 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
127 $r_req = $w_res = undef;
128 $w_req->autoflush(1);
129 $self->{-ipc_req} = $w_req;
130 $self->{-ipc_res} = $r_res;
131 $self->{-ipc_ppid} = $$;
132 $self->{-ipc_pid} = $pid;
135 sub ipc_worker_reap { # dwaitpid callback
136 my ($args, $pid) = @_;
137 my ($self, @uargs) = @$args;
138 delete $self->{-wq_workers}->{$pid};
139 return $self->{-reap_do}->($args, $pid) if $self->{-reap_do};
142 # TERM(15) is our default exit signal, PIPE(13) is likely w/ pager
143 warn "$self->{-wq_ident} PID:$pid died \$?=$?\n" if $s != 15 && $s != 13
147 my ($self, $cb, @uargs) = @_;
148 local $PublicInbox::DS::in_loop = 1;
149 $self->{-reap_async} = 1;
150 $self->{-reap_do} = $cb;
151 my @pids = keys %{$self->{-wq_workers}};
152 dwaitpid($_, \&ipc_worker_reap, [ $self, @uargs ]) for @pids;
155 # for base class, override in sub classes
156 sub ipc_atfork_prepare {}
158 sub wq_atexit_child {}
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 {
169 my ($self, $args) = @_;
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, $args]);
183 # use this if we have multiple readers reading curl or "pigz -dc"
184 # and writing to the same store
187 $f // die 'BUG: no filename given';
188 require PublicInbox::Lock;
189 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
192 sub _wait_return ($$) {
193 my ($r_res, $sub) = @_;
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;
199 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
201 my ($self, $sub, @args) = @_;
202 if (my $w_req = $self->{-ipc_req}) { # run in worker
203 my $ipc_lock = $self->{-ipc_lock};
204 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
205 if (defined(wantarray)) {
206 my $r_res = $self->{-ipc_res} or die 'no ipc_res';
207 _send_rec($w_req, [ wantarray, $sub, @args ]);
208 _wait_return($r_res, $sub);
209 } else { # likely, fire-and-forget into pipe
210 _send_rec($w_req, [ undef , $sub, @args ]);
212 } else { # run locally
217 # needed when there's multiple IPC workers and the parent forking
218 # causes newer siblings to inherit older siblings sockets
219 sub ipc_sibling_atfork_child {
221 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
222 delete(@$self{qw(-ipc_req -ipc_res)});
223 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
227 my ($self, $s2, $len, $full_stream) = @_;
228 my @fds = $recv_cmd->($s2, my $buf, $len // $MY_MAX_ARG_STRLEN);
229 return if scalar(@fds) && !defined($fds[0]);
230 my $n = length($buf) or return 0;
233 if (open(my $cmdfh, '+<&=', $fd)) {
234 $self->{$nfd++} = $cmdfh;
235 $cmdfh->autoflush(1);
237 die "$$ open(+<&=$fd) (FD:$nfd): $!";
240 while ($full_stream && $n < $len) {
241 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
242 croak "read EOF after $n/$len bytes" if $r == 0;
245 # Sereal dies on truncated data, Storable returns undef
246 my $args = ipc_thaw($buf) // die "thaw error on buffer of size: $n";
248 my $sub = shift @$args;
249 eval { $self->$sub(@$args) };
250 warn "$$ $0 wq_worker: $@" if $@;
251 delete @$self{0..($nfd-1)};
255 sub wq_worker_loop ($$) {
256 my ($self, $bcast2) = @_;
257 my $wqw = PublicInbox::WQWorker->new($self, $self->{-wq_s2});
258 PublicInbox::WQWorker->new($self, $bcast2) if $bcast2;
259 PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
260 PublicInbox::DS::event_loop();
261 PublicInbox::DS->Reset;
264 sub do_sock_stream { # via wq_io_do, for big requests
265 my ($self, $len) = @_;
266 recv_and_run($self, my $s2 = delete $self->{0}, $len, 1);
270 my ($self, $sub, @args) = @_;
271 if (my $wkr = $self->{-wq_workers}) {
272 my $buf = ipc_freeze([$sub, @args]);
273 for my $bcast1 (values %$wkr) {
274 my $sock = $bcast1 // $self->{-wq_s1} // next;
275 send($sock, $buf, MSG_EOR) // croak "send: $!";
276 # XXX shouldn't have to deal with EMSGSIZE here...
279 eval { $self->$sub(@args) };
280 warn "wq_broadcast: $@" if $@;
284 sub stream_in_full ($$$) {
285 my ($s1, $fds, $buf) = @_;
286 socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
287 croak "socketpair: $!";
288 my $n = $send_cmd->($s1, [ fileno($r) ],
289 ipc_freeze(['do_sock_stream', length($buf)]),
290 MSG_EOR) // croak "sendmsg: $!";
292 $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
293 while ($n < length($buf)) {
294 my $x = syswrite($w, $buf, length($buf) - $n, $n) //
295 croak "syswrite: $!";
296 croak "syswrite wrote 0 bytes" if $x == 0;
301 sub wq_io_do { # always async
302 my ($self, $sub, $ios, @args) = @_;
303 if (my $s1 = $self->{-wq_s1}) { # run in worker
304 my $fds = [ map { fileno($_) } @$ios ];
305 my $buf = ipc_freeze([$sub, @args]);
306 if (length($buf) > $MY_MAX_ARG_STRLEN) {
307 stream_in_full($s1, $fds, $buf);
309 my $n = $send_cmd->($s1, $fds, $buf, MSG_EOR);
310 return if defined($n); # likely
312 croak "sendmsg: $! (check RLIMIT_NOFILE)";
313 $!{EMSGSIZE} ? stream_in_full($s1, $fds, $buf) :
314 croak("sendmsg: $!");
317 @$self{0..$#$ios} = @$ios;
318 eval { $self->$sub(@args) };
319 warn "wq_io_do: $@" if $@;
320 delete @$self{0..$#$ios}; # don't close
325 my ($self, $wantarray, $sub, @args) = @_;
327 my @ret = eval { $self->$sub(@args) };
328 ipc_return($self->{0}, \@ret, $@);
329 } else { # '' => wantscalar
330 my $ret = eval { $self->$sub(@args) };
331 ipc_return($self->{0}, \$ret, $@);
336 my ($self, $sub, @args) = @_;
337 if (defined(wantarray)) {
338 pipe(my ($r, $w)) or die "pipe: $!";
339 wq_io_do($self, 'wq_sync_run', [ $w ], wantarray, $sub, @args);
341 _wait_return($r, $sub);
343 wq_io_do($self, $sub, [], @args);
347 sub _wq_worker_start ($$$$) {
348 my ($self, $oldset, $fields, $one) = @_;
349 my ($bcast1, $bcast2);
350 $one or socketpair($bcast1, $bcast2, AF_UNIX, $SEQPACKET, 0) or
351 die "socketpair: $!";
352 my $seed = rand(0xffffffff);
353 my $pid = fork // die "fork: $!";
356 eval { Net::SSLeay::randomize() };
358 eval { PublicInbox::DS->Reset };
359 delete @$self{qw(-wq_s1 -wq_ppid)};
360 $self->{-wq_worker_nr} =
361 keys %{delete($self->{-wq_workers}) // {}};
362 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
363 local $0 = $one ? $self->{-wq_ident} :
364 "$self->{-wq_ident} $self->{-wq_worker_nr}";
365 # ensure we properly exit even if warn() dies:
366 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
369 local @$self{keys %$fields} = values(%$fields);
370 my $on_destroy = $self->ipc_atfork_child;
371 local @SIG{keys %SIG} = values %SIG;
372 PublicInbox::DS::sig_setmask($oldset);
373 wq_worker_loop($self, $bcast2);
375 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
376 undef $end; # trigger exit
378 $self->{-wq_workers}->{$pid} = $bcast1;
382 # starts workqueue workers if Sereal or Storable is installed
383 sub wq_workers_start {
384 my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
385 ($send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
386 return if $self->{-wq_s1}; # idempotent
387 $self->{-wq_s1} = $self->{-wq_s2} = undef;
388 socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
389 die "socketpair: $!";
390 $self->ipc_atfork_prepare;
391 $nr_workers //= $self->{-wq_nr_workers}; # was set earlier
392 my $sigset = $oldset // PublicInbox::DS::block_signals();
393 $self->{-wq_workers} = {};
394 $self->{-wq_ident} = $ident;
395 my $one = $nr_workers == 1;
396 $self->{-wq_nr_workers} = $nr_workers;
397 _wq_worker_start($self, $sigset, $fields, $one) for (1..$nr_workers);
398 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
399 $self->{-wq_ppid} = $$;
404 delete @$self{qw(-wq_s1 -wq_s2)} or return;
405 return if $self->{-reap_async};
406 my @pids = keys %{$self->{-wq_workers}};
407 dwaitpid($_, \&ipc_worker_reap, [ $self ]) for @pids;
411 my ($self, $sig) = @_;
412 kill($sig // 'TERM', keys %{$self->{-wq_workers}});
417 my $ppid = $self->{-wq_ppid};
418 wq_kill($self) if $ppid && $ppid == $$;
420 ipc_worker_stop($self);
423 sub detect_nproc () {
424 # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
425 return POSIX::sysconf(84) if $^O eq 'linux';
426 return POSIX::sysconf(58) if $^O eq 'freebsd';
429 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
430 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
431 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
433 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
434 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
437 # should we bother with `sysctl hw.ncpu`? Those only give
438 # us total processor count, not online processor count.