]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IPC.pm
searchidxshard: use PublicInbox::IPC to kill lots of code
[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, requires Storable
5 # TODO: this ought to be usable in SearchIdxShard
6 package PublicInbox::IPC;
7 use strict;
8 use v5.10.1;
9 use Socket qw(AF_UNIX SOCK_STREAM);
10 use Carp qw(confess croak);
11 use PublicInbox::Sigfd;
12 my ($enc, $dec);
13 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
14 # and eliminate method call overhead
15 BEGIN {
16         eval {
17                 require Sereal::Encoder;
18                 require Sereal::Decoder;
19                 Sereal::Encoder->import('sereal_encode_with_object');
20                 Sereal::Decoder->import('sereal_decode_with_object');
21                 ($enc, $dec) = (Sereal::Encoder->new, Sereal::Decoder->new);
22         };
23 };
24
25 if ($enc && $dec) { # should be custom ops
26         *freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
27         *thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
28 } else {
29         eval { # some distros have Storable as a separate package from Perl
30                 require Storable;
31                 Storable->import(qw(freeze thaw));
32                 $enc = 1;
33         } // warn("Storable (part of Perl) missing: $@\n");
34 }
35
36 sub _get_rec ($) {
37         my ($sock) = @_;
38         local $/ = "\n";
39         defined(my $len = <$sock>) or return;
40         chop($len) eq "\n" or croak "no LF byte in $len";
41         defined(my $r = read($sock, my $buf, $len)) or croak "read error: $!";
42         $r == $len or croak "short read: $r != $len";
43         thaw($buf);
44 }
45
46 sub _send_rec ($$) {
47         my ($sock, $ref) = @_;
48         my $buf = freeze($ref);
49         print $sock length($buf), "\n", $buf or croak "print: $!";
50 }
51
52 sub ipc_return ($$$) {
53         my ($s2, $ret, $exc) = @_;
54         _send_rec($s2, $exc ? bless(\$exc, 'PublicInbox::IPC::Die') : $ret);
55 }
56
57 sub ipc_worker_loop ($$) {
58         my ($self, $s2) = @_;
59         while (my $rec = _get_rec($s2)) {
60                 my ($wantarray, $sub, @args) = @$rec;
61                 if (!defined($wantarray)) { # no waiting if client doesn't care
62                         eval { $self->$sub(@args) };
63                         eval { warn "die: $@ (from nowait $sub)\n" } if $@;
64                 } elsif ($wantarray) {
65                         my @ret = eval { $self->$sub(@args) };
66                         ipc_return($s2, \@ret, $@);
67                 } else {
68                         my $ret = eval { $self->$sub(@args) };
69                         ipc_return($s2, \$ret, $@);
70                 }
71         }
72 }
73
74 # starts a worker if Sereal or Storable is installed
75 sub ipc_worker_spawn {
76         my ($self, $ident, $oldset) = @_;
77         return unless $enc; # no Sereal or Storable
78         my $pid = $self->{-ipc_worker_pid};
79         confess "BUG: already spawned PID:$pid" if $pid;
80         confess "BUG: already have worker socket" if $self->{-ipc_sock};
81         my ($s1, $s2);
82         socketpair($s1, $s2, AF_UNIX, SOCK_STREAM, 0) or die "socketpair: $!";
83         my $sigset = $oldset // PublicInbox::Sigfd::block_signals();
84         my $parent = $$;
85         $self->ipc_atfork_parent;
86         defined($pid = fork) or die "fork: $!";
87         if ($pid == 0) {
88                 eval { PublicInbox::DS->Reset };
89                 $self->{-ipc_parent_pid} = $parent;
90                 close $s1 or die "close(\$s1): $!";
91                 $s2->autoflush(1);
92                 $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
93                 local $0 = $ident;
94                 PublicInbox::Sigfd::sig_setmask($oldset);
95                 my $on_destroy = $self->ipc_atfork_child;
96                 eval { ipc_worker_loop($self, $s2) };
97                 die "worker $ident PID:$$ died: $@\n" if $@;
98                 exit;
99         }
100         PublicInbox::Sigfd::sig_setmask($sigset) unless $oldset;
101         close $s2 or die "close(\$s2): $!";
102         $s1->autoflush(1);
103         $self->{-ipc_sock} = $s1;
104         $self->{-ipc_worker_pid} = $pid;
105 }
106
107 sub ipc_worker_reap { # dwaitpid callback
108         my ($self, $pid) = @_;
109         warn "PID:$pid died with \$?=$?\n" if $?;
110 }
111
112 # for base class, override in sub classes
113 sub ipc_atfork_parent {}
114 sub ipc_atfork_child {}
115
116 # should only be called inside the worker process
117 sub ipc_worker_exit {
118         my (undef, $code) = @_;
119         exit($code);
120 }
121
122 # idempotent, can be called regardless of whether worker is active or not
123 sub ipc_worker_stop {
124         my ($self) = @_;
125         my $pid;
126         my $s1 = delete $self->{-ipc_sock} or do {
127                 $pid = delete $self->{-ipc_worker_pid} and
128                         die "unexpected PID:$pid without ipc_sock";
129                 return;
130         };
131         $pid = delete $self->{-ipc_worker_pid} or die "no PID?";
132         _send_rec($s1, [ undef, 'ipc_worker_exit', 0 ]);
133         shutdown($s1, 2) or die "shutdown(\$s1) for PID:$pid";
134         eval {
135                 my $reap = $self->can('ipc_worker_reap');
136                 PublicInbox::DS::dwaitpid($pid, $reap, $self);
137         };
138         if ($@) {
139                 my $wp = waitpid($pid, 0);
140                 $pid == $wp or die "waitpid($pid) returned $wp: \$?=$?";
141                 $self->ipc_worker_reap($pid);
142         }
143 }
144
145 # use this if we have multiple readers reading curl or "pigz -dc"
146 # and writing to the same store
147 sub ipc_lock_init {
148         my ($self, $f) = @_;
149         require PublicInbox::Lock;
150         $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
151 }
152
153 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
154 sub ipc_do {
155         my ($self, $sub, @args) = @_;
156         if (my $s1 = $self->{-ipc_sock}) {
157                 my $ipc_lock = $self->{-ipc_lock};
158                 my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
159                 _send_rec($s1, [ wantarray, $sub, @args ]);
160                 return unless defined(wantarray);
161                 my $ret = _get_rec($s1) // die "no response on $sub";
162                 die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
163                 wantarray ? @$ret : $$ret;
164         } else {
165                 $self->$sub(@args);
166         }
167 }
168
169 1;