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