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