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 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
13 # and eliminate method call overhead
16 require Sereal::Encoder;
17 require Sereal::Decoder;
18 Sereal::Encoder->import('sereal_encode_with_object');
19 Sereal::Decoder->import('sereal_decode_with_object');
20 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
24 if ($enc && $dec) { # should be custom ops
25 *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
26 *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
28 eval { # some distros have Storable as a separate package from Perl
30 Storable->import(qw(freeze thaw));
32 } // warn("Storable (part of Perl) missing: $@\n");
37 defined(my $len = <$r>) or return;
38 chop($len) eq "\n" or croak "no LF byte in $len";
39 defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
40 $n == $len or croak "short read: $n != $len";
46 my $buf = freeze($ref);
47 print $w length($buf), "\n", $buf or croak "print: $!";
50 sub ipc_return ($$$) {
51 my ($w, $ret, $exc) = @_;
52 _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
55 sub ipc_worker_loop ($$$) {
56 my ($self, $r_req, $w_res) = @_;
57 my ($rec, $wantarray, $sub, @args);
59 while ($rec = _get_rec($r_req)) {
60 ($wantarray, $sub, @args) = @$rec;
61 # no waiting if client doesn't care,
62 # this is the overwhelmingly likely case
63 if (!defined($wantarray)) {
64 eval { $self->$sub(@args) };
65 eval { warn "$$ die: $@ (from nowait $sub)\n" } if $@;
66 } elsif ($wantarray) {
67 my @ret = eval { $self->$sub(@args) };
68 ipc_return($w_res, \@ret, $@);
69 } else { # '' => wantscalar
70 my $ret = eval { $self->$sub(@args) };
71 ipc_return($w_res, \$ret, $@);
76 # starts a worker if Sereal or Storable is installed
77 sub ipc_worker_spawn {
78 my ($self, $ident, $oldset) = @_;
79 return unless $enc; # no Sereal or Storable
80 return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
81 delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
82 pipe(my ($r_req, $w_req)) or die "pipe: $!";
83 pipe(my ($r_res, $w_res)) or die "pipe: $!";
84 my $sigset = $oldset // PublicInbox::Sigfd::block_signals();
86 $self->ipc_atfork_parent;
87 defined(my $pid = fork) or die "fork: $!";
89 eval { PublicInbox::DS->Reset };
90 $self->{-ipc_parent_pid} = $parent;
91 $w_req = $r_res = undef;
93 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
95 PublicInbox::Sigfd::sig_setmask($oldset);
96 my $on_destroy = $self->ipc_atfork_child;
97 eval { ipc_worker_loop($self, $r_req, $w_res) };
98 die "worker $ident PID:$$ died: $@\n" if $@;
101 PublicInbox::Sigfd::sig_setmask($sigset) unless $oldset;
102 $r_req = $w_res = undef;
103 $w_req->autoflush(1);
104 $self->{-ipc_req} = $w_req;
105 $self->{-ipc_res} = $r_res;
106 $self->{-ipc_ppid} = $$;
107 $self->{-ipc_pid} = $pid;
110 sub ipc_worker_reap { # dwaitpid callback
111 my ($self, $pid) = @_;
112 warn "PID:$pid died with \$?=$?\n" if $?;
115 # for base class, override in sub classes
116 sub ipc_atfork_parent {}
117 sub ipc_atfork_child {}
119 # should only be called inside the worker process
120 sub ipc_worker_exit {
121 my (undef, $code) = @_;
125 # idempotent, can be called regardless of whether worker is active or not
126 sub ipc_worker_stop {
128 my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
129 my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
130 if (!$w_req && !$r_res) {
131 die "unexpected PID:$pid without IPC pipes" if $pid;
134 die 'no PID with IPC pipes' unless $pid;
135 _send_rec($w_req, [ undef, 'ipc_worker_exit', 0 ]);
136 $w_req = $r_res = undef;
138 # allow any sibling to send ipc_worker_exit, but siblings can't wait
139 return if $$ != $ppid;
141 my $reap = $self->can('ipc_worker_reap');
142 PublicInbox::DS::dwaitpid($pid, $reap, $self);
145 my $wp = waitpid($pid, 0);
146 $pid == $wp or die "waitpid($pid) returned $wp: \$?=$?";
147 $self->ipc_worker_reap($pid);
151 # use this if we have multiple readers reading curl or "pigz -dc"
152 # and writing to the same store
155 require PublicInbox::Lock;
156 $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
159 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
161 my ($self, $sub, @args) = @_;
162 if (my $w_req = $self->{-ipc_req}) { # run in worker
163 my $ipc_lock = $self->{-ipc_lock};
164 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
165 if (defined(wantarray)) {
166 my $r_res = $self->{-ipc_res} or die 'no ipc_res';
167 _send_rec($w_req, [ wantarray, $sub, @args ]);
168 my $ret = _get_rec($r_res) // die "no response on $sub";
169 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
170 wantarray ? @$ret : $$ret;
171 } else { # likely, fire-and-forget into pipe
172 _send_rec($w_req, [ undef , $sub, @args ]);
174 } else { # run locally
179 # needed when there's multiple IPC workers and the parent forking
180 # causes newer siblings to inherit older siblings sockets
181 sub ipc_sibling_atfork_child {
183 my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
184 delete(@$self{qw(-ipc_req -ipc_res)});
185 $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";