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);
85 sigset_t set, old, cset;
86 int ret, perrnum, cerrnum = 0;
91 ret = sigfillset(&set);
92 assert(ret == 0 && "BUG calling sigfillset");
93 ret = sigprocmask(SIG_SETMASK, &set, &old);
94 assert(ret == 0 && "BUG calling sigprocmask to block");
95 ret = sigemptyset(&cset);
96 assert(ret == 0 && "BUG calling sigemptyset");
97 ret = sigaddset(&cset, SIGCHLD);
98 assert(ret == 0 && "BUG calling sigaddset for 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)
131 * don't bother unblocking other signals for now, just SIGCHLD.
132 * we don't want signals to the group taking out a subprocess
134 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
135 execve(filename, argv, envp);
139 ret = sigprocmask(SIG_SETMASK, &old, NULL);
140 assert(ret == 0 && "BUG calling sigprocmask to restore");
143 waitpid(pid, NULL, 0);
146 } else if (perrnum) {
152 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
153 #define SEND_FD_CAPA 10
154 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
157 char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
160 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
162 struct msghdr msg = { 0 };
163 union my_cmsg cmsg = { 0 };
167 AV *fds = (AV *)SvRV(svfds);
168 I32 i, nfds = av_len(fds) + 1;
172 iov.iov_base = SvPV(data, dlen);
175 if (!dlen) { /* must be non-zero */
176 iov.iov_base = &msg.msg_namelen; /* whatever */
182 if (nfds > SEND_FD_CAPA) {
183 fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
186 msg.msg_control = &cmsg.hdr;
187 msg.msg_controllen = CMSG_SPACE(nfds * sizeof(int));
188 cmsg.hdr.cmsg_level = SOL_SOCKET;
189 cmsg.hdr.cmsg_type = SCM_RIGHTS;
190 cmsg.hdr.cmsg_len = CMSG_LEN(nfds * sizeof(int));
191 fdp = (int *)CMSG_DATA(&cmsg.hdr);
192 for (i = 0; i < nfds; i++) {
193 SV **fd = av_fetch(fds, i, 0);
197 sent = sendmsg(PerlIO_fileno(s), &msg, flags);
198 return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
201 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
203 union my_cmsg cmsg = { 0 };
204 struct msghdr msg = { 0 };
211 sv_setpvn(buf, "", 0);
212 iov.iov_base = SvGROW(buf, n + 1);
216 msg.msg_control = &cmsg.hdr;
217 msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
219 i = recvmsg(PerlIO_fileno(s), &msg, 0);
221 Inline_Stack_Push(&PL_sv_undef);
224 if (i > 0 && cmsg.hdr.cmsg_level == SOL_SOCKET &&
225 cmsg.hdr.cmsg_type == SCM_RIGHTS) {
226 size_t len = cmsg.hdr.cmsg_len;
227 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
228 for (i = 0; CMSG_LEN((i + 1) * sizeof(int)) <= len; i++)
229 Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
233 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
236 # btrfs on Linux is copy-on-write (COW) by default. As of Linux 5.7,
237 # this still leads to fragmentation for SQLite and Xapian files where
238 # random I/O happens, so we disable COW just for SQLite files and Xapian
239 # directories. Disabling COW disables checksumming, so we only do this
240 # for regeneratable files, and not canonical git storage (git doesn't
241 # checksum refs, only data under $GIT_DIR/objects).
242 my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
243 #include <sys/ioctl.h>
245 #include <linux/magic.h>
246 #include <linux/fs.h>
252 void nodatacow_fd(int fd)
257 if (fstatfs(fd, &buf) < 0) {
258 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
262 /* only btrfs is known to have this problem, so skip for non-btrfs */
263 if (buf.f_type != BTRFS_SUPER_MAGIC)
266 if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
267 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
271 if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
272 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
275 void nodatacow_dir(const char *dir)
277 DIR *dh = opendir(dir);
280 if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
284 /* ENOTSUP probably won't happen under Linux... */
289 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
290 $ENV{XDG_CACHE_HOME} //
291 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
292 ).'/public-inbox/inline-c';
294 $set_nodatacow = $all_libc = undef unless -d $inline_dir && -w _;
295 if (defined $all_libc) {
296 # Inline 0.64 or later has locking in multi-process env,
297 # but we support 0.5 on Debian wheezy
298 use Fcntl qw(:flock);
300 my $f = "$inline_dir/.public-inbox.lock";
301 open my $fh, '>', $f or die "failed to open $f: $!\n";
302 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
303 eval 'use Inline C => $all_libc.$set_nodatacow';
304 # . ', BUILD_NOISY => 1';
307 if ($err && $set_nodatacow) { # missing Linux kernel headers
309 undef $set_nodatacow;
310 eval 'use Inline C => $all_libc';
312 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
314 warn $ndc_err if $ndc_err;
317 warn "Inline::C failed for vfork: $@\n";
318 $set_nodatacow = $all_libc = undef;
323 require PublicInbox::SpawnPP;
324 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
326 unless ($set_nodatacow) {
327 require PublicInbox::NDC_PP;
329 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
330 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
333 undef $set_nodatacow;
338 return $file if index($file, '/') >= 0;
339 for my $p (split(/:/, $ENV{PATH})) {
347 my ($cmd, $env, $opts) = @_;
348 my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
352 my %env = $env ? (%ENV, %$env) : %ENV;
353 while (my ($k, $v) = each %env) {
357 for my $child_fd (0..2) {
358 my $parent_fd = $opts->{$child_fd};
359 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
360 my $fd = fileno($parent_fd) //
361 die "$parent_fd not an IO GLOB? $!";
364 $redir->[$child_fd] = $parent_fd // $child_fd;
368 foreach my $l (@RLIMITS) {
369 my $v = $opts->{$l} // next;
370 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
371 unless (defined $r) {
372 warn "$l undefined by BSD::Resource: $@\n";
375 push @$rlim, $r, @$v;
377 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
378 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
379 die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
384 my ($cmd, $env, $opt) = @_;
385 pipe(my ($r, $w)) or die "pipe: $!\n";
387 $opt->{1} = fileno($w);
388 my $pid = spawn($cmd, $env, $opt);
389 return ($r, $pid) if wantarray;
391 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
396 my ($cmd, $env, $rdr) = @_;
397 my $pid = spawn($cmd, $env, $rdr);
398 waitpid($pid, 0) == $pid or die "@$cmd did not finish";
399 $? == 0 or die "@$cmd failed: \$?=$?\n";