]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
spawn: avoid C++ keyword `try'
[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 #include <time.h>
38 #include <stdio.h>
39 #include <string.h>
40
41 /* some platforms need alloca.h, but some don't */
42 #if defined(__GNUC__) && !defined(alloca)
43 #  define alloca(sz) __builtin_alloca(sz)
44 #endif
45
46 #include <signal.h>
47 #include <assert.h>
48
49 /*
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.
55  */
56 #define AV2C_COPY(dst, src) do { \
57         I32 i; \
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); \
65         } \
66         dst[real_len] = 0; \
67 } while (0)
68
69 /* needs to be safe inside a vfork'ed process */
70 static void exit_err(const char *fn, volatile int *cerrnum)
71 {
72         *cerrnum = errno;
73         write(2, fn, strlen(fn));
74         _exit(1);
75 }
76
77 /*
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
81  */
82 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
83                  const char *cd, int pgid)
84 {
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);
90         pid_t pid;
91         char **argv, **envp;
92         sigset_t set, old;
93         int ret, perrnum;
94         volatile int cerrnum = 0; /* shared due to vfork */
95         int chld_is_member;
96         I32 max_fd = av_len(redir);
97
98         AV2C_COPY(argv, cmd);
99         AV2C_COPY(envp, env);
100
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);
107
108         pid = vfork();
109         if (pid == 0) {
110                 int sig;
111                 I32 i, child_fd, max_rlim;
112
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)
117                                 continue;
118                         if (dup2(parent_fd, child_fd) < 0)
119                                 exit_err("dup2", &cerrnum);
120                 }
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);
127
128                 max_rlim = av_len(rlim);
129                 for (i = 0; i < max_rlim; i += 3) {
130                         struct rlimit rl;
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);
134
135                         rl.rlim_cur = SvIV(*soft);
136                         rl.rlim_max = SvIV(*hard);
137                         if (setrlimit(SvIV(*res), &rl) < 0)
138                                 exit_err("setrlimit", &cerrnum);
139                 }
140
141                 (void)sigprocmask(SIG_SETMASK, &old, NULL);
142                 execve(filename, argv, envp);
143                 exit_err("execve", &cerrnum);
144         }
145         perrnum = errno;
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");
150         if (cerrnum) {
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);
155                 }
156                 if (pid > 0)
157                         waitpid(pid, NULL, 0);
158                 pid = -1;
159                 /* continue message started by exit_err in child */
160                 dprintf(err_fd, ": %s\n", strerror(cerrnum));
161                 errno = cerrnum;
162         } else if (perrnum) {
163                 errno = perrnum;
164         }
165         return (int)pid;
166 }
167
168 static int sleep_wait(unsigned *tries, int err)
169 {
170         const struct timespec req = { 0, 100000000 }; /* 100ms */
171         switch (err) {
172         case ENOBUFS: case ENOMEM: case ETOOMANYREFS:
173                 if (++*tries < 50) {
174                         fprintf(stderr, "sleeping on sendmsg: %s (#%u)\n",
175                                 strerror(err), *tries);
176                         nanosleep(&req, NULL);
177                         return 1;
178                 }
179         default:
180                 return 0;
181         }
182 }
183
184 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
185 #define SEND_FD_CAPA 10
186 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
187 union my_cmsg {
188         struct cmsghdr hdr;
189         char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
190 };
191
192 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
193 {
194         struct msghdr msg = { 0 };
195         union my_cmsg cmsg = { 0 };
196         STRLEN dlen = 0;
197         struct iovec iov;
198         ssize_t sent;
199         AV *fds = (AV *)SvRV(svfds);
200         I32 i, nfds = av_len(fds) + 1;
201         int *fdp;
202         unsigned tries = 0;
203
204         if (SvOK(data)) {
205                 iov.iov_base = SvPV(data, dlen);
206                 iov.iov_len = dlen;
207         }
208         if (!dlen) { /* must be non-zero */
209                 iov.iov_base = &msg.msg_namelen; /* whatever */
210                 iov.iov_len = 1;
211         }
212         msg.msg_iov = &iov;
213         msg.msg_iovlen = 1;
214         if (nfds) {
215                 if (nfds > SEND_FD_CAPA) {
216                         fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
217                         nfds = SEND_FD_CAPA;
218                 }
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);
227                         *fdp++ = SvIV(*fd);
228                 }
229         }
230         do {
231                 sent = sendmsg(PerlIO_fileno(s), &msg, flags);
232         } while (sent < 0 && sleep_wait(&tries, errno));
233         return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
234 }
235
236 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
237 {
238         union my_cmsg cmsg = { 0 };
239         struct msghdr msg = { 0 };
240         struct iovec iov;
241         ssize_t i;
242         Inline_Stack_Vars;
243         Inline_Stack_Reset;
244
245         if (!SvOK(buf))
246                 sv_setpvn(buf, "", 0);
247         iov.iov_base = SvGROW(buf, n + 1);
248         iov.iov_len = n;
249         msg.msg_iov = &iov;
250         msg.msg_iovlen = 1;
251         msg.msg_control = &cmsg.hdr;
252         msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
253
254         i = recvmsg(PerlIO_fileno(s), &msg, 0);
255         if (i < 0)
256                 Inline_Stack_Push(&PL_sv_undef);
257         else
258                 SvCUR_set(buf, i);
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++)));
265         }
266         Inline_Stack_Done;
267 }
268 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
269 ALL_LIBC
270
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>
279 #include <sys/vfs.h>
280 #include <linux/magic.h>
281 #include <linux/fs.h>
282 #include <dirent.h>
283
284 void nodatacow_fd(int fd)
285 {
286         struct statfs buf;
287         int val = 0;
288
289         if (fstatfs(fd, &buf) < 0) {
290                 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
291                 return;
292         }
293
294         /* only btrfs is known to have this problem, so skip for non-btrfs */
295         if (buf.f_type != BTRFS_SUPER_MAGIC)
296                 return;
297
298         if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
299                 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
300                 return;
301         }
302         val |= FS_NOCOW_FL;
303         if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
304                 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
305 }
306
307 void nodatacow_dir(const char *dir)
308 {
309         DIR *dh = opendir(dir);
310         int fd;
311
312         if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
313         fd = dirfd(dh);
314         if (fd >= 0)
315                 nodatacow_fd(fd);
316         /* ENOTSUP probably won't happen under Linux... */
317         closedir(dh);
318 }
319 SET_NODATACOW
320
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);
336
337                 # CentOS 7.x ships Inline 0.53, 0.64+ has built-in locking
338                 flock($fh, LOCK_EX) or die "LOCK_EX($f): $!";
339                 eval <<'EOM';
340 use Inline C => $all_libc.$set_nodatacow, BUILD_NOISY => 1;
341 EOM
342                 my $err = $@;
343                 my $ndc_err = '';
344                 if ($err && $set_nodatacow) { # missing Linux kernel headers
345                         $ndc_err = "with set_nodatacow: <\n$err\n>\n";
346                         undef $set_nodatacow;
347                         eval <<'EOM';
348 use Inline C => $all_libc, BUILD_NOISY => 1;
349 EOM
350                 };
351                 $err = $@;
352                 open(STDERR, '>&', $olderr) or warn "restore stderr: $!";
353                 open(STDOUT, '>&', $oldout) or warn "restore stdout: $!";
354                 if ($err) {
355                         seek($fh, 0, SEEK_SET);
356                         my @msg = <$fh>;
357                         warn "Inline::C build failed:\n",
358                                 $ndc_err, $err, "\n", @msg;
359                         $set_nodatacow = $all_libc = undef;
360                 } elsif ($ndc_err) {
361                         warn "Inline::C build succeeded w/o set_nodatacow\n",
362                                 "error $ndc_err";
363                 }
364         }
365         unless ($all_libc) {
366                 require PublicInbox::SpawnPP;
367                 *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
368         }
369         unless ($set_nodatacow) {
370                 require PublicInbox::NDC_PP;
371                 no warnings 'once';
372                 *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
373                 *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
374         }
375 } # /BEGIN
376
377 sub which ($) {
378         my ($file) = @_;
379         return $file if index($file, '/') >= 0;
380         for my $p (split(/:/, $ENV{PATH})) {
381                 $p .= "/$file";
382                 return $p if -x $p;
383         }
384         undef;
385 }
386
387 sub spawn ($;$$) {
388         my ($cmd, $env, $opts) = @_;
389         my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
390         my @env;
391         $opts ||= {};
392         my %env = (%ENV, $env ? %$env : ());
393         while (my ($k, $v) = each %env) {
394                 push @env, "$k=$v" if defined($v);
395         }
396         my $redir = [];
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? $!";
402                         $parent_fd = $fd;
403                 }
404                 $redir->[$child_fd] = $parent_fd // $child_fd;
405         }
406         my $rlim = [];
407
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";
413                         next;
414                 }
415                 push @$rlim, $r, @$v;
416         }
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;
421         $pid;
422 }
423
424 sub popen_rd {
425         my ($cmd, $env, $opt) = @_;
426         pipe(my ($r, $w)) or die "pipe: $!\n";
427         $opt ||= {};
428         $opt->{1} = fileno($w);
429         my $pid = spawn($cmd, $env, $opt);
430         return ($r, $pid) if wantarray;
431         my $ret = gensym;
432         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
433         $ret;
434 }
435
436 sub run_die ($;$$) {
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";
441 }
442
443 1;