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>
41 /* some platforms need alloca.h, but some don't */
42 #if defined(__GNUC__) && !defined(alloca)
43 # define alloca(sz) __builtin_alloca(sz)
50 * From the av_len apidoc:
51 * Note that, unlike what the name implies, it returns
52 * the highest index in the array, so to get the size of
53 * the array you need to use "av_len(av) + 1".
54 * This is unlike "sv_len", which returns what you would expect.
56 #define AV2C_COPY(dst, src) do { \
58 I32 top_index = av_len(src); \
59 I32 real_len = top_index + 1; \
60 I32 capa = real_len + 1; \
61 dst = alloca(capa * sizeof(char *)); \
62 for (i = 0; i < real_len; i++) { \
63 SV **sv = av_fetch(src, i, 0); \
64 dst[i] = SvPV_nolen(*sv); \
69 /* needs to be safe inside a vfork'ed process */
70 static void exit_err(const char *fn, volatile int *cerrnum)
73 write(2, fn, strlen(fn));
78 * unstable internal API. It'll be updated depending on
79 * whatever we'll need in the future.
80 * Be sure to update PublicInbox::SpawnPP if this changes
82 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
83 const char *cd, int pgid)
85 AV *redir = (AV *)SvRV(redirref);
86 AV *cmd = (AV *)SvRV(cmdref);
87 AV *env = (AV *)SvRV(envref);
88 AV *rlim = (AV *)SvRV(rlimref);
89 const char *filename = SvPV_nolen(file);
94 volatile int cerrnum = 0; /* shared due to vfork */
96 I32 max_fd = av_len(redir);
101 if (sigfillset(&set)) return -1;
102 if (sigprocmask(SIG_SETMASK, &set, &old)) return -1;
103 chld_is_member = sigismember(&old, SIGCHLD);
104 if (chld_is_member < 0) return -1;
105 if (chld_is_member > 0)
106 sigdelset(&old, SIGCHLD);
111 I32 i, child_fd, max_rlim;
113 for (child_fd = 0; child_fd <= max_fd; child_fd++) {
114 SV **parent = av_fetch(redir, child_fd, 0);
115 int parent_fd = SvIV(*parent);
116 if (parent_fd == child_fd)
118 if (dup2(parent_fd, child_fd) < 0)
119 exit_err("dup2", &cerrnum);
121 if (pgid >= 0 && setpgid(0, pgid) < 0)
122 exit_err("setpgid", &cerrnum);
123 for (sig = 1; sig < NSIG; sig++)
124 signal(sig, SIG_DFL); /* ignore errors on signals */
125 if (*cd && chdir(cd) < 0)
126 exit_err("chdir", &cerrnum);
128 max_rlim = av_len(rlim);
129 for (i = 0; i < max_rlim; i += 3) {
131 SV **res = av_fetch(rlim, i, 0);
132 SV **soft = av_fetch(rlim, i + 1, 0);
133 SV **hard = av_fetch(rlim, i + 2, 0);
135 rl.rlim_cur = SvIV(*soft);
136 rl.rlim_max = SvIV(*hard);
137 if (setrlimit(SvIV(*res), &rl) < 0)
138 exit_err("setrlimit", &cerrnum);
141 (void)sigprocmask(SIG_SETMASK, &old, NULL);
142 execve(filename, argv, envp);
143 exit_err("execve", &cerrnum);
146 if (chld_is_member > 0)
147 sigaddset(&old, SIGCHLD);
148 ret = sigprocmask(SIG_SETMASK, &old, NULL);
149 assert(ret == 0 && "BUG calling sigprocmask to restore");
151 int err_fd = STDERR_FILENO;
152 if (err_fd <= max_fd) {
153 SV **parent = av_fetch(redir, err_fd, 0);
154 err_fd = SvIV(*parent);
157 waitpid(pid, NULL, 0);
159 /* continue message started by exit_err in child */
160 dprintf(err_fd, ": %s\n", strerror(cerrnum));
162 } else if (perrnum) {
168 static int sleep_wait(unsigned *try, int err)
170 const struct timespec req = { 0, 100000000 }; /* 100ms */
172 case ENOBUFS: case ENOMEM: case ETOOMANYREFS:
174 fprintf(stderr, "sleeping on sendmsg: %s (#%u)\n",
175 strerror(err), *try);
176 nanosleep(&req, NULL);
184 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
185 #define SEND_FD_CAPA 10
186 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
189 char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
192 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
194 struct msghdr msg = { 0 };
195 union my_cmsg cmsg = { 0 };
199 AV *fds = (AV *)SvRV(svfds);
200 I32 i, nfds = av_len(fds) + 1;
205 iov.iov_base = SvPV(data, dlen);
208 if (!dlen) { /* must be non-zero */
209 iov.iov_base = &msg.msg_namelen; /* whatever */
215 if (nfds > SEND_FD_CAPA) {
216 fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
219 msg.msg_control = &cmsg.hdr;
220 msg.msg_controllen = CMSG_SPACE(nfds * sizeof(int));
221 cmsg.hdr.cmsg_level = SOL_SOCKET;
222 cmsg.hdr.cmsg_type = SCM_RIGHTS;
223 cmsg.hdr.cmsg_len = CMSG_LEN(nfds * sizeof(int));
224 fdp = (int *)CMSG_DATA(&cmsg.hdr);
225 for (i = 0; i < nfds; i++) {
226 SV **fd = av_fetch(fds, i, 0);
231 sent = sendmsg(PerlIO_fileno(s), &msg, flags);
232 } while (sent < 0 && sleep_wait(&try, errno));
233 return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
236 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
238 union my_cmsg cmsg = { 0 };
239 struct msghdr msg = { 0 };
246 sv_setpvn(buf, "", 0);
247 iov.iov_base = SvGROW(buf, n + 1);
251 msg.msg_control = &cmsg.hdr;
252 msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
254 i = recvmsg(PerlIO_fileno(s), &msg, 0);
256 Inline_Stack_Push(&PL_sv_undef);
259 if (i > 0 && cmsg.hdr.cmsg_level == SOL_SOCKET &&
260 cmsg.hdr.cmsg_type == SCM_RIGHTS) {
261 size_t len = cmsg.hdr.cmsg_len;
262 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
263 for (i = 0; CMSG_LEN((i + 1) * sizeof(int)) <= len; i++)
264 Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
268 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
271 # btrfs on Linux is copy-on-write (COW) by default. As of Linux 5.7,
272 # this still leads to fragmentation for SQLite and Xapian files where
273 # random I/O happens, so we disable COW just for SQLite files and Xapian
274 # directories. Disabling COW disables checksumming, so we only do this
275 # for regeneratable files, and not canonical git storage (git doesn't
276 # checksum refs, only data under $GIT_DIR/objects).
277 my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
278 #include <sys/ioctl.h>
280 #include <linux/magic.h>
281 #include <linux/fs.h>
284 void nodatacow_fd(int fd)
289 if (fstatfs(fd, &buf) < 0) {
290 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
294 /* only btrfs is known to have this problem, so skip for non-btrfs */
295 if (buf.f_type != BTRFS_SUPER_MAGIC)
298 if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
299 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
303 if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
304 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
307 void nodatacow_dir(const char *dir)
309 DIR *dh = opendir(dir);
312 if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
316 /* ENOTSUP probably won't happen under Linux... */
321 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
322 $ENV{XDG_CACHE_HOME} //
323 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
324 ).'/public-inbox/inline-c';
325 warn "$inline_dir exists, not writable\n" if -e $inline_dir && !-w _;
326 $set_nodatacow = $all_libc = undef unless -d _ && -w _;
327 if (defined $all_libc) {
328 my $f = "$inline_dir/.public-inbox.lock";
329 open my $oldout, '>&', \*STDOUT or die "dup(1): $!";
330 open my $olderr, '>&', \*STDERR or die "dup(2): $!";
331 open my $fh, '+>', $f or die "open($f): $!";
332 open STDOUT, '>&', $fh or die "1>$f: $!";
333 open STDERR, '>&', $fh or die "2>$f: $!";
334 STDERR->autoflush(1);
335 STDOUT->autoflush(1);
337 # CentOS 7.x ships Inline 0.53, 0.64+ has built-in locking
338 flock($fh, LOCK_EX) or die "LOCK_EX($f): $!";
340 use Inline C => $all_libc.$set_nodatacow, BUILD_NOISY => 1;
344 if ($err && $set_nodatacow) { # missing Linux kernel headers
345 $ndc_err = "with set_nodatacow: <\n$err\n>\n";
346 undef $set_nodatacow;
348 use Inline C => $all_libc, BUILD_NOISY => 1;
352 open(STDERR, '>&', $olderr) or warn "restore stderr: $!";
353 open(STDOUT, '>&', $oldout) or warn "restore stdout: $!";
355 seek($fh, 0, SEEK_SET);
357 warn "Inline::C build failed:\n",
358 $ndc_err, $err, "\n", @msg;
359 $set_nodatacow = $all_libc = undef;
361 warn "Inline::C build succeeded w/o set_nodatacow\n",
366 require PublicInbox::SpawnPP;
367 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
369 unless ($set_nodatacow) {
370 require PublicInbox::NDC_PP;
372 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
373 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
379 return $file if index($file, '/') >= 0;
380 for my $p (split(/:/, $ENV{PATH})) {
388 my ($cmd, $env, $opts) = @_;
389 my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
392 my %env = (%ENV, $env ? %$env : ());
393 while (my ($k, $v) = each %env) {
394 push @env, "$k=$v" if defined($v);
397 for my $child_fd (0..2) {
398 my $parent_fd = $opts->{$child_fd};
399 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
400 my $fd = fileno($parent_fd) //
401 die "$parent_fd not an IO GLOB? $!";
404 $redir->[$child_fd] = $parent_fd // $child_fd;
408 foreach my $l (@RLIMITS) {
409 my $v = $opts->{$l} // next;
410 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
411 unless (defined $r) {
412 warn "$l undefined by BSD::Resource: $@\n";
415 push @$rlim, $r, @$v;
417 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
418 my $pgid = $opts->{pgid} // -1;
419 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd, $pgid);
420 die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
425 my ($cmd, $env, $opt) = @_;
426 pipe(my ($r, $w)) or die "pipe: $!\n";
428 $opt->{1} = fileno($w);
429 my $pid = spawn($cmd, $env, $opt);
430 return ($r, $pid) if wantarray;
432 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
437 my ($cmd, $env, $rdr) = @_;
438 my $pid = spawn($cmd, $env, $rdr);
439 waitpid($pid, 0) == $pid or die "@$cmd did not finish";
440 $? == 0 or die "@$cmd failed: \$?=$?\n";