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