]> Sergey Matveev's repositories - public-inbox.git/blob - t/common.perl
2126a76106e94e4c5abebf9ceca1096c949e9184
[public-inbox.git] / t / common.perl
1 # Copyright (C) 2015-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
5 use POSIX qw(dup2);
6 use strict;
7 use warnings;
8 use IO::Socket::INET;
9
10 sub tcp_server () {
11         IO::Socket::INET->new(
12                 LocalAddr => '127.0.0.1',
13                 ReuseAddr => 1,
14                 Proto => 'tcp',
15                 Type => Socket::SOCK_STREAM(),
16                 Listen => 1024,
17                 Blocking => 0,
18         )
19 }
20
21 sub tcp_connect {
22         my ($dest, %opt) = @_;
23         my $s = IO::Socket::INET->new(
24                 Proto => 'tcp',
25                 Type => Socket::SOCK_STREAM(),
26                 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
27                 %opt,
28         );
29         $s->autoflush(1);
30         $s;
31 }
32
33 sub require_git ($;$) {
34         my ($req, $maybe) = @_;
35         my ($req_maj, $req_min) = split(/\./, $req);
36         my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
37
38         my $req_int = ($req_maj << 24) | ($req_min << 16);
39         my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
40         if ($cur_int < $req_int) {
41                 return 0 if $maybe;
42                 plan skip_all => "git $req+ required, have $cur_maj.$cur_min";
43         }
44         1;
45 }
46
47 sub key2script ($) {
48         my ($key) = @_;
49         return $key if $key =~ m!\A/!;
50         # n.b. we may have scripts which don't start with "public-inbox" in
51         # the future:
52         $key =~ s/\A([-\.])/public-inbox$1/;
53         'blib/script/'.$key;
54 }
55
56 sub _prepare_redirects ($) {
57         my ($fhref) = @_;
58         my @x = ([ \*STDIN, '<&' ], [ \*STDOUT, '>&' ], [ \*STDERR, '>&' ]);
59         for (my $fd = 0; $fd <= $#x; $fd++) {
60                 my $fh = $fhref->[$fd] or next;
61                 my ($oldfh, $mode) = @{$x[$fd]};
62                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
63         }
64 }
65
66 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
67 # three ways to spawn our own short-lived Perl scripts for testing:
68 #
69 # 0 - (fork|vfork) + execve, the most realistic but slowest
70 # 1 - preloading and running in a forked subprocess (fast)
71 # 2 - preloading and running in current process (slightly faster than 1)
72 #
73 # 2 is not compatible with scripts which use "exit" (which we'll try to
74 # avoid in the future).
75 # The default is 2.
76 our $run_script_exit_code;
77 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
78 sub run_script_exit (;$) {
79         $run_script_exit_code = $_[0] // 0;
80         die RUN_SCRIPT_EXIT;
81 }
82
83 my %cached_scripts;
84 sub key2sub ($) {
85         my ($key) = @_;
86         $cached_scripts{$key} //= do {
87                 my $f = key2script($key);
88                 open my $fh, '<', $f or die "open $f: $!";
89                 my $str = do { local $/; <$fh> };
90                 my ($fc, $rest) = ($key =~ m/([a-z])([a-z0-9]+)\z/);
91                 $fc = uc($fc);
92                 my $pkg = "PublicInbox::TestScript::$fc$rest";
93                 eval <<EOF;
94 package $pkg;
95 use strict;
96 use subs qw(exit);
97
98 *exit = *::run_script_exit;
99 sub main {
100 $str
101         0;
102 }
103 1;
104 EOF
105                 $pkg->can('main');
106         }
107 }
108
109 sub _run_sub ($$$) {
110         my ($sub, $key, $argv) = @_;
111         local @ARGV = @$argv;
112         $run_script_exit_code = undef;
113         my $exit_code = eval { $sub->(@$argv) };
114         if ($@ eq RUN_SCRIPT_EXIT) {
115                 $@ = '';
116                 $exit_code = $run_script_exit_code;
117                 $? = ($exit_code << 8);
118         } elsif (defined($exit_code)) {
119                 $? = ($exit_code << 8);
120         } elsif ($@) { # mimic die() behavior when uncaught
121                 warn "E: eval-ed $key: $@\n";
122                 $? = ($! << 8) if $!;
123                 $? = (255 << 8) if $? == 0;
124         } else {
125                 die "BUG: eval-ed $key: no exit code or \$@\n";
126         }
127 }
128
129 sub run_script ($;$$) {
130         my ($cmd, $env, $opt) = @_;
131         my ($key, @argv) = @$cmd;
132         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
133         my $sub = $run_mode == 0 ? undef : key2sub($key);
134         my $fhref = [];
135         my $spawn_opt = {};
136         for my $fd (0..2) {
137                 my $redir = $opt->{$fd};
138                 next unless ref($redir);
139                 open my $fh, '+>', undef or die "open: $!";
140                 $fhref->[$fd] = $fh;
141                 $spawn_opt->{$fd} = fileno($fh);
142                 next if $fd > 0;
143                 $fh->autoflush(1);
144                 print $fh $$redir or die "print: $!";
145                 seek($fh, 0, SEEK_SET) or die "seek: $!";
146         }
147         if ($run_mode == 0) {
148                 # spawn an independent new process, like real-world use cases:
149                 require PublicInbox::Spawn;
150                 my $cmd = [ key2script($key), @argv ];
151                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
152                 defined($pid) or die "spawn: $!";
153                 if (defined $pid) {
154                         my $r = waitpid($pid, 0);
155                         defined($r) or die "waitpid: $!";
156                         $r == $pid or die "waitpid: expected $pid, got $r";
157                 }
158         } else { # localize and run everything in the same process:
159                 local *STDIN = *STDIN;
160                 local *STDOUT = *STDOUT;
161                 local *STDERR = *STDERR;
162                 local %ENV = $env ? (%ENV, %$env) : %ENV;
163                 local %SIG = %SIG;
164                 _prepare_redirects($fhref);
165                 _run_sub($sub, $key, \@argv);
166         }
167
168         # slurp the redirects back into user-supplied strings
169         for my $fd (1..2) {
170                 my $fh = $fhref->[$fd] or next;
171                 seek($fh, 0, SEEK_SET) or die "seek: $!";
172                 my $redir = $opt->{$fd};
173                 local $/;
174                 $$redir = <$fh>;
175         }
176         $? == 0;
177 }
178
179 sub wait_for_tail () { sleep(2) }
180
181 sub start_script {
182         my ($cmd, $env, $opt) = @_;
183         my ($key, @argv) = @$cmd;
184         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
185         my $sub = $run_mode == 0 ? undef : key2sub($key);
186         my $tail_pid;
187         if (my $tail_cmd = $ENV{TAIL}) {
188                 my @paths;
189                 for (@argv) {
190                         next unless /\A--std(?:err|out)=(.+)\z/;
191                         push @paths, $1;
192                 }
193                 if (@paths) {
194                         defined($tail_pid = fork) or die "fork: $!\n";
195                         if ($tail_pid == 0) {
196                                 # make sure files exist, first
197                                 open my $fh, '>>', $_ for @paths;
198                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
199                                 exec(split(' ', $tail_cmd), @paths);
200                                 die "$tail_cmd failed: $!";
201                         }
202                         wait_for_tail();
203                 }
204         }
205         defined(my $pid = fork) or die "fork: $!\n";
206         if ($pid == 0) {
207                 # pretend to be systemd (cf. sd_listen_fds(3))
208                 # 3 == SD_LISTEN_FDS_START
209                 my $fd;
210                 for ($fd = 0; 1; $fd++) {
211                         my $s = $opt->{$fd};
212                         last if $fd >= 3 && !defined($s);
213                         next unless $s;
214                         my $fl = fcntl($s, F_GETFD, 0);
215                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
216                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
217                         }
218                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
219                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
220                 }
221                 %ENV = (%ENV, %$env) if $env;
222                 my $fds = $fd - 3;
223                 if ($fds > 0) {
224                         $ENV{LISTEN_PID} = $$;
225                         $ENV{LISTEN_FDS} = $fds;
226                 }
227                 $0 = join(' ', @$cmd);
228                 if ($sub) {
229                         _run_sub($sub, $key, \@argv);
230                         POSIX::_exit($? >> 8);
231                 } else {
232                         exec(key2script($key), @argv);
233                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
234                 }
235         }
236         TestProcess->new($pid, $tail_pid);
237 }
238
239 package TestProcess;
240 use strict;
241
242 # prevent new threads from inheriting these objects
243 sub CLONE_SKIP { 1 }
244
245 sub new {
246         my ($klass, $pid, $tail_pid) = @_;
247         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
248 }
249
250 sub kill {
251         my ($self, $sig) = @_;
252         CORE::kill($sig // 'TERM', $self->{pid});
253 }
254
255 sub join {
256         my ($self) = @_;
257         my $pid = delete $self->{pid} or return;
258         my $ret = waitpid($pid, 0);
259         defined($ret) or die "waitpid($pid): $!";
260         $ret == $pid or die "waitpid($pid) != $ret";
261 }
262
263 sub DESTROY {
264         my ($self) = @_;
265         return if $self->{owner} != $$;
266         if (my $tail = delete $self->{tail_pid}) {
267                 ::wait_for_tail();
268                 CORE::kill('TERM', $tail);
269         }
270         my $pid = delete $self->{pid} or return;
271         CORE::kill('TERM', $pid);
272 }
273
274 1;