]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
testcommon: fix run_script for older Perls
[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 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
71                 [ *STDERR{IO}, '>&' ]);
72
73 sub _prepare_redirects ($) {
74         my ($fhref) = @_;
75         my $orig_io = [];
76         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
77                 my $fh = $fhref->[$fd] or next;
78                 my ($oldfh, $mode) = @{$io_mode[$fd]};
79                 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
80                 $orig_io->[$fd] = $orig;
81                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
82         }
83         $orig_io;
84 }
85
86 sub _undo_redirects ($) {
87         my ($orig_io) = @_;
88         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
89                 my $fh = $orig_io->[$fd] or next;
90                 my ($oldfh, $mode) = @{$io_mode[$fd]};
91                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
92         }
93 }
94
95 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
96 # three ways to spawn our own short-lived Perl scripts for testing:
97 #
98 # 0 - (fork|vfork) + execve, the most realistic but slowest
99 # 1 - preloading and running in a forked subprocess (fast)
100 # 2 - preloading and running in current process (slightly faster than 1)
101 #
102 # 2 is not compatible with scripts which use "exit" (which we'll try to
103 # avoid in the future).
104 # The default is 2.
105 our $run_script_exit_code;
106 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
107 sub run_script_exit (;$) {
108         $run_script_exit_code = $_[0] // 0;
109         die RUN_SCRIPT_EXIT;
110 }
111
112 my %cached_scripts;
113 sub key2sub ($) {
114         my ($key) = @_;
115         $cached_scripts{$key} //= do {
116                 my $f = key2script($key);
117                 open my $fh, '<', $f or die "open $f: $!";
118                 my $str = do { local $/; <$fh> };
119                 my $pkg = (split(m!/!, $f))[-1];
120                 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
121                 $pkg .= "_T" if $3;
122                 $pkg =~ tr/-.//d;
123                 $pkg = "PublicInbox::TestScript::$pkg";
124                 eval <<EOF;
125 package $pkg;
126 use strict;
127 use subs qw(exit);
128
129 *exit = *PublicInbox::TestCommon::run_script_exit;
130 sub main {
131 # the below "line" directive is a magic comment, see perlsyn(1) manpage
132 # line 1 "$f"
133 $str
134         0;
135 }
136 1;
137 EOF
138                 $pkg->can('main');
139         }
140 }
141
142 sub _run_sub ($$$) {
143         my ($sub, $key, $argv) = @_;
144         local @ARGV = @$argv;
145         $run_script_exit_code = undef;
146         my $exit_code = eval { $sub->(@$argv) };
147         if ($@ eq RUN_SCRIPT_EXIT) {
148                 $@ = '';
149                 $exit_code = $run_script_exit_code;
150                 $? = ($exit_code << 8);
151         } elsif (defined($exit_code)) {
152                 $? = ($exit_code << 8);
153         } elsif ($@) { # mimic die() behavior when uncaught
154                 warn "E: eval-ed $key: $@\n";
155                 $? = ($! << 8) if $!;
156                 $? = (255 << 8) if $? == 0;
157         } else {
158                 die "BUG: eval-ed $key: no exit code or \$@\n";
159         }
160 }
161
162 sub run_script ($;$$) {
163         my ($cmd, $env, $opt) = @_;
164         my ($key, @argv) = @$cmd;
165         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
166         my $sub = $run_mode == 0 ? undef : key2sub($key);
167         my $fhref = [];
168         my $spawn_opt = {};
169         for my $fd (0..2) {
170                 my $redir = $opt->{$fd};
171                 next unless ref($redir);
172                 open my $fh, '+>', undef or die "open: $!";
173                 $fhref->[$fd] = $fh;
174                 $spawn_opt->{$fd} = fileno($fh);
175                 next if $fd > 0;
176                 $fh->autoflush(1);
177                 print $fh $$redir or die "print: $!";
178                 seek($fh, 0, SEEK_SET) or die "seek: $!";
179         }
180         if ($run_mode == 0) {
181                 # spawn an independent new process, like real-world use cases:
182                 require PublicInbox::Spawn;
183                 my $cmd = [ key2script($key), @argv ];
184                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
185                 defined($pid) or die "spawn: $!";
186                 if (defined $pid) {
187                         my $r = waitpid($pid, 0);
188                         defined($r) or die "waitpid: $!";
189                         $r == $pid or die "waitpid: expected $pid, got $r";
190                 }
191         } else { # localize and run everything in the same process:
192                 # note: "local *STDIN = *STDIN;" and so forth did not work in
193                 # old versions of perl
194                 local %ENV = $env ? (%ENV, %$env) : %ENV;
195                 local %SIG = %SIG;
196                 local $0 = join(' ', @$cmd);
197                 my $orig_io = _prepare_redirects($fhref);
198                 _run_sub($sub, $key, \@argv);
199                 _undo_redirects($orig_io);
200         }
201
202         # slurp the redirects back into user-supplied strings
203         for my $fd (1..2) {
204                 my $fh = $fhref->[$fd] or next;
205                 seek($fh, 0, SEEK_SET) or die "seek: $!";
206                 my $redir = $opt->{$fd};
207                 local $/;
208                 $$redir = <$fh>;
209         }
210         $? == 0;
211 }
212
213 sub wait_for_tail () { sleep(2) }
214
215 sub start_script {
216         my ($cmd, $env, $opt) = @_;
217         my ($key, @argv) = @$cmd;
218         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
219         my $sub = $run_mode == 0 ? undef : key2sub($key);
220         my $tail_pid;
221         if (my $tail_cmd = $ENV{TAIL}) {
222                 my @paths;
223                 for (@argv) {
224                         next unless /\A--std(?:err|out)=(.+)\z/;
225                         push @paths, $1;
226                 }
227                 if (@paths) {
228                         defined($tail_pid = fork) or die "fork: $!\n";
229                         if ($tail_pid == 0) {
230                                 # make sure files exist, first
231                                 open my $fh, '>>', $_ for @paths;
232                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
233                                 exec(split(' ', $tail_cmd), @paths);
234                                 die "$tail_cmd failed: $!";
235                         }
236                         wait_for_tail();
237                 }
238         }
239         defined(my $pid = fork) or die "fork: $!\n";
240         if ($pid == 0) {
241                 # pretend to be systemd (cf. sd_listen_fds(3))
242                 # 3 == SD_LISTEN_FDS_START
243                 my $fd;
244                 for ($fd = 0; 1; $fd++) {
245                         my $s = $opt->{$fd};
246                         last if $fd >= 3 && !defined($s);
247                         next unless $s;
248                         my $fl = fcntl($s, F_GETFD, 0);
249                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
250                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
251                         }
252                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
253                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
254                 }
255                 %ENV = (%ENV, %$env) if $env;
256                 my $fds = $fd - 3;
257                 if ($fds > 0) {
258                         $ENV{LISTEN_PID} = $$;
259                         $ENV{LISTEN_FDS} = $fds;
260                 }
261                 $0 = join(' ', @$cmd);
262                 if ($sub) {
263                         _run_sub($sub, $key, \@argv);
264                         POSIX::_exit($? >> 8);
265                 } else {
266                         exec(key2script($key), @argv);
267                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
268                 }
269         }
270         PublicInboxTestProcess->new($pid, $tail_pid);
271 }
272
273 package PublicInboxTestProcess;
274 use strict;
275
276 # prevent new threads from inheriting these objects
277 sub CLONE_SKIP { 1 }
278
279 sub new {
280         my ($klass, $pid, $tail_pid) = @_;
281         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
282 }
283
284 sub kill {
285         my ($self, $sig) = @_;
286         CORE::kill($sig // 'TERM', $self->{pid});
287 }
288
289 sub join {
290         my ($self) = @_;
291         my $pid = delete $self->{pid} or return;
292         my $ret = waitpid($pid, 0);
293         defined($ret) or die "waitpid($pid): $!";
294         $ret == $pid or die "waitpid($pid) != $ret";
295 }
296
297 sub DESTROY {
298         my ($self) = @_;
299         return if $self->{owner} != $$;
300         if (my $tail = delete $self->{tail_pid}) {
301                 PublicInbox::TestCommon::wait_for_tail();
302                 CORE::kill('TERM', $tail);
303         }
304         my $pid = delete $self->{pid} or return;
305         CORE::kill('TERM', $pid);
306 }
307
308 1;