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, requires Storable
5 # TODO: this ought to be usable in SearchIdxShard
6 package PublicInbox::IPC;
9 use Carp qw(confess croak);
10 use PublicInbox::Sigfd;
12 use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
14 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
15 # and eliminate method call overhead
18 require Sereal::Encoder;
19 require Sereal::Decoder;
20 Sereal::Encoder->import('sereal_encode_with_object');
21 Sereal::Decoder->import('sereal_decode_with_object');
22 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
26 if ($enc && $dec) { # should be custom ops
27 *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
28 *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
30 eval { # some distros have Storable as a separate package from Perl
32 Storable->import(qw(freeze thaw));
34 } // warn("Storable (part of Perl) missing: $@\n");
39 defined(my $len = <$r>) or return;
40 chop($len) eq "\n" or croak "no LF byte in $len";
41 defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
42 $n == $len or croak "short read: $n != $len";
48 my $buf = freeze($ref);
49 length($buf) . "\n" . $buf;
54 print $w _pack_rec($ref) or croak "print: $!";
57 sub ipc_return ($$$) {
58 my ($w, $ret, $exc) = @_;
59 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
62 sub ipc_worker_loop ($$$) {
63 my ($self, $r_req, $w_res) = @_;
64 my ($rec, $wantarray, $sub, @args);
66 while ($rec = _get_rec($r_req)) {
67 ($wantarray, $sub, @args) = @$rec;
68 # no waiting if client doesn't care,
69 # this is the overwhelmingly likely case
70 if (!defined($wantarray)) {
71 eval { $self->$sub(@args) };
72 eval { warn "$$ die: $@ (from nowait $sub)\n" } if $@;
73 } elsif ($wantarray) {
74 my @ret = eval { $self->$sub(@args) };
75 ipc_return($w_res, \@ret, $@);
76 } else { # '' => wantscalar
77 my $ret = eval { $self->$sub(@args) };
78 ipc_return($w_res, \$ret, $@);
83 # starts a worker if Sereal or Storable is installed
84 sub ipc_worker_spawn {
85 my ($self, $ident, $oldset) = @_;
86 return unless $enc; # no Sereal or Storable
87 return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
88 delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
89 pipe(my ($r_req, $w_req)) or die "pipe: $!";
90 pipe(my ($r_res, $w_res)) or die "pipe: $!";
91 my $sigset = $oldset // PublicInbox::DS::block_signals();
93 $self->ipc_atfork_parent;
94 defined(my $pid = fork) or die "fork: $!";
96 eval { PublicInbox::DS->Reset };
97 $self->{-ipc_parent_pid} = $parent;
98 $w_req = $r_res = undef;
100 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
102 PublicInbox::DS::sig_setmask($oldset);
103 my $on_destroy = $self->ipc_atfork_child;
104 eval { ipc_worker_loop($self, $r_req, $w_res) };
105 die "worker $ident PID:$$ died: $@\n" if $@;
108 PublicInbox::DS::sig_setmask($sigset) unless $oldset;
109 $r_req = $w_res = undef;
110 $w_req->autoflush(1);
111 $self->{-ipc_req} = $w_req;
112 $self->{-ipc_res} = $r_res;
113 $self->{-ipc_ppid} = $$;
114 $self->{-ipc_pid} = $pid;
117 sub ipc_worker_reap { # dwaitpid callback
118 my ($self, $pid) = @_;
119 warn "PID:$pid died with \$?=$?\n" if $?;
122 # for base class, override in sub classes
123 sub ipc_atfork_parent {}
124 sub ipc_atfork_child {}
126 # should only be called inside the worker process
127 sub ipc_worker_exit {
128 my (undef, $code) = @_;
132 # idempotent, can be called regardless of whether worker is active or not
133 sub ipc_worker_stop {
135 my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
136 my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
137 if (!$w_req && !$r_res) {
138 die "unexpected PID:$pid without IPC pipes" if $pid;
141 die 'no PID with IPC pipes' unless $pid;
142 _send_rec($w_req, [ undef, 'ipc_worker_exit', 0 ]);
143 $w_req = $r_res = undef;
145 # allow any sibling to send ipc_worker_exit, but siblings can't wait
146 return if $$ != $ppid;
148 my $reap = $self->can('ipc_worker_reap');
149 PublicInbox::DS::dwaitpid($pid, $reap, $self);
152 my $wp = waitpid($pid, 0);
153 $pid == $wp or die "waitpid($pid) returned $wp: \$?=$?";
154 $self->ipc_worker_reap($pid);
158 # use this if we have multiple readers reading curl or "pigz -dc"
159 # and writing to the same store
162 require PublicInbox::Lock;
163 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
166 sub ipc_async_wait ($$) {
167 my ($self, $max) = @_; # max == -1 to wait for all
168 my $aif = $self->{-async_inflight} or return;
169 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
170 while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
171 my $ret = _get_rec($r_res) //
172 die "no response on $sub (req.size=$bytes)";
173 $self->{-async_inflight_bytes} -= $bytes;
175 eval { $cb->($cb_arg, $ret) };
176 warn "E: $sub callback error: $@\n" if $@;
177 return if --$max == 0;
181 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
183 my ($self, $sub, @args) = @_;
184 if (my $w_req = $self->{-ipc_req}) { # run in worker
185 my $ipc_lock = $self->{-ipc_lock};
186 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
187 if (defined(wantarray)) {
188 my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
189 ipc_async_wait($self, -1);
190 _send_rec($w_req, [ wantarray, $sub, @args ]);
191 my $ret = _get_rec($r_res) // die "no response on $sub";
192 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
193 wantarray ? @$ret : $$ret;
194 } else { # likely, fire-and-forget into pipe
195 _send_rec($w_req, [ undef , $sub, @args ]);
197 } else { # run locally
203 my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
204 if (my $w_req = $self->{-ipc_req}) { # run in worker
205 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
206 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
207 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
208 ipc_async_wait($self, 1);
210 my $ipc_lock = $self->{-ipc_lock};
211 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
212 print $w_req $rec or croak "print: $!";
213 $$cur_bytes += length($rec);
214 push @{$self->{-async_inflight}},
215 $sub, length($rec), $cb, $cb_arg;
217 my $ret = [ eval { $self->$sub(@$sub_args) } ];
219 $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
221 eval { $cb->($cb_arg, $ret) };
222 warn "E: $sub callback error: $@\n" if $@;
226 # needed when there's multiple IPC workers and the parent forking
227 # causes newer siblings to inherit older siblings sockets
228 sub ipc_sibling_atfork_child {
230 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
231 delete(@$self{qw(-ipc_req -ipc_res)});
232 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";