]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
ipc: work queue support via SOCK_SEQPACKET
[public-inbox.git] / lib / PublicInbox / IPC.pm
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>
3
4 # base class for remote IPC calls and workqueues, requires Storable or Sereal
5 package PublicInbox::IPC;
6 use strict;
7 use v5.10.1;
8 use Carp qw(confess croak);
9 use PublicInbox::DS qw(dwaitpid);
10 use PublicInbox::Spawn;
11 use POSIX ();
12 use Socket qw(AF_UNIX MSG_EOR);
13 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
14 use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
15 my ($enc, $dec);
16 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
17 # and eliminate method call overhead
18 BEGIN {
19         eval {
20                 require Sereal::Encoder;
21                 require Sereal::Decoder;
22                 Sereal::Encoder->import('sereal_encode_with_object');
23                 Sereal::Decoder->import('sereal_decode_with_object');
24                 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
25         };
26 };
27
28 if ($enc && $dec) { # should be custom ops
29         *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
30         *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
31 } else {
32         eval { # some distros have Storable as a separate package from Perl
33                 require Storable;
34                 Storable->import(qw(freeze thaw));
35                 $enc = 1;
36         } // warn("Storable (part of Perl) missing: $@\n");
37 }
38
39 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
40 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
41         require PublicInbox::CmdIPC4;
42         $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
43         PublicInbox::CmdIPC4->can('send_cmd4');
44 } // do {
45         require PublicInbox::CmdIPC1;
46         $recv_cmd = PublicInbox::CmdIPC1->can('recv_cmd1');
47         PublicInbox::CmdIPC1->can('send_cmd1');
48 };
49
50 sub _get_rec ($) {
51         my ($r) = @_;
52         defined(my $len = <$r>) or return;
53         chop($len) eq "\n" or croak "no LF byte in $len";
54         defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
55         $n == $len or croak "short read: $n != $len";
56         thaw($buf);
57 }
58
59 sub _pack_rec ($) {
60         my ($ref) = @_;
61         my $buf = freeze($ref);
62         length($buf) . "\n" . $buf;
63 }
64
65 sub _send_rec ($$) {
66         my ($w, $ref) = @_;
67         print $w _pack_rec($ref) or croak "print: $!";
68 }
69
70 sub ipc_return ($$$) {
71         my ($w, $ret, $exc) = @_;
72         _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
73 }
74
75 sub ipc_worker_loop ($$$) {
76         my ($self, $r_req, $w_res) = @_;
77         my ($rec, $wantarray, $sub, @args);
78         local $/ = "\n";
79         while ($rec = _get_rec($r_req)) {
80                 ($wantarray, $sub, @args) = @$rec;
81                 # no waiting if client doesn't care,
82                 # this is the overwhelmingly likely case
83                 if (!defined($wantarray)) {
84                         eval { $self->$sub(@args) };
85                         warn "$$ die: $@ (from nowait $sub)\n" if $@;
86                 } elsif ($wantarray) {
87                         my @ret = eval { $self->$sub(@args) };
88                         ipc_return($w_res, \@ret, $@);
89                 } else { # '' => wantscalar
90                         my $ret = eval { $self->$sub(@args) };
91                         ipc_return($w_res, \$ret, $@);
92                 }
93         }
94 }
95
96 # starts a worker if Sereal or Storable is installed
97 sub ipc_worker_spawn {
98         my ($self, $ident, $oldset) = @_;
99         return unless $enc; # no Sereal or Storable
100         return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
101         delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
102         pipe(my ($r_req, $w_req)) or die "pipe: $!";
103         pipe(my ($r_res, $w_res)) or die "pipe: $!";
104         my $sigset = $oldset // PublicInbox::DS::block_signals();
105         my $parent = $$;
106         $self->ipc_atfork_parent;
107         defined(my $pid = fork) or die "fork: $!";
108         if ($pid == 0) {
109                 eval { PublicInbox::DS->Reset };
110                 $self->{-ipc_parent_pid} = $parent;
111                 $w_req = $r_res = undef;
112                 $w_res->autoflush(1);
113                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
114                 local $0 = $ident;
115                 PublicInbox::DS::sig_setmask($oldset);
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 $@;
119                 exit;
120         }
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;
128 }
129
130 sub ipc_worker_reap { # dwaitpid callback
131         my ($self, $pid) = @_;
132         warn "PID:$pid died with \$?=$?\n" if $?;
133 }
134
135 # for base class, override in sub classes
136 sub ipc_atfork_parent {}
137 sub ipc_atfork_child {}
138
139 # should only be called inside the worker process
140 sub ipc_worker_exit {
141         my (undef, $code) = @_;
142         exit($code);
143 }
144
145 # idempotent, can be called regardless of whether worker is active or not
146 sub ipc_worker_stop {
147         my ($self) = @_;
148         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
149         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
150         if (!$w_req && !$r_res) {
151                 die "unexpected PID:$pid without IPC pipes" if $pid;
152                 return; # idempotent
153         }
154         die 'no PID with IPC pipes' unless $pid;
155         _send_rec($w_req, [ undef, 'ipc_worker_exit', 0 ]);
156         $w_req = $r_res = undef;
157
158         # allow any sibling to send ipc_worker_exit, but siblings can't wait
159         return if $$ != $ppid;
160         dwaitpid($pid, \&ipc_worker_reap, $self);
161 }
162
163 # use this if we have multiple readers reading curl or "pigz -dc"
164 # and writing to the same store
165 sub ipc_lock_init {
166         my ($self, $f) = @_;
167         require PublicInbox::Lock;
168         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
169 }
170
171 sub ipc_async_wait ($$) {
172         my ($self, $max) = @_; # max == -1 to wait for all
173         my $aif = $self->{-async_inflight} or return;
174         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
175         while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
176                 my $ret = _get_rec($r_res) //
177                         die "no response on $sub (req.size=$bytes)";
178                 $self->{-async_inflight_bytes} -= $bytes;
179
180                 eval { $cb->($cb_arg, $ret) };
181                 warn "E: $sub callback error: $@\n" if $@;
182                 return if --$max == 0;
183         }
184 }
185
186 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
187 sub ipc_do {
188         my ($self, $sub, @args) = @_;
189         if (my $w_req = $self->{-ipc_req}) { # run in worker
190                 my $ipc_lock = $self->{-ipc_lock};
191                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
192                 if (defined(wantarray)) {
193                         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
194                         ipc_async_wait($self, -1);
195                         _send_rec($w_req, [ wantarray, $sub, @args ]);
196                         my $ret = _get_rec($r_res) // die "no response on $sub";
197                         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
198                         wantarray ? @$ret : $$ret;
199                 } else { # likely, fire-and-forget into pipe
200                         _send_rec($w_req, [ undef , $sub, @args ]);
201                 }
202         } else { # run locally
203                 $self->$sub(@args);
204         }
205 }
206
207 sub ipc_async {
208         my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
209         if (my $w_req = $self->{-ipc_req}) { # run in worker
210                 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
211                 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
212                 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
213                         ipc_async_wait($self, 1);
214                 }
215                 my $ipc_lock = $self->{-ipc_lock};
216                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
217                 print $w_req $rec or croak "print: $!";
218                 $$cur_bytes += length($rec);
219                 push @{$self->{-async_inflight}},
220                                 $sub, length($rec), $cb, $cb_arg;
221         } else {
222                 my $ret = [ eval { $self->$sub(@$sub_args) } ];
223                 if (my $exc = $@) {
224                         $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
225                 }
226                 eval { $cb->($cb_arg, $ret) };
227                 warn "E: $sub callback error: $@\n" if $@;
228         }
229 }
230
231 # needed when there's multiple IPC workers and the parent forking
232 # causes newer siblings to inherit older siblings sockets
233 sub ipc_sibling_atfork_child {
234         my ($self) = @_;
235         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
236         delete(@$self{qw(-ipc_req -ipc_res)});
237         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
238 }
239
240 sub wq_worker_loop ($$) {
241         my ($self, $s2) = @_;
242         my $buf;
243         my $len = $self->{wq_req_len} // (4096 * 33);
244         my ($rec, $sub, @args);
245         while (1) {
246                 my (@fds) = $recv_cmd->($s2, $buf, $len) or return; # EOF
247                 my $i = 0;
248                 my @m = @{$self->{wq_open_modes} // [qw( +<&= >&= >&= )]};
249                 for my $fd (@fds) {
250                         my $mode = shift(@m);
251                         if (open(my $fh, $mode, $fd)) {
252                                 $self->{$i++} = $fh;
253                         } else {
254                                 die "$$ open($mode$fd) (FD:$i): $!";
255                         }
256                 }
257                 # Sereal dies, Storable returns undef
258                 $rec = thaw($buf) //
259                         die "thaw error on buffer of size:".length($buf);
260                 ($sub, @args) = @$rec;
261                 eval { $self->$sub(@args) };
262                 warn "$$ wq_worker: $@" if $@;
263                 delete @$self{0, 1, 2};
264         }
265 }
266
267 sub wq_do { # always async
268         my ($self, $sub, $in, $out, $err, @args) = @_;
269         if (my $s1 = $self->{-wq_seq}) { # run in worker
270                 $_ = fileno($_) for ($in, $out, $err);
271                 $send_cmd->($s1, $in, $out, $err,
272                                 freeze([$sub, @args]), MSG_EOR);
273         } else {
274                 @$self{0, 1, 2} = ($in, $out, $err);
275                 eval { $self->$sub(@args) };
276                 warn "wq_do: $@" if $@;
277                 delete @$self{0, 1, 2};
278         }
279 }
280
281 # starts workqueue workers if Sereal or Storable is installed
282 sub wq_workers_start {
283         my ($self, $ident, $nr_workers, $oldset) = @_;
284         ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
285         return if $self->{-wq_seq}; # idempotent
286         my ($s1, $s2);
287         socketpair($s1, $s2, AF_UNIX, $SEQPACKET, 0) or die "socketpair: $!";
288         my $sigset = $oldset // PublicInbox::DS::block_signals();
289         $self->ipc_atfork_parent;
290         $nr_workers //= 4;
291         $self->{-wq_workers} = {};
292         for my $i (0..($nr_workers - 1)) {
293                 defined(my $pid = fork) or die "fork: $!";
294                 if ($pid == 0) {
295                         eval { PublicInbox::DS->Reset };
296                         $s1 = undef;
297                         $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
298                         local $0 = $ident."[$i]";
299                         PublicInbox::DS::sig_setmask($oldset);
300                         my $on_destroy = $self->ipc_atfork_child;
301                         eval { wq_worker_loop($self, $s2) };
302                         die "worker $ident PID:$$ died: $@\n" if $@;
303                         exit;
304                 } else {
305                         $self->{-wq_workers}->{$pid} = $i;
306                 }
307         }
308         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
309         $s2 = undef;
310         $self->{-wq_seq} = $s1;
311         $self->{-wq_ppid} = $$;
312 }
313
314 sub wq_close {
315         my ($self) = @_;
316         delete $self->{-wq_seq} or return;
317         my $ppid = delete $self->{-wq_ppid} // die 'BUG: no wq_ppid';
318         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
319         return if $ppid != $$; # can't reap siblings or parents
320         for my $pid (keys %$workers) {
321                 dwaitpid($pid, \&ipc_worker_reap, $self);
322         }
323 }
324
325 1;