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