]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
e940d3c9d7f44710e86b8b1118f921cf8cea562e
[public-inbox.git] / lib / PublicInbox / Spawn.pm
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>
3 #
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
12 # Perl routines.
13 #
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
16
17 package PublicInbox::Spawn;
18 use strict;
19 use parent qw(Exporter);
20 use Symbol qw(gensym);
21 use Fcntl qw(LOCK_EX SEEK_SET);
22 use IO::Handle ();
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);
26
27 BEGIN {
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>
32 #include <sys/time.h>
33 #include <sys/uio.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <errno.h>
37
38 /* some platforms need alloca.h, but some don't */
39 #if defined(__GNUC__) && !defined(alloca)
40 #  define alloca(sz) __builtin_alloca(sz)
41 #endif
42
43 #include <signal.h>
44 #include <assert.h>
45
46 /*
47  * From the av_len apidoc:
48  *   Note that, unlike what the name implies, it returns
49  *   the highest index in the array, so to get the size of
50  *   the array you need to use "av_len(av) + 1".
51  *   This is unlike "sv_len", which returns what you would expect.
52  */
53 #define AV2C_COPY(dst, src) do { \
54         I32 i; \
55         I32 top_index = av_len(src); \
56         I32 real_len = top_index + 1; \
57         I32 capa = real_len + 1; \
58         dst = alloca(capa * sizeof(char *)); \
59         for (i = 0; i < real_len; i++) { \
60                 SV **sv = av_fetch(src, i, 0); \
61                 dst[i] = SvPV_nolen(*sv); \
62         } \
63         dst[real_len] = 0; \
64 } while (0)
65
66 /* needs to be safe inside a vfork'ed process */
67 static void exit_err(const char *fn, volatile int *cerrnum)
68 {
69         *cerrnum = errno;
70         write(2, fn, strlen(fn));
71         _exit(1);
72 }
73
74 /*
75  * unstable internal API.  It'll be updated depending on
76  * whatever we'll need in the future.
77  * Be sure to update PublicInbox::SpawnPP if this changes
78  */
79 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
80                  const char *cd, int pgid)
81 {
82         AV *redir = (AV *)SvRV(redirref);
83         AV *cmd = (AV *)SvRV(cmdref);
84         AV *env = (AV *)SvRV(envref);
85         AV *rlim = (AV *)SvRV(rlimref);
86         const char *filename = SvPV_nolen(file);
87         pid_t pid;
88         char **argv, **envp;
89         sigset_t set, old;
90         int ret, perrnum;
91         volatile int cerrnum = 0; /* shared due to vfork */
92         int chld_is_member;
93         I32 max_fd = av_len(redir);
94
95         AV2C_COPY(argv, cmd);
96         AV2C_COPY(envp, env);
97
98         if (sigfillset(&set)) return -1;
99         if (sigprocmask(SIG_SETMASK, &set, &old)) return -1;
100         chld_is_member = sigismember(&old, SIGCHLD);
101         if (chld_is_member < 0) return -1;
102         if (chld_is_member > 0)
103                 sigdelset(&old, SIGCHLD);
104
105         pid = vfork();
106         if (pid == 0) {
107                 int sig;
108                 I32 i, child_fd, max_rlim;
109
110                 for (child_fd = 0; child_fd <= max_fd; child_fd++) {
111                         SV **parent = av_fetch(redir, child_fd, 0);
112                         int parent_fd = SvIV(*parent);
113                         if (parent_fd == child_fd)
114                                 continue;
115                         if (dup2(parent_fd, child_fd) < 0)
116                                 exit_err("dup2", &cerrnum);
117                 }
118                 if (pgid >= 0 && setpgid(0, pgid) < 0)
119                         exit_err("setpgid", &cerrnum);
120                 for (sig = 1; sig < NSIG; sig++)
121                         signal(sig, SIG_DFL); /* ignore errors on signals */
122                 if (*cd && chdir(cd) < 0)
123                         exit_err("chdir", &cerrnum);
124
125                 max_rlim = av_len(rlim);
126                 for (i = 0; i < max_rlim; i += 3) {
127                         struct rlimit rl;
128                         SV **res = av_fetch(rlim, i, 0);
129                         SV **soft = av_fetch(rlim, i + 1, 0);
130                         SV **hard = av_fetch(rlim, i + 2, 0);
131
132                         rl.rlim_cur = SvIV(*soft);
133                         rl.rlim_max = SvIV(*hard);
134                         if (setrlimit(SvIV(*res), &rl) < 0)
135                                 exit_err("setrlimit", &cerrnum);
136                 }
137
138                 (void)sigprocmask(SIG_SETMASK, &old, NULL);
139                 execve(filename, argv, envp);
140                 exit_err("execve", &cerrnum);
141         }
142         perrnum = errno;
143         if (chld_is_member > 0)
144                 sigaddset(&old, SIGCHLD);
145         ret = sigprocmask(SIG_SETMASK, &old, NULL);
146         assert(ret == 0 && "BUG calling sigprocmask to restore");
147         if (cerrnum) {
148                 int err_fd = STDERR_FILENO;
149                 if (err_fd <= max_fd) {
150                         SV **parent = av_fetch(redir, err_fd, 0);
151                         err_fd = SvIV(*parent);
152                 }
153                 if (pid > 0)
154                         waitpid(pid, NULL, 0);
155                 pid = -1;
156                 /* continue message started by exit_err in child */
157                 dprintf(err_fd, ": %s\n", strerror(cerrnum));
158                 errno = cerrnum;
159         } else if (perrnum) {
160                 errno = perrnum;
161         }
162         return (int)pid;
163 }
164
165 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
166 #define SEND_FD_CAPA 10
167 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
168 union my_cmsg {
169         struct cmsghdr hdr;
170         char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
171 };
172
173 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
174 {
175         struct msghdr msg = { 0 };
176         union my_cmsg cmsg = { 0 };
177         STRLEN dlen = 0;
178         struct iovec iov;
179         ssize_t sent;
180         AV *fds = (AV *)SvRV(svfds);
181         I32 i, nfds = av_len(fds) + 1;
182         int *fdp;
183
184         if (SvOK(data)) {
185                 iov.iov_base = SvPV(data, dlen);
186                 iov.iov_len = dlen;
187         }
188         if (!dlen) { /* must be non-zero */
189                 iov.iov_base = &msg.msg_namelen; /* whatever */
190                 iov.iov_len = 1;
191         }
192         msg.msg_iov = &iov;
193         msg.msg_iovlen = 1;
194         if (nfds) {
195                 if (nfds > SEND_FD_CAPA) {
196                         fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
197                         nfds = SEND_FD_CAPA;
198                 }
199                 msg.msg_control = &cmsg.hdr;
200                 msg.msg_controllen = CMSG_SPACE(nfds * sizeof(int));
201                 cmsg.hdr.cmsg_level = SOL_SOCKET;
202                 cmsg.hdr.cmsg_type = SCM_RIGHTS;
203                 cmsg.hdr.cmsg_len = CMSG_LEN(nfds * sizeof(int));
204                 fdp = (int *)CMSG_DATA(&cmsg.hdr);
205                 for (i = 0; i < nfds; i++) {
206                         SV **fd = av_fetch(fds, i, 0);
207                         *fdp++ = SvIV(*fd);
208                 }
209         }
210         sent = sendmsg(PerlIO_fileno(s), &msg, flags);
211         return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
212 }
213
214 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
215 {
216         union my_cmsg cmsg = { 0 };
217         struct msghdr msg = { 0 };
218         struct iovec iov;
219         ssize_t i;
220         Inline_Stack_Vars;
221         Inline_Stack_Reset;
222
223         if (!SvOK(buf))
224                 sv_setpvn(buf, "", 0);
225         iov.iov_base = SvGROW(buf, n + 1);
226         iov.iov_len = n;
227         msg.msg_iov = &iov;
228         msg.msg_iovlen = 1;
229         msg.msg_control = &cmsg.hdr;
230         msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
231
232         i = recvmsg(PerlIO_fileno(s), &msg, 0);
233         if (i < 0)
234                 Inline_Stack_Push(&PL_sv_undef);
235         else
236                 SvCUR_set(buf, i);
237         if (i > 0 && cmsg.hdr.cmsg_level == SOL_SOCKET &&
238                         cmsg.hdr.cmsg_type == SCM_RIGHTS) {
239                 size_t len = cmsg.hdr.cmsg_len;
240                 int *fdp = (int *)CMSG_DATA(&cmsg.hdr);
241                 for (i = 0; CMSG_LEN((i + 1) * sizeof(int)) <= len; i++)
242                         Inline_Stack_Push(sv_2mortal(newSViv(*fdp++)));
243         }
244         Inline_Stack_Done;
245 }
246 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
247 ALL_LIBC
248
249 # btrfs on Linux is copy-on-write (COW) by default.  As of Linux 5.7,
250 # this still leads to fragmentation for SQLite and Xapian files where
251 # random I/O happens, so we disable COW just for SQLite files and Xapian
252 # directories.  Disabling COW disables checksumming, so we only do this
253 # for regeneratable files, and not canonical git storage (git doesn't
254 # checksum refs, only data under $GIT_DIR/objects).
255         my $set_nodatacow = $^O eq 'linux' ? <<'SET_NODATACOW' : '';
256 #include <sys/ioctl.h>
257 #include <sys/vfs.h>
258 #include <linux/magic.h>
259 #include <linux/fs.h>
260 #include <dirent.h>
261 #include <errno.h>
262 #include <stdio.h>
263 #include <string.h>
264
265 void nodatacow_fd(int fd)
266 {
267         struct statfs buf;
268         int val = 0;
269
270         if (fstatfs(fd, &buf) < 0) {
271                 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
272                 return;
273         }
274
275         /* only btrfs is known to have this problem, so skip for non-btrfs */
276         if (buf.f_type != BTRFS_SUPER_MAGIC)
277                 return;
278
279         if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
280                 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
281                 return;
282         }
283         val |= FS_NOCOW_FL;
284         if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
285                 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
286 }
287
288 void nodatacow_dir(const char *dir)
289 {
290         DIR *dh = opendir(dir);
291         int fd;
292
293         if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
294         fd = dirfd(dh);
295         if (fd >= 0)
296                 nodatacow_fd(fd);
297         /* ENOTSUP probably won't happen under Linux... */
298         closedir(dh);
299 }
300 SET_NODATACOW
301
302         my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
303                         $ENV{XDG_CACHE_HOME} //
304                         ( ($ENV{HOME} // '/nonexistent').'/.cache' )
305                 ).'/public-inbox/inline-c';
306         warn "$inline_dir exists, not writable\n" if -e $inline_dir && !-w _;
307         $set_nodatacow = $all_libc = undef unless -d _ && -w _;
308         if (defined $all_libc) {
309                 my $f = "$inline_dir/.public-inbox.lock";
310                 open my $oldout, '>&', \*STDOUT or die "dup(1): $!";
311                 open my $olderr, '>&', \*STDERR or die "dup(2): $!";
312                 open my $fh, '+>', $f or die "open($f): $!";
313                 open STDOUT, '>&', $fh or die "1>$f: $!";
314                 open STDERR, '>&', $fh or die "2>$f: $!";
315                 STDERR->autoflush(1);
316                 STDOUT->autoflush(1);
317
318                 # CentOS 7.x ships Inline 0.53, 0.64+ has built-in locking
319                 flock($fh, LOCK_EX) or die "LOCK_EX($f): $!";
320                 eval <<'EOM';
321 use Inline C => $all_libc.$set_nodatacow, BUILD_NOISY => 1;
322 EOM
323                 my $err = $@;
324                 my $ndc_err = '';
325                 if ($err && $set_nodatacow) { # missing Linux kernel headers
326                         $ndc_err = "with set_nodatacow: <\n$err\n>\n";
327                         undef $set_nodatacow;
328                         eval <<'EOM';
329 use Inline C => $all_libc, BUILD_NOISY => 1;
330 EOM
331                 };
332                 $err = $@;
333                 open(STDERR, '>&', $olderr) or warn "restore stderr: $!";
334                 open(STDOUT, '>&', $oldout) or warn "restore stdout: $!";
335                 if ($err) {
336                         seek($fh, 0, SEEK_SET);
337                         my @msg = <$fh>;
338                         warn "Inline::C build failed:\n",
339                                 $ndc_err, $err, "\n", @msg;
340                         $set_nodatacow = $all_libc = undef;
341                 } elsif ($ndc_err) {
342                         warn "Inline::C build succeeded w/o set_nodatacow\n",
343                                 "error $ndc_err";
344                 }
345         }
346         unless ($all_libc) {
347                 require PublicInbox::SpawnPP;
348                 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
349         }
350         unless ($set_nodatacow) {
351                 require PublicInbox::NDC_PP;
352                 no warnings 'once';
353                 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
354                 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
355         }
356 } # /BEGIN
357
358 sub which ($) {
359         my ($file) = @_;
360         return $file if index($file, '/') >= 0;
361         for my $p (split(/:/, $ENV{PATH})) {
362                 $p .= "/$file";
363                 return $p if -x $p;
364         }
365         undef;
366 }
367
368 sub spawn ($;$$) {
369         my ($cmd, $env, $opts) = @_;
370         my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
371         my @env;
372         $opts ||= {};
373         my %env = (%ENV, $env ? %$env : ());
374         while (my ($k, $v) = each %env) {
375                 push @env, "$k=$v" if defined($v);
376         }
377         my $redir = [];
378         for my $child_fd (0..2) {
379                 my $parent_fd = $opts->{$child_fd};
380                 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
381                         my $fd = fileno($parent_fd) //
382                                         die "$parent_fd not an IO GLOB? $!";
383                         $parent_fd = $fd;
384                 }
385                 $redir->[$child_fd] = $parent_fd // $child_fd;
386         }
387         my $rlim = [];
388
389         foreach my $l (@RLIMITS) {
390                 my $v = $opts->{$l} // next;
391                 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
392                 unless (defined $r) {
393                         warn "$l undefined by BSD::Resource: $@\n";
394                         next;
395                 }
396                 push @$rlim, $r, @$v;
397         }
398         my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
399         my $pgid = $opts->{pgid} // -1;
400         my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd, $pgid);
401         die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
402         $pid;
403 }
404
405 sub popen_rd {
406         my ($cmd, $env, $opt) = @_;
407         pipe(my ($r, $w)) or die "pipe: $!\n";
408         $opt ||= {};
409         $opt->{1} = fileno($w);
410         my $pid = spawn($cmd, $env, $opt);
411         return ($r, $pid) if wantarray;
412         my $ret = gensym;
413         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
414         $ret;
415 }
416
417 sub run_die ($;$$) {
418         my ($cmd, $env, $rdr) = @_;
419         my $pid = spawn($cmd, $env, $rdr);
420         waitpid($pid, 0) == $pid or die "@$cmd did not finish";
421         $? == 0 or die "@$cmd failed: \$?=$?\n";
422 }
423
424 1;