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