]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Spawn.pm
spawn: disable popen optimization for non-vfork
[public-inbox.git] / lib / PublicInbox / Spawn.pm
1 # Copyright (C) 2016 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 # PERL_INLINE_DIRECTORY is explicitly defined in the environment.
6 # Under Linux, vfork can make a big difference in spawning performance
7 # as process size increases (fork still needs to mark pages for CoW use).
8 # Currently, we only use this for code intended for long running
9 # daemons (inside the PSGI code (-httpd) and -nntpd).  The short-lived
10 # scripts (-mda, -index, -learn, -init) either use IPC::run or standard
11 # Perl routines.
12
13 package PublicInbox::Spawn;
14 use strict;
15 use warnings;
16 use base qw(Exporter);
17 use Symbol qw(gensym);
18 use PublicInbox::ProcessPipe;
19 our @EXPORT_OK = qw/which spawn popen_rd/;
20
21 my $vfork_spawn = <<'VFORK_SPAWN';
22 #include <sys/types.h>
23 #include <sys/uio.h>
24 #include <unistd.h>
25 #include <alloca.h>
26
27 #define AV_ALLOCA(av, max) alloca((max = (av_len((av)) + 1)) * sizeof(char *))
28
29 static void av2c_copy(char **dst, AV *src, I32 max)
30 {
31         I32 i;
32
33         for (i = 0; i < max; i++) {
34                 SV **sv = av_fetch(src, i, 0);
35                 dst[i] = sv ? SvPV_nolen(*sv) : 0;
36         }
37         dst[max] = 0;
38 }
39
40 static void *deconst(const char *s)
41 {
42         union { const char *in; void *out; } u;
43         u.in = s;
44         return u.out;
45 }
46
47 /* needs to be safe inside a vfork'ed process */
48 static void xerr(const char *msg)
49 {
50         struct iovec iov[3];
51         const char *err = strerror(errno); /* should be safe in practice */
52
53         iov[0].iov_base = deconst(msg);
54         iov[0].iov_len = strlen(msg);
55         iov[1].iov_base = deconst(err);
56         iov[1].iov_len = strlen(err);
57         iov[2].iov_base = deconst("\n");
58         iov[2].iov_len = 1;
59         writev(2, iov, 3);
60         _exit(1);
61 }
62
63 #define REDIR(var,fd) do { \
64         if (var != fd && dup2(var, fd) < 0) \
65                 xerr("error redirecting std"#var ": "); \
66 } while (0)
67
68 /*
69  * unstable internal API.  This was easy to implement but does not
70  * support arbitrary redirects.  It'll be updated depending on
71  * whatever we'll need in the future.
72  * Be sure to update PublicInbox::SpawnPP if this changes
73  */
74 int public_inbox_fork_exec(int in, int out, int err,
75                         SV *file, SV *cmdref, SV *envref)
76 {
77         AV *cmd = (AV *)SvRV(cmdref);
78         AV *env = (AV *)SvRV(envref);
79         const char *filename = SvPV_nolen(file);
80         pid_t pid;
81         char **argv, **envp;
82         I32 max;
83
84         argv = AV_ALLOCA(cmd, max);
85         av2c_copy(argv, cmd, max);
86
87         envp = AV_ALLOCA(env, max);
88         av2c_copy(envp, env, max);
89
90         pid = vfork();
91         if (pid == 0) {
92                 REDIR(in, 0);
93                 REDIR(out, 1);
94                 REDIR(err, 2);
95                 execve(filename, argv, envp);
96                 xerr("execve failed");
97         }
98
99         return (int)pid;
100 }
101 VFORK_SPAWN
102
103 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY};
104 $vfork_spawn = undef unless defined $inline_dir && -d $inline_dir && -w _;
105 if (defined $vfork_spawn) {
106         # Inline 0.64 or later has locking in multi-process env,
107         # but we support 0.5 on Debian wheezy
108         use Fcntl qw(:flock);
109         eval {
110                 my $f = "$inline_dir/.public-inbox.lock";
111                 open my $fh, '>', $f or die "failed to open $f: $!\n";
112                 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
113                 eval 'use Inline C => $vfork_spawn';
114                 my $err = $@;
115                 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
116                 die $err if $err;
117         };
118         if ($@) {
119                 warn "Inline::C failed for vfork: $@\n";
120                 $vfork_spawn = undef;
121         }
122 }
123
124 unless (defined $vfork_spawn) {
125         require PublicInbox::SpawnPP;
126         no warnings 'once';
127         *public_inbox_fork_exec = *PublicInbox::SpawnPP::public_inbox_fork_exec
128 }
129
130 sub which ($) {
131         my ($file) = @_;
132         foreach my $p (split(':', $ENV{PATH})) {
133                 $p .= "/$file";
134                 return $p if -x $p;
135         }
136         undef;
137 }
138
139 sub spawn ($;$$) {
140         my ($cmd, $env, $opts) = @_;
141         my $f = which($cmd->[0]);
142         defined $f or die "$cmd->[0]: command not found\n";
143         my @env;
144         $opts ||= {};
145
146         my %env = $opts->{-env} ? () : %ENV;
147         if ($env) {
148                 foreach my $k (keys %$env) {
149                         my $v = $env->{$k};
150                         if (defined $v) {
151                                 $env{$k} = $v;
152                         } else {
153                                 delete $env{$k};
154                         }
155                 }
156         }
157         while (my ($k, $v) = each %env) {
158                 push @env, "$k=$v";
159         }
160         my $in = $opts->{0} || 0;
161         my $out = $opts->{1} || 1;
162         my $err = $opts->{2} || 2;
163         public_inbox_fork_exec($in, $out, $err, $f, $cmd, \@env);
164 }
165
166 sub popen_rd {
167         my ($cmd, $env, $opts) = @_;
168         pipe(my ($r, $w)) or die "pipe: $!\n";
169         $opts ||= {};
170         my $blocking = $opts->{Blocking};
171         $r->blocking($blocking) if defined $blocking;
172         $opts->{1} = fileno($w);
173         my $pid = spawn($cmd, $env, $opts);
174         close $w;
175         return ($r, $pid) if wantarray;
176         my $ret = gensym;
177         tie *$ret, 'PublicInbox::ProcessPipe', $pid, $r;
178         $ret;
179 }
180
181 1;