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