]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
45306a5a7f56722891fea6be5e91fec82b8a902c
[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 $key =~ m!\A/!;
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 ($fc, $rest) = ($key =~ m/([a-z])([a-z0-9]+)\z/);
105                 $fc = uc($fc);
106                 my $pkg = "PublicInbox::TestScript::$fc$rest";
107                 eval <<EOF;
108 package $pkg;
109 use strict;
110 use subs qw(exit);
111
112 *exit = *PublicInbox::TestCommon::run_script_exit;
113 sub main {
114 $str
115         0;
116 }
117 1;
118 EOF
119                 $pkg->can('main');
120         }
121 }
122
123 sub _run_sub ($$$) {
124         my ($sub, $key, $argv) = @_;
125         local @ARGV = @$argv;
126         $run_script_exit_code = undef;
127         my $exit_code = eval { $sub->(@$argv) };
128         if ($@ eq RUN_SCRIPT_EXIT) {
129                 $@ = '';
130                 $exit_code = $run_script_exit_code;
131                 $? = ($exit_code << 8);
132         } elsif (defined($exit_code)) {
133                 $? = ($exit_code << 8);
134         } elsif ($@) { # mimic die() behavior when uncaught
135                 warn "E: eval-ed $key: $@\n";
136                 $? = ($! << 8) if $!;
137                 $? = (255 << 8) if $? == 0;
138         } else {
139                 die "BUG: eval-ed $key: no exit code or \$@\n";
140         }
141 }
142
143 sub run_script ($;$$) {
144         my ($cmd, $env, $opt) = @_;
145         my ($key, @argv) = @$cmd;
146         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
147         my $sub = $run_mode == 0 ? undef : key2sub($key);
148         my $fhref = [];
149         my $spawn_opt = {};
150         for my $fd (0..2) {
151                 my $redir = $opt->{$fd};
152                 next unless ref($redir);
153                 open my $fh, '+>', undef or die "open: $!";
154                 $fhref->[$fd] = $fh;
155                 $spawn_opt->{$fd} = fileno($fh);
156                 next if $fd > 0;
157                 $fh->autoflush(1);
158                 print $fh $$redir or die "print: $!";
159                 seek($fh, 0, SEEK_SET) or die "seek: $!";
160         }
161         if ($run_mode == 0) {
162                 # spawn an independent new process, like real-world use cases:
163                 require PublicInbox::Spawn;
164                 my $cmd = [ key2script($key), @argv ];
165                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
166                 defined($pid) or die "spawn: $!";
167                 if (defined $pid) {
168                         my $r = waitpid($pid, 0);
169                         defined($r) or die "waitpid: $!";
170                         $r == $pid or die "waitpid: expected $pid, got $r";
171                 }
172         } else { # localize and run everything in the same process:
173                 local *STDIN = *STDIN;
174                 local *STDOUT = *STDOUT;
175                 local *STDERR = *STDERR;
176                 local %ENV = $env ? (%ENV, %$env) : %ENV;
177                 local %SIG = %SIG;
178                 local $0 = join(' ', @$cmd);
179                 _prepare_redirects($fhref);
180                 _run_sub($sub, $key, \@argv);
181         }
182
183         # slurp the redirects back into user-supplied strings
184         for my $fd (1..2) {
185                 my $fh = $fhref->[$fd] or next;
186                 seek($fh, 0, SEEK_SET) or die "seek: $!";
187                 my $redir = $opt->{$fd};
188                 local $/;
189                 $$redir = <$fh>;
190         }
191         $? == 0;
192 }
193
194 sub wait_for_tail () { sleep(2) }
195
196 sub start_script {
197         my ($cmd, $env, $opt) = @_;
198         my ($key, @argv) = @$cmd;
199         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
200         my $sub = $run_mode == 0 ? undef : key2sub($key);
201         my $tail_pid;
202         if (my $tail_cmd = $ENV{TAIL}) {
203                 my @paths;
204                 for (@argv) {
205                         next unless /\A--std(?:err|out)=(.+)\z/;
206                         push @paths, $1;
207                 }
208                 if (@paths) {
209                         defined($tail_pid = fork) or die "fork: $!\n";
210                         if ($tail_pid == 0) {
211                                 # make sure files exist, first
212                                 open my $fh, '>>', $_ for @paths;
213                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
214                                 exec(split(' ', $tail_cmd), @paths);
215                                 die "$tail_cmd failed: $!";
216                         }
217                         wait_for_tail();
218                 }
219         }
220         defined(my $pid = fork) or die "fork: $!\n";
221         if ($pid == 0) {
222                 # pretend to be systemd (cf. sd_listen_fds(3))
223                 # 3 == SD_LISTEN_FDS_START
224                 my $fd;
225                 for ($fd = 0; 1; $fd++) {
226                         my $s = $opt->{$fd};
227                         last if $fd >= 3 && !defined($s);
228                         next unless $s;
229                         my $fl = fcntl($s, F_GETFD, 0);
230                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
231                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
232                         }
233                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
234                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
235                 }
236                 %ENV = (%ENV, %$env) if $env;
237                 my $fds = $fd - 3;
238                 if ($fds > 0) {
239                         $ENV{LISTEN_PID} = $$;
240                         $ENV{LISTEN_FDS} = $fds;
241                 }
242                 $0 = join(' ', @$cmd);
243                 if ($sub) {
244                         _run_sub($sub, $key, \@argv);
245                         POSIX::_exit($? >> 8);
246                 } else {
247                         exec(key2script($key), @argv);
248                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
249                 }
250         }
251         PublicInboxTestProcess->new($pid, $tail_pid);
252 }
253
254 package PublicInboxTestProcess;
255 use strict;
256
257 # prevent new threads from inheriting these objects
258 sub CLONE_SKIP { 1 }
259
260 sub new {
261         my ($klass, $pid, $tail_pid) = @_;
262         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
263 }
264
265 sub kill {
266         my ($self, $sig) = @_;
267         CORE::kill($sig // 'TERM', $self->{pid});
268 }
269
270 sub join {
271         my ($self) = @_;
272         my $pid = delete $self->{pid} or return;
273         my $ret = waitpid($pid, 0);
274         defined($ret) or die "waitpid($pid): $!";
275         $ret == $pid or die "waitpid($pid) != $ret";
276 }
277
278 sub DESTROY {
279         my ($self) = @_;
280         return if $self->{owner} != $$;
281         if (my $tail = delete $self->{tail_pid}) {
282                 PublicInbox::TestCommon::wait_for_tail();
283                 CORE::kill('TERM', $tail);
284         }
285         my $pid = delete $self->{pid} or return;
286         CORE::kill('TERM', $pid);
287 }
288
289 1;