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(int *cerrnum)
71 * unstable internal API. It'll be updated depending on
72 * whatever we'll need in the future.
73 * Be sure to update PublicInbox::SpawnPP if this changes
75 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
78 AV *redir = (AV *)SvRV(redirref);
79 AV *cmd = (AV *)SvRV(cmdref);
80 AV *env = (AV *)SvRV(envref);
81 AV *rlim = (AV *)SvRV(rlimref);
82 const char *filename = SvPV_nolen(file);
86 int ret, perrnum, cerrnum = 0;
92 if (sigfillset(&set)) return -1;
93 if (sigprocmask(SIG_SETMASK, &set, &old)) return -1;
94 chld_is_member = sigismember(&old, SIGCHLD);
95 if (chld_is_member < 0) return -1;
96 if (chld_is_member > 0)
97 sigdelset(&old, SIGCHLD);
102 I32 i, child_fd, max = av_len(redir);
104 for (child_fd = 0; child_fd <= max; child_fd++) {
105 SV **parent = av_fetch(redir, child_fd, 0);
106 int parent_fd = SvIV(*parent);
107 if (parent_fd == child_fd)
109 if (dup2(parent_fd, child_fd) < 0)
112 for (sig = 1; sig < NSIG; sig++)
113 signal(sig, SIG_DFL); /* ignore errors on signals */
114 if (*cd && chdir(cd) < 0)
118 for (i = 0; i < max; i += 3) {
120 SV **res = av_fetch(rlim, i, 0);
121 SV **soft = av_fetch(rlim, i + 1, 0);
122 SV **hard = av_fetch(rlim, i + 2, 0);
124 rl.rlim_cur = SvIV(*soft);
125 rl.rlim_max = SvIV(*hard);
126 if (setrlimit(SvIV(*res), &rl) < 0)
130 (void)sigprocmask(SIG_SETMASK, &old, NULL);
131 execve(filename, argv, envp);
135 if (chld_is_member > 0)
136 sigaddset(&old, SIGCHLD);
137 ret = sigprocmask(SIG_SETMASK, &old, NULL);
138 assert(ret == 0 && "BUG calling sigprocmask to restore");
141 waitpid(pid, NULL, 0);
144 } else if (perrnum) {
150 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
151 #define SEND_FD_CAPA 10
152 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
155 char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
158 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
160 struct msghdr msg = { 0 };
161 union my_cmsg cmsg = { 0 };
165 AV *fds = (AV *)SvRV(svfds);
166 I32 i, nfds = av_len(fds) + 1;
170 iov.iov_base = SvPV(data, dlen);
173 if (!dlen) { /* must be non-zero */
174 iov.iov_base = &msg.msg_namelen; /* whatever */
180 if (nfds > SEND_FD_CAPA) {
181 fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
184 msg.msg_control = &cmsg.hdr;
185 msg.msg_controllen = CMSG_SPACE(nfds * sizeof(int));
186 cmsg.hdr.cmsg_level = SOL_SOCKET;
187 cmsg.hdr.cmsg_type = SCM_RIGHTS;
188 cmsg.hdr.cmsg_len = CMSG_LEN(nfds * sizeof(int));
189 fdp = (int *)CMSG_DATA(&cmsg.hdr);
190 for (i = 0; i < nfds; i++) {
191 SV **fd = av_fetch(fds, i, 0);
195 sent = sendmsg(PerlIO_fileno(s), &msg, flags);
196 return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
199 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
201 union my_cmsg cmsg = { 0 };
202 struct msghdr msg = { 0 };
209 sv_setpvn(buf, "", 0);
210 iov.iov_base = SvGROW(buf, n + 1);
214 msg.msg_control = &cmsg.hdr;
215 msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
217 i = recvmsg(PerlIO_fileno(s), &msg, 0);
219 Inline_Stack_Push(&PL_sv_undef);
222 if (i > 0 && cmsg.hdr.cmsg_level == SOL_SOCKET &&
223 cmsg.hdr.cmsg_type == SCM_RIGHTS) {
224 size_t len = cmsg.hdr.cmsg_len;
225 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
226 for (i = 0; CMSG_LEN((i + 1) * sizeof(int)) <= len; i++)
227 Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
231 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
234 # btrfs on Linux is copy-on-write (COW) by default. As of Linux 5.7,
235 # this still leads to fragmentation for SQLite and Xapian files where
236 # random I/O happens, so we disable COW just for SQLite files and Xapian
237 # directories. Disabling COW disables checksumming, so we only do this
238 # for regeneratable files, and not canonical git storage (git doesn't
239 # checksum refs, only data under $GIT_DIR/objects).
240 my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
241 #include <sys/ioctl.h>
243 #include <linux/magic.h>
244 #include <linux/fs.h>
250 void nodatacow_fd(int fd)
255 if (fstatfs(fd, &buf) < 0) {
256 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
260 /* only btrfs is known to have this problem, so skip for non-btrfs */
261 if (buf.f_type != BTRFS_SUPER_MAGIC)
264 if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
265 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
269 if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
270 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
273 void nodatacow_dir(const char *dir)
275 DIR *dh = opendir(dir);
278 if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
282 /* ENOTSUP probably won't happen under Linux... */
287 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
288 $ENV{XDG_CACHE_HOME} //
289 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
290 ).'/public-inbox/inline-c';
292 $set_nodatacow = $all_libc = undef unless -d $inline_dir && -w _;
293 if (defined $all_libc) {
294 # Inline 0.64 or later has locking in multi-process env,
295 # but we support 0.5 on Debian wheezy
296 use Fcntl qw(:flock);
298 my $f = "$inline_dir/.public-inbox.lock";
299 open my $fh, '>', $f or die "failed to open $f: $!\n";
300 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
301 eval 'use Inline C => $all_libc.$set_nodatacow';
302 # . ', BUILD_NOISY => 1';
305 if ($err && $set_nodatacow) { # missing Linux kernel headers
307 undef $set_nodatacow;
308 eval 'use Inline C => $all_libc';
310 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
312 warn $ndc_err if $ndc_err;
315 warn "Inline::C failed for vfork: $@\n";
316 $set_nodatacow = $all_libc = undef;
321 require PublicInbox::SpawnPP;
322 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
324 unless ($set_nodatacow) {
325 require PublicInbox::NDC_PP;
327 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
328 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
331 undef $set_nodatacow;
336 return $file if index($file, '/') >= 0;
337 for my $p (split(/:/, $ENV{PATH})) {
345 my ($cmd, $env, $opts) = @_;
346 my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
350 my %env = $env ? (%ENV, %$env) : %ENV;
351 while (my ($k, $v) = each %env) {
355 for my $child_fd (0..2) {
356 my $parent_fd = $opts->{$child_fd};
357 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
358 my $fd = fileno($parent_fd) //
359 die "$parent_fd not an IO GLOB? $!";
362 $redir->[$child_fd] = $parent_fd // $child_fd;
366 foreach my $l (@RLIMITS) {
367 my $v = $opts->{$l} // next;
368 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
369 unless (defined $r) {
370 warn "$l undefined by BSD::Resource: $@\n";
373 push @$rlim, $r, @$v;
375 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
376 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
377 die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
382 my ($cmd, $env, $opt) = @_;
383 pipe(my ($r, $w)) or die "pipe: $!\n";
385 $opt->{1} = fileno($w);
386 my $pid = spawn($cmd, $env, $opt);
387 return ($r, $pid) if wantarray;
389 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
394 my ($cmd, $env, $rdr) = @_;
395 my $pid = spawn($cmd, $env, $rdr);
396 waitpid($pid, 0) == $pid or die "@$cmd did not finish";
397 $? == 0 or die "@$cmd failed: \$?=$?\n";