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