]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
db679b770cfd81d985c4416db9b7186d718587a4
[public-inbox.git] / lib / PublicInbox / Spawn.pm
1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # This allows vfork to be used for spawning subprocesses if
5 # ~/.cache/public-inbox/inline-c is writable or if PERL_INLINE_DIRECTORY
6 # is explicitly defined in the environment (and writable).
7 # Under Linux, vfork can make a big difference in spawning performance
8 # as process size increases (fork still needs to mark pages for CoW use).
9 # Currently, we only use this for code intended for long running
10 # daemons (inside the PSGI code (-httpd) and -nntpd).  The short-lived
11 # scripts (-mda, -index, -learn, -init) either use IPC::run or standard
12 # Perl routines.
13
14 package PublicInbox::Spawn;
15 use strict;
16 use parent qw(Exporter);
17 use Symbol qw(gensym);
18 use PublicInbox::ProcessPipe;
19 our @EXPORT_OK = qw/which spawn popen_rd/;
20 our @RLIMITS = qw(RLIMIT_CPU RLIMIT_CORE RLIMIT_DATA);
21
22 my $vfork_spawn = <<'VFORK_SPAWN';
23 #include <sys/types.h>
24 #include <sys/time.h>
25 #include <sys/resource.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28
29 /* some platforms need alloca.h, but some don't */
30 #if defined(__GNUC__) && !defined(alloca)
31 #  define alloca(sz) __builtin_alloca(sz)
32 #endif
33
34 #include <signal.h>
35 #include <assert.h>
36
37 /*
38  * From the av_len apidoc:
39  *   Note that, unlike what the name implies, it returns
40  *   the highest index in the array, so to get the size of
41  *   the array you need to use "av_len(av) + 1".
42  *   This is unlike "sv_len", which returns what you would expect.
43  */
44 #define AV2C_COPY(dst, src) do { \
45         I32 i; \
46         I32 top_index = av_len(src); \
47         I32 real_len = top_index + 1; \
48         I32 capa = real_len + 1; \
49         dst = alloca(capa * sizeof(char *)); \
50         for (i = 0; i < real_len; i++) { \
51                 SV **sv = av_fetch(src, i, 0); \
52                 dst[i] = SvPV_nolen(*sv); \
53         } \
54         dst[real_len] = 0; \
55 } while (0)
56
57 /* needs to be safe inside a vfork'ed process */
58 static void exit_err(int *cerrnum)
59 {
60         *cerrnum = errno;
61         _exit(1);
62 }
63
64 /*
65  * unstable internal API.  It'll be updated depending on
66  * whatever we'll need in the future.
67  * Be sure to update PublicInbox::SpawnPP if this changes
68  */
69 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
70                  const char *cd)
71 {
72         AV *redir = (AV *)SvRV(redirref);
73         AV *cmd = (AV *)SvRV(cmdref);
74         AV *env = (AV *)SvRV(envref);
75         AV *rlim = (AV *)SvRV(rlimref);
76         const char *filename = SvPV_nolen(file);
77         pid_t pid;
78         char **argv, **envp;
79         sigset_t set, old, cset;
80         int ret, perrnum, cerrnum = 0;
81
82         AV2C_COPY(argv, cmd);
83         AV2C_COPY(envp, env);
84
85         ret = sigfillset(&set);
86         assert(ret == 0 && "BUG calling sigfillset");
87         ret = sigprocmask(SIG_SETMASK, &set, &old);
88         assert(ret == 0 && "BUG calling sigprocmask to block");
89         ret = sigemptyset(&cset);
90         assert(ret == 0 && "BUG calling sigemptyset");
91         ret = sigaddset(&cset, SIGCHLD);
92         assert(ret == 0 && "BUG calling sigaddset for SIGCHLD");
93         pid = vfork();
94         if (pid == 0) {
95                 int sig;
96                 I32 i, child_fd, max = av_len(redir);
97
98                 for (child_fd = 0; child_fd <= max; child_fd++) {
99                         SV **parent = av_fetch(redir, child_fd, 0);
100                         int parent_fd = SvIV(*parent);
101                         if (parent_fd == child_fd)
102                                 continue;
103                         if (dup2(parent_fd, child_fd) < 0)
104                                 exit_err(&cerrnum);
105                 }
106                 for (sig = 1; sig < NSIG; sig++)
107                         signal(sig, SIG_DFL); /* ignore errors on signals */
108                 if (*cd && chdir(cd) < 0)
109                         exit_err(&cerrnum);
110
111                 max = av_len(rlim);
112                 for (i = 0; i < max; i += 3) {
113                         struct rlimit rl;
114                         SV **res = av_fetch(rlim, i, 0);
115                         SV **soft = av_fetch(rlim, i + 1, 0);
116                         SV **hard = av_fetch(rlim, i + 2, 0);
117
118                         rl.rlim_cur = SvIV(*soft);
119                         rl.rlim_max = SvIV(*hard);
120                         if (setrlimit(SvIV(*res), &rl) < 0)
121                                 exit_err(&cerrnum);
122                 }
123
124                 /*
125                  * don't bother unblocking other signals for now, just SIGCHLD.
126                  * we don't want signals to the group taking out a subprocess
127                  */
128                 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
129                 execve(filename, argv, envp);
130                 exit_err(&cerrnum);
131         }
132         perrnum = errno;
133         ret = sigprocmask(SIG_SETMASK, &old, NULL);
134         assert(ret == 0 && "BUG calling sigprocmask to restore");
135         if (cerrnum) {
136                 if (pid > 0)
137                         waitpid(pid, NULL, 0);
138                 pid = -1;
139                 errno = cerrnum;
140         } else if (perrnum) {
141                 errno = perrnum;
142         }
143         return (int)pid;
144 }
145 VFORK_SPAWN
146
147 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
148                 $ENV{XDG_CACHE_HOME} //
149                 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
150         ).'/public-inbox/inline-c';
151
152 $vfork_spawn = undef unless -d $inline_dir && -w _;
153 if (defined $vfork_spawn) {
154         # Inline 0.64 or later has locking in multi-process env,
155         # but we support 0.5 on Debian wheezy
156         use Fcntl qw(:flock);
157         eval {
158                 my $f = "$inline_dir/.public-inbox.lock";
159                 open my $fh, '>', $f or die "failed to open $f: $!\n";
160                 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
161                 eval 'use Inline C => $vfork_spawn';
162                 my $err = $@;
163                 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
164                 die $err if $err;
165         };
166         if ($@) {
167                 warn "Inline::C failed for vfork: $@\n";
168                 $vfork_spawn = undef;
169         }
170 }
171
172 unless (defined $vfork_spawn) {
173         require PublicInbox::SpawnPP;
174         *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
175 }
176
177 sub which ($) {
178         my ($file) = @_;
179         return $file if index($file, '/') >= 0;
180         foreach my $p (split(':', $ENV{PATH})) {
181                 $p .= "/$file";
182                 return $p if -x $p;
183         }
184         undef;
185 }
186
187 sub spawn ($;$$) {
188         my ($cmd, $env, $opts) = @_;
189         my $f = which($cmd->[0]);
190         defined $f or die "$cmd->[0]: command not found\n";
191         my @env;
192         $opts ||= {};
193
194         my %env = $env ? (%ENV, %$env) : %ENV;
195         while (my ($k, $v) = each %env) {
196                 push @env, "$k=$v";
197         }
198         my $redir = [];
199         for my $child_fd (0..2) {
200                 my $parent_fd = $opts->{$child_fd};
201                 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
202                         defined(my $fd = fileno($parent_fd)) or
203                                         die "$parent_fd not an IO GLOB? $!";
204                         $parent_fd = $fd;
205                 }
206                 $redir->[$child_fd] = $parent_fd // $child_fd;
207         }
208         my $rlim = [];
209
210         foreach my $l (@RLIMITS) {
211                 defined(my $v = $opts->{$l}) or next;
212                 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
213                 unless (defined $r) {
214                         warn "$l undefined by BSD::Resource: $@\n";
215                         next;
216                 }
217                 push @$rlim, $r, @$v;
218         }
219         my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
220         my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
221         die "fork_exec failed: $!\n" unless $pid > 0;
222         $pid;
223 }
224
225 sub popen_rd {
226         my ($cmd, $env, $opts) = @_;
227         pipe(my ($r, $w)) or die "pipe: $!\n";
228         $opts ||= {};
229         $opts->{1} = fileno($w);
230         my $pid = spawn($cmd, $env, $opts);
231         return ($r, $pid) if wantarray;
232         my $ret = gensym;
233         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r;
234         $ret;
235 }
236
237 1;