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