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 PublicInbox::ProcessPipe;
22 our @EXPORT_OK = qw(which spawn popen_rd run_die nodatacow_dir);
23 our @RLIMITS = qw(RLIMIT_CPU RLIMIT_CORE RLIMIT_DATA);
25 my $all_libc = <<'ALL_LIBC'; # all *nix systems we support
26 #include <sys/resource.h>
27 #include <sys/socket.h>
28 #include <sys/types.h>
35 /* some platforms need alloca.h, but some don't */
36 #if defined(__GNUC__) && !defined(alloca)
37 # define alloca(sz) __builtin_alloca(sz)
44 * From the av_len apidoc:
45 * Note that, unlike what the name implies, it returns
46 * the highest index in the array, so to get the size of
47 * the array you need to use "av_len(av) + 1".
48 * This is unlike "sv_len", which returns what you would expect.
50 #define AV2C_COPY(dst, src) do { \
52 I32 top_index = av_len(src); \
53 I32 real_len = top_index + 1; \
54 I32 capa = real_len + 1; \
55 dst = alloca(capa * sizeof(char *)); \
56 for (i = 0; i < real_len; i++) { \
57 SV **sv = av_fetch(src, i, 0); \
58 dst[i] = SvPV_nolen(*sv); \
63 /* needs to be safe inside a vfork'ed process */
64 static void exit_err(const char *fn, volatile int *cerrnum)
67 write(2, fn, strlen(fn));
72 * unstable internal API. It'll be updated depending on
73 * whatever we'll need in the future.
74 * Be sure to update PublicInbox::SpawnPP if this changes
76 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
77 const char *cd, int pgid)
79 AV *redir = (AV *)SvRV(redirref);
80 AV *cmd = (AV *)SvRV(cmdref);
81 AV *env = (AV *)SvRV(envref);
82 AV *rlim = (AV *)SvRV(rlimref);
83 const char *filename = SvPV_nolen(file);
88 volatile int cerrnum = 0; /* shared due to vfork */
90 I32 max_fd = av_len(redir);
95 if (sigfillset(&set)) return -1;
96 if (sigprocmask(SIG_SETMASK, &set, &old)) return -1;
97 chld_is_member = sigismember(&old, SIGCHLD);
98 if (chld_is_member < 0) return -1;
99 if (chld_is_member > 0)
100 sigdelset(&old, SIGCHLD);
105 I32 i, child_fd, max_rlim;
107 for (child_fd = 0; child_fd <= max_fd; child_fd++) {
108 SV **parent = av_fetch(redir, child_fd, 0);
109 int parent_fd = SvIV(*parent);
110 if (parent_fd == child_fd)
112 if (dup2(parent_fd, child_fd) < 0)
113 exit_err("dup2", &cerrnum);
115 if (pgid >= 0 && setpgid(0, pgid) < 0)
116 exit_err("setpgid", &cerrnum);
117 for (sig = 1; sig < NSIG; sig++)
118 signal(sig, SIG_DFL); /* ignore errors on signals */
119 if (*cd && chdir(cd) < 0)
120 exit_err("chdir", &cerrnum);
122 max_rlim = av_len(rlim);
123 for (i = 0; i < max_rlim; i += 3) {
125 SV **res = av_fetch(rlim, i, 0);
126 SV **soft = av_fetch(rlim, i + 1, 0);
127 SV **hard = av_fetch(rlim, i + 2, 0);
129 rl.rlim_cur = SvIV(*soft);
130 rl.rlim_max = SvIV(*hard);
131 if (setrlimit(SvIV(*res), &rl) < 0)
132 exit_err("setrlimit", &cerrnum);
135 (void)sigprocmask(SIG_SETMASK, &old, NULL);
136 execve(filename, argv, envp);
137 exit_err("execve", &cerrnum);
140 if (chld_is_member > 0)
141 sigaddset(&old, SIGCHLD);
142 ret = sigprocmask(SIG_SETMASK, &old, NULL);
143 assert(ret == 0 && "BUG calling sigprocmask to restore");
145 int err_fd = STDERR_FILENO;
146 if (err_fd <= max_fd) {
147 SV **parent = av_fetch(redir, err_fd, 0);
148 err_fd = SvIV(*parent);
151 waitpid(pid, NULL, 0);
153 /* continue message started by exit_err in child */
154 dprintf(err_fd, ": %s\n", strerror(cerrnum));
156 } else if (perrnum) {
162 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
163 #define SEND_FD_CAPA 10
164 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
167 char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
170 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
172 struct msghdr msg = { 0 };
173 union my_cmsg cmsg = { 0 };
177 AV *fds = (AV *)SvRV(svfds);
178 I32 i, nfds = av_len(fds) + 1;
182 iov.iov_base = SvPV(data, dlen);
185 if (!dlen) { /* must be non-zero */
186 iov.iov_base = &msg.msg_namelen; /* whatever */
192 if (nfds > SEND_FD_CAPA) {
193 fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
196 msg.msg_control = &cmsg.hdr;
197 msg.msg_controllen = CMSG_SPACE(nfds * sizeof(int));
198 cmsg.hdr.cmsg_level = SOL_SOCKET;
199 cmsg.hdr.cmsg_type = SCM_RIGHTS;
200 cmsg.hdr.cmsg_len = CMSG_LEN(nfds * sizeof(int));
201 fdp = (int *)CMSG_DATA(&cmsg.hdr);
202 for (i = 0; i < nfds; i++) {
203 SV **fd = av_fetch(fds, i, 0);
207 sent = sendmsg(PerlIO_fileno(s), &msg, flags);
208 return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
211 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
213 union my_cmsg cmsg = { 0 };
214 struct msghdr msg = { 0 };
221 sv_setpvn(buf, "", 0);
222 iov.iov_base = SvGROW(buf, n + 1);
226 msg.msg_control = &cmsg.hdr;
227 msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
229 i = recvmsg(PerlIO_fileno(s), &msg, 0);
231 Inline_Stack_Push(&PL_sv_undef);
234 if (i > 0 && cmsg.hdr.cmsg_level == SOL_SOCKET &&
235 cmsg.hdr.cmsg_type == SCM_RIGHTS) {
236 size_t len = cmsg.hdr.cmsg_len;
237 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
238 for (i = 0; CMSG_LEN((i + 1) * sizeof(int)) <= len; i++)
239 Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
243 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
246 # btrfs on Linux is copy-on-write (COW) by default. As of Linux 5.7,
247 # this still leads to fragmentation for SQLite and Xapian files where
248 # random I/O happens, so we disable COW just for SQLite files and Xapian
249 # directories. Disabling COW disables checksumming, so we only do this
250 # for regeneratable files, and not canonical git storage (git doesn't
251 # checksum refs, only data under $GIT_DIR/objects).
252 my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
253 #include <sys/ioctl.h>
255 #include <linux/magic.h>
256 #include <linux/fs.h>
262 void nodatacow_fd(int fd)
267 if (fstatfs(fd, &buf) < 0) {
268 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
272 /* only btrfs is known to have this problem, so skip for non-btrfs */
273 if (buf.f_type != BTRFS_SUPER_MAGIC)
276 if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
277 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
281 if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
282 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
285 void nodatacow_dir(const char *dir)
287 DIR *dh = opendir(dir);
290 if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
294 /* ENOTSUP probably won't happen under Linux... */
299 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
300 $ENV{XDG_CACHE_HOME} //
301 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
302 ).'/public-inbox/inline-c';
304 $set_nodatacow = $all_libc = undef unless -d $inline_dir && -w _;
305 if (defined $all_libc) {
306 # Inline 0.64 or later has locking in multi-process env,
307 # but we support 0.5 on Debian wheezy
308 use Fcntl qw(:flock);
310 my $f = "$inline_dir/.public-inbox.lock";
311 open my $fh, '>', $f or die "failed to open $f: $!\n";
312 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
313 eval 'use Inline C => $all_libc.$set_nodatacow';
314 # . ', BUILD_NOISY => 1';
317 if ($err && $set_nodatacow) { # missing Linux kernel headers
319 undef $set_nodatacow;
320 eval 'use Inline C => $all_libc';
322 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
324 warn $ndc_err if $ndc_err;
327 warn "Inline::C failed for vfork: $@\n";
328 $set_nodatacow = $all_libc = undef;
333 require PublicInbox::SpawnPP;
334 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
336 unless ($set_nodatacow) {
337 require PublicInbox::NDC_PP;
339 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
340 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
343 undef $set_nodatacow;
348 return $file if index($file, '/') >= 0;
349 for my $p (split(/:/, $ENV{PATH})) {
357 my ($cmd, $env, $opts) = @_;
358 my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
361 my %env = (%ENV, $env ? %$env : ());
362 while (my ($k, $v) = each %env) {
363 push @env, "$k=$v" if defined($v);
366 for my $child_fd (0..2) {
367 my $parent_fd = $opts->{$child_fd};
368 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
369 my $fd = fileno($parent_fd) //
370 die "$parent_fd not an IO GLOB? $!";
373 $redir->[$child_fd] = $parent_fd // $child_fd;
377 foreach my $l (@RLIMITS) {
378 my $v = $opts->{$l} // next;
379 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
380 unless (defined $r) {
381 warn "$l undefined by BSD::Resource: $@\n";
384 push @$rlim, $r, @$v;
386 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
387 my $pgid = $opts->{pgid} // -1;
388 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd, $pgid);
389 die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
394 my ($cmd, $env, $opt) = @_;
395 pipe(my ($r, $w)) or die "pipe: $!\n";
397 $opt->{1} = fileno($w);
398 my $pid = spawn($cmd, $env, $opt);
399 return ($r, $pid) if wantarray;
401 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
406 my ($cmd, $env, $rdr) = @_;
407 my $pid = spawn($cmd, $env, $rdr);
408 waitpid($pid, 0) == $pid or die "@$cmd did not finish";
409 $? == 0 or die "@$cmd failed: \$?=$?\n";