]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
spawn: make @RLIMITS an array
[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 warnings;
17 use base qw(Exporter);
18 use Symbol qw(gensym);
19 use PublicInbox::ProcessPipe;
20 our @EXPORT_OK = qw/which spawn popen_rd/;
21 our @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 /* needs to be safe inside a vfork'ed process */
60 static void exit_err(int *cerrnum)
61 {
62         *cerrnum = errno;
63         _exit(1);
64 }
65
66 /*
67  * unstable internal API.  It'll be updated depending on
68  * whatever we'll need in the future.
69  * Be sure to update PublicInbox::SpawnPP if this changes
70  */
71 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
72                  const char *cd)
73 {
74         AV *redir = (AV *)SvRV(redirref);
75         AV *cmd = (AV *)SvRV(cmdref);
76         AV *env = (AV *)SvRV(envref);
77         AV *rlim = (AV *)SvRV(rlimref);
78         const char *filename = SvPV_nolen(file);
79         pid_t pid;
80         char **argv, **envp;
81         sigset_t set, old, cset;
82         int ret, perrnum, cerrnum = 0;
83
84         AV2C_COPY(argv, cmd);
85         AV2C_COPY(envp, env);
86
87         ret = sigfillset(&set);
88         assert(ret == 0 && "BUG calling sigfillset");
89         ret = sigprocmask(SIG_SETMASK, &set, &old);
90         assert(ret == 0 && "BUG calling sigprocmask to block");
91         ret = sigemptyset(&cset);
92         assert(ret == 0 && "BUG calling sigemptyset");
93         ret = sigaddset(&cset, SIGCHLD);
94         assert(ret == 0 && "BUG calling sigaddset for SIGCHLD");
95         pid = vfork();
96         if (pid == 0) {
97                 int sig;
98                 I32 i, child_fd, max = av_len(redir);
99
100                 for (child_fd = 0; child_fd <= max; child_fd++) {
101                         SV **parent = av_fetch(redir, child_fd, 0);
102                         int parent_fd = SvIV(*parent);
103                         if (parent_fd == child_fd)
104                                 continue;
105                         if (dup2(parent_fd, child_fd) < 0)
106                                 exit_err(&cerrnum);
107                 }
108                 for (sig = 1; sig < NSIG; sig++)
109                         signal(sig, SIG_DFL); /* ignore errors on signals */
110                 if (*cd && chdir(cd) < 0)
111                         exit_err(&cerrnum);
112
113                 max = av_len(rlim);
114                 for (i = 0; i < max; i += 3) {
115                         struct rlimit rl;
116                         SV **res = av_fetch(rlim, i, 0);
117                         SV **soft = av_fetch(rlim, i + 1, 0);
118                         SV **hard = av_fetch(rlim, i + 2, 0);
119
120                         rl.rlim_cur = SvIV(*soft);
121                         rl.rlim_max = SvIV(*hard);
122                         if (setrlimit(SvIV(*res), &rl) < 0)
123                                 exit_err(&cerrnum);
124                 }
125
126                 /*
127                  * don't bother unblocking other signals for now, just SIGCHLD.
128                  * we don't want signals to the group taking out a subprocess
129                  */
130                 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
131                 execve(filename, argv, envp);
132                 exit_err(&cerrnum);
133         }
134         perrnum = errno;
135         ret = sigprocmask(SIG_SETMASK, &old, NULL);
136         assert(ret == 0 && "BUG calling sigprocmask to restore");
137         if (cerrnum) {
138                 if (pid > 0)
139                         waitpid(pid, NULL, 0);
140                 pid = -1;
141                 errno = cerrnum;
142         } else if (perrnum) {
143                 errno = perrnum;
144         }
145         return (int)pid;
146 }
147 VFORK_SPAWN
148
149 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
150                 $ENV{XDG_CACHE_HOME} //
151                 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
152         ).'/public-inbox/inline-c';
153
154 $vfork_spawn = undef unless -d $inline_dir && -w _;
155 if (defined $vfork_spawn) {
156         # Inline 0.64 or later has locking in multi-process env,
157         # but we support 0.5 on Debian wheezy
158         use Fcntl qw(:flock);
159         eval {
160                 my $f = "$inline_dir/.public-inbox.lock";
161                 open my $fh, '>', $f or die "failed to open $f: $!\n";
162                 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
163                 eval 'use Inline C => $vfork_spawn';
164                 my $err = $@;
165                 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
166                 die $err if $err;
167         };
168         if ($@) {
169                 warn "Inline::C failed for vfork: $@\n";
170                 $vfork_spawn = undef;
171         }
172 }
173
174 unless (defined $vfork_spawn) {
175         require PublicInbox::SpawnPP;
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 = $env ? (%ENV, %$env) : %ENV;
197         while (my ($k, $v) = each %env) {
198                 push @env, "$k=$v";
199         }
200         my $redir = [];
201         for my $child_fd (0..2) {
202                 my $parent_fd = $opts->{$child_fd};
203                 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
204                         defined(my $fd = fileno($parent_fd)) or
205                                         die "$parent_fd not an IO GLOB? $!";
206                         $parent_fd = $fd;
207                 }
208                 $redir->[$child_fd] = $parent_fd // $child_fd;
209         }
210         my $rlim = [];
211
212         foreach my $l (@RLIMITS) {
213                 defined(my $v = $opts->{$l}) or next;
214                 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
215                 unless (defined $r) {
216                         warn "$l undefined by BSD::Resource: $@\n";
217                         next;
218                 }
219                 push @$rlim, $r, @$v;
220         }
221         my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
222         my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
223         die "fork_exec failed: $!\n" unless $pid > 0;
224         $pid;
225 }
226
227 sub popen_rd {
228         my ($cmd, $env, $opts) = @_;
229         pipe(my ($r, $w)) or die "pipe: $!\n";
230         $opts ||= {};
231         $opts->{1} = fileno($w);
232         my $pid = spawn($cmd, $env, $opts);
233         return ($r, $pid) if wantarray;
234         my $ret = gensym;
235         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r;
236         $ret;
237 }
238
239 1;