2 # Copyright (C) 2019-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
5 # Parallel test runner which preloads code and reuses worker processes
6 # to give a nice speedup over prove(1). It also generates per-test
7 # .log files (similar to automake tests).
9 # *.t files run by this should not rely on global state.
11 # Usage: $PERL -I lib -w t/run.perl -j4
12 # Or via prove(1): prove -lvw t/run.perl :: -j4
15 use IO::Handle; # ->autoflush
16 use PublicInbox::TestCommon;
17 use PublicInbox::Spawn;
18 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
21 use POSIX qw(WNOHANG);
26 our $log_suffix = '.log';
27 my ($shuffle, %pids, @err);
28 GetOptions('j|jobs=i' => \$jobs,
29 'repeat=i' => \$repeat,
30 'log=s' => \$log_suffix,
31 's|shuffle' => \$shuffle,
32 ) or die "Usage: $0 [-j JOBS] [--log=SUFFIX] [--repeat RUNS]";
33 if (($ENV{TEST_RUN_MODE} // 2) == 0) {
34 die "$0 is not compatible with TEST_RUN_MODE=0\n";
36 my @tests = scalar(@ARGV) ? @ARGV : glob('t/*.t');
37 open my $cwd_fh, '<', '.' or die "open .: $!";
38 open my $OLDOUT, '>&STDOUT' or die "dup STDOUT: $!";
39 open my $OLDERR, '>&STDERR' or die "dup STDERR: $!";
40 $OLDOUT->autoflush(1);
41 $OLDERR->autoflush(1);
43 my ($run_log, $tmp_rl);
44 my $rl = $ENV{TEST_RUN_LOG};
46 $tmp_rl = File::Temp->new(CLEANUP => 1);
47 $rl = $tmp_rl->filename;
49 open $run_log, '+>>', $rl or die "open $rl: $!";
50 $run_log->autoflush(1); # one reader, many writers
52 key2sub($_) for @tests; # precache
54 my ($for_destroy, $lei_env, $lei_daemon_pid, $owner_pid);
56 # TEST_LEI_DAEMON_PERSIST is currently broken. I get ECONNRESET from
57 # lei even with high kern.ipc.soacceptqueue=1073741823 or SOMAXCONN, not
58 # sure why. Also, testing our internal inotify usage is unreliable
59 # because lei-daemon uses a single inotify FD for all clients.
60 if ($ENV{TEST_LEI_DAEMON_PERSIST} && !$ENV{TEST_LEI_DAEMON_PERSIST_DIR} &&
61 (PublicInbox::Spawn->can('recv_cmd4') ||
62 eval { require Socket::MsgHdr })) {
64 ($lei_env->{XDG_RUNTIME_DIR}, $for_destroy) = tmpdir;
65 $ENV{TEST_LEI_DAEMON_PERSIST_DIR} = $lei_env->{XDG_RUNTIME_DIR};
66 run_script([qw(lei daemon-pid)], $lei_env, { 1 => \$lei_daemon_pid });
67 chomp $lei_daemon_pid;
68 $lei_daemon_pid =~ /\A[0-9]+\z/ or die "no daemon pid: $lei_daemon_pid";
69 kill(0, $lei_daemon_pid) or die "kill $lei_daemon_pid: $!";
70 if (my $t = $ENV{GNU_TAIL}) {
71 system("$t --pid=$lei_daemon_pid -F " .
72 "$lei_env->{XDG_RUNTIME_DIR}/lei/errors.log >&2 &");
74 if (my $strace_cmd = $ENV{STRACE_CMD}) {
75 system("$strace_cmd -p $lei_daemon_pid &");
82 } elsif (open(my $prove_state, '<', '.prove') && eval { require YAML::XS }) {
83 # reuse "prove --state=save" data to start slowest tests, first
84 my $state = YAML::XS::Load(do { local $/; <$prove_state> });
85 my $t = $state->{tests};
87 ($t->{$b}->{elapsed} // 0) <=> ($t->{$a}->{elapsed} // 0)
91 our $tb = Test::More->builder;
98 our ($worker, $worker_test);
101 $? = 255 if $? == 0 && !$tb->is_passing;
102 my $status = $? ? 'not ok' : 'ok';
103 chdir($cwd_fh) or DIE "fchdir: $!";
104 if ($log_suffix ne '') {
105 my $log = $worker_test;
106 $log =~ s/\.t\z/$log_suffix/;
108 if (open my $fh, '<', $log) {
109 my @not_ok = grep(!/^(?:ok |[ \t]*#)/ms, <$fh>);
110 my $last = $not_ok[-1] // '';
111 pop @not_ok if $last =~ /^[0-9]+\.\.[0-9]+$/;
112 my $pfx = "# $log: ";
113 print $OLDERR map { $pfx.$_ } @not_ok;
114 seek($fh, 0, SEEK_SET) or die "seek: $!";
116 # show unique skip texts and the number of times
117 # each text was skipped
119 my @sk = (<$fh> =~ m/^ok [0-9]+ (# skip [^\n]+)/mgs);
122 my @err = grep { !$nr{$_}++ } @sk;
123 print $OLDERR "$pfx$_ ($nr{$_})\n" for @err;
124 $skip = ' # total skipped: '.scalar(@sk);
127 print $OLDERR "could not open: $log: $!\n";
129 print $OLDOUT "$status $worker_test$skip\n";
133 # Test::Builder or Test2::Hub may call exit() from plan(skip_all => ...)
134 END { test_status() if (defined($worker_test) && $worker == $$) }
138 syswrite($run_log, "$$ $test\n");
140 if ($log_suffix ne '') {
142 $log =~ s/\.[^\.]+\z/$log_suffix/ or DIE "can't log for $test";
143 open $log_fh, '>', $log or DIE "open $log: $!";
144 $log_fh->autoflush(1);
145 $tb->output($log_fh);
146 $tb->failure_output($log_fh);
147 $tb->todo_output($log_fh);
148 open STDOUT, '>&', $log_fh or DIE "1>$log: $!";
149 open STDERR, '>&', $log_fh or DIE "2>$log: $!";
151 $worker_test = $test;
154 $worker_test = undef;
155 push @err, "$test ($?)" if $?;
158 sub UINT_SIZE () { 4 }
160 # worker processes will SIGUSR1 the producer process when it
161 # sees EOF on the pipe. On FreeBSD 11.2 and Perl 5.30.0,
162 # sys/ioctl.ph gives the wrong value for FIONREAD().
164 my $eof; # we stop respawning if true
166 my $start_worker = sub {
167 my ($j, $rd, $wr, $todo) = @_;
168 my $pid = fork // DIE "fork: $!";
171 $SIG{USR1} = undef; # undo parent $SIG{USR1}
174 my $r = sysread($rd, my $buf, UINT_SIZE);
180 DIE "short read $r" if $r != UINT_SIZE;
181 my $t = unpack('I', $buf);
182 run_test($todo->[$t]);
185 kill 'USR1', $producer if !$eof; # sets $eof in $producer
186 if (@err) { # write to run_log for $sigchld handler
187 syswrite($run_log, "$$ @err\n");
188 DIE join('', map { "E: $_\n" } @err);
196 # negative $repeat means loop forever:
197 for (my $i = $repeat; $i != 0; $i--) {
198 my @todo = $shuffle ? List::Util::shuffle(@tests) : @tests;
200 # single-producer, multi-consumer queue relying on POSIX pipe semantics
201 # POSIX.1-2008 stipulates a regular file should work, but Linux <3.14
202 # had broken read(2) semantics according to the read(2) manpage
203 pipe(my ($rd, $wr)) or DIE "pipe: $!";
205 # fill the queue before forking so children can start earlier
206 my $n = (POSIX::PIPE_BUF / UINT_SIZE);
208 print $wr join('', map { pack('I', $_) } (0..$#todo)) or DIE;
210 } else { # write what we can...
212 print $wr join('', map { pack('I', $_) } (0..$n)) or DIE;
213 $n += 1; # and send more ($n..$#todo), later
216 local $SIG{USR1} = sub { $eof = 1 };
219 my $flags = $sig ? WNOHANG : 0;
221 my $pid = waitpid(-1, $flags) or return;
223 my $j = delete $pids{$pid};
225 push @err, "reaped unknown $pid ($?)";
229 seek($run_log, 0, SEEK_SET);
230 chomp(my @t = grep(/^$pid /, <$run_log>));
231 $t[0] //= "$pid unknown";
232 push @err, "job[$j] ($?) PID=$t[-1]";
234 # skip_all can exit(0), respawn if needed:
236 print $OLDERR "# respawning job[$j]\n";
237 $start_worker->($j, $rd, $wr, \@todo);
242 # start the workers to consume the queue
243 for (my $j = 0; $j < $jobs; $j++) {
244 $start_worker->($j, $rd, $wr, \@todo);
247 local $SIG{CHLD} = $sigchld;
248 # too many tests to fit in the pipe before starting workers,
249 # send the rest now the workers are running
250 print $wr join('', map { pack('I', $_) } ($n..$#todo)) or DIE;
254 $sigchld->(0) while scalar(keys(%pids));
255 DIE join('', map { "E: $_\n" } @err) if @err;
258 print $OLDOUT "1..".($repeat * scalar(@tests))."\n" if $repeat >= 0;
259 if ($lei_env && $$ == $owner_pid) {
260 my $opt = { 1 => $OLDOUT, 2 => $OLDERR };
262 run_script([qw(lei daemon-pid)], $lei_env, { 1 => \$cur_daemon_pid });
263 run_script([qw(lei daemon-kill)], $lei_env, $opt);
264 DIE "lei daemon restarted\n" if $cur_daemon_pid != $lei_daemon_pid;