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 $vfork_spawn = <<'VFORK_SPAWN';
26 #include <sys/types.h>
28 #include <sys/resource.h>
33 /* some platforms need alloca.h, but some don't */
34 #if defined(__GNUC__) && !defined(alloca)
35 # define alloca(sz) __builtin_alloca(sz)
42 * From the av_len apidoc:
43 * Note that, unlike what the name implies, it returns
44 * the highest index in the array, so to get the size of
45 * the array you need to use "av_len(av) + 1".
46 * This is unlike "sv_len", which returns what you would expect.
48 #define AV2C_COPY(dst, src) do { \
50 I32 top_index = av_len(src); \
51 I32 real_len = top_index + 1; \
52 I32 capa = real_len + 1; \
53 dst = alloca(capa * sizeof(char *)); \
54 for (i = 0; i < real_len; i++) { \
55 SV **sv = av_fetch(src, i, 0); \
56 dst[i] = SvPV_nolen(*sv); \
61 /* needs to be safe inside a vfork'ed process */
62 static void exit_err(int *cerrnum)
69 * unstable internal API. It'll be updated depending on
70 * whatever we'll need in the future.
71 * Be sure to update PublicInbox::SpawnPP if this changes
73 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
76 AV *redir = (AV *)SvRV(redirref);
77 AV *cmd = (AV *)SvRV(cmdref);
78 AV *env = (AV *)SvRV(envref);
79 AV *rlim = (AV *)SvRV(rlimref);
80 const char *filename = SvPV_nolen(file);
83 sigset_t set, old, cset;
84 int ret, perrnum, cerrnum = 0;
89 ret = sigfillset(&set);
90 assert(ret == 0 && "BUG calling sigfillset");
91 ret = sigprocmask(SIG_SETMASK, &set, &old);
92 assert(ret == 0 && "BUG calling sigprocmask to block");
93 ret = sigemptyset(&cset);
94 assert(ret == 0 && "BUG calling sigemptyset");
95 ret = sigaddset(&cset, SIGCHLD);
96 assert(ret == 0 && "BUG calling sigaddset for SIGCHLD");
100 I32 i, child_fd, max = av_len(redir);
102 for (child_fd = 0; child_fd <= max; child_fd++) {
103 SV **parent = av_fetch(redir, child_fd, 0);
104 int parent_fd = SvIV(*parent);
105 if (parent_fd == child_fd)
107 if (dup2(parent_fd, child_fd) < 0)
110 for (sig = 1; sig < NSIG; sig++)
111 signal(sig, SIG_DFL); /* ignore errors on signals */
112 if (*cd && chdir(cd) < 0)
116 for (i = 0; i < max; i += 3) {
118 SV **res = av_fetch(rlim, i, 0);
119 SV **soft = av_fetch(rlim, i + 1, 0);
120 SV **hard = av_fetch(rlim, i + 2, 0);
122 rl.rlim_cur = SvIV(*soft);
123 rl.rlim_max = SvIV(*hard);
124 if (setrlimit(SvIV(*res), &rl) < 0)
129 * don't bother unblocking other signals for now, just SIGCHLD.
130 * we don't want signals to the group taking out a subprocess
132 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
133 execve(filename, argv, envp);
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) {
151 # btrfs on Linux is copy-on-write (COW) by default. As of Linux 5.7,
152 # this still leads to fragmentation for SQLite and Xapian files where
153 # random I/O happens, so we disable COW just for SQLite files and Xapian
154 # directories. Disabling COW disables checksumming, so we only do this
155 # for regeneratable files, and not canonical git storage (git doesn't
156 # checksum refs, only data under $GIT_DIR/objects).
157 my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
158 #include <sys/ioctl.h>
160 #include <linux/magic.h>
161 #include <linux/fs.h>
167 void nodatacow_fd(int fd)
172 if (fstatfs(fd, &buf) < 0) {
173 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
177 /* only btrfs is known to have this problem, so skip for non-btrfs */
178 if (buf.f_type != BTRFS_SUPER_MAGIC)
181 if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
182 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
186 if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
187 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
190 void nodatacow_dir(const char *dir)
192 DIR *dh = opendir(dir);
195 if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
199 /* ENOTSUP probably won't happen under Linux... */
204 my $fdpass = <<'FDPASS';
205 #include <sys/types.h>
207 #include <sys/socket.h>
209 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
210 struct my_3fds { int fds[3]; };
213 char pad[sizeof(struct cmsghdr)+ 8 + sizeof(struct my_3fds) + 8];
216 int send_3fds(int sockfd, int infd, int outfd, int errfd)
218 struct msghdr msg = { 0 };
220 union my_cmsg cmsg = { 0 };
224 iov.iov_base = &msg.msg_namelen; /* whatever */
228 msg.msg_control = &cmsg.hdr;
229 msg.msg_controllen = CMSG_SPACE(sizeof(struct my_3fds));
231 cmsg.hdr.cmsg_level = SOL_SOCKET;
232 cmsg.hdr.cmsg_type = SCM_RIGHTS;
233 cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(struct my_3fds));
234 fdp = (int *)CMSG_DATA(&cmsg.hdr);
238 return sendmsg(sockfd, &msg, 0) >= 0;
241 void recv_3fds(int sockfd)
243 union my_cmsg cmsg = { 0 };
244 struct msghdr msg = { 0 };
249 iov.iov_base = &msg.msg_namelen; /* whatever */
253 msg.msg_control = &cmsg.hdr;
254 msg.msg_controllen = CMSG_SPACE(sizeof(struct my_3fds));
256 if (recvmsg(sockfd, &msg, 0) <= 0)
261 if (cmsg.hdr.cmsg_level == SOL_SOCKET &&
262 cmsg.hdr.cmsg_type == SCM_RIGHTS &&
263 cmsg.hdr.cmsg_len == CMSG_LEN(sizeof(struct my_3fds))) {
264 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
267 for (i = 0; i < 3; i++)
268 Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
272 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
275 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
276 $ENV{XDG_CACHE_HOME} //
277 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
278 ).'/public-inbox/inline-c';
280 $set_nodatacow = $vfork_spawn = $fdpass = undef unless -d $inline_dir && -w _;
281 if (defined $vfork_spawn) {
282 # Inline 0.64 or later has locking in multi-process env,
283 # but we support 0.5 on Debian wheezy
284 use Fcntl qw(:flock);
286 my $f = "$inline_dir/.public-inbox.lock";
287 open my $fh, '>', $f or die "failed to open $f: $!\n";
288 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
289 eval 'use Inline C => $vfork_spawn.$fdpass.$set_nodatacow';
290 # . ', BUILD_NOISY => 1';
293 if ($err && $set_nodatacow) { # missing Linux kernel headers
295 undef $set_nodatacow;
296 eval 'use Inline C => $vfork_spawn . $fdpass';
298 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
300 warn $ndc_err if $ndc_err;
303 warn "Inline::C failed for vfork: $@\n";
304 $set_nodatacow = $vfork_spawn = $fdpass = undef;
308 unless (defined $vfork_spawn) {
309 require PublicInbox::SpawnPP;
310 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
312 unless ($set_nodatacow) {
313 require PublicInbox::NDC_PP;
315 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
316 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
319 undef $set_nodatacow;
325 return $file if index($file, '/') >= 0;
326 foreach my $p (split(':', $ENV{PATH})) {
334 my ($cmd, $env, $opts) = @_;
335 my $f = which($cmd->[0]);
336 defined $f or die "$cmd->[0]: command not found\n";
340 my %env = $env ? (%ENV, %$env) : %ENV;
341 while (my ($k, $v) = each %env) {
345 for my $child_fd (0..2) {
346 my $parent_fd = $opts->{$child_fd};
347 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
348 defined(my $fd = fileno($parent_fd)) or
349 die "$parent_fd not an IO GLOB? $!";
352 $redir->[$child_fd] = $parent_fd // $child_fd;
356 foreach my $l (@RLIMITS) {
357 defined(my $v = $opts->{$l}) or next;
358 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
359 unless (defined $r) {
360 warn "$l undefined by BSD::Resource: $@\n";
363 push @$rlim, $r, @$v;
365 my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
366 my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
367 die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
372 my ($cmd, $env, $opt) = @_;
373 pipe(my ($r, $w)) or die "pipe: $!\n";
375 $opt->{1} = fileno($w);
376 my $pid = spawn($cmd, $env, $opt);
377 return ($r, $pid) if wantarray;
379 tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
384 my ($cmd, $env, $rdr) = @_;
385 my $pid = spawn($cmd, $env, $rdr);
386 waitpid($pid, 0) == $pid or die "@$cmd did not finish";
387 $? == 0 or die "@$cmd failed: \$?=$?\n";