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