]> Sergey Matveev's repositories - public-inbox.git/blob - t/common.perl
t/httpd-unix: FreeBSD expects to fail with EADDRINUSE
[public-inbox.git] / t / common.perl
1 # Copyright (C) 2015-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
5 use POSIX qw(dup2);
6 use strict;
7 use warnings;
8 use IO::Socket::INET;
9
10 sub tmpdir (;$) {
11         my ($base) = @_;
12         require File::Temp;
13         unless (defined $base) {
14                 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
15         }
16         my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
17         ($tmpdir->dirname, $tmpdir);
18 }
19
20 sub tcp_server () {
21         IO::Socket::INET->new(
22                 LocalAddr => '127.0.0.1',
23                 ReuseAddr => 1,
24                 Proto => 'tcp',
25                 Type => Socket::SOCK_STREAM(),
26                 Listen => 1024,
27                 Blocking => 0,
28         )
29 }
30
31 sub tcp_connect {
32         my ($dest, %opt) = @_;
33         my $s = IO::Socket::INET->new(
34                 Proto => 'tcp',
35                 Type => Socket::SOCK_STREAM(),
36                 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
37                 %opt,
38         );
39         $s->autoflush(1);
40         $s;
41 }
42
43 sub require_git ($;$) {
44         my ($req, $maybe) = @_;
45         my ($req_maj, $req_min) = split(/\./, $req);
46         my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
47
48         my $req_int = ($req_maj << 24) | ($req_min << 16);
49         my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
50         if ($cur_int < $req_int) {
51                 return 0 if $maybe;
52                 plan skip_all => "git $req+ required, have $cur_maj.$cur_min";
53         }
54         1;
55 }
56
57 sub key2script ($) {
58         my ($key) = @_;
59         return $key if $key =~ m!\A/!;
60         # n.b. we may have scripts which don't start with "public-inbox" in
61         # the future:
62         $key =~ s/\A([-\.])/public-inbox$1/;
63         'blib/script/'.$key;
64 }
65
66 sub _prepare_redirects ($) {
67         my ($fhref) = @_;
68         my @x = ([ \*STDIN, '<&' ], [ \*STDOUT, '>&' ], [ \*STDERR, '>&' ]);
69         for (my $fd = 0; $fd <= $#x; $fd++) {
70                 my $fh = $fhref->[$fd] or next;
71                 my ($oldfh, $mode) = @{$x[$fd]};
72                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
73         }
74 }
75
76 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
77 # three ways to spawn our own short-lived Perl scripts for testing:
78 #
79 # 0 - (fork|vfork) + execve, the most realistic but slowest
80 # 1 - preloading and running in a forked subprocess (fast)
81 # 2 - preloading and running in current process (slightly faster than 1)
82 #
83 # 2 is not compatible with scripts which use "exit" (which we'll try to
84 # avoid in the future).
85 # The default is 2.
86 our $run_script_exit_code;
87 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
88 sub run_script_exit (;$) {
89         $run_script_exit_code = $_[0] // 0;
90         die RUN_SCRIPT_EXIT;
91 }
92
93 my %cached_scripts;
94 sub key2sub ($) {
95         my ($key) = @_;
96         $cached_scripts{$key} //= do {
97                 my $f = key2script($key);
98                 open my $fh, '<', $f or die "open $f: $!";
99                 my $str = do { local $/; <$fh> };
100                 my ($fc, $rest) = ($key =~ m/([a-z])([a-z0-9]+)\z/);
101                 $fc = uc($fc);
102                 my $pkg = "PublicInbox::TestScript::$fc$rest";
103                 eval <<EOF;
104 package $pkg;
105 use strict;
106 use subs qw(exit);
107
108 *exit = *::run_script_exit;
109 sub main {
110 $str
111         0;
112 }
113 1;
114 EOF
115                 $pkg->can('main');
116         }
117 }
118
119 sub _run_sub ($$$) {
120         my ($sub, $key, $argv) = @_;
121         local @ARGV = @$argv;
122         $run_script_exit_code = undef;
123         my $exit_code = eval { $sub->(@$argv) };
124         if ($@ eq RUN_SCRIPT_EXIT) {
125                 $@ = '';
126                 $exit_code = $run_script_exit_code;
127                 $? = ($exit_code << 8);
128         } elsif (defined($exit_code)) {
129                 $? = ($exit_code << 8);
130         } elsif ($@) { # mimic die() behavior when uncaught
131                 warn "E: eval-ed $key: $@\n";
132                 $? = ($! << 8) if $!;
133                 $? = (255 << 8) if $? == 0;
134         } else {
135                 die "BUG: eval-ed $key: no exit code or \$@\n";
136         }
137 }
138
139 sub run_script ($;$$) {
140         my ($cmd, $env, $opt) = @_;
141         my ($key, @argv) = @$cmd;
142         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
143         my $sub = $run_mode == 0 ? undef : key2sub($key);
144         my $fhref = [];
145         my $spawn_opt = {};
146         for my $fd (0..2) {
147                 my $redir = $opt->{$fd};
148                 next unless ref($redir);
149                 open my $fh, '+>', undef or die "open: $!";
150                 $fhref->[$fd] = $fh;
151                 $spawn_opt->{$fd} = fileno($fh);
152                 next if $fd > 0;
153                 $fh->autoflush(1);
154                 print $fh $$redir or die "print: $!";
155                 seek($fh, 0, SEEK_SET) or die "seek: $!";
156         }
157         if ($run_mode == 0) {
158                 # spawn an independent new process, like real-world use cases:
159                 require PublicInbox::Spawn;
160                 my $cmd = [ key2script($key), @argv ];
161                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
162                 defined($pid) or die "spawn: $!";
163                 if (defined $pid) {
164                         my $r = waitpid($pid, 0);
165                         defined($r) or die "waitpid: $!";
166                         $r == $pid or die "waitpid: expected $pid, got $r";
167                 }
168         } else { # localize and run everything in the same process:
169                 local *STDIN = *STDIN;
170                 local *STDOUT = *STDOUT;
171                 local *STDERR = *STDERR;
172                 local %ENV = $env ? (%ENV, %$env) : %ENV;
173                 local %SIG = %SIG;
174                 _prepare_redirects($fhref);
175                 _run_sub($sub, $key, \@argv);
176         }
177
178         # slurp the redirects back into user-supplied strings
179         for my $fd (1..2) {
180                 my $fh = $fhref->[$fd] or next;
181                 seek($fh, 0, SEEK_SET) or die "seek: $!";
182                 my $redir = $opt->{$fd};
183                 local $/;
184                 $$redir = <$fh>;
185         }
186         $? == 0;
187 }
188
189 sub wait_for_tail () { sleep(2) }
190
191 sub start_script {
192         my ($cmd, $env, $opt) = @_;
193         my ($key, @argv) = @$cmd;
194         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
195         my $sub = $run_mode == 0 ? undef : key2sub($key);
196         my $tail_pid;
197         if (my $tail_cmd = $ENV{TAIL}) {
198                 my @paths;
199                 for (@argv) {
200                         next unless /\A--std(?:err|out)=(.+)\z/;
201                         push @paths, $1;
202                 }
203                 if (@paths) {
204                         defined($tail_pid = fork) or die "fork: $!\n";
205                         if ($tail_pid == 0) {
206                                 # make sure files exist, first
207                                 open my $fh, '>>', $_ for @paths;
208                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
209                                 exec(split(' ', $tail_cmd), @paths);
210                                 die "$tail_cmd failed: $!";
211                         }
212                         wait_for_tail();
213                 }
214         }
215         defined(my $pid = fork) or die "fork: $!\n";
216         if ($pid == 0) {
217                 # pretend to be systemd (cf. sd_listen_fds(3))
218                 # 3 == SD_LISTEN_FDS_START
219                 my $fd;
220                 for ($fd = 0; 1; $fd++) {
221                         my $s = $opt->{$fd};
222                         last if $fd >= 3 && !defined($s);
223                         next unless $s;
224                         my $fl = fcntl($s, F_GETFD, 0);
225                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
226                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
227                         }
228                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
229                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
230                 }
231                 %ENV = (%ENV, %$env) if $env;
232                 my $fds = $fd - 3;
233                 if ($fds > 0) {
234                         $ENV{LISTEN_PID} = $$;
235                         $ENV{LISTEN_FDS} = $fds;
236                 }
237                 $0 = join(' ', @$cmd);
238                 if ($sub) {
239                         _run_sub($sub, $key, \@argv);
240                         POSIX::_exit($? >> 8);
241                 } else {
242                         exec(key2script($key), @argv);
243                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
244                 }
245         }
246         TestProcess->new($pid, $tail_pid);
247 }
248
249 package TestProcess;
250 use strict;
251
252 # prevent new threads from inheriting these objects
253 sub CLONE_SKIP { 1 }
254
255 sub new {
256         my ($klass, $pid, $tail_pid) = @_;
257         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
258 }
259
260 sub kill {
261         my ($self, $sig) = @_;
262         CORE::kill($sig // 'TERM', $self->{pid});
263 }
264
265 sub join {
266         my ($self) = @_;
267         my $pid = delete $self->{pid} or return;
268         my $ret = waitpid($pid, 0);
269         defined($ret) or die "waitpid($pid): $!";
270         $ret == $pid or die "waitpid($pid) != $ret";
271 }
272
273 sub DESTROY {
274         my ($self) = @_;
275         return if $self->{owner} != $$;
276         if (my $tail = delete $self->{tail_pid}) {
277                 ::wait_for_tail();
278                 CORE::kill('TERM', $tail);
279         }
280         my $pid = delete $self->{pid} or return;
281         CORE::kill('TERM', $pid);
282 }
283
284 1;