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