]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
treewide: reseed RNG in child processes
[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 qw(WNOHANG);
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 $WQ_MAX_WORKERS = 4096;
16 my ($enc, $dec);
17 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
18 # and eliminate method call overhead
19 BEGIN {
20         eval {
21                 require Sereal::Encoder;
22                 require Sereal::Decoder;
23                 Sereal::Encoder->import('sereal_encode_with_object');
24                 Sereal::Decoder->import('sereal_decode_with_object');
25                 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
26         };
27 };
28
29 if ($enc && $dec) { # should be custom ops
30         *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
31         *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
32 } else {
33         eval { # some distros have Storable as a separate package from Perl
34                 require Storable;
35                 Storable->import(qw(freeze thaw));
36                 $enc = 1;
37         } // warn("Storable (part of Perl) missing: $@\n");
38 }
39
40 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
41 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
42         require PublicInbox::CmdIPC4;
43         $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
44         PublicInbox::CmdIPC4->can('send_cmd4');
45 };
46
47 sub wq_set_recv_modes {
48         my ($self, @modes) = @_;
49         $self->{-wq_recv_modes} = \@modes;
50 }
51
52 sub _get_rec ($) {
53         my ($r) = @_;
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";
58         thaw($buf);
59 }
60
61 sub _pack_rec ($) {
62         my ($ref) = @_;
63         my $buf = freeze($ref);
64         length($buf) . "\n" . $buf;
65 }
66
67 sub _send_rec ($$) {
68         my ($w, $ref) = @_;
69         print $w _pack_rec($ref) or croak "print: $!";
70 }
71
72 sub ipc_return ($$$) {
73         my ($w, $ret, $exc) = @_;
74         _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
75 }
76
77 sub ipc_worker_loop ($$$) {
78         my ($self, $r_req, $w_res) = @_;
79         my ($rec, $wantarray, $sub, @args);
80         local $/ = "\n";
81         while ($rec = _get_rec($r_req)) {
82                 ($wantarray, $sub, @args) = @$rec;
83                 # no waiting if client doesn't care,
84                 # this is the overwhelmingly likely case
85                 if (!defined($wantarray)) {
86                         eval { $self->$sub(@args) };
87                         warn "$$ die: $@ (from nowait $sub)\n" if $@;
88                 } elsif ($wantarray) {
89                         my @ret = eval { $self->$sub(@args) };
90                         ipc_return($w_res, \@ret, $@);
91                 } else { # '' => wantscalar
92                         my $ret = eval { $self->$sub(@args) };
93                         ipc_return($w_res, \$ret, $@);
94                 }
95         }
96 }
97
98 # starts a worker if Sereal or Storable is installed
99 sub ipc_worker_spawn {
100         my ($self, $ident, $oldset) = @_;
101         return unless $enc; # no Sereal or Storable
102         return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
103         delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
104         pipe(my ($r_req, $w_req)) or die "pipe: $!";
105         pipe(my ($r_res, $w_res)) or die "pipe: $!";
106         my $sigset = $oldset // PublicInbox::DS::block_signals();
107         $self->ipc_atfork_prepare;
108         my $seed = rand(0xffffffff);
109         my $pid = fork // die "fork: $!";
110         if ($pid == 0) {
111                 srand($seed);
112                 eval { PublicInbox::DS->Reset };
113                 delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
114                 $w_req = $r_res = undef;
115                 $w_res->autoflush(1);
116                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
117                 local $0 = $ident;
118                 PublicInbox::DS::sig_setmask($sigset);
119                 my $on_destroy = $self->ipc_atfork_child;
120                 eval { ipc_worker_loop($self, $r_req, $w_res) };
121                 die "worker $ident PID:$$ died: $@\n" if $@;
122                 exit;
123         }
124         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
125         $r_req = $w_res = undef;
126         $w_req->autoflush(1);
127         $self->{-ipc_req} = $w_req;
128         $self->{-ipc_res} = $r_res;
129         $self->{-ipc_ppid} = $$;
130         $self->{-ipc_pid} = $pid;
131 }
132
133 sub ipc_worker_reap { # dwaitpid callback
134         my ($self, $pid) = @_;
135         # SIGTERM (15) is our default exit signal
136         warn "PID:$pid died with \$?=$?\n" if $? && ($? & 127) != 15;
137 }
138
139 sub wq_wait_old {
140         my ($self) = @_;
141         my $pids = delete $self->{"-wq_old_pids.$$"} or return;
142         dwaitpid($_, \&ipc_worker_reap, $self) for @$pids;
143 }
144
145 # for base class, override in sub classes
146 sub ipc_atfork_prepare {}
147
148 sub ipc_atfork_child {
149         my ($self) = @_;
150         my $io = delete($self->{-ipc_atfork_child_close}) or return;
151         close($_) for @$io;
152         undef;
153 }
154
155 # idempotent, can be called regardless of whether worker is active or not
156 sub ipc_worker_stop {
157         my ($self) = @_;
158         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
159         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
160         if (!$w_req && !$r_res) {
161                 die "unexpected PID:$pid without IPC pipes" if $pid;
162                 return; # idempotent
163         }
164         die 'no PID with IPC pipes' unless $pid;
165         $w_req = $r_res = undef;
166
167         return if $$ != $ppid;
168         dwaitpid($pid, \&ipc_worker_reap, $self);
169 }
170
171 # use this if we have multiple readers reading curl or "pigz -dc"
172 # and writing to the same store
173 sub ipc_lock_init {
174         my ($self, $f) = @_;
175         require PublicInbox::Lock;
176         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
177 }
178
179 sub ipc_async_wait ($$) {
180         my ($self, $max) = @_; # max == -1 to wait for all
181         my $aif = $self->{-async_inflight} or return;
182         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
183         while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
184                 my $ret = _get_rec($r_res) //
185                         die "no response on $sub (req.size=$bytes)";
186                 $self->{-async_inflight_bytes} -= $bytes;
187
188                 eval { $cb->($cb_arg, $ret) };
189                 warn "E: $sub callback error: $@\n" if $@;
190                 return if --$max == 0;
191         }
192 }
193
194 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
195 sub ipc_do {
196         my ($self, $sub, @args) = @_;
197         if (my $w_req = $self->{-ipc_req}) { # run in worker
198                 my $ipc_lock = $self->{-ipc_lock};
199                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
200                 if (defined(wantarray)) {
201                         my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
202                         ipc_async_wait($self, -1);
203                         _send_rec($w_req, [ wantarray, $sub, @args ]);
204                         my $ret = _get_rec($r_res) // die "no response on $sub";
205                         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
206                         wantarray ? @$ret : $$ret;
207                 } else { # likely, fire-and-forget into pipe
208                         _send_rec($w_req, [ undef , $sub, @args ]);
209                 }
210         } else { # run locally
211                 $self->$sub(@args);
212         }
213 }
214
215 sub ipc_async {
216         my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
217         if (my $w_req = $self->{-ipc_req}) { # run in worker
218                 my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
219                 my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
220                 while (($$cur_bytes + length($rec)) > PIPE_BUF) {
221                         ipc_async_wait($self, 1);
222                 }
223                 my $ipc_lock = $self->{-ipc_lock};
224                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
225                 print $w_req $rec or croak "print: $!";
226                 $$cur_bytes += length($rec);
227                 push @{$self->{-async_inflight}},
228                                 $sub, length($rec), $cb, $cb_arg;
229         } else {
230                 my $ret = [ eval { $self->$sub(@$sub_args) } ];
231                 if (my $exc = $@) {
232                         $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
233                 }
234                 eval { $cb->($cb_arg, $ret) };
235                 warn "E: $sub callback error: $@\n" if $@;
236         }
237 }
238
239 # needed when there's multiple IPC workers and the parent forking
240 # causes newer siblings to inherit older siblings sockets
241 sub ipc_sibling_atfork_child {
242         my ($self) = @_;
243         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
244         delete(@$self{qw(-ipc_req -ipc_res)});
245         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
246 }
247
248 sub wq_worker_loop ($) {
249         my ($self) = @_;
250         my $len = $self->{wq_req_len} // (4096 * 33);
251         my $s2 = $self->{-wq_s2} // die 'BUG: no -wq_s2';
252         while (1) {
253                 my @fds = $recv_cmd->($s2, my $buf, $len) or return; # EOF
254                 my @m = @{$self->{-wq_recv_modes} // [qw( +<&= >&= >&= )]};
255                 my $nfd = 0;
256                 for my $fd (@fds) {
257                         my $mode = shift(@m);
258                         if (open(my $cmdfh, $mode, $fd)) {
259                                 $self->{$nfd++} = $cmdfh;
260                                 $cmdfh->autoflush(1);
261                         } else {
262                                 die "$$ open($mode$fd) (FD:$nfd): $!";
263                         }
264                 }
265                 # Sereal dies on truncated data, Storable returns undef
266                 my $args = thaw($buf) //
267                         die "thaw error on buffer of size:".length($buf);
268                 my $sub = shift @$args;
269                 eval { $self->$sub(@$args) };
270                 warn "$$ wq_worker: $@" if $@ &&
271                                         ref($@) ne 'PublicInbox::SIGPIPE';
272                 delete @$self{0..($nfd-1)};
273         }
274 }
275
276 sub wq_do { # always async
277         my ($self, $sub, $ios, @args) = @_;
278         if (my $s1 = $self->{-wq_s1}) { # run in worker
279                 my $fds = [ map { fileno($_) } @$ios ];
280                 $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
281         } else {
282                 @$self{0..$#$ios} = @$ios;
283                 eval { $self->$sub(@args) };
284                 warn "wq_do: $@" if $@ && ref($@) ne 'PublicInbox::SIGPIPE';
285                 delete @$self{0..$#$ios}; # don't close
286         }
287 }
288
289 sub _wq_worker_start ($$) {
290         my ($self, $oldset) = @_;
291         my $seed = rand(0xffffffff);
292         my $pid = fork // die "fork: $!";
293         if ($pid == 0) {
294                 srand($seed);
295                 eval { PublicInbox::DS->Reset };
296                 delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
297                 $SIG{$_} = 'IGNORE' for (qw(PIPE TTOU TTIN));
298                 $SIG{$_} = 'DEFAULT' for (qw(TERM QUIT INT CHLD));
299                 local $0 = $self->{-wq_ident};
300                 PublicInbox::DS::sig_setmask($oldset);
301                 # ensure we properly exit even if warn() dies:
302                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
303                 my $on_destroy = $self->ipc_atfork_child;
304                 eval { wq_worker_loop($self) };
305                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
306                 undef $on_destroy;
307                 undef $end; # trigger exit
308         } else {
309                 $self->{-wq_workers}->{$pid} = \undef;
310         }
311 }
312
313 # starts workqueue workers if Sereal or Storable is installed
314 sub wq_workers_start {
315         my ($self, $ident, $nr_workers, $oldset) = @_;
316         ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
317         return if $self->{-wq_s1}; # idempotent
318         $self->{-wq_s1} = $self->{-wq_s2} = undef;
319         socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
320                 die "socketpair: $!";
321         $self->ipc_atfork_prepare;
322         $nr_workers //= 4;
323         $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
324         my $sigset = $oldset // PublicInbox::DS::block_signals();
325         $self->{-wq_workers} = {};
326         $self->{-wq_ident} = $ident;
327         _wq_worker_start($self, $sigset) for (1..$nr_workers);
328         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
329         $self->{-wq_ppid} = $$;
330 }
331
332 sub wq_worker_incr { # SIGTTIN handler
333         my ($self, $oldset) = @_;
334         $self->{-wq_s2} or return;
335         return if wq_workers($self) >= $WQ_MAX_WORKERS;
336         $self->ipc_atfork_prepare;
337         my $sigset = $oldset // PublicInbox::DS::block_signals();
338         _wq_worker_start($self, $sigset);
339         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
340 }
341
342 sub wq_exit { # wakes up wq_worker_decr_wait
343         send($_[0]->{-wq_s2}, $$, MSG_EOR) // die "$$ send: $!";
344         exit;
345 }
346
347 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
348         my ($self) = @_;
349         return unless wq_workers($self);
350         my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
351         $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
352         # caller must call wq_worker_decr_wait in main loop
353 }
354
355 sub wq_worker_decr_wait {
356         my ($self, $timeout) = @_;
357         return if $self->{-wq_ppid} != $$; # can't reap siblings or parents
358         my $s1 = $self->{-wq_s1} // croak 'BUG: no wq_s1';
359         vec(my $rin = '', fileno($s1), 1) = 1;
360         select(my $rout = $rin, undef, undef, $timeout) or
361                 croak 'timed out waiting for wq_exit';
362         recv($s1, my $pid, 64, 0) // croak "recv: $!";
363         my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
364         delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
365         dwaitpid($pid, \&ipc_worker_reap, $self);
366 }
367
368 # set or retrieve number of workers
369 sub wq_workers {
370         my ($self, $nr) = @_;
371         my $cur = $self->{-wq_workers} or return;
372         if (defined $nr) {
373                 while (scalar(keys(%$cur)) > $nr) {
374                         $self->wq_worker_decr;
375                         $self->wq_worker_decr_wait;
376                 }
377                 $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
378         }
379         scalar(keys(%$cur));
380 }
381
382 sub wq_close {
383         my ($self, $nohang) = @_;
384         delete @$self{qw(-wq_s1 -wq_s2)} or return;
385         my $ppid = delete $self->{-wq_ppid} or return;
386         my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
387         return if $ppid != $$; # can't reap siblings or parents
388         my @pids = map { $_ + 0 } keys %$workers;
389         if ($nohang) {
390                 push @{$self->{"-wq_old_pids.$$"}}, @pids;
391         } else {
392                 dwaitpid($_, \&ipc_worker_reap, $self) for @pids;
393         }
394 }
395
396 sub wq_kill_old {
397         my ($self) = @_;
398         my $pids = $self->{"-wq_old_pids.$$"} or return;
399         kill 'TERM', @$pids;
400 }
401
402 sub wq_kill {
403         my ($self, $sig) = @_;
404         my $workers = $self->{-wq_workers} or return;
405         kill($sig // 'TERM', keys %$workers);
406 }
407
408 sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
409
410 sub DESTROY {
411         my ($self) = @_;
412         my $ppid = $self->{-wq_ppid};
413         wq_kill($self) if $ppid && $ppid == $$;
414         wq_close($self);
415         wq_wait_old($self);
416         ipc_worker_stop($self);
417 }
418
419 # Sereal doesn't have dclone
420 sub deep_clone { thaw(freeze($_[-1])) }
421
422 1;