]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
600843f006663815a3b0f95b1f61a1c24dfa3899
[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 xsys xqx mime_load eml_load);
13
14 sub mime_load ($) {
15         my ($path) = @_;
16         open(my $fh, '<', $path) or die "open $path: $!";
17         PublicInbox::MIME->new(\(do { local $/; <$fh> }));
18 }
19
20 sub eml_load ($) {
21         my ($path, $cb) = @_;
22         open(my $fh, '<', $path) or die "open $path: $!";
23         binmode $fh;
24         PublicInbox::Eml->new(\(do { local $/; <$fh> }));
25 }
26
27 sub tmpdir (;$) {
28         my ($base) = @_;
29         require File::Temp;
30         unless (defined $base) {
31                 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
32         }
33         my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
34         ($tmpdir->dirname, $tmpdir);
35 }
36
37 sub tcp_server () {
38         IO::Socket::INET->new(
39                 LocalAddr => '127.0.0.1',
40                 ReuseAddr => 1,
41                 Proto => 'tcp',
42                 Type => Socket::SOCK_STREAM(),
43                 Listen => 1024,
44                 Blocking => 0,
45         )
46 }
47
48 sub tcp_connect {
49         my ($dest, %opt) = @_;
50         my $s = IO::Socket::INET->new(
51                 Proto => 'tcp',
52                 Type => Socket::SOCK_STREAM(),
53                 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
54                 %opt,
55         );
56         $s->autoflush(1);
57         $s;
58 }
59
60 sub require_git ($;$) {
61         my ($req, $maybe) = @_;
62         my ($req_maj, $req_min) = split(/\./, $req);
63         my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
64
65         my $req_int = ($req_maj << 24) | ($req_min << 16);
66         my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
67         if ($cur_int < $req_int) {
68                 return 0 if $maybe;
69                 Test::More::plan(skip_all =>
70                                 "git $req+ required, have $cur_maj.$cur_min");
71         }
72         1;
73 }
74
75 sub require_mods {
76         my @mods = @_;
77         my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
78         my @need;
79         for my $mod (@mods) {
80                 if ($mod eq 'Search::Xapian') {
81                         if (eval { require PublicInbox::Search } &&
82                                 PublicInbox::Search::load_xapian()) {
83                                 next;
84                         }
85                 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
86                         if (eval { require PublicInbox::SearchIdx } &&
87                                 PublicInbox::SearchIdx::load_xapian_writable()){
88                                         next;
89                         }
90                 } else {
91                         eval "require $mod";
92                 }
93                 push @need, $mod if $@;
94         }
95         return unless @need;
96         my $m = join(', ', @need)." missing for $0";
97         Test::More::skip($m, $maybe) if $maybe;
98         Test::More::plan(skip_all => $m)
99 }
100
101 sub key2script ($) {
102         my ($key) = @_;
103         return $key if ($key eq 'git' || index($key, '/') >= 0);
104         # n.b. we may have scripts which don't start with "public-inbox" in
105         # the future:
106         $key =~ s/\A([-\.])/public-inbox$1/;
107         'blib/script/'.$key;
108 }
109
110 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
111                 [ *STDERR{IO}, '>&' ]);
112
113 sub _prepare_redirects ($) {
114         my ($fhref) = @_;
115         my $orig_io = [];
116         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
117                 my $fh = $fhref->[$fd] or next;
118                 my ($oldfh, $mode) = @{$io_mode[$fd]};
119                 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
120                 $orig_io->[$fd] = $orig;
121                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
122         }
123         $orig_io;
124 }
125
126 sub _undo_redirects ($) {
127         my ($orig_io) = @_;
128         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
129                 my $fh = $orig_io->[$fd] or next;
130                 my ($oldfh, $mode) = @{$io_mode[$fd]};
131                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
132         }
133 }
134
135 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
136 # three ways to spawn our own short-lived Perl scripts for testing:
137 #
138 # 0 - (fork|vfork) + execve, the most realistic but slowest
139 # 1 - (not currently implemented)
140 # 2 - preloading and running in current process (slightly faster than 1)
141 #
142 # 2 is not compatible with scripts which use "exit" (which we'll try to
143 # avoid in the future).
144 # The default is 2.
145 our $run_script_exit_code;
146 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
147 sub run_script_exit (;$) {
148         $run_script_exit_code = $_[0] // 0;
149         die RUN_SCRIPT_EXIT;
150 }
151
152 my %cached_scripts;
153 sub key2sub ($) {
154         my ($key) = @_;
155         $cached_scripts{$key} //= do {
156                 my $f = key2script($key);
157                 open my $fh, '<', $f or die "open $f: $!";
158                 my $str = do { local $/; <$fh> };
159                 my $pkg = (split(m!/!, $f))[-1];
160                 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
161                 $pkg .= "_T" if $3;
162                 $pkg =~ tr/-.//d;
163                 $pkg = "PublicInbox::TestScript::$pkg";
164                 eval <<EOF;
165 package $pkg;
166 use strict;
167 use subs qw(exit);
168
169 *exit = *PublicInbox::TestCommon::run_script_exit;
170 sub main {
171 # the below "line" directive is a magic comment, see perlsyn(1) manpage
172 # line 1 "$f"
173 $str
174         0;
175 }
176 1;
177 EOF
178                 $pkg->can('main');
179         }
180 }
181
182 sub _run_sub ($$$) {
183         my ($sub, $key, $argv) = @_;
184         local @ARGV = @$argv;
185         $run_script_exit_code = undef;
186         my $exit_code = eval { $sub->(@$argv) };
187         if ($@ eq RUN_SCRIPT_EXIT) {
188                 $@ = '';
189                 $exit_code = $run_script_exit_code;
190                 $? = ($exit_code << 8);
191         } elsif (defined($exit_code)) {
192                 $? = ($exit_code << 8);
193         } elsif ($@) { # mimic die() behavior when uncaught
194                 warn "E: eval-ed $key: $@\n";
195                 $? = ($! << 8) if $!;
196                 $? = (255 << 8) if $? == 0;
197         } else {
198                 die "BUG: eval-ed $key: no exit code or \$@\n";
199         }
200 }
201
202 sub run_script ($;$$) {
203         my ($cmd, $env, $opt) = @_;
204         my ($key, @argv) = @$cmd;
205         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
206         my $sub = $run_mode == 0 ? undef : key2sub($key);
207         my $fhref = [];
208         my $spawn_opt = {};
209         for my $fd (0..2) {
210                 my $redir = $opt->{$fd};
211                 my $ref = ref($redir);
212                 if ($ref eq 'SCALAR') {
213                         open my $fh, '+>', undef or die "open: $!";
214                         $fhref->[$fd] = $fh;
215                         $spawn_opt->{$fd} = $fh;
216                         next if $fd > 0;
217                         $fh->autoflush(1);
218                         print $fh $$redir or die "print: $!";
219                         seek($fh, 0, SEEK_SET) or die "seek: $!";
220                 } elsif ($ref eq 'GLOB') {
221                         $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
222                 } elsif ($ref) {
223                         die "unable to deal with $ref $redir";
224                 }
225         }
226         if ($run_mode == 0) {
227                 # spawn an independent new process, like real-world use cases:
228                 require PublicInbox::Spawn;
229                 my $cmd = [ key2script($key), @argv ];
230                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
231                 if (defined $pid) {
232                         my $r = waitpid($pid, 0);
233                         defined($r) or die "waitpid: $!";
234                         $r == $pid or die "waitpid: expected $pid, got $r";
235                 }
236         } else { # localize and run everything in the same process:
237                 # note: "local *STDIN = *STDIN;" and so forth did not work in
238                 # old versions of perl
239                 local %ENV = $env ? (%ENV, %$env) : %ENV;
240                 local %SIG = %SIG;
241                 local $0 = join(' ', @$cmd);
242                 my $orig_io = _prepare_redirects($fhref);
243                 _run_sub($sub, $key, \@argv);
244                 _undo_redirects($orig_io);
245         }
246
247         # slurp the redirects back into user-supplied strings
248         for my $fd (1..2) {
249                 my $fh = $fhref->[$fd] or next;
250                 seek($fh, 0, SEEK_SET) or die "seek: $!";
251                 my $redir = $opt->{$fd};
252                 local $/;
253                 $$redir = <$fh>;
254         }
255         $? == 0;
256 }
257
258 sub wait_for_tail () { sleep(2) }
259
260 # like system() built-in, but uses spawn() for env/rdr + vfork
261 sub xsys {
262         my ($cmd, $env, $rdr) = @_;
263         if (ref($cmd)) {
264                 $rdr ||= {};
265         } else {
266                 $cmd = [ @_ ];
267                 $env = undef;
268                 $rdr = {};
269         }
270         run_script($cmd, $env, { %$rdr, run_mode => 0 });
271         $? >> 8
272 }
273
274 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
275 sub xqx {
276         my ($cmd, $env, $rdr) = @_;
277         $rdr //= {};
278         run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
279         wantarray ? split(/^/m, $out) : $out;
280 }
281
282 sub start_script {
283         my ($cmd, $env, $opt) = @_;
284         my ($key, @argv) = @$cmd;
285         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
286         my $sub = $run_mode == 0 ? undef : key2sub($key);
287         my $tail_pid;
288         if (my $tail_cmd = $ENV{TAIL}) {
289                 my @paths;
290                 for (@argv) {
291                         next unless /\A--std(?:err|out)=(.+)\z/;
292                         push @paths, $1;
293                 }
294                 if (@paths) {
295                         defined($tail_pid = fork) or die "fork: $!\n";
296                         if ($tail_pid == 0) {
297                                 # make sure files exist, first
298                                 open my $fh, '>>', $_ for @paths;
299                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
300                                 exec(split(' ', $tail_cmd), @paths);
301                                 die "$tail_cmd failed: $!";
302                         }
303                         wait_for_tail();
304                 }
305         }
306         defined(my $pid = fork) or die "fork: $!\n";
307         if ($pid == 0) {
308                 # pretend to be systemd (cf. sd_listen_fds(3))
309                 # 3 == SD_LISTEN_FDS_START
310                 my $fd;
311                 for ($fd = 0; 1; $fd++) {
312                         my $s = $opt->{$fd};
313                         last if $fd >= 3 && !defined($s);
314                         next unless $s;
315                         my $fl = fcntl($s, F_GETFD, 0);
316                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
317                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
318                         }
319                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
320                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
321                 }
322                 %ENV = (%ENV, %$env) if $env;
323                 my $fds = $fd - 3;
324                 if ($fds > 0) {
325                         $ENV{LISTEN_PID} = $$;
326                         $ENV{LISTEN_FDS} = $fds;
327                 }
328                 $0 = join(' ', @$cmd);
329                 if ($sub) {
330                         _run_sub($sub, $key, \@argv);
331                         POSIX::_exit($? >> 8);
332                 } else {
333                         exec(key2script($key), @argv);
334                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
335                 }
336         }
337         PublicInboxTestProcess->new($pid, $tail_pid);
338 }
339
340 package PublicInboxTestProcess;
341 use strict;
342
343 # prevent new threads from inheriting these objects
344 sub CLONE_SKIP { 1 }
345
346 sub new {
347         my ($klass, $pid, $tail_pid) = @_;
348         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
349 }
350
351 sub kill {
352         my ($self, $sig) = @_;
353         CORE::kill($sig // 'TERM', $self->{pid});
354 }
355
356 sub join {
357         my ($self, $sig) = @_;
358         my $pid = delete $self->{pid} or return;
359         CORE::kill($sig, $pid) if defined $sig;
360         my $ret = waitpid($pid, 0);
361         defined($ret) or die "waitpid($pid): $!";
362         $ret == $pid or die "waitpid($pid) != $ret";
363 }
364
365 sub DESTROY {
366         my ($self) = @_;
367         return if $self->{owner} != $$;
368         if (my $tail = delete $self->{tail_pid}) {
369                 PublicInbox::TestCommon::wait_for_tail();
370                 CORE::kill('TERM', $tail);
371         }
372         $self->join('TERM');
373 }
374
375 1;