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