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