]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / IPC.pm
1 # Copyright (C) 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 # - ipc_do and ipc_worker_* is for a single worker/producer and uses pipes
6 # - wq_io_do and wq_worker* is for a single producer and multiple workers,
7 #   using SOCK_SEQPACKET for work distribution
8 # use ipc_do when you need work done on a certain process
9 # use wq_io_do when your work can be done on any idle worker
10 package PublicInbox::IPC;
11 use strict;
12 use v5.10.1;
13 use parent qw(Exporter);
14 use Carp qw(croak);
15 use PublicInbox::DS qw(dwaitpid);
16 use PublicInbox::Spawn;
17 use PublicInbox::OnDestroy;
18 use PublicInbox::WQWorker;
19 use Socket qw(AF_UNIX MSG_EOR SOCK_STREAM);
20 my $MY_MAX_ARG_STRLEN = 4096 * 33; # extra 4K for serialization
21 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
22 our @EXPORT_OK = qw(ipc_freeze ipc_thaw);
23 my ($enc, $dec);
24 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
25 # and eliminate method call overhead
26 BEGIN {
27         eval {
28                 require Sereal::Encoder;
29                 require Sereal::Decoder;
30                 Sereal::Encoder->import('sereal_encode_with_object');
31                 Sereal::Decoder->import('sereal_decode_with_object');
32                 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
33         };
34 };
35
36 if ($enc && $dec) { # should be custom ops
37         *ipc_freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
38         *ipc_thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
39 } else {
40         require Storable;
41         *ipc_freeze = \&Storable::freeze;
42         *ipc_thaw = \&Storable::thaw;
43 }
44
45 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
46 our $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
47         require PublicInbox::CmdIPC4;
48         $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
49         PublicInbox::CmdIPC4->can('send_cmd4');
50 } // do {
51         require PublicInbox::Syscall;
52         $recv_cmd //= PublicInbox::Syscall->can('recv_cmd4');
53         PublicInbox::Syscall->can('send_cmd4');
54 };
55
56 sub _get_rec ($) {
57         my ($r) = @_;
58         defined(my $len = <$r>) or return;
59         chop($len) eq "\n" or croak "no LF byte in $len";
60         defined(my $n = read($r, my $buf, $len)) or croak "read error: $!";
61         $n == $len or croak "short read: $n != $len";
62         ipc_thaw($buf);
63 }
64
65 sub _send_rec ($$) {
66         my ($w, $ref) = @_;
67         my $buf = ipc_freeze($ref);
68         print $w length($buf), "\n", $buf or croak "print: $!";
69 }
70
71 sub ipc_return ($$$) {
72         my ($w, $ret, $exc) = @_;
73         _send_rec($w, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
74 }
75
76 sub ipc_worker_loop ($$$) {
77         my ($self, $r_req, $w_res) = @_;
78         my ($rec, $wantarray, $sub, @args);
79         local $/ = "\n";
80         while ($rec = _get_rec($r_req)) {
81                 ($wantarray, $sub, @args) = @$rec;
82                 # no waiting if client doesn't care,
83                 # this is the overwhelmingly likely case
84                 if (!defined($wantarray)) {
85                         eval { $self->$sub(@args) };
86                         warn "$$ die: $@ (from nowait $sub)\n" if $@;
87                 } elsif ($wantarray) {
88                         my @ret = eval { $self->$sub(@args) };
89                         ipc_return($w_res, \@ret, $@);
90                 } else { # '' => wantscalar
91                         my $ret = eval { $self->$sub(@args) };
92                         ipc_return($w_res, \$ret, $@);
93                 }
94         }
95 }
96
97 # starts a worker if Sereal or Storable is installed
98 sub ipc_worker_spawn {
99         my ($self, $ident, $oldset, $fields) = @_;
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         $self->ipc_atfork_prepare;
106         my $seed = rand(0xffffffff);
107         my $pid = fork // die "fork: $!";
108         if ($pid == 0) {
109                 srand($seed);
110                 eval { Net::SSLeay::randomize() };
111                 eval { PublicInbox::DS->Reset };
112                 delete @$self{qw(-wq_s1 -wq_s2 -wq_workers -wq_ppid)};
113                 $w_req = $r_res = undef;
114                 $w_res->autoflush(1);
115                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
116                 local $0 = $ident;
117                 # ensure we properly exit even if warn() dies:
118                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
119                 eval {
120                         $fields //= {};
121                         local @$self{keys %$fields} = values(%$fields);
122                         my $on_destroy = $self->ipc_atfork_child;
123                         local @SIG{keys %SIG} = values %SIG;
124                         PublicInbox::DS::sig_setmask($sigset);
125                         ipc_worker_loop($self, $r_req, $w_res);
126                 };
127                 warn "worker $ident PID:$$ died: $@\n" if $@;
128                 undef $end; # trigger exit
129         }
130         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
131         $r_req = $w_res = undef;
132         $w_req->autoflush(1);
133         $self->{-ipc_req} = $w_req;
134         $self->{-ipc_res} = $r_res;
135         $self->{-ipc_ppid} = $$;
136         $self->{-ipc_pid} = $pid;
137 }
138
139 sub ipc_worker_reap { # dwaitpid callback
140         my ($args, $pid) = @_;
141         my ($self, @uargs) = @$args;
142         delete $self->{-wq_workers}->{$pid};
143         return $self->{-reap_do}->($args, $pid) if $self->{-reap_do};
144         return if !$?;
145         my $s = $? & 127;
146         # TERM(15) is our default exit signal, PIPE(13) is likely w/ pager
147         warn "$self->{-wq_ident} PID:$pid died \$?=$?\n" if $s != 15 && $s != 13
148 }
149
150 sub wq_wait_async {
151         my ($self, $cb, @uargs) = @_;
152         local $PublicInbox::DS::in_loop = 1;
153         $self->{-reap_async} = 1;
154         $self->{-reap_do} = $cb;
155         my @pids = keys %{$self->{-wq_workers}};
156         dwaitpid($_, \&ipc_worker_reap, [ $self, @uargs ]) for @pids;
157 }
158
159 # for base class, override in sub classes
160 sub ipc_atfork_prepare {}
161
162 sub wq_atexit_child {}
163
164 sub ipc_atfork_child {
165         my ($self) = @_;
166         my $io = delete($self->{-ipc_atfork_child_close}) or return;
167         close($_) for @$io;
168         undef;
169 }
170
171 # idempotent, can be called regardless of whether worker is active or not
172 sub ipc_worker_stop {
173         my ($self, $args) = @_;
174         my ($pid, $ppid) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
175         my ($w_req, $r_res) = delete(@$self{qw(-ipc_req -ipc_res)});
176         if (!$w_req && !$r_res) {
177                 die "unexpected PID:$pid without IPC pipes" if $pid;
178                 return; # idempotent
179         }
180         die 'no PID with IPC pipes' unless $pid;
181         $w_req = $r_res = undef;
182
183         return if $$ != $ppid;
184         dwaitpid($pid, \&ipc_worker_reap, [$self, $args]);
185 }
186
187 # use this if we have multiple readers reading curl or "pigz -dc"
188 # and writing to the same store
189 sub ipc_lock_init {
190         my ($self, $f) = @_;
191         $f // die 'BUG: no filename given';
192         require PublicInbox::Lock;
193         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
194 }
195
196 sub _wait_return ($$) {
197         my ($r_res, $sub) = @_;
198         my $ret = _get_rec($r_res) // die "no response on $sub";
199         die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
200         wantarray ? @$ret : $$ret;
201 }
202
203 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
204 sub ipc_do {
205         my ($self, $sub, @args) = @_;
206         if (my $w_req = $self->{-ipc_req}) { # run in worker
207                 my $ipc_lock = $self->{-ipc_lock};
208                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
209                 if (defined(wantarray)) {
210                         my $r_res = $self->{-ipc_res} or die 'no ipc_res';
211                         _send_rec($w_req, [ wantarray, $sub, @args ]);
212                         _wait_return($r_res, $sub);
213                 } else { # likely, fire-and-forget into pipe
214                         _send_rec($w_req, [ undef , $sub, @args ]);
215                 }
216         } else { # run locally
217                 $self->$sub(@args);
218         }
219 }
220
221 # needed when there's multiple IPC workers and the parent forking
222 # causes newer siblings to inherit older siblings sockets
223 sub ipc_sibling_atfork_child {
224         my ($self) = @_;
225         my ($pid, undef) = delete(@$self{qw(-ipc_pid -ipc_ppid)});
226         delete(@$self{qw(-ipc_req -ipc_res)});
227         $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
228 }
229
230 sub recv_and_run {
231         my ($self, $s2, $len, $full_stream) = @_;
232         my @fds = $recv_cmd->($s2, my $buf, $len // $MY_MAX_ARG_STRLEN);
233         return if scalar(@fds) && !defined($fds[0]);
234         my $n = length($buf) or return 0;
235         my $nfd = 0;
236         for my $fd (@fds) {
237                 if (open(my $cmdfh, '+<&=', $fd)) {
238                         $self->{$nfd++} = $cmdfh;
239                         $cmdfh->autoflush(1);
240                 } else {
241                         die "$$ open(+<&=$fd) (FD:$nfd): $!";
242                 }
243         }
244         while ($full_stream && $n < $len) {
245                 my $r = sysread($s2, $buf, $len - $n, $n) // croak "read: $!";
246                 croak "read EOF after $n/$len bytes" if $r == 0;
247                 $n = length($buf);
248         }
249         # Sereal dies on truncated data, Storable returns undef
250         my $args = ipc_thaw($buf) // die "thaw error on buffer of size: $n";
251         undef $buf;
252         my $sub = shift @$args;
253         eval { $self->$sub(@$args) };
254         warn "$$ $0 wq_worker: $sub: $@" if $@;
255         delete @$self{0..($nfd-1)};
256         $n;
257 }
258
259 sub wq_worker_loop ($$) {
260         my ($self, $bcast2) = @_;
261         my $wqw = PublicInbox::WQWorker->new($self, $self->{-wq_s2});
262         PublicInbox::WQWorker->new($self, $bcast2) if $bcast2;
263         PublicInbox::DS->SetPostLoopCallback(sub { $wqw->{sock} });
264         PublicInbox::DS::event_loop();
265         PublicInbox::DS->Reset;
266 }
267
268 sub do_sock_stream { # via wq_io_do, for big requests
269         my ($self, $len) = @_;
270         recv_and_run($self, my $s2 = delete $self->{0}, $len, 1);
271 }
272
273 sub wq_broadcast {
274         my ($self, $sub, @args) = @_;
275         if (my $wkr = $self->{-wq_workers}) {
276                 my $buf = ipc_freeze([$sub, @args]);
277                 for my $bcast1 (values %$wkr) {
278                         my $sock = $bcast1 // $self->{-wq_s1} // next;
279                         send($sock, $buf, MSG_EOR) // croak "send: $!";
280                         # XXX shouldn't have to deal with EMSGSIZE here...
281                 }
282         } else {
283                 eval { $self->$sub(@args) };
284                 warn "wq_broadcast: $@" if $@;
285         }
286 }
287
288 sub stream_in_full ($$$) {
289         my ($s1, $fds, $buf) = @_;
290         socketpair(my $r, my $w, AF_UNIX, SOCK_STREAM, 0) or
291                 croak "socketpair: $!";
292         my $n = $send_cmd->($s1, [ fileno($r) ],
293                         ipc_freeze(['do_sock_stream', length($buf)]),
294                         MSG_EOR) // croak "sendmsg: $!";
295         undef $r;
296         $n = $send_cmd->($w, $fds, $buf, 0) // croak "sendmsg: $!";
297         while ($n < length($buf)) {
298                 my $x = syswrite($w, $buf, length($buf) - $n, $n) //
299                                 croak "syswrite: $!";
300                 croak "syswrite wrote 0 bytes" if $x == 0;
301                 $n += $x;
302         }
303 }
304
305 sub wq_io_do { # always async
306         my ($self, $sub, $ios, @args) = @_;
307         if (my $s1 = $self->{-wq_s1}) { # run in worker
308                 my $fds = [ map { fileno($_) } @$ios ];
309                 my $buf = ipc_freeze([$sub, @args]);
310                 if (length($buf) > $MY_MAX_ARG_STRLEN) {
311                         stream_in_full($s1, $fds, $buf);
312                 } else {
313                         my $n = $send_cmd->($s1, $fds, $buf, MSG_EOR);
314                         return if defined($n); # likely
315                         $!{ETOOMANYREFS} and
316                                 croak "sendmsg: $! (check RLIMIT_NOFILE)";
317                         $!{EMSGSIZE} ? stream_in_full($s1, $fds, $buf) :
318                                 croak("sendmsg: $!");
319                 }
320         } else {
321                 @$self{0..$#$ios} = @$ios;
322                 eval { $self->$sub(@args) };
323                 warn "wq_io_do: $@" if $@;
324                 delete @$self{0..$#$ios}; # don't close
325         }
326 }
327
328 sub wq_sync_run {
329         my ($self, $wantarray, $sub, @args) = @_;
330         if ($wantarray) {
331                 my @ret = eval { $self->$sub(@args) };
332                 ipc_return($self->{0}, \@ret, $@);
333         } else { # '' => wantscalar
334                 my $ret = eval { $self->$sub(@args) };
335                 ipc_return($self->{0}, \$ret, $@);
336         }
337 }
338
339 sub wq_do {
340         my ($self, $sub, @args) = @_;
341         if (defined(wantarray)) {
342                 pipe(my ($r, $w)) or die "pipe: $!";
343                 wq_io_do($self, 'wq_sync_run', [ $w ], wantarray, $sub, @args);
344                 undef $w;
345                 _wait_return($r, $sub);
346         } else {
347                 wq_io_do($self, $sub, [], @args);
348         }
349 }
350
351 sub prepare_nonblock {
352         ($_[0]->{-wq_s1} // die 'BUG: no {-wq_s1}')->blocking(0);
353         $_[0]->{-reap_async} or die 'BUG: {-reap_async} needed for nonblock';
354         require PublicInbox::WQBlocked;
355 }
356
357 sub wq_nonblock_do { # always async
358         my ($self, $sub, @args) = @_;
359         my $buf = ipc_freeze([$sub, @args]);
360         if ($self->{wqb}) { # saturated once, assume saturated forever
361                 $self->{wqb}->flush_send($buf);
362         } else {
363                 $send_cmd->($self->{-wq_s1}, [], $buf, MSG_EOR) //
364                         ($!{EAGAIN} ? PublicInbox::WQBlocked->new($self, $buf)
365                                         : croak("sendmsg: $!"));
366         }
367 }
368
369 sub _wq_worker_start ($$$$) {
370         my ($self, $oldset, $fields, $one) = @_;
371         my ($bcast1, $bcast2);
372         $one or socketpair($bcast1, $bcast2, AF_UNIX, $SEQPACKET, 0) or
373                                                         die "socketpair: $!";
374         my $seed = rand(0xffffffff);
375         my $pid = fork // die "fork: $!";
376         if ($pid == 0) {
377                 srand($seed);
378                 eval { Net::SSLeay::randomize() };
379                 undef $bcast1;
380                 eval { PublicInbox::DS->Reset };
381                 delete @$self{qw(-wq_s1 -wq_ppid)};
382                 $self->{-wq_worker_nr} =
383                                 keys %{delete($self->{-wq_workers}) // {}};
384                 $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
385                 local $0 = $one ? $self->{-wq_ident} :
386                         "$self->{-wq_ident} $self->{-wq_worker_nr}";
387                 # ensure we properly exit even if warn() dies:
388                 my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
389                 eval {
390                         $fields //= {};
391                         local @$self{keys %$fields} = values(%$fields);
392                         my $on_destroy = $self->ipc_atfork_child;
393                         local @SIG{keys %SIG} = values %SIG;
394                         PublicInbox::DS::sig_setmask($oldset);
395                         wq_worker_loop($self, $bcast2);
396                 };
397                 warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
398                 undef $end; # trigger exit
399         } else {
400                 $self->{-wq_workers}->{$pid} = $bcast1;
401         }
402 }
403
404 # starts workqueue workers if Sereal or Storable is installed
405 sub wq_workers_start {
406         my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
407         ($send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
408         return if $self->{-wq_s1}; # idempotent
409         $self->{-wq_s1} = $self->{-wq_s2} = undef;
410         socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
411                 die "socketpair: $!";
412         $self->ipc_atfork_prepare;
413         $nr_workers //= $self->{-wq_nr_workers}; # was set earlier
414         my $sigset = $oldset // PublicInbox::DS::block_signals();
415         $self->{-wq_workers} = {};
416         $self->{-wq_ident} = $ident;
417         my $one = $nr_workers == 1;
418         $self->{-wq_nr_workers} = $nr_workers;
419         _wq_worker_start($self, $sigset, $fields, $one) for (1..$nr_workers);
420         PublicInbox::DS::sig_setmask($sigset) unless $oldset;
421         $self->{-wq_ppid} = $$;
422 }
423
424 sub wq_close {
425         my ($self) = @_;
426         if (my $wqb = delete $self->{wqb}) {
427                 $self->{-reap_async} or die 'BUG: {-reap_async} unset';
428                 $wqb->enq_close;
429         }
430         delete @$self{qw(-wq_s1 -wq_s2)} or return;
431         return if $self->{-reap_async};
432         my @pids = keys %{$self->{-wq_workers}};
433         dwaitpid($_, \&ipc_worker_reap, [ $self ]) for @pids;
434 }
435
436 sub wq_kill {
437         my ($self, $sig) = @_;
438         kill($sig // 'TERM', keys %{$self->{-wq_workers}});
439 }
440
441 sub DESTROY {
442         my ($self) = @_;
443         my $ppid = $self->{-wq_ppid};
444         wq_kill($self) if $ppid && $ppid == $$;
445         wq_close($self);
446         ipc_worker_stop($self);
447 }
448
449 sub detect_nproc () {
450         # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
451         return POSIX::sysconf(84) if $^O eq 'linux';
452         return POSIX::sysconf(58) if $^O eq 'freebsd';
453         # TODO: more OSes
454
455         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
456         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
457                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
458         }
459         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
460                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
461         }
462
463         # should we bother with `sysctl hw.ncpu`?  Those only give
464         # us total processor count, not online processor count.
465         undef
466 }
467
468 1;