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