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