]> Sergey Matveev's repositories - public-inbox.git/blob - t/v2mirror.t
No ext_urls
[public-inbox.git] / t / v2mirror.t
1 # Copyright (C) 2018-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 use strict;
4 use v5.10.1;
5 use PublicInbox::TestCommon;
6 use File::Path qw(remove_tree make_path);
7 use Cwd qw(abs_path);
8 use Carp ();
9 use PublicInbox::Spawn qw(which);
10 require_git(2.6);
11 require_cmd('curl');
12 local $ENV{HOME} = abs_path('t');
13 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
14
15 # Integration tests for HTTP cloning + mirroring
16 require_mods(qw(Plack::Util Plack::Builder
17                 HTTP::Date HTTP::Status Search::Xapian DBD::SQLite));
18 use_ok 'PublicInbox::V2Writable';
19 use PublicInbox::InboxWritable;
20 use PublicInbox::Eml;
21 use PublicInbox::Config;
22 # FIXME: too much setup
23 my ($tmpdir, $for_destroy) = tmpdir();
24 my $pi_config = "$tmpdir/config";
25 {
26         open my $fh, '>', $pi_config or die "open($pi_config): $!";
27         print $fh <<"" or die "print $pi_config: $!";
28 [publicinbox "v2"]
29 ; using "mainrepo" rather than "inboxdir" for v1.1.0-pre1 WWW compat below
30         mainrepo = $tmpdir/in
31         address = test\@example.com
32
33         close $fh or die "close($pi_config): $!";
34 }
35 local $ENV{PI_CONFIG} = $pi_config;
36
37 my $cfg = PublicInbox::Config->new($pi_config);
38 my $ibx = $cfg->lookup('test@example.com');
39 ok($ibx, 'inbox found');
40 $ibx->{version} = 2;
41 $ibx->{-no_fsync} = 1;
42 my $v2w = PublicInbox::V2Writable->new($ibx, 1);
43 ok $v2w, 'v2w loaded';
44 $v2w->{parallel} = 0;
45 my $mime = PublicInbox::Eml->new(<<'');
46 From: Me <me@example.com>
47 To: You <you@example.com>
48 Subject: a
49 Date: Thu, 01 Jan 1970 00:00:00 +0000
50
51 my $old_rotate_bytes = $v2w->{rotate_bytes};
52 $v2w->{rotate_bytes} = 500; # force rotating
53 for my $i (1..9) {
54         $mime->header_set('Message-ID', "<$i\@example.com>");
55         $mime->header_set('Subject', "subject = $i");
56         ok($v2w->add($mime), "add msg $i OK");
57 }
58
59 my $epoch_max = $v2w->{epoch_max};
60 ok($epoch_max > 0, "multiple epochs");
61 $v2w->done;
62 {
63         my $smsg = $ibx->over->get_art(1);
64         like($smsg->{lines}, qr/\A[0-9]+\z/, 'lines is a digit');
65         like($smsg->{bytes}, qr/\A[0-9]+\z/, 'bytes is a digit');
66 }
67 $ibx->cleanup;
68
69 local $ENV{TEST_IPV4_ONLY} = 1; # plackup (below) doesn't do IPv6
70 my $rdr = { 3 => tcp_server() };
71 my @cmd = ('-httpd', '-W0', "--stdout=$tmpdir/out", "--stderr=$tmpdir/err");
72 my $td = start_script(\@cmd, undef, $rdr);
73 my ($host, $port) = tcp_host_port(delete $rdr->{3});
74
75 @cmd = (qw(-clone -q), "http://$host:$port/v2/", "$tmpdir/m");
76 run_script(\@cmd) or xbail '-clone';
77
78 for my $i (0..$epoch_max) {
79         ok(-d "$tmpdir/m/git/$i.git", "epoch $i cloned");
80 }
81
82 @cmd = ("-init", '-j1', '-V2', 'm', "$tmpdir/m", 'http://example.com/m',
83         'alt@example.com');
84 ok(run_script(\@cmd), 'initialized public-inbox -V2');
85 my @shards = glob("$tmpdir/m/xap*/?");
86 is(scalar(@shards), 1, 'got a single shard on init');
87
88 ok(run_script([qw(-index -j0), "$tmpdir/m"]), 'indexed');
89
90 my $mibx = { inboxdir => "$tmpdir/m", address => 'alt@example.com' };
91 $mibx = PublicInbox::Inbox->new($mibx);
92 is_deeply([$mibx->mm->minmax], [$ibx->mm->minmax], 'index synched minmax');
93
94 for my $i (10..15) {
95         $mime->header_set('Message-ID', "<$i\@example.com>");
96         $mime->header_set('Subject', "subject = $i");
97         ok($v2w->add($mime), "add msg $i OK");
98 }
99 $v2w->done;
100 $ibx->cleanup;
101
102 my @new_epochs;
103 my $fetch_each_epoch = sub {
104         my %before = map { $_ => 1 } glob("$tmpdir/m/git/*");
105         run_script([qw(-fetch --exit-code -q)], undef, {-C => "$tmpdir/m"}) or
106                 xbail('-fetch fail ',
107                         [ xqx([which('find'), "$tmpdir/m", qw(-type f -ls) ]) ],
108                         Carp::longmess());
109         is($?, 0, '--exit-code 0 after fetch updated');
110         my @after = grep { !$before{$_} } glob("$tmpdir/m/git/*");
111         push @new_epochs, @after;
112 };
113
114 $fetch_each_epoch->();
115
116 my $mset = $mibx->search->reopen->mset('m:15@example.com');
117 is(scalar($mset->items), 0, 'new message not found in mirror, yet');
118 ok(run_script([qw(-index -j0), "$tmpdir/m"]), 'index updated');
119 is_deeply([$mibx->mm->minmax], [$ibx->mm->minmax], 'index synched minmax');
120 $mset = $mibx->search->reopen->mset('m:15@example.com');
121 is(scalar($mset->items), 1, 'found message in mirror');
122
123 # purge:
124 $mime->header_set('Message-ID', '<10@example.com>');
125 $mime->header_set('Subject', 'subject = 10');
126 {
127         my @warn;
128         local $SIG{__WARN__} = sub { push @warn, @_ };
129         ok($v2w->purge($mime), 'purge a message');
130         my $warn = join('', @warn);
131         like($warn, qr/purge rewriting/);
132         my @subj = ($warn =~ m/^# subject .*$/mg);
133         is_deeply(\@subj, ["# subject = 10"], "only rewrote one");
134 }
135
136 $v2w->done;
137
138 my $msgs = $mibx->over->get_thread('10@example.com');
139 my $to_purge = $msgs->[0]->{blob};
140 like($to_purge, qr/\A[a-f0-9]{40,}\z/, 'read blob to be purged');
141 $mset = $ibx->search->reopen->mset('m:10@example.com');
142 is(scalar($mset->items), 0, 'purged message gone from origin');
143
144 $fetch_each_epoch->();
145 {
146         $ibx->cleanup;
147         PublicInbox::InboxWritable::cleanup($mibx);
148         $v2w->done;
149         my $cmd = [ qw(-index --prune -j0), "$tmpdir/m" ];
150         my ($out, $err) = ('', '');
151         my $opt = { 1 => \$out, 2 => \$err };
152         ok(run_script($cmd, undef, $opt), '-index --prune');
153         like($err, qr/discontiguous range/, 'warned about discontiguous range');
154         unlike($err, qr/fatal/, 'no scary fatal error shown');
155 }
156
157 $mset = $mibx->search->reopen->mset('m:10@example.com');
158 is(scalar($mset->items), 0, 'purged message not found in mirror');
159 is_deeply([$mibx->mm->minmax], [$ibx->mm->minmax], 'minmax still synced');
160 for my $i ((1..9),(11..15)) {
161         $mset = $mibx->search->mset("m:$i\@example.com");
162         is(scalar($mset->items), 1, "$i\@example.com remains visible");
163 }
164 is($mibx->git->check($to_purge), undef, 'unindex+prune successful in mirror');
165
166 {
167         my @warn;
168         local $SIG{__WARN__} = sub { push @warn, @_ };
169         $v2w->index_sync;
170         is_deeply(\@warn, [], 'no warnings from index_sync after purge');
171 }
172
173 # deletes happen in a different fetch window
174 {
175         $mset = $mibx->search->reopen->mset('m:1@example.com');
176         is(scalar($mset->items), 1, '1@example.com visible in mirror');
177         $mime->header_set('Message-ID', '<1@example.com>');
178         $mime->header_set('Subject', 'subject = 1');
179         ok($v2w->remove($mime), 'removed <1@example.com> from source');
180         $v2w->done;
181         $ibx->cleanup;
182         $fetch_each_epoch->();
183         PublicInbox::InboxWritable::cleanup($mibx);
184
185         my $cmd = [ qw(-index -j0), "$tmpdir/m" ];
186         my ($out, $err) = ('', '');
187         my $opt = { 1 => \$out, 2 => \$err };
188         ok(run_script($cmd, undef, $opt), 'index ran');
189         is($err, '', 'no errors reported by index');
190         $mset = $mibx->search->reopen->mset('m:1@example.com');
191         is(scalar($mset->items), 0, '1@example.com no longer visible in mirror');
192 }
193
194 if ('sequential-shard') {
195         $mset = $mibx->search->mset('m:15@example.com');
196         is(scalar($mset->items), 1, 'large message not indexed');
197         remove_tree(glob("$tmpdir/m/xap*"), glob("$tmpdir/m/msgmap.*"));
198         my $cmd = [ qw(-index -j9 --sequential-shard), "$tmpdir/m" ];
199         ok(run_script($cmd), '--sequential-shard works');
200         my @shards = glob("$tmpdir/m/xap*/?");
201         is(scalar(@shards), 8, 'got expected shard count');
202         PublicInbox::InboxWritable::cleanup($mibx);
203         $mset = $mibx->search->mset('m:15@example.com');
204         is(scalar($mset->items), 1, 'search works after --sequential-shard');
205 }
206
207 if ('max size') {
208         $mime->header_set('Message-ID', '<2big@a>');
209         my $max = '2k';
210         $mime->body_str_set("z\n" x 1024);
211         ok($v2w->add($mime), "add big message");
212         $v2w->done;
213         $ibx->cleanup;
214         $fetch_each_epoch->();
215         PublicInbox::InboxWritable::cleanup($mibx);
216         my $cmd = [qw(-index -j0), "$tmpdir/m", "--max-size=$max" ];
217         my $opt = { 2 => \(my $err) };
218         ok(run_script($cmd, undef, $opt), 'indexed with --max-size');
219         like($err, qr/skipping [a-f0-9]{40,}/, 'warned about skipping message');
220         $mset = $mibx->search->reopen->mset('m:2big@a');
221         is(scalar($mset->items), 0, 'large message not indexed');
222
223         {
224                 open my $fh, '>>', $pi_config or die;
225                 print $fh <<EOF or die;
226 [publicinbox]
227         indexMaxSize = 2k
228 EOF
229                 close $fh or die;
230         }
231         $cmd = [ qw(-index -j0 --reindex), "$tmpdir/m" ];
232         ok(run_script($cmd, undef, $opt), 'reindexed w/ indexMaxSize in file');
233         like($err, qr/skipping [a-f0-9]{40,}/, 'warned about skipping message');
234         $mset = $mibx->search->reopen->mset('m:2big@a');
235         is(scalar($mset->items), 0, 'large message not re-indexed');
236 }
237 ok(scalar(@new_epochs), 'new epochs were created and fetched');
238 for my $d (@new_epochs) {
239         is(xqx(['git', "--git-dir=$d", 'config', qw(include.path)]),
240                 "../../all.git/config\n",
241                 'include.path set');
242 }
243
244 if ('test read-only epoch dirs') {
245         my @git = ('git', "--git-dir=$new_epochs[0]");
246         my $get_objs = [@git,
247                 qw(cat-file --buffer --batch-check --batch-all-objects)];
248         my $before = [sort xqx($get_objs)];
249
250         remove_tree(map { "$new_epochs[0]/$_" } qw(objects refs/heads));
251         chmod(0555, $new_epochs[0]) or xbail "chmod: $!";
252
253         # force a refetch
254         unlink("$tmpdir/m/manifest.js.gz") or xbail "unlink: $!";
255
256         run_script([qw(-fetch -q)], undef, {-C => "$tmpdir/m"}) or
257                 xbail '-fetch failed';
258
259         ok(!-d "$new_epochs[0]/objects", 'no objects after fetch to R/O dir');
260
261         chmod(0755, $new_epochs[0]) or xbail "chmod: $!";
262         mkdir("$new_epochs[0]/objects") or xbail "mkdir: $!";
263         mkdir("$new_epochs[0]/refs/heads") or xbail "mkdir: $!";
264
265         my $err = '';
266         run_script([qw(-fetch -q)], undef, {-C => "$tmpdir/m", 2 => \$err}) or
267                 xbail '-fetch failed '.$err;
268         is_deeply([ sort xqx($get_objs) ], $before,
269                 'fetch restored objects once GIT_DIR became writable');
270 }
271
272 {
273         my $dst = "$tmpdir/partial";
274         run_script([qw(-clone -q --epoch=~0), "http://$host:$port/v2/", $dst]);
275         is($?, 0, 'no error from partial clone');
276         my @g = glob("$dst/git/*.git");
277         my @w = grep { -w $_ } @g;
278         my @r = grep { ! -w $_ } @g;
279         if ($> == 0) {
280                 @w = grep { (stat($_))[2] & 0200 } @g;
281                 @r = grep { !((stat($_))[2] & 0200) } @g;
282         }
283         is(scalar(@w), 1, 'one writable directory');
284         my ($w) = ($w[0] =~ m!/([0-9]+)\.git\z!);
285         is((grep {
286                 m!/([0-9]+)\.git\z! or xbail "no digit in $_";
287                 $w > ($1 + 0)
288         } @r), scalar(@r), 'writable epoch # exceeds read-only ones');
289         run_script([qw(-fetch -q)], undef, { -C => $dst });
290         is($?, 0, 'no error from partial fetch');
291         remove_tree($dst);
292
293         run_script([qw(-clone -q --epoch=~1..),
294                         "http://$host:$port/v2/", $dst]);
295         my @g2 = glob("$dst/git/*.git") ;
296         is_deeply(\@g2, \@g, 'cloned again');
297         is(scalar(grep { (stat($_))[2] & 0200 } @g2), scalar(@w) + 1,
298                 'got one more cloned epoch');
299
300         # make 0.git writable and fetch into it, relies on culled manifest
301         chmod(0755, $g2[0]) or xbail "chmod: $!";
302         my @before = glob("$g2[0]/objects/*/*");
303         run_script([qw(-fetch -q)], undef, { -C => $dst });
304         is($?, 0, 'no error from partial fetch');
305         my @after = glob("$g2[0]/objects/*/*");
306         ok(scalar(@before) < scalar(@after), 'fetched after chmod 0755 0.git');
307
308         # ensure culled manifest is maintained after fetch
309         gunzip("$dst/manifest.js.gz" => \(my $m), MultiStream => 1) or
310                 xbail "gunzip: $GunzipError";
311         $m = PublicInbox::Config->json->decode($m);
312         for my $k (keys %$m) { # /$name/git/$N.git
313                 my ($nr) = ($k =~ m!/git/([0-9]+)\.git\z!);
314                 ok(-w "$dst/git/$nr.git", "writable $nr.git in manifest");
315         }
316         for my $ro (grep { !-w $_ } @g2) {
317                 my ($nr) = ($ro =~ m!/git/([0-9]+)\.git\z!);
318                 is(grep(m!/git/$nr\.git\z!, keys %$m), 0,
319                         "read-only $nr.git not in manifest")
320                         or xbail([sort keys %$m]);
321         }
322 }
323
324 my $err = '';
325 my $oldrev = '0b3e19584c90d958a723ac2d3dec3f84f5513688~1';
326 # 3e0e596105198cfa (wwwlisting: allow hiding entries from manifest, 2019-06-09)
327 $oldrev = xqx([qw(git rev-parse), $oldrev], undef, { 2 => \$err });
328 SKIP: {
329         skip("no detected public-inbox GIT_DIR ($err)", 1) if $?;
330         require_mods('Email::MIME', 1); # for legacy revision
331         # using plackup to test old PublicInbox::WWW since -httpd from
332         # back then relied on some packages we no longer depend on
333         my $plackup = which('plackup') or skip('no plackup in path', 1);
334         require PublicInbox::Lock;
335         chomp $oldrev;
336         my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
337         my $wt = "t/data-gen/$base.pre-manifest-$oldrev";
338         my $lk = bless { lock_path => __FILE__ }, 'PublicInbox::Lock';
339         $lk->lock_acquire;
340         my $psgi = "$wt/app.psgi";
341         if (!-f $psgi) { # checkout a pre-manifest.js.gz version
342                 my $t = File::Temp->new(TEMPLATE => 'g-XXXX', TMPDIR => 1);
343                 my $env = { GIT_INDEX_FILE => $t->filename };
344                 xsys([qw(git read-tree), $oldrev], $env) and xbail 'read-tree';
345                 xsys([qw(git checkout-index -a), "--prefix=$wt/"], $env)
346                         and xbail 'checkout-index';
347                 my $f = "$wt/app.psgi.tmp.$$";
348                 open my $fh, '>', $f or xbail $!;
349                 print $fh <<'EOM' or xbail $!;
350 use Plack::Builder;
351 use PublicInbox::WWW;
352 my $www = PublicInbox::WWW->new;
353 builder { enable 'Head'; sub { $www->call(@_) } }
354 EOM
355                 close $fh or xbail $!;
356                 rename($f, $psgi) or xbail $!;
357         }
358         $lk->lock_release;
359
360         $rdr->{run_mode} = 0;
361         $rdr->{-C} = $wt;
362         my $cmd = [$plackup, qw(-Enone -Ilib), "--host=$host", "--port=$port"];
363         $td->join('TERM');
364         open $rdr->{2}, '>>', "$tmpdir/plackup.err.log" or xbail "open: $!";
365         open $rdr->{1}, '>>&', $rdr->{2} or xbail "open: $!";
366         my $env = { PERL5LIB => 'lib', PERL_INLINE_DIRECTORY => undef };
367         $td = start_script($cmd, $env, $rdr);
368         # wait for plackup socket()+bind()+listen()
369         my %opt = ( Proto => 'tcp', Type => Socket::SOCK_STREAM(),
370                 PeerAddr => "$host:$port" );
371         for (0..50) {
372                 tick();
373                 last if IO::Socket::INET->new(%opt);
374         }
375         my $dst = "$tmpdir/scrape";
376         @cmd = (qw(-clone -q), "http://$host:$port/v2", $dst);
377         run_script(\@cmd, undef, { 2 => \($err = '') });
378         is($?, 0, 'scraping clone on old PublicInbox::WWW')
379                 or diag $err;
380         my @g_all = glob("$dst/git/*.git");
381         ok(scalar(@g_all) > 1, 'cloned multiple epochs');
382
383         remove_tree($dst);
384         @cmd = (qw(-clone -q --epoch=~0), "http://$host:$port/v2", $dst);
385         run_script(\@cmd, undef, { 2 => \($err = '') });
386         is($?, 0, 'partial scraping clone on old PublicInbox::WWW');
387         my @g_last = grep { (stat($_))[2] & 0200 } glob("$dst/git/*.git");
388         is_deeply(\@g_last, [ $g_all[-1] ], 'partial clone of ~0 worked');
389
390         chmod(0755, $g_all[0]) or xbail "chmod $!";
391         my @before = glob("$g_all[0]/objects/*/*");
392         run_script([qw(-fetch -v)], undef, { -C => $dst, 2 => \($err = '') });
393         is($?, 0, 'scraping fetch on old PublicInbox::WWW') or diag $err;
394         my @after = glob("$g_all[0]/objects/*/*");
395         ok(scalar(@before) < scalar(@after),
396                 'fetched 0.git after enabling write-bit');
397
398         $td->join('TERM');
399 }
400
401 done_testing;