]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
spawn: support send_fd+recv_fd w/o IO::FDPass
[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 $vfork_spawn = <<'VFORK_SPAWN';
26 #include <sys/types.h>
27 #include <sys/time.h>
28 #include <sys/resource.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <errno.h>
32
33 /* some platforms need alloca.h, but some don't */
34 #if defined(__GNUC__) && !defined(alloca)
35 #  define alloca(sz) __builtin_alloca(sz)
36 #endif
37
38 #include <signal.h>
39 #include <assert.h>
40
41 /*
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.
47  */
48 #define AV2C_COPY(dst, src) do { \
49         I32 i; \
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); \
57         } \
58         dst[real_len] = 0; \
59 } while (0)
60
61 /* needs to be safe inside a vfork'ed process */
62 static void exit_err(int *cerrnum)
63 {
64         *cerrnum = errno;
65         _exit(1);
66 }
67
68 /*
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
72  */
73 int pi_fork_exec(SV *redirref, SV *file, SV *cmdref, SV *envref, SV *rlimref,
74                  const char *cd)
75 {
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);
81         pid_t pid;
82         char **argv, **envp;
83         sigset_t set, old, cset;
84         int ret, perrnum, cerrnum = 0;
85
86         AV2C_COPY(argv, cmd);
87         AV2C_COPY(envp, env);
88
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");
97         pid = vfork();
98         if (pid == 0) {
99                 int sig;
100                 I32 i, child_fd, max = av_len(redir);
101
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)
106                                 continue;
107                         if (dup2(parent_fd, child_fd) < 0)
108                                 exit_err(&cerrnum);
109                 }
110                 for (sig = 1; sig < NSIG; sig++)
111                         signal(sig, SIG_DFL); /* ignore errors on signals */
112                 if (*cd && chdir(cd) < 0)
113                         exit_err(&cerrnum);
114
115                 max = av_len(rlim);
116                 for (i = 0; i < max; i += 3) {
117                         struct rlimit rl;
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);
121
122                         rl.rlim_cur = SvIV(*soft);
123                         rl.rlim_max = SvIV(*hard);
124                         if (setrlimit(SvIV(*res), &rl) < 0)
125                                 exit_err(&cerrnum);
126                 }
127
128                 /*
129                  * don't bother unblocking other signals for now, just SIGCHLD.
130                  * we don't want signals to the group taking out a subprocess
131                  */
132                 (void)sigprocmask(SIG_UNBLOCK, &cset, NULL);
133                 execve(filename, argv, envp);
134                 exit_err(&cerrnum);
135         }
136         perrnum = errno;
137         ret = sigprocmask(SIG_SETMASK, &old, NULL);
138         assert(ret == 0 && "BUG calling sigprocmask to restore");
139         if (cerrnum) {
140                 if (pid > 0)
141                         waitpid(pid, NULL, 0);
142                 pid = -1;
143                 errno = cerrnum;
144         } else if (perrnum) {
145                 errno = perrnum;
146         }
147         return (int)pid;
148 }
149 VFORK_SPAWN
150
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>
159 #include <sys/vfs.h>
160 #include <linux/magic.h>
161 #include <linux/fs.h>
162 #include <dirent.h>
163 #include <errno.h>
164 #include <stdio.h>
165 #include <string.h>
166
167 void nodatacow_fd(int fd)
168 {
169         struct statfs buf;
170         int val = 0;
171
172         if (fstatfs(fd, &buf) < 0) {
173                 fprintf(stderr, "fstatfs: %s\\n", strerror(errno));
174                 return;
175         }
176
177         /* only btrfs is known to have this problem, so skip for non-btrfs */
178         if (buf.f_type != BTRFS_SUPER_MAGIC)
179                 return;
180
181         if (ioctl(fd, FS_IOC_GETFLAGS, &val) < 0) {
182                 fprintf(stderr, "FS_IOC_GET_FLAGS: %s\\n", strerror(errno));
183                 return;
184         }
185         val |= FS_NOCOW_FL;
186         if (ioctl(fd, FS_IOC_SETFLAGS, &val) < 0)
187                 fprintf(stderr, "FS_IOC_SET_FLAGS: %s\\n", strerror(errno));
188 }
189
190 void nodatacow_dir(const char *dir)
191 {
192         DIR *dh = opendir(dir);
193         int fd;
194
195         if (!dh) croak("opendir(%s): %s", dir, strerror(errno));
196         fd = dirfd(dh);
197         if (fd >= 0)
198                 nodatacow_fd(fd);
199         /* ENOTSUP probably won't happen under Linux... */
200         closedir(dh);
201 }
202 SET_NODATACOW
203
204 my $fdpass = <<'FDPASS';
205 #include <sys/types.h>
206 #include <sys/uio.h>
207 #include <sys/socket.h>
208
209 #if defined(CMSG_SPACE) && defined(CMSG_LEN)
210 union my_cmsg {
211         struct cmsghdr hdr;
212         char pad[sizeof(struct cmsghdr)+8+sizeof(int)+8];
213 };
214
215 int send_fd(int sockfd, int fd)
216 {
217         struct msghdr msg = { 0 };
218         struct iovec iov;
219         union my_cmsg cmsg = { 0 };
220
221         iov.iov_base = &msg.msg_namelen;
222         iov.iov_len = 1;
223         msg.msg_iov = &iov;
224         msg.msg_iovlen = 1;
225         msg.msg_control = &cmsg.hdr;
226         msg.msg_controllen = CMSG_SPACE(sizeof(int));
227
228         cmsg.hdr.cmsg_level = SOL_SOCKET;
229         cmsg.hdr.cmsg_type = SCM_RIGHTS;
230         cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(int));
231         *(int *)CMSG_DATA(&cmsg.hdr) = fd;
232
233         return sendmsg(sockfd, &msg, 0) >= 0;
234 }
235
236 int recv_fd(int sockfd)
237 {
238         union my_cmsg cmsg = { 0 };
239         struct msghdr msg = { 0 };
240         struct iovec iov;
241         int fd = -1;
242
243         iov.iov_base = &msg.msg_namelen;
244         iov.iov_len = 1;
245         msg.msg_iov = &iov;
246         msg.msg_iovlen = 1;
247         msg.msg_control = &cmsg.hdr;
248         msg.msg_controllen = CMSG_SPACE(sizeof(int));
249
250         if (recvmsg(sockfd, &msg, 0) <= 0)
251                 return -1;
252
253         errno = EDOM;
254         if (cmsg.hdr.cmsg_level == SOL_SOCKET &&
255                         cmsg.hdr.cmsg_type == SCM_RIGHTS &&
256                         cmsg.hdr.cmsg_len == CMSG_LEN(sizeof(int)))
257                 fd = *(int *)CMSG_DATA(&cmsg.hdr);
258
259         return fd;
260 }
261 #endif /* defined(CMSG_SPACE) && defined(CMSG_LEN) */
262 FDPASS
263
264 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY} //= (
265                 $ENV{XDG_CACHE_HOME} //
266                 ( ($ENV{HOME} // '/nonexistent').'/.cache' )
267         ).'/public-inbox/inline-c';
268
269 $set_nodatacow = $vfork_spawn = $fdpass = undef unless -d $inline_dir && -w _;
270 if (defined $vfork_spawn) {
271         # Inline 0.64 or later has locking in multi-process env,
272         # but we support 0.5 on Debian wheezy
273         use Fcntl qw(:flock);
274         eval {
275                 my $f = "$inline_dir/.public-inbox.lock";
276                 open my $fh, '>', $f or die "failed to open $f: $!\n";
277                 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
278                 eval 'use Inline C => $vfork_spawn . $fdpass . $set_nodatacow';
279                 my $err = $@;
280                 my $ndc_err;
281                 if ($err && $set_nodatacow) { # missing Linux kernel headers
282                         $ndc_err = $err;
283                         undef $set_nodatacow;
284                         eval 'use Inline C => $vfork_spawn . $fdpass';
285                 }
286                 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
287                 die $err if $err;
288                 warn $ndc_err if $ndc_err;
289         };
290         if ($@) {
291                 warn "Inline::C failed for vfork: $@\n";
292                 $set_nodatacow = $vfork_spawn = $fdpass = undef;
293         }
294 }
295
296 unless (defined $vfork_spawn) {
297         require PublicInbox::SpawnPP;
298         *pi_fork_exec = \&PublicInbox::SpawnPP::pi_fork_exec
299 }
300 unless ($set_nodatacow) {
301         require PublicInbox::NDC_PP;
302         no warnings 'once';
303         *nodatacow_fd = \&PublicInbox::NDC_PP::nodatacow_fd;
304         *nodatacow_dir = \&PublicInbox::NDC_PP::nodatacow_dir;
305 }
306 unless (__PACKAGE__->can('recv_fd')) {
307         eval { # try the XS IO::FDPass package
308                 require IO::FDPass;
309                 no warnings 'once';
310                 *recv_fd = \&IO::FDPass::recv;
311                 *send_fd = \&IO::FDPass::send;
312         };
313 }
314
315 undef $set_nodatacow;
316 undef $vfork_spawn;
317 undef $fdpass;
318
319 sub which ($) {
320         my ($file) = @_;
321         return $file if index($file, '/') >= 0;
322         foreach my $p (split(':', $ENV{PATH})) {
323                 $p .= "/$file";
324                 return $p if -x $p;
325         }
326         undef;
327 }
328
329 sub spawn ($;$$) {
330         my ($cmd, $env, $opts) = @_;
331         my $f = which($cmd->[0]);
332         defined $f or die "$cmd->[0]: command not found\n";
333         my @env;
334         $opts ||= {};
335
336         my %env = $env ? (%ENV, %$env) : %ENV;
337         while (my ($k, $v) = each %env) {
338                 push @env, "$k=$v";
339         }
340         my $redir = [];
341         for my $child_fd (0..2) {
342                 my $parent_fd = $opts->{$child_fd};
343                 if (defined($parent_fd) && $parent_fd !~ /\A[0-9]+\z/) {
344                         defined(my $fd = fileno($parent_fd)) or
345                                         die "$parent_fd not an IO GLOB? $!";
346                         $parent_fd = $fd;
347                 }
348                 $redir->[$child_fd] = $parent_fd // $child_fd;
349         }
350         my $rlim = [];
351
352         foreach my $l (@RLIMITS) {
353                 defined(my $v = $opts->{$l}) or next;
354                 my $r = eval "require BSD::Resource; BSD::Resource::$l();";
355                 unless (defined $r) {
356                         warn "$l undefined by BSD::Resource: $@\n";
357                         next;
358                 }
359                 push @$rlim, $r, @$v;
360         }
361         my $cd = $opts->{'-C'} // ''; # undef => NULL mapping doesn't work?
362         my $pid = pi_fork_exec($redir, $f, $cmd, \@env, $rlim, $cd);
363         die "fork_exec @$cmd failed: $!\n" unless $pid > 0;
364         $pid;
365 }
366
367 sub popen_rd {
368         my ($cmd, $env, $opt) = @_;
369         pipe(my ($r, $w)) or die "pipe: $!\n";
370         $opt ||= {};
371         $opt->{1} = fileno($w);
372         my $pid = spawn($cmd, $env, $opt);
373         return ($r, $pid) if wantarray;
374         my $ret = gensym;
375         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r, @$opt{qw(cb arg)};
376         $ret;
377 }
378
379 sub run_die ($;$$) {
380         my ($cmd, $env, $rdr) = @_;
381         my $pid = spawn($cmd, $env, $rdr);
382         waitpid($pid, 0) == $pid or die "@$cmd did not finish";
383         $? == 0 or die "@$cmd failed: \$?=$?\n";
384 }
385
386 1;