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