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