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