]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
spawn: modernize with parent.pm, drop warnings.pm
[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/uio.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29
30 /* some platforms need alloca.h, but some don't */
31 #if defined(__GNUC__) && !defined(alloca)
32 #  define alloca(sz) __builtin_alloca(sz)
33 #endif
34
35 #include <signal.h>
36 #include <assert.h>
37
38 /*
39  * From the av_len apidoc:
40  *   Note that, unlike what the name implies, it returns
41  *   the highest index in the array, so to get the size of
42  *   the array you need to use "av_len(av) + 1".
43  *   This is unlike "sv_len", which returns what you would expect.
44  */
45 #define AV2C_COPY(dst, src) do { \
46         I32 i; \
47         I32 top_index = av_len(src); \
48         I32 real_len = top_index + 1; \
49         I32 capa = real_len + 1; \
50         dst = alloca(capa * sizeof(char *)); \
51         for (i = 0; i < real_len; i++) { \
52                 SV **sv = av_fetch(src, i, 0); \
53                 dst[i] = SvPV_nolen(*sv); \
54         } \
55         dst[real_len] = 0; \
56 } while (0)
57
58 /* needs to be safe inside a vfork'ed process */
59 static void exit_err(int *cerrnum)
60 {
61         *cerrnum = errno;
62         _exit(1);
63 }
64
65 /*
66  * unstable internal API.  It'll be updated depending on
67  * whatever we'll need in the future.
68  * Be sure to update PublicInbox::SpawnPP if this changes
69  */
70 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
71                  const char *cd)
72 {
73         AV *redir = (AV *)SvRV(redirref);
74         AV *cmd = (AV *)SvRV(cmdref);
75         AV *env = (AV *)SvRV(envref);
76         AV *rlim = (AV *)SvRV(rlimref);
77         const char *filename = SvPV_nolen(file);
78         pid_t pid;
79         char **argv, **envp;
80         sigset_t set, old, cset;
81         int ret, perrnum, cerrnum = 0;
82
83         AV2C_COPY(argv, cmd);
84         AV2C_COPY(envp, env);
85
86         ret = sigfillset(&set);
87         assert(ret == 0 && "BUG calling sigfillset");
88         ret = sigprocmask(SIG_SETMASK, &set, &old);
89         assert(ret == 0 && "BUG calling sigprocmask to block");
90         ret = sigemptyset(&cset);
91         assert(ret == 0 && "BUG calling sigemptyset");
92         ret = sigaddset(&cset, SIGCHLD);
93         assert(ret == 0 && "BUG calling sigaddset for SIGCHLD");
94         pid = vfork();
95         if (pid == 0) {
96                 int sig;
97                 I32 i, child_fd, max = av_len(redir);
98
99                 for (child_fd = 0; child_fd <= max; child_fd++) {
100                         SV **parent = av_fetch(redir, child_fd, 0);
101                         int parent_fd = SvIV(*parent);
102                         if (parent_fd == child_fd)
103                                 continue;
104                         if (dup2(parent_fd, child_fd) < 0)
105                                 exit_err(&cerrnum);
106                 }
107                 for (sig = 1; sig < NSIG; sig++)
108                         signal(sig, SIG_DFL); /* ignore errors on signals */
109                 if (*cd && chdir(cd) < 0)
110                         exit_err(&cerrnum);
111
112                 max = av_len(rlim);
113                 for (i = 0; i < max; i += 3) {
114                         struct rlimit rl;
115                         SV **res = av_fetch(rlim, i, 0);
116                         SV **soft = av_fetch(rlim, i + 1, 0);
117                         SV **hard = av_fetch(rlim, i + 2, 0);
118
119                         rl.rlim_cur = SvIV(*soft);
120                         rl.rlim_max = SvIV(*hard);
121                         if (setrlimit(SvIV(*res), &rl) < 0)
122                                 exit_err(&cerrnum);
123                 }
124
125                 /*
126                  * don't bother unblocking other signals for now, just SIGCHLD.
127                  * we don't want signals to the group taking out a subprocess
128                  */
129                 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
130                 execve(filename, argv, envp);
131                 exit_err(&cerrnum);
132         }
133         perrnum = errno;
134         ret = sigprocmask(SIG_SETMASK, &old, NULL);
135         assert(ret == 0 && "BUG calling sigprocmask to restore");
136         if (cerrnum) {
137                 if (pid > 0)
138                         waitpid(pid, NULL, 0);
139                 pid = -1;
140                 errno = cerrnum;
141         } else if (perrnum) {
142                 errno = perrnum;
143         }
144         return (int)pid;
145 }
146 VFORK_SPAWN
147
148 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
149                 $ENV{XDG_CACHE_HOME} //
150                 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
151         ).'/public-inbox/inline-c';
152
153 $vfork_spawn = undef unless -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';
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         *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
176 }
177
178 sub which ($) {
179         my ($file) = @_;
180         return $file if index($file, '/') >= 0;
181         foreach my $p (split(':', $ENV{PATH})) {
182                 $p .= "/$file";
183                 return $p if -x $p;
184         }
185         undef;
186 }
187
188 sub spawn ($;$$) {
189         my ($cmd, $env, $opts) = @_;
190         my $f = which($cmd->[0]);
191         defined $f or die "$cmd->[0]: command not found\n";
192         my @env;
193         $opts ||= {};
194
195         my %env = $env ? (%ENV, %$env) : %ENV;
196         while (my ($k, $v) = each %env) {
197                 push @env, "$k=$v";
198         }
199         my $redir = [];
200         for my $child_fd (0..2) {
201                 my $parent_fd = $opts->{$child_fd};
202                 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
203                         defined(my $fd = fileno($parent_fd)) or
204                                         die "$parent_fd not an IO GLOB? $!";
205                         $parent_fd = $fd;
206                 }
207                 $redir->[$child_fd] = $parent_fd // $child_fd;
208         }
209         my $rlim = [];
210
211         foreach my $l (@RLIMITS) {
212                 defined(my $v = $opts->{$l}) or next;
213                 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
214                 unless (defined $r) {
215                         warn "$l undefined by BSD::Resource: $@\n";
216                         next;
217                 }
218                 push @$rlim, $r, @$v;
219         }
220         my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
221         my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
222         die "fork_exec failed: $!\n" unless $pid > 0;
223         $pid;
224 }
225
226 sub popen_rd {
227         my ($cmd, $env, $opts) = @_;
228         pipe(my ($r, $w)) or die "pipe: $!\n";
229         $opts ||= {};
230         $opts->{1} = fileno($w);
231         my $pid = spawn($cmd, $env, $opts);
232         return ($r, $pid) if wantarray;
233         my $ret = gensym;
234         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r;
235         $ret;
236 }
237
238 1;