]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
spawn: merge common C code together
[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 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);
24
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>
29 #include <sys/time.h>
30 #include <sys/uio.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33 #include <errno.h>
34
35 /* some platforms need alloca.h, but some don't */
36 #if defined(__GNUC__) && !defined(alloca)
37 #  define alloca(sz) __builtin_alloca(sz)
38 #endif
39
40 #include <signal.h>
41 #include <assert.h>
42
43 /*
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.
49  */
50 #define AV2C_COPY(dst, src) do { \
51         I32 i; \
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); \
59         } \
60         dst[real_len] = 0; \
61 } while (0)
62
63 /* needs to be safe inside a vfork'ed process */
64 static void exit_err(int *cerrnum)
65 {
66         *cerrnum = errno;
67         _exit(1);
68 }
69
70 /*
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
74  */
75 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
76                  const char *cd)
77 {
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);
83         pid_t pid;
84         char **argv, **envp;
85         sigset_t set, old, cset;
86         int ret, perrnum, cerrnum = 0;
87
88         AV2C_COPY(argv, cmd);
89         AV2C_COPY(envp, env);
90
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");
99         pid = vfork();
100         if (pid == 0) {
101                 int sig;
102                 I32 i, child_fd, max = av_len(redir);
103
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)
108                                 continue;
109                         if (dup2(parent_fd, child_fd) < 0)
110                                 exit_err(&cerrnum);
111                 }
112                 for (sig = 1; sig < NSIG; sig++)
113                         signal(sig, SIG_DFL); /* ignore errors on signals */
114                 if (*cd && chdir(cd) < 0)
115                         exit_err(&cerrnum);
116
117                 max = av_len(rlim);
118                 for (i = 0; i < max; i += 3) {
119                         struct rlimit rl;
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);
123
124                         rl.rlim_cur = SvIV(*soft);
125                         rl.rlim_max = SvIV(*hard);
126                         if (setrlimit(SvIV(*res), &rl) < 0)
127                                 exit_err(&cerrnum);
128                 }
129
130                 /*
131                  * don't bother unblocking other signals for now, just SIGCHLD.
132                  * we don't want signals to the group taking out a subprocess
133                  */
134                 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
135                 execve(filename, argv, envp);
136                 exit_err(&cerrnum);
137         }
138         perrnum = errno;
139         ret = sigprocmask(SIG_SETMASK, &old, NULL);
140         assert(ret == 0 && "BUG calling sigprocmask to restore");
141         if (cerrnum) {
142                 if (pid > 0)
143                         waitpid(pid, NULL, 0);
144                 pid = -1;
145                 errno = cerrnum;
146         } else if (perrnum) {
147                 errno = perrnum;
148         }
149         return (int)pid;
150 }
151
152 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
153 #define SEND_FD_CAPA 10
154 #define SEND_FD_SPACE (SEND_FD_CAPA * sizeof(int))
155 union my_cmsg {
156         struct cmsghdr hdr;
157         char pad[sizeof(struct cmsghdr) + 16 + SEND_FD_SPACE];
158 };
159
160 SV *send_cmd4(PerlIO *s, SV *svfds, SV *data, int flags)
161 {
162         struct msghdr msg = { 0 };
163         union my_cmsg cmsg = { 0 };
164         STRLEN dlen = 0;
165         struct iovec iov;
166         ssize_t sent;
167         AV *fds = (AV *)SvRV(svfds);
168         I32 i, nfds = av_len(fds) + 1;
169         int *fdp;
170
171         if (SvOK(data)) {
172                 iov.iov_base = SvPV(data, dlen);
173                 iov.iov_len = dlen;
174         }
175         if (!dlen) { /* must be non-zero */
176                 iov.iov_base = &msg.msg_namelen; /* whatever */
177                 iov.iov_len = 1;
178         }
179         msg.msg_iov = &iov;
180         msg.msg_iovlen = 1;
181         if (nfds) {
182                 if (nfds > SEND_FD_CAPA) {
183                         fprintf(stderr, "FIXME: bump SEND_FD_CAPA=%d\n", nfds);
184                         nfds = SEND_FD_CAPA;
185                 }
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);
194                         *fdp++ = SvIV(*fd);
195                 }
196         }
197         sent = sendmsg(PerlIO_fileno(s), &msg, flags);
198         return sent >= 0 ? newSViv(sent) : &PL_sv_undef;
199 }
200
201 void recv_cmd4(PerlIO *s, SV *buf, STRLEN n)
202 {
203         union my_cmsg cmsg = { 0 };
204         struct msghdr msg = { 0 };
205         struct iovec iov;
206         ssize_t i;
207         Inline_Stack_Vars;
208         Inline_Stack_Reset;
209
210         if (!SvOK(buf))
211                 sv_setpvn(buf, "", 0);
212         iov.iov_base = SvGROW(buf, n + 1);
213         iov.iov_len = n;
214         msg.msg_iov = &iov;
215         msg.msg_iovlen = 1;
216         msg.msg_control = &cmsg.hdr;
217         msg.msg_controllen = CMSG_SPACE(SEND_FD_SPACE);
218
219         i = recvmsg(PerlIO_fileno(s), &msg, 0);
220         if (i < 0)
221                 Inline_Stack_Push(&PL_sv_undef);
222         else
223                 SvCUR_set(buf, i);
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++)));
230         }
231         Inline_Stack_Done;
232 }
233 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
234 ALL_LIBC
235
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>
244 #include <sys/vfs.h>
245 #include <linux/magic.h>
246 #include <linux/fs.h>
247 #include <dirent.h>
248 #include <errno.h>
249 #include <stdio.h>
250 #include <string.h>
251
252 void nodatacow_fd(int fd)
253 {
254         struct statfs buf;
255         int val = 0;
256
257         if (fstatfs(fd, &buf) < 0) {
258                 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
259                 return;
260         }
261
262         /* only btrfs is known to have this problem, so skip for non-btrfs */
263         if (buf.f_type != BTRFS_SUPER_MAGIC)
264                 return;
265
266         if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
267                 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
268                 return;
269         }
270         val |= FS_NOCOW_FL;
271         if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
272                 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
273 }
274
275 void nodatacow_dir(const char *dir)
276 {
277         DIR *dh = opendir(dir);
278         int fd;
279
280         if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
281         fd = dirfd(dh);
282         if (fd >= 0)
283                 nodatacow_fd(fd);
284         /* ENOTSUP probably won't happen under Linux... */
285         closedir(dh);
286 }
287 SET_NODATACOW
288
289 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
290                 $ENV{XDG_CACHE_HOME} //
291                 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
292         ).'/public-inbox/inline-c';
293
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);
299         eval {
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';
305                 my $err = $@;
306                 my $ndc_err;
307                 if ($err && $set_nodatacow) { # missing Linux kernel headers
308                         $ndc_err = $err;
309                         undef $set_nodatacow;
310                         eval 'use Inline C => $all_libc';
311                 }
312                 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
313                 die $err if $err;
314                 warn $ndc_err if $ndc_err;
315         };
316         if ($@) {
317                 warn "Inline::C failed for vfork: $@\n";
318                 $set_nodatacow = $all_libc = undef;
319         }
320 }
321
322 unless ($all_libc) {
323         require PublicInbox::SpawnPP;
324         *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
325 }
326 unless ($set_nodatacow) {
327         require PublicInbox::NDC_PP;
328         no warnings 'once';
329         *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
330         *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
331 }
332
333 undef $set_nodatacow;
334 undef $all_libc;
335
336 sub which ($) {
337         my ($file) = @_;
338         return $file if index($file, '/') >= 0;
339         for my $p (split(/:/, $ENV{PATH})) {
340                 $p .= "/$file";
341                 return $p if -x $p;
342         }
343         undef;
344 }
345
346 sub spawn ($;$$) {
347         my ($cmd, $env, $opts) = @_;
348         my $f = which($cmd->[0]) // die "$cmd->[0]: command not found\n";
349         my @env;
350         $opts ||= {};
351
352         my %env = $env ? (%ENV, %$env) : %ENV;
353         while (my ($k, $v) = each %env) {
354                 push @env, "$k=$v";
355         }
356         my $redir = [];
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? $!";
362                         $parent_fd = $fd;
363                 }
364                 $redir->[$child_fd] = $parent_fd // $child_fd;
365         }
366         my $rlim = [];
367
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";
373                         next;
374                 }
375                 push @$rlim, $r, @$v;
376         }
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;
380         $pid;
381 }
382
383 sub popen_rd {
384         my ($cmd, $env, $opt) = @_;
385         pipe(my ($r, $w)) or die "pipe: $!\n";
386         $opt ||= {};
387         $opt->{1} = fileno($w);
388         my $pid = spawn($cmd, $env, $opt);
389         return ($r, $pid) if wantarray;
390         my $ret = gensym;
391         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
392         $ret;
393 }
394
395 sub run_die ($;$$) {
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";
400 }
401
402 1;