1 # Copyright (C) 2016-2021 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 # There'll probably be more OS-level C stuff here, down the line.
15 # We don't want too many DSOs: https://udrepper.livejournal.com/8790.html
17 package PublicInbox::Spawn;
19 use parent qw(Exporter);
20 use Symbol qw(gensym);
21 use Fcntl qw(LOCK_EX SEEK_SET);
23 use PublicInbox::ProcessPipe;
24 our @EXPORT_OK = qw(which spawn popen_rd run_die nodatacow_dir);
25 our @RLIMITS = qw(RLIMIT_CPU RLIMIT_CORE RLIMIT_DATA);
28 my $all_libc = <<'ALL_LIBC'; # all *nix systems we support
29 #include <sys/resource.h>
30 #include <sys/socket.h>
31 #include <sys/types.h>
38 /* some platforms need alloca.h, but some don't */
39 #if defined(__GNUC__) && !defined(alloca)
40 # define alloca(sz) __builtin_alloca(sz)
47 * From the av_len apidoc:
48 * Note that, unlike what the name implies, it returns
49 * the highest index in the array, so to get the size of
50 * the array you need to use "av_len(av) + 1".
51 * This is unlike "sv_len", which returns what you would expect.
53 #define AV2C_COPY(dst, src) do { \
55 I32 top_index = av_len(src); \
56 I32 real_len = top_index + 1; \
57 I32 capa = real_len + 1; \
58 dst = alloca(capa * sizeof(char *)); \
59 for (i = 0; i < real_len; i++) { \
60 SV **sv = av_fetch(src, i, 0); \
61 dst[i] = SvPV_nolen(*sv); \
66 /* needs to be safe inside a vfork'ed process */
67 static void exit_err(const char *fn, volatile int *cerrnum)
70 write(2, fn, strlen(fn));
75 * unstable internal API. It'll be updated depending on
76 * whatever we'll need in the future.
77 * Be sure to update PublicInbox::SpawnPP if this changes
79 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
80 const char *cd, int pgid)
82 AV *redir = (AV *)SvRV(redirref);
83 AV *cmd = (AV *)SvRV(cmdref);
84 AV *env = (AV *)SvRV(envref);
85 AV *rlim = (AV *)SvRV(rlimref);
86 const char *filename = SvPV_nolen(file);
91 volatile int cerrnum = 0; /* shared due to vfork */
93 I32 max_fd = av_len(redir);
98 if (sigfillset(&set)) return -1;
99 if (sigprocmask(SIG_SETMASK, &set, &old)) return -1;
100 chld_is_member = sigismember(&old, SIGCHLD);
101 if (chld_is_member < 0) return -1;
102 if (chld_is_member > 0)
103 sigdelset(&old, SIGCHLD);
108 I32 i, child_fd, max_rlim;
110 for (child_fd = 0; child_fd <= max_fd; child_fd++) {
111 SV **parent = av_fetch(redir, child_fd, 0);
112 int parent_fd = SvIV(*parent);
113 if (parent_fd == child_fd)
115 if (dup2(parent_fd, child_fd) < 0)
116 exit_err("dup2", &cerrnum);
118 if (pgid >= 0 && setpgid(0, pgid) < 0)
119 exit_err("setpgid", &cerrnum);
120 for (sig = 1; sig < NSIG; sig++)
121 signal(sig, SIG_DFL); /* ignore errors on signals */
122 if (*cd && chdir(cd) < 0)
123 exit_err("chdir", &cerrnum);
125 max_rlim = av_len(rlim);
126 for (i = 0; i < max_rlim; i += 3) {
128 SV **res = av_fetch(rlim, i, 0);
129 SV **soft = av_fetch(rlim, i + 1, 0);
130 SV **hard = av_fetch(rlim, i + 2, 0);
132 rl.rlim_cur = SvIV(*soft);
133 rl.rlim_max = SvIV(*hard);
134 if (setrlimit(SvIV(*res), &rl) < 0)
135 exit_err("setrlimit", &cerrnum);
138 (void)sigprocmask(SIG_SETMASK, &old, NULL);
139 execve(filename, argv, envp);
140 exit_err("execve", &cerrnum);
143 if (chld_is_member > 0)
144 sigaddset(&old, SIGCHLD);
145 ret = sigprocmask(SIG_SETMASK, &old, NULL);
146 assert(ret == 0 && "BUG calling sigprocmask to restore");
148 int err_fd = STDERR_FILENO;
149 if (err_fd <= max_fd) {
150 SV **parent = av_fetch(redir, err_fd, 0);
151 err_fd = SvIV(*parent);
154 waitpid(pid, NULL, 0);
156 /* continue message started by exit_err in child */
157 dprintf(err_fd, ": %s\n", strerror(cerrnum));
159 } else if (perrnum) {
165 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
166 #define SEND_FD_CAPA 10
167 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
170 char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
173 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
175 struct msghdr msg = { 0 };
176 union my_cmsg cmsg = { 0 };
180 AV *fds = (AV *)SvRV(svfds);
181 I32 i, nfds = av_len(fds) + 1;
185 iov.iov_base = SvPV(data, dlen);
188 if (!dlen) { /* must be non-zero */
189 iov.iov_base = &msg.msg_namelen; /* whatever */
195 if (nfds > SEND_FD_CAPA) {
196 fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
199 msg.msg_control = &cmsg.hdr;
200 msg.msg_controllen = CMSG_SPACE(nfds * sizeof(int));
201 cmsg.hdr.cmsg_level = SOL_SOCKET;
202 cmsg.hdr.cmsg_type = SCM_RIGHTS;
203 cmsg.hdr.cmsg_len = CMSG_LEN(nfds * sizeof(int));
204 fdp = (int *)CMSG_DATA(&cmsg.hdr);
205 for (i = 0; i < nfds; i++) {
206 SV **fd = av_fetch(fds, i, 0);
210 sent = sendmsg(PerlIO_fileno(s), &msg, flags);
211 return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
214 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
216 union my_cmsg cmsg = { 0 };
217 struct msghdr msg = { 0 };
224 sv_setpvn(buf, "", 0);
225 iov.iov_base = SvGROW(buf, n + 1);
229 msg.msg_control = &cmsg.hdr;
230 msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
232 i = recvmsg(PerlIO_fileno(s), &msg, 0);
234 Inline_Stack_Push(&PL_sv_undef);
237 if (i > 0 && cmsg.hdr.cmsg_level == SOL_SOCKET &&
238 cmsg.hdr.cmsg_type == SCM_RIGHTS) {
239 size_t len = cmsg.hdr.cmsg_len;
240 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
241 for (i = 0; CMSG_LEN((i + 1) * sizeof(int)) <= len; i++)
242 Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
246 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
249 # btrfs on Linux is copy-on-write (COW) by default. As of Linux 5.7,
250 # this still leads to fragmentation for SQLite and Xapian files where
251 # random I/O happens, so we disable COW just for SQLite files and Xapian
252 # directories. Disabling COW disables checksumming, so we only do this
253 # for regeneratable files, and not canonical git storage (git doesn't
254 # checksum refs, only data under $GIT_DIR/objects).
255 my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
256 #include <sys/ioctl.h>
258 #include <linux/magic.h>
259 #include <linux/fs.h>
265 void nodatacow_fd(int fd)
270 if (fstatfs(fd, &buf) < 0) {
271 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
275 /* only btrfs is known to have this problem, so skip for non-btrfs */
276 if (buf.f_type != BTRFS_SUPER_MAGIC)
279 if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
280 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
284 if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
285 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
288 void nodatacow_dir(const char *dir)
290 DIR *dh = opendir(dir);
293 if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
297 /* ENOTSUP probably won't happen under Linux... */
302 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
303 $ENV{XDG_CACHE_HOME} //
304 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
305 ).'/public-inbox/inline-c';
306 warn "$inline_dir exists, not writable\n" if -e $inline_dir && !-w _;
307 $set_nodatacow = $all_libc = undef unless -d _ && -w _;
308 if (defined $all_libc) {
309 my $f = "$inline_dir/.public-inbox.lock";
310 open my $oldout, '>&', \*STDOUT or die "dup(1): $!";
311 open my $olderr, '>&', \*STDERR or die "dup(2): $!";
312 open my $fh, '+>', $f or die "open($f): $!";
313 open STDOUT, '>&', $fh or die "1>$f: $!";
314 open STDERR, '>&', $fh or die "2>$f: $!";
315 STDERR->autoflush(1);
316 STDOUT->autoflush(1);
318 # CentOS 7.x ships Inline 0.53, 0.64+ has built-in locking
319 flock($fh, LOCK_EX) or die "LOCK_EX($f): $!";
321 use Inline C => $all_libc.$set_nodatacow, BUILD_NOISY => 1;
325 if ($err && $set_nodatacow) { # missing Linux kernel headers
326 $ndc_err = "with set_nodatacow: <\n$err\n>\n";
327 undef $set_nodatacow;
329 use Inline C => $all_libc, BUILD_NOISY => 1;
333 open(STDERR, '>&', $olderr) or warn "restore stderr: $!";
334 open(STDOUT, '>&', $oldout) or warn "restore stdout: $!";
336 seek($fh, 0, SEEK_SET);
338 warn "Inline::C build failed:\n",
339 $ndc_err, $err, "\n", @msg;
340 $set_nodatacow = $all_libc = undef;
342 warn "Inline::C build succeeded w/o set_nodatacow\n",
347 require PublicInbox::SpawnPP;
348 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
350 unless ($set_nodatacow) {
351 require PublicInbox::NDC_PP;
353 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
354 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
360 return $file if index($file, '/') >= 0;
361 for my $p (split(/:/, $ENV{PATH})) {
369 my ($cmd, $env, $opts) = @_;
370 my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
373 my %env = (%ENV, $env ? %$env : ());
374 while (my ($k, $v) = each %env) {
375 push @env, "$k=$v" if defined($v);
378 for my $child_fd (0..2) {
379 my $parent_fd = $opts->{$child_fd};
380 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
381 my $fd = fileno($parent_fd) //
382 die "$parent_fd not an IO GLOB? $!";
385 $redir->[$child_fd] = $parent_fd // $child_fd;
389 foreach my $l (@RLIMITS) {
390 my $v = $opts->{$l} // next;
391 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
392 unless (defined $r) {
393 warn "$l undefined by BSD::Resource: $@\n";
396 push @$rlim, $r, @$v;
398 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
399 my $pgid = $opts->{pgid} // -1;
400 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd, $pgid);
401 die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
406 my ($cmd, $env, $opt) = @_;
407 pipe(my ($r, $w)) or die "pipe: $!\n";
409 $opt->{1} = fileno($w);
410 my $pid = spawn($cmd, $env, $opt);
411 return ($r, $pid) if wantarray;
413 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
418 my ($cmd, $env, $rdr) = @_;
419 my $pid = spawn($cmd, $env, $rdr);
420 waitpid($pid, 0) == $pid or die "@$cmd did not finish";
421 $? == 0 or die "@$cmd failed: \$?=$?\n";