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