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