]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
lei: XDG_RUNTIME_DIR=/dev/null disables daemon mode
[public-inbox.git] / lib / PublicInbox / TestCommon.pm
1 # Copyright (C) 2015-2021 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 use File::Spec;
13 our @EXPORT;
14 my $lei_loud = $ENV{TEST_LEI_ERR_LOUD};
15 BEGIN {
16         @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
17                 run_script start_script key2sub xsys xsys_e xqx eml_load tick
18                 have_xapian_compact json_utf8 setup_public_inboxes create_inbox
19                 tcp_host_port test_lei lei lei_ok $lei_out $lei_err $lei_opt
20                 test_httpd xbail);
21         require Test::More;
22         my @methods = grep(!/\W/, @Test::More::EXPORT);
23         eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
24         die $@ if $@;
25         push @EXPORT, @methods;
26 }
27
28 sub xbail (@) { BAIL_OUT join(' ', map { ref() ? (explain($_)) : ($_) } @_) }
29
30 sub eml_load ($) {
31         my ($path, $cb) = @_;
32         open(my $fh, '<', $path) or die "open $path: $!";
33         require PublicInbox::Eml;
34         PublicInbox::Eml->new(\(do { local $/; <$fh> }));
35 }
36
37 sub tmpdir (;$) {
38         my ($base) = @_;
39         require File::Temp;
40         unless (defined $base) {
41                 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
42         }
43         my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXX", TMPDIR => 1);
44         ($tmpdir->dirname, $tmpdir);
45 }
46
47 sub tcp_server () {
48         my %opt = (
49                 ReuseAddr => 1,
50                 Proto => 'tcp',
51                 Type => Socket::SOCK_STREAM(),
52                 Listen => 1024,
53                 Blocking => 0,
54         );
55         eval {
56                 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
57                 require IO::Socket::INET6;
58                 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
59         } || eval {
60                 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
61                 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
62         } || BAIL_OUT "failed to create TCP server: $! ($@)";
63 }
64
65 sub tcp_host_port ($) {
66         my ($s) = @_;
67         my ($h, $p) = ($s->sockhost, $s->sockport);
68         my $ipv4 = $s->sockdomain == Socket::AF_INET();
69         if (wantarray) {
70                 $ipv4 ? ($h, $p) : ("[$h]", $p);
71         } else {
72                 $ipv4 ? "$h:$p" : "[$h]:$p";
73         }
74 }
75
76 sub tcp_connect {
77         my ($dest, %opt) = @_;
78         my $addr = tcp_host_port($dest);
79         my $s = ref($dest)->new(
80                 Proto => 'tcp',
81                 Type => Socket::SOCK_STREAM(),
82                 PeerAddr => $addr,
83                 %opt,
84         ) or BAIL_OUT "failed to connect to $addr: $!";
85         $s->autoflush(1);
86         $s;
87 }
88
89 sub require_git ($;$) {
90         my ($req, $maybe) = @_;
91         my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
92         my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
93                         =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
94
95         my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
96         my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
97         if ($cur_int < $req_int) {
98                 return 0 if $maybe;
99                 plan skip_all =>
100                         "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
101         }
102         1;
103 }
104
105 sub require_mods {
106         my @mods = @_;
107         my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
108         my @need;
109         while (my $mod = shift(@mods)) {
110                 if ($mod eq 'lei') {
111                         require_git(2.6, $maybe ? $maybe : ());
112                         push @mods, qw(DBD::SQLite Search::Xapian);
113                         $mod = 'json'; # fall-through
114                 }
115                 if ($mod eq 'json') {
116                         $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||JSON||JSON::PP'
117                 } elsif ($mod eq '-httpd') {
118                         push @mods, qw(Plack::Builder Plack::Util);
119                         next;
120                 } elsif ($mod eq '-imapd') {
121                         push @mods, qw(Parse::RecDescent DBD::SQLite
122                                         Email::Address::XS||Mail::Address);
123                         next;
124                 } elsif ($mod eq '-nntpd') {
125                         push @mods, qw(DBD::SQLite);
126                         next;
127                 }
128                 if ($mod eq 'Search::Xapian') {
129                         if (eval { require PublicInbox::Search } &&
130                                 PublicInbox::Search::load_xapian()) {
131                                 next;
132                         }
133                 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
134                         my $ok;
135                         for my $m (split(/\Q||\E/, $mod)) {
136                                 eval "require $m";
137                                 next if $@;
138                                 $ok = $m;
139                                 last;
140                         }
141                         next if $ok;
142                 } else {
143                         eval "require $mod";
144                 }
145                 if ($@) {
146                         push @need, $mod;
147                 } elsif ($mod eq 'IO::Socket::SSL' &&
148                         # old versions of IO::Socket::SSL aren't supported
149                         # by libnet, at least:
150                         # https://rt.cpan.org/Ticket/Display.html?id=100529
151                                 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
152                         push @need, $@;
153                 }
154         }
155         return unless @need;
156         my $m = join(', ', @need)." missing for $0";
157         skip($m, $maybe) if $maybe;
158         plan(skip_all => $m)
159 }
160
161 sub key2script ($) {
162         my ($key) = @_;
163         return $key if ($key eq 'git' || index($key, '/') >= 0);
164         # n.b. we may have scripts which don't start with "public-inbox" in
165         # the future:
166         $key =~ s/\A([-\.])/public-inbox$1/;
167         'blib/script/'.$key;
168 }
169
170 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
171                 [ *STDERR{IO}, '+>&' ]);
172
173 sub _prepare_redirects ($) {
174         my ($fhref) = @_;
175         my $orig_io = [];
176         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
177                 my $fh = $fhref->[$fd] or next;
178                 my ($oldfh, $mode) = @{$io_mode[$fd]};
179                 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
180                 $orig_io->[$fd] = $orig;
181                 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
182         }
183         $orig_io;
184 }
185
186 sub _undo_redirects ($) {
187         my ($orig_io) = @_;
188         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
189                 my $fh = $orig_io->[$fd] or next;
190                 my ($oldfh, $mode) = @{$io_mode[$fd]};
191                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
192         }
193 }
194
195 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
196 # three ways to spawn our own short-lived Perl scripts for testing:
197 #
198 # 0 - (fork|vfork) + execve, the most realistic but slowest
199 # 1 - (not currently implemented)
200 # 2 - preloading and running in current process (slightly faster than 1)
201 #
202 # 2 is not compatible with scripts which use "exit" (which we'll try to
203 # avoid in the future).
204 # The default is 2.
205 our $run_script_exit_code;
206 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
207 sub run_script_exit {
208         $run_script_exit_code = $_[0] // 0;
209         die RUN_SCRIPT_EXIT;
210 }
211
212 our %cached_scripts;
213 sub key2sub ($) {
214         my ($key) = @_;
215         $cached_scripts{$key} //= do {
216                 my $f = key2script($key);
217                 open my $fh, '<', $f or die "open $f: $!";
218                 my $str = do { local $/; <$fh> };
219                 my $pkg = (split(m!/!, $f))[-1];
220                 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
221                 $pkg .= "_T" if $3;
222                 $pkg =~ tr/-.//d;
223                 $pkg = "PublicInbox::TestScript::$pkg";
224                 eval <<EOF;
225 package $pkg;
226 use strict;
227 use subs qw(exit);
228
229 *exit = \\&PublicInbox::TestCommon::run_script_exit;
230 sub main {
231 # the below "line" directive is a magic comment, see perlsyn(1) manpage
232 # line 1 "$f"
233 $str
234         0;
235 }
236 1;
237 EOF
238                 $pkg->can('main');
239         }
240 }
241
242 sub _run_sub ($$$) {
243         my ($sub, $key, $argv) = @_;
244         local @ARGV = @$argv;
245         $run_script_exit_code = undef;
246         my $exit_code = eval { $sub->(@$argv) };
247         if ($@ eq RUN_SCRIPT_EXIT) {
248                 $@ = '';
249                 $exit_code = $run_script_exit_code;
250                 $? = ($exit_code << 8);
251         } elsif (defined($exit_code)) {
252                 $? = ($exit_code << 8);
253         } elsif ($@) { # mimic die() behavior when uncaught
254                 warn "E: eval-ed $key: $@\n";
255                 $? = ($! << 8) if $!;
256                 $? = (255 << 8) if $? == 0;
257         } else {
258                 die "BUG: eval-ed $key: no exit code or \$@\n";
259         }
260 }
261
262 sub run_script ($;$$) {
263         my ($cmd, $env, $opt) = @_;
264         my ($key, @argv) = @$cmd;
265         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
266         my $sub = $run_mode == 0 ? undef : key2sub($key);
267         my $fhref = [];
268         my $spawn_opt = {};
269         for my $fd (0..2) {
270                 my $redir = $opt->{$fd};
271                 my $ref = ref($redir);
272                 if ($ref eq 'SCALAR') {
273                         open my $fh, '+>', undef or die "open: $!";
274                         $fhref->[$fd] = $fh;
275                         $spawn_opt->{$fd} = $fh;
276                         next if $fd > 0;
277                         $fh->autoflush(1);
278                         print $fh $$redir or die "print: $!";
279                         seek($fh, 0, SEEK_SET) or die "seek: $!";
280                 } elsif ($ref eq 'GLOB') {
281                         $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
282                 } elsif ($ref) {
283                         die "unable to deal with $ref $redir";
284                 }
285         }
286         if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
287                 unshift @argv, '--no-fsync';
288         }
289         if ($run_mode == 0) {
290                 # spawn an independent new process, like real-world use cases:
291                 require PublicInbox::Spawn;
292                 my $cmd = [ key2script($key), @argv ];
293                 if (my $d = $opt->{'-C'}) {
294                         $cmd->[0] = File::Spec->rel2abs($cmd->[0]);
295                         $spawn_opt->{'-C'} = $d;
296                 }
297                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
298                 if (defined $pid) {
299                         my $r = waitpid($pid, 0) // die "waitpid: $!";
300                         $r == $pid or die "waitpid: expected $pid, got $r";
301                 }
302         } else { # localize and run everything in the same process:
303                 # note: "local *STDIN = *STDIN;" and so forth did not work in
304                 # old versions of perl
305                 local %ENV = $env ? (%ENV, %$env) : %ENV;
306                 local %SIG = %SIG;
307                 local $0 = join(' ', @$cmd);
308                 my $orig_io = _prepare_redirects($fhref);
309                 my $cwdfh;
310                 if (my $d = $opt->{'-C'}) {
311                         opendir $cwdfh, '.' or die "opendir .: $!";
312                         chdir $d or die "chdir $d: $!";
313                 }
314                 _run_sub($sub, $key, \@argv);
315                 eval { PublicInbox::Inbox::cleanup_task() };
316                 die "chdir(restore): $!" if $cwdfh && !chdir($cwdfh);
317                 _undo_redirects($orig_io);
318                 select STDOUT;
319         }
320
321         # slurp the redirects back into user-supplied strings
322         for my $fd (1..2) {
323                 my $fh = $fhref->[$fd] or next;
324                 seek($fh, 0, SEEK_SET) or die "seek: $!";
325                 my $redir = $opt->{$fd};
326                 local $/;
327                 $$redir = <$fh>;
328         }
329         $? == 0;
330 }
331
332 sub tick (;$) {
333         my $tick = shift // 0.1;
334         select undef, undef, undef, $tick;
335         1;
336 }
337
338 sub wait_for_tail ($;$) {
339         my ($tail_pid, $want) = @_;
340         my $wait = 2;
341         if ($^O eq 'linux') { # GNU tail may use inotify
342                 state $tail_has_inotify;
343                 return tick if $want < 0 && $tail_has_inotify;
344                 my $end = time + $wait;
345                 my @ino;
346                 do {
347                         @ino = grep {
348                                 readlink($_) =~ /\binotify\b/
349                         } glob("/proc/$tail_pid/fd/*");
350                 } while (!@ino && time <= $end and tick);
351                 return if !@ino;
352                 $tail_has_inotify = 1;
353                 $ino[0] =~ s!/fd/!/fdinfo/!;
354                 my @info;
355                 do {
356                         if (open my $fh, '<', $ino[0]) {
357                                 local $/ = "\n";
358                                 @info = grep(/^inotify wd:/, <$fh>);
359                         }
360                 } while (scalar(@info) < $want && time <= $end and tick);
361         } else {
362                 sleep($wait);
363         }
364 }
365
366 # like system() built-in, but uses spawn() for env/rdr + vfork
367 sub xsys {
368         my ($cmd, $env, $rdr) = @_;
369         if (ref($cmd)) {
370                 $rdr ||= {};
371         } else {
372                 $cmd = [ @_ ];
373                 $env = undef;
374                 $rdr = {};
375         }
376         run_script($cmd, $env, { %$rdr, run_mode => 0 });
377         $? >> 8
378 }
379
380 sub xsys_e { # like "/bin/sh -e"
381         xsys(@_) == 0 or
382                 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
383 }
384
385 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
386 sub xqx {
387         my ($cmd, $env, $rdr) = @_;
388         $rdr //= {};
389         run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
390         wantarray ? split(/^/m, $out) : $out;
391 }
392
393 sub start_script {
394         my ($cmd, $env, $opt) = @_;
395         my ($key, @argv) = @$cmd;
396         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
397         my $sub = $run_mode == 0 ? undef : key2sub($key);
398         my $tail_pid;
399         if (my $tail_cmd = $ENV{TAIL}) {
400                 my @paths;
401                 for (@argv) {
402                         next unless /\A--std(?:err|out)=(.+)\z/;
403                         push @paths, $1;
404                 }
405                 if ($opt) {
406                         for (1, 2) {
407                                 my $f = $opt->{$_} or next;
408                                 if (!ref($f)) {
409                                         push @paths, $f;
410                                 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
411                                         my $fd = fileno($f);
412                                         my $f = readlink "/proc/$$/fd/$fd";
413                                         push @paths, $f if -e $f;
414                                 }
415                         }
416                 }
417                 if (@paths) {
418                         $tail_pid = fork // die "fork: $!";
419                         if ($tail_pid == 0) {
420                                 # make sure files exist, first
421                                 open my $fh, '>>', $_ for @paths;
422                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
423                                 exec(split(' ', $tail_cmd), @paths);
424                                 die "$tail_cmd failed: $!";
425                         }
426                         wait_for_tail($tail_pid, scalar @paths);
427                 }
428         }
429         my $pid = fork // die "fork: $!\n";
430         if ($pid == 0) {
431                 eval { PublicInbox::DS->Reset };
432                 # pretend to be systemd (cf. sd_listen_fds(3))
433                 # 3 == SD_LISTEN_FDS_START
434                 my $fd;
435                 for ($fd = 0; 1; $fd++) {
436                         my $s = $opt->{$fd};
437                         last if $fd >= 3 && !defined($s);
438                         next unless $s;
439                         my $fl = fcntl($s, F_GETFD, 0);
440                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
441                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
442                         }
443                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
444                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
445                 }
446                 %ENV = (%ENV, %$env) if $env;
447                 my $fds = $fd - 3;
448                 if ($fds > 0) {
449                         $ENV{LISTEN_PID} = $$;
450                         $ENV{LISTEN_FDS} = $fds;
451                 }
452                 $0 = join(' ', @$cmd);
453                 if ($sub) {
454                         eval { PublicInbox::DS->Reset };
455                         _run_sub($sub, $key, \@argv);
456                         POSIX::_exit($? >> 8);
457                 } else {
458                         exec(key2script($key), @argv);
459                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
460                 }
461         }
462         PublicInboxTestProcess->new($pid, $tail_pid);
463 }
464
465 sub have_xapian_compact () {
466         require PublicInbox::Spawn;
467         # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
468         PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
469 }
470
471 our ($lei_opt, $lei_out, $lei_err);
472 # favor lei() or lei_ok() over $lei for new code
473 sub lei (@) {
474         my ($cmd, $env, $xopt) = @_;
475         $lei_out = $lei_err = '';
476         if (!ref($cmd)) {
477                 ($env, $xopt) = grep { (!defined) || ref } @_;
478                 $cmd = [ grep { defined && !ref } @_ ];
479         }
480         my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
481         if ($lei_err ne '') {
482                 if ($lei_err =~ /Use of uninitialized/ ||
483                         $lei_err =~ m!\bArgument .*? isn't numeric in !) {
484                         fail "lei_err=$lei_err";
485                 } else {
486                         diag "lei_err=$lei_err" if $lei_loud;
487                 }
488         }
489         $res;
490 };
491
492 sub lei_ok (@) {
493         state $PWD = $ENV{PWD} // Cwd::getcwd();
494         my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
495         my $tmpdir = quotemeta(File::Spec->tmpdir);
496         # filter out anything that looks like a path name for consistent logs
497         my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
498         if (!$lei_loud) {
499                 for (@msg) {
500                         s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/!;
501                         s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!g;
502                         s!\Q$PWD\E\b!\$PWD!g;
503                 }
504         }
505         ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or
506                 diag "\$?=$? err=$lei_err";
507 }
508
509 sub json_utf8 () {
510         state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
511 }
512
513 sub test_lei {
514 SKIP: {
515         my ($cb) = pop @_;
516         my $test_opt = shift // {};
517         require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
518         require_mods(qw(json DBD::SQLite Search::Xapian), 2);
519         require PublicInbox::Config;
520         local %ENV = %ENV;
521         delete $ENV{XDG_DATA_HOME};
522         delete $ENV{XDG_CONFIG_HOME};
523         $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
524         $ENV{GIT_COMMITTER_NAME} = 'lei user';
525         my (undef, $fn, $lineno) = caller(0);
526         my $t = "$fn:$lineno";
527         require PublicInbox::Spawn;
528         state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
529                                 eval { require Socket::MsgHdr; 1 };
530         # XXX fix and move this inside daemon-only before 1.7 release
531         skip <<'EOM', 1 unless $lei_daemon;
532 Socket::MsgHdr missing or Inline::C is unconfigured/missing
533 EOM
534         $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
535         my ($daemon_pid, $for_destroy, $daemon_xrd);
536         my $tmpdir = $test_opt->{tmpdir};
537         ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
538         state $persist_xrd = $ENV{TEST_LEI_DAEMON_PERSIST_DIR};
539         SKIP: {
540                 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
541                 my $home = "$tmpdir/lei-daemon";
542                 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
543                 local $ENV{HOME} = $home;
544                 my $persist;
545                 if ($persist_xrd && !$test_opt->{daemon_only}) {
546                         $persist = $daemon_xrd = $persist_xrd;
547                 } else {
548                         $daemon_xrd = "$home/xdg_run";
549                         mkdir($daemon_xrd, 0700) or BAIL_OUT "mkdir: $!";
550                 }
551                 local $ENV{XDG_RUNTIME_DIR} = $daemon_xrd;
552                 $cb->();
553                 unless ($persist) {
554                         lei_ok(qw(daemon-pid), \"daemon-pid after $t");
555                         chomp($daemon_pid = $lei_out);
556                         if (!$daemon_pid) {
557                                 fail("daemon not running after $t");
558                                 skip 'daemon died unexpectedly', 2;
559                         }
560                         ok(kill(0, $daemon_pid), "daemon running after $t");
561                         lei_ok(qw(daemon-kill), \"daemon-kill after $t");
562                 }
563         }; # SKIP for lei_daemon
564         unless ($test_opt->{daemon_only}) {
565                 $ENV{TEST_LEI_DAEMON_ONLY} and
566                         skip 'TEST_LEI_DAEMON_ONLY set', 1;
567                 require_ok 'PublicInbox::LEI';
568                 my $home = "$tmpdir/lei-oneshot";
569                 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
570                 local $ENV{HOME} = $home;
571                 local $ENV{XDG_RUNTIME_DIR} = '/dev/null';
572                 $cb->();
573         }
574         if ($daemon_pid) {
575                 for (0..10) {
576                         kill(0, $daemon_pid) or last;
577                         tick;
578                 }
579                 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
580                 my $f = "$daemon_xrd/lei/errors.log";
581                 open my $fh, '<', $f or BAIL_OUT "$f: $!";
582                 my @l = <$fh>;
583                 is_deeply(\@l, [],
584                         "$t daemon XDG_RUNTIME_DIR/lei/errors.log empty");
585         }
586 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
587 } # /test_lei
588
589 # returns the pathname to a ~/.public-inbox/config in scalar context,
590 # ($test_home, $pi_config_pathname) in list context
591 sub setup_public_inboxes () {
592         my $test_home = "t/home2";
593         my $pi_config = "$test_home/.public-inbox/config";
594         my $stamp = "$test_home/setup-stamp";
595         my @ret = ($test_home, $pi_config);
596         return @ret if -f $stamp;
597
598         require PublicInbox::Lock;
599         my $lk = bless { lock_path => "$test_home/setup.lock" },
600                         'PublicInbox::Lock';
601         my $end = $lk->lock_for_scope;
602         return @ret if -f $stamp;
603
604         local $ENV{PI_CONFIG} = $pi_config;
605         for my $V (1, 2) {
606                 run_script([qw(-init --skip-docdata), "-V$V",
607                                 '--newsgroup', "t.v$V", "t$V",
608                                 "$test_home/t$V", "http://example.com/t$V",
609                                 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
610         }
611         require PublicInbox::Config;
612         require PublicInbox::InboxWritable;
613         my $cfg = PublicInbox::Config->new;
614         my $seen = 0;
615         $cfg->each_inbox(sub {
616                 my ($ibx) = @_;
617                 $ibx->{-no_fsync} = 1;
618                 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
619                 my $V = $ibx->version;
620                 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
621                 for (@eml) {
622                         next if $_ eq 't/psgi_v2-old.eml'; # dup mid
623                         $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
624                         $seen++;
625                 }
626                 $im->done;
627         });
628         $seen or BAIL_OUT 'no imports';
629         open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
630         @ret;
631 }
632
633 sub create_inbox ($$;@) {
634         my $ident = shift;
635         my $cb = pop;
636         my %opt = @_;
637         require PublicInbox::Lock;
638         require PublicInbox::InboxWritable;
639         my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
640         my $dir = "t/data-gen/$base.$ident";
641         my $new = !-d $dir;
642         if ($new) {
643                 mkdir $dir; # may race
644                 -d $dir or BAIL_OUT "$dir could not be created: $!";
645         }
646         my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
647         $opt{inboxdir} = File::Spec->rel2abs($dir);
648         $opt{name} //= $ident;
649         my $scope = $lk->lock_for_scope;
650         my $pre_cb = delete $opt{pre_cb};
651         $pre_cb->($dir) if $pre_cb && $new;
652         $opt{-no_fsync} = 1;
653         my $no_gc = delete $opt{-no_gc};
654         my $tmpdir = delete $opt{tmpdir};
655         my $addr = $opt{address} // [];
656         $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
657         my $parallel = delete($opt{importer_parallel}) // 0;
658         my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
659         my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
660         if (!-f "$dir/creat.stamp") {
661                 my $im = $ibx->importer($parallel);
662                 $cb->($im, $ibx);
663                 $im->done if $im;
664                 unless ($no_gc) {
665                         my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
666                                         glob("$ibx->{inboxdir}/git/*.git");
667                         for my $dir (@to_gc) {
668                                 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
669                         }
670                 }
671                 open my $s, '>', "$dir/creat.stamp" or
672                         BAIL_OUT "error creating $dir/creat.stamp: $!";
673         }
674         if ($tmpdir) {
675                 undef $ibx;
676                 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
677                         BAIL_OUT "cp $dir $tmpdir";
678                 $opt{inboxdir} = $tmpdir;
679                 $ibx = PublicInbox::InboxWritable->new(\%opt);
680         }
681         $ibx;
682 }
683
684 sub test_httpd ($$;$) {
685         my ($env, $client, $skip) = @_;
686         for (qw(PI_CONFIG TMPDIR)) {
687                 $env->{$_} or BAIL_OUT "$_ unset";
688         }
689         SKIP: {
690                 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
691                 my $sock = tcp_server() or die;
692                 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
693                 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
694                 my $td = start_script($cmd, $env, { 3 => $sock });
695                 my ($h, $p) = tcp_host_port($sock);
696                 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
697                 Plack::Test::ExternalServer::test_psgi(client => $client);
698                 $td->join('TERM');
699                 open my $fh, '<', $err or BAIL_OUT $!;
700                 my $e = do { local $/; <$fh> };
701                 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
702                         $e =~ s/^URL generation for redirects .*\n//gms;
703                 }
704                 is($e, '', 'no errors');
705         }
706 };
707
708
709 package PublicInboxTestProcess;
710 use strict;
711
712 # prevent new threads from inheriting these objects
713 sub CLONE_SKIP { 1 }
714
715 sub new {
716         my ($klass, $pid, $tail_pid) = @_;
717         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
718 }
719
720 sub kill {
721         my ($self, $sig) = @_;
722         CORE::kill($sig // 'TERM', $self->{pid});
723 }
724
725 sub join {
726         my ($self, $sig) = @_;
727         my $pid = delete $self->{pid} or return;
728         CORE::kill($sig, $pid) if defined $sig;
729         my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
730         $ret == $pid or die "waitpid($pid) != $ret";
731 }
732
733 sub DESTROY {
734         my ($self) = @_;
735         return if $self->{owner} != $$;
736         if (my $tail_pid = delete $self->{tail_pid}) {
737                 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
738                 CORE::kill('TERM', $tail_pid);
739         }
740         $self->join('TERM');
741 }
742
743 package PublicInbox::TestCommon::InboxWakeup;
744 use strict;
745 sub on_inbox_unlock { ${$_[0]}->($_[1]) }
746
747 1;