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