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 # ~/.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
14 package PublicInbox::Spawn;
17 use base qw(Exporter);
18 use Symbol qw(gensym);
19 use PublicInbox::ProcessPipe;
20 our @EXPORT_OK = qw/which spawn popen_rd/;
21 sub RLIMITS () { qw(RLIMIT_CPU RLIMIT_CORE RLIMIT_DATA) }
23 my $vfork_spawn = <<'VFORK_SPAWN';
24 #include <sys/types.h>
27 #include <sys/resource.h>
31 /* some platforms need alloca.h, but some don't */
32 #if defined(__GNUC__) && !defined(alloca)
33 # define alloca(sz) __builtin_alloca(sz)
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.
46 #define AV2C_COPY(dst, src) do { \
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); \
59 /* needs to be safe inside a vfork'ed process */
60 static void exit_err(int *cerrnum)
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
71 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
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);
82 int ret, perrnum, cerrnum = 0;
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");
94 I32 i, child_fd, max = av_len(redir);
96 for (child_fd = 0; child_fd <= max; child_fd++) {
97 SV **parent = av_fetch(redir, child_fd, 0);
98 int parent_fd = SvIV(*parent);
99 if (parent_fd == child_fd)
101 if (dup2(parent_fd, child_fd) < 0)
104 for (sig = 1; sig < NSIG; sig++)
105 signal(sig, SIG_DFL); /* ignore errors on signals */
106 if (*cd && chdir(cd) < 0)
110 for (i = 0; i < max; i += 3) {
112 SV **res = av_fetch(rlim, i, 0);
113 SV **soft = av_fetch(rlim, i + 1, 0);
114 SV **hard = av_fetch(rlim, i + 2, 0);
116 rl.rlim_cur = SvIV(*soft);
117 rl.rlim_max = SvIV(*hard);
118 if (setrlimit(SvIV(*res), &rl) < 0)
123 * don't bother unblocking, we don't want signals
124 * to the group taking out a subprocess
126 execve(filename, argv, envp);
130 ret = sigprocmask(SIG_SETMASK, &old, NULL);
131 assert(ret == 0 && "BUG calling sigprocmask to restore");
134 waitpid(pid, NULL, 0);
137 } else if (perrnum) {
144 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} // (
145 $ENV{XDG_CACHE_HOME} //
146 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
147 ).'/public-inbox/inline-c';
149 $vfork_spawn = undef unless -d $inline_dir && -w _;
150 if (defined $vfork_spawn) {
151 # Inline 0.64 or later has locking in multi-process env,
152 # but we support 0.5 on Debian wheezy
153 use Fcntl qw(:flock);
155 my $f = "$inline_dir/.public-inbox.lock";
156 open my $fh, '>', $f or die "failed to open $f: $!\n";
157 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
158 eval 'use Inline C => $vfork_spawn, directory => $inline_dir';
160 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
164 warn "Inline::C failed for vfork: $@\n";
165 $vfork_spawn = undef;
169 unless (defined $vfork_spawn) {
170 require PublicInbox::SpawnPP;
171 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
176 return $file if index($file, '/') >= 0;
177 foreach my $p (split(':', $ENV{PATH})) {
185 my ($cmd, $env, $opts) = @_;
186 my $f = which($cmd->[0]);
187 defined $f or die "$cmd->[0]: command not found\n";
191 my %env = $env ? (%ENV, %$env) : %ENV;
192 while (my ($k, $v) = each %env) {
196 for my $child_fd (0..2) {
197 my $parent_fd = $opts->{$child_fd};
198 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
199 defined(my $fd = fileno($parent_fd)) or
200 die "$parent_fd not an IO GLOB? $!";
203 $redir->[$child_fd] = $parent_fd // $child_fd;
207 foreach my $l (RLIMITS()) {
208 defined(my $v = $opts->{$l}) or next;
209 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
210 unless (defined $r) {
211 warn "$l undefined by BSD::Resource: $@\n";
214 push @$rlim, $r, @$v;
216 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
217 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
218 die "fork_exec failed: $!\n" unless $pid > 0;
223 my ($cmd, $env, $opts) = @_;
224 pipe(my ($r, $w)) or die "pipe: $!\n";
226 $opts->{1} = fileno($w);
227 my $pid = spawn($cmd, $env, $opts);
228 return ($r, $pid) if wantarray;
230 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r;