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>
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
13 package PublicInbox::Spawn;
16 use base qw(Exporter);
17 use Symbol qw(gensym);
18 use PublicInbox::ProcessPipe;
19 our @EXPORT_OK = qw/which spawn popen_rd/;
20 sub RLIMITS () { qw(RLIMIT_CPU RLIMIT_CORE RLIMIT_DATA) }
22 my $vfork_spawn = <<'VFORK_SPAWN';
23 #include <sys/types.h>
26 #include <sys/resource.h>
30 /* some platforms need alloca.h, but some don't */
31 #if defined(__GNUC__) && !defined(alloca)
32 # define alloca(sz) __builtin_alloca(sz)
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.
45 #define AV2C_COPY(dst, src) do { \
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); \
58 /* needs to be safe inside a vfork'ed process */
59 static void exit_err(int *cerrnum)
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
70 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
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);
81 int ret, perrnum, cerrnum = 0;
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");
93 I32 i, child_fd, max = av_len(redir);
95 for (child_fd = 0; child_fd <= max; child_fd++) {
96 SV **parent = av_fetch(redir, child_fd, 0);
97 int parent_fd = SvIV(*parent);
98 if (parent_fd == child_fd)
100 if (dup2(parent_fd, child_fd) < 0)
103 for (sig = 1; sig < NSIG; sig++)
104 signal(sig, SIG_DFL); /* ignore errors on signals */
105 if (*cd && chdir(cd) < 0)
109 for (i = 0; i < max; i += 3) {
111 SV **res = av_fetch(rlim, i, 0);
112 SV **soft = av_fetch(rlim, i + 1, 0);
113 SV **hard = av_fetch(rlim, i + 2, 0);
115 rl.rlim_cur = SvIV(*soft);
116 rl.rlim_max = SvIV(*hard);
117 if (setrlimit(SvIV(*res), &rl) < 0)
122 * don't bother unblocking, we don't want signals
123 * to the group taking out a subprocess
125 execve(filename, argv, envp);
129 ret = sigprocmask(SIG_SETMASK, &old, NULL);
130 assert(ret == 0 && "BUG calling sigprocmask to restore");
133 waitpid(pid, NULL, 0);
136 } else if (perrnum) {
143 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY};
144 $vfork_spawn = undef unless defined $inline_dir && -d $inline_dir && -w _;
145 if (defined $vfork_spawn) {
146 # Inline 0.64 or later has locking in multi-process env,
147 # but we support 0.5 on Debian wheezy
148 use Fcntl qw(:flock);
150 my $f = "$inline_dir/.public-inbox.lock";
151 open my $fh, '>', $f or die "failed to open $f: $!\n";
152 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
153 eval 'use Inline C => $vfork_spawn'; #, BUILD_NOISY => 1';
155 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
159 warn "Inline::C failed for vfork: $@\n";
160 $vfork_spawn = undef;
164 unless (defined $vfork_spawn) {
165 require PublicInbox::SpawnPP;
166 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
171 return $file if index($file, '/') >= 0;
172 foreach my $p (split(':', $ENV{PATH})) {
180 my ($cmd, $env, $opts) = @_;
181 my $f = which($cmd->[0]);
182 defined $f or die "$cmd->[0]: command not found\n";
186 my %env = $env ? (%ENV, %$env) : %ENV;
187 while (my ($k, $v) = each %env) {
191 for my $child_fd (0..2) {
192 my $parent_fd = $opts->{$child_fd};
193 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
194 defined(my $fd = fileno($parent_fd)) or
195 die "$parent_fd not an IO GLOB? $!";
198 $redir->[$child_fd] = $parent_fd // $child_fd;
202 foreach my $l (RLIMITS()) {
203 defined(my $v = $opts->{$l}) or next;
204 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
205 unless (defined $r) {
206 warn "$l undefined by BSD::Resource: $@\n";
209 push @$rlim, $r, @$v;
211 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
212 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
213 die "fork_exec failed: $!\n" unless $pid > 0;
218 my ($cmd, $env, $opts) = @_;
219 pipe(my ($r, $w)) or die "pipe: $!\n";
221 $opts->{1} = fileno($w);
222 my $pid = spawn($cmd, $env, $opts);
223 return ($r, $pid) if wantarray;
225 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r;