]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: share log2stack code with v1
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This interface wraps and mimics PublicInbox::Import
5 # Used to write to V2 inboxes (see L<public-inbox-v2-format(5)>).
6 package PublicInbox::V2Writable;
7 use strict;
8 use v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::IdxStack;
12 use PublicInbox::Eml;
13 use PublicInbox::Git;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentHash qw(content_hash content_digest);
17 use PublicInbox::InboxWritable;
18 use PublicInbox::OverIdx;
19 use PublicInbox::Msgmap;
20 use PublicInbox::Spawn qw(spawn popen_rd);
21 use PublicInbox::SearchIdx qw(too_big log2stack crlf_adjust is_ancestor);
22 use IO::Handle; # ->autoflush
23 use File::Temp qw(tempfile);
24
25 my $OID = qr/[a-f0-9]{40,}/;
26 # an estimate of the post-packed size to the raw uncompressed size
27 my $PACKING_FACTOR = 0.4;
28
29 # SATA storage lags behind what CPUs are capable of, so relying on
30 # nproc(1) can be misleading and having extra Xapian shards is a
31 # waste of FDs and space.  It can also lead to excessive IO latency
32 # and slow things down.  Users on NVME or other fast storage can
33 # use the NPROC env or switches in our script/public-inbox-* programs
34 # to increase Xapian shards
35 our $NPROC_MAX_DEFAULT = 4;
36
37 sub detect_nproc () {
38         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
39                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
40         }
41
42         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
43         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
44                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
45         }
46
47         # should we bother with `sysctl hw.ncpu`?  Those only give
48         # us total processor count, not online processor count.
49         undef
50 }
51
52 sub nproc_shards ($) {
53         my ($creat_opt) = @_;
54         my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
55         $n //= $ENV{NPROC};
56         if (!$n) {
57                 # assume 2 cores if not detectable or zero
58                 state $NPROC_DETECTED = detect_nproc() || 2;
59                 $n = $NPROC_DETECTED;
60                 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
61         }
62
63         # subtract for the main process and git-fast-import
64         $n -= 1;
65         $n < 1 ? 1 : $n;
66 }
67
68 sub count_shards ($) {
69         my ($self) = @_;
70         my $n = 0;
71         my $xpfx = $self->{xpfx};
72
73         # always load existing shards in case core count changes:
74         # Also, shard count may change while -watch is running
75         # due to "xcpdb --reshard"
76         if (-d $xpfx) {
77                 my $XapianDatabase;
78                 foreach my $shard (<$xpfx/*>) {
79                         -d $shard && $shard =~ m!/[0-9]+\z! or next;
80                         $XapianDatabase //= do {
81                                 require PublicInbox::Search;
82                                 PublicInbox::Search::load_xapian();
83                                 $PublicInbox::Search::X{Database};
84                         };
85                         eval {
86                                 $XapianDatabase->new($shard)->close;
87                                 $n++;
88                         };
89                 }
90         }
91         $n;
92 }
93
94 sub new {
95         # $creat may be any true value, or 0/undef.  A hashref is true,
96         # and $creat->{nproc} may be set to an integer
97         my ($class, $v2ibx, $creat) = @_;
98         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
99         my $dir = $v2ibx->assert_usable_dir;
100         unless (-d $dir) {
101                 if ($creat) {
102                         require File::Path;
103                         File::Path::mkpath($dir);
104                 } else {
105                         die "$dir does not exist\n";
106                 }
107         }
108         $v2ibx->umask_prepare;
109
110         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
111         my $self = {
112                 ibx => $v2ibx,
113                 im => undef, #  PublicInbox::Import
114                 parallel => 1,
115                 transact_bytes => 0,
116                 total_bytes => 0,
117                 current_info => '',
118                 xpfx => $xpfx,
119                 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
120                 lock_path => "$dir/inbox.lock",
121                 # limit each git repo (epoch) to 1GB or so
122                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
123                 last_commit => [], # git epoch -> commit
124         };
125         $self->{over}->{-no_sync} = 1 if $v2ibx->{-no_sync};
126         $self->{shards} = count_shards($self) || nproc_shards($creat);
127         $self->{index_max_size} = $v2ibx->{index_max_size};
128         bless $self, $class;
129 }
130
131 # public (for now?)
132 sub init_inbox {
133         my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
134         if (defined $shards) {
135                 $self->{parallel} = 0 if $shards == 0;
136                 $self->{shards} = $shards if $shards > 0;
137         }
138         $self->idx_init;
139         $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
140         my $epoch_max = -1;
141         git_dir_latest($self, \$epoch_max);
142         if (defined $skip_epoch && $epoch_max == -1) {
143                 $epoch_max = $skip_epoch;
144         }
145         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
146         $self->done;
147 }
148
149 # returns undef on duplicate or spam
150 # mimics Import::add and wraps it for v2
151 sub add {
152         my ($self, $eml, $check_cb) = @_;
153         $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
154 }
155
156 # indexes a message, returns true if checkpointing is needed
157 sub do_idx ($$$$) {
158         my ($self, $msgref, $mime, $smsg) = @_;
159         $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
160         $self->{over}->add_overview($mime, $smsg);
161         my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
162         $idx->index_raw($msgref, $mime, $smsg);
163         my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
164         $n >= ($PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
165 }
166
167 sub _add {
168         my ($self, $mime, $check_cb) = @_;
169
170         # spam check:
171         if ($check_cb) {
172                 $mime = $check_cb->($mime, $self->{ibx}) or return;
173         }
174
175         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
176         # as does SQLite 3.4.1+ (released in 2007-07-20), and
177         # Xapian 1.3.2+ (released 2015-03-15).
178         # For the most part, we can spawn git-fast-import without
179         # leaking FDs to it...
180         $self->idx_init;
181
182         my ($num, $mid0) = v2_num_for($self, $mime);
183         defined $num or return; # duplicate
184         defined $mid0 or die "BUG: \$mid0 undefined\n";
185         my $im = $self->importer;
186         my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
187         my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
188         $cmt = $im->get_mark($cmt);
189         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
190
191         my $msgref = delete $smsg->{-raw_email};
192         if (do_idx($self, $msgref, $mime, $smsg)) {
193                 $self->checkpoint;
194         }
195
196         $cmt;
197 }
198
199 sub v2_num_for {
200         my ($self, $mime) = @_;
201         my $mids = mids($mime->header_obj);
202         if (@$mids) {
203                 my $mid = $mids->[0];
204                 my $num = $self->{mm}->mid_insert($mid);
205                 if (defined $num) { # common case
206                         return ($num, $mid);
207                 }
208
209                 # crap, Message-ID is already known, hope somebody just resent:
210                 foreach my $m (@$mids) {
211                         # read-only lookup now safe to do after above barrier
212                         # easy, don't store duplicates
213                         # note: do not add more diagnostic info here since
214                         # it gets noisy on public-inbox-watch restarts
215                         return () if content_exists($self, $mime, $m);
216                 }
217
218                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
219                 # or NNTP article number), use that article number if it's
220                 # not in Over.
221                 my $altid = $self->{ibx}->{altid};
222                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
223                         my $num = $self->{mm}->num_for($mid);
224
225                         if (defined $num && !$self->{over}->get_art($num)) {
226                                 return ($num, $mid);
227                         }
228                 }
229
230                 # very unlikely:
231                 warn "<$mid> reused for mismatched content\n";
232
233                 # try the rest of the mids
234                 for(my $i = $#$mids; $i >= 1; $i--) {
235                         my $m = $mids->[$i];
236                         $num = $self->{mm}->mid_insert($m);
237                         if (defined $num) {
238                                 warn "alternative <$m> for <$mid> found\n";
239                                 return ($num, $m);
240                         }
241                 }
242         }
243         # none of the existing Message-IDs are good, generate a new one:
244         v2_num_for_harder($self, $mime);
245 }
246
247 sub v2_num_for_harder {
248         my ($self, $mime) = @_;
249
250         my $hdr = $mime->header_obj;
251         my $dig = content_digest($mime);
252         my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
253         my $num = $self->{mm}->mid_insert($mid0);
254         unless (defined $num) {
255                 # it's hard to spoof the last Received: header
256                 my @recvd = $hdr->header_raw('Received');
257                 $dig->add("Received: $_") foreach (@recvd);
258                 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
259                 $num = $self->{mm}->mid_insert($mid0);
260
261                 # fall back to a random Message-ID and give up determinism:
262                 until (defined($num)) {
263                         $dig->add(rand);
264                         $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
265                         warn "using random Message-ID <$mid0> as fallback\n";
266                         $num = $self->{mm}->mid_insert($mid0);
267                 }
268         }
269         PublicInbox::Import::append_mid($hdr, $mid0);
270         ($num, $mid0);
271 }
272
273 sub idx_shard {
274         my ($self, $shard_i) = @_;
275         $self->{idx_shards}->[$shard_i];
276 }
277
278 sub _idx_init { # with_umask callback
279         my ($self, $opt) = @_;
280         $self->lock_acquire unless $opt && $opt->{-skip_lock};
281         $self->{over}->create;
282
283         # xcpdb can change shard count while -watch is idle
284         my $nshards = count_shards($self);
285         $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
286
287         # need to create all shards before initializing msgmap FD
288         # idx_shards must be visible to all forked processes
289         my $max = $self->{shards} - 1;
290         my $idx = $self->{idx_shards} = [];
291         push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
292
293         # Now that all subprocesses are up, we can open the FDs
294         # for SQLite:
295         my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
296                                 "$self->{ibx}->{inboxdir}/msgmap.sqlite3",
297                                 $self->{ibx}->{-no_sync} ? 2 : 1);
298         $mm->{dbh}->begin_work;
299 }
300
301 # idempotent
302 sub idx_init {
303         my ($self, $opt) = @_;
304         return if $self->{idx_shards};
305         my $ibx = $self->{ibx};
306
307         # do not leak read-only FDs to child processes, we only have these
308         # FDs for duplicate detection so they should not be
309         # frequently activated.
310         # delete @$ibx{qw(git mm search)};
311         delete $ibx->{$_} foreach (qw(git mm search));
312
313         $self->{parallel} = 0 if ($ibx->{indexlevel}//'') eq 'basic';
314         if ($self->{parallel}) {
315                 pipe(my ($r, $w)) or die "pipe failed: $!";
316                 # pipe for barrier notifications doesn't need to be big,
317                 # 1031: F_SETPIPE_SZ
318                 fcntl($w, 1031, 4096) if $^O eq 'linux';
319                 $self->{bnote} = [ $r, $w ];
320                 $w->autoflush(1);
321         }
322
323         $ibx->umask_prepare;
324         $ibx->with_umask(\&_idx_init, $self, $opt);
325 }
326
327 # returns an array mapping [ epoch => latest_commit ]
328 # latest_commit may be undef if nothing was done to that epoch
329 # $replace_map = { $object_id => $strref, ... }
330 sub _replace_oids ($$$) {
331         my ($self, $mime, $replace_map) = @_;
332         $self->done;
333         my $pfx = "$self->{ibx}->{inboxdir}/git";
334         my $rewrites = []; # epoch => commit
335         my $max = $self->{epoch_max};
336
337         unless (defined($max)) {
338                 defined(my $latest = git_dir_latest($self, \$max)) or return;
339                 $self->{epoch_max} = $max;
340         }
341
342         foreach my $i (0..$max) {
343                 my $git_dir = "$pfx/$i.git";
344                 -d $git_dir or next;
345                 my $git = PublicInbox::Git->new($git_dir);
346                 my $im = $self->import_init($git, 0, 1);
347                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
348                 $im->done;
349         }
350         $rewrites;
351 }
352
353 sub content_hashes ($) {
354         my ($mime) = @_;
355         my @chashes = ( content_hash($mime) );
356
357         # We still support Email::MIME, here, and
358         # Email::MIME->as_string doesn't always round-trip, so we may
359         # use a second content_hash
360         my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
361         push @chashes, $rt if $chashes[0] ne $rt;
362         \@chashes;
363 }
364
365 sub content_matches ($$) {
366         my ($chashes, $existing) = @_;
367         my $chash = content_hash($existing);
368         foreach (@$chashes) {
369                 return 1 if $_ eq $chash
370         }
371         0
372 }
373
374 # used for removing or replacing (purging)
375 sub rewrite_internal ($$;$$$) {
376         my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
377         $self->idx_init;
378         my ($im, $need_reindex, $replace_map);
379         if ($sref) {
380                 $replace_map = {}; # oid => sref
381                 $need_reindex = [] if $new_eml;
382         } else {
383                 $im = $self->importer;
384         }
385         my $over = $self->{over};
386         my $chashes = content_hashes($old_eml);
387         my $removed = [];
388         my $mids = mids($old_eml->header_obj);
389
390         # We avoid introducing new blobs into git since the raw content
391         # can be slightly different, so we do not need the user-supplied
392         # message now that we have the mids and content_hash
393         $old_eml = undef;
394         my $mark;
395
396         foreach my $mid (@$mids) {
397                 my %gone; # num => [ smsg, $mime, raw ]
398                 my ($id, $prev);
399                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
400                         my $msg = get_blob($self, $smsg);
401                         if (!defined($msg)) {
402                                 warn "broken smsg for $mid\n";
403                                 next; # continue
404                         }
405                         my $orig = $$msg;
406                         my $cur = PublicInbox::Eml->new($msg);
407                         if (content_matches($chashes, $cur)) {
408                                 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
409                         }
410                 }
411                 my $n = scalar keys %gone;
412                 next unless $n;
413                 if ($n > 1) {
414                         warn "BUG: multiple articles linked to <$mid>\n",
415                                 join(',', sort keys %gone), "\n";
416                 }
417                 foreach my $num (keys %gone) {
418                         my ($smsg, $mime, $orig) = @{$gone{$num}};
419                         # $removed should only be set once assuming
420                         # no bugs in our deduplication code:
421                         $removed = [ undef, $mime, $smsg ];
422                         my $oid = $smsg->{blob};
423                         if ($replace_map) {
424                                 $replace_map->{$oid} = $sref;
425                         } else {
426                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
427                                 $removed->[0] = $mark;
428                         }
429                         $orig = undef;
430                         if ($need_reindex) { # ->replace
431                                 push @$need_reindex, $smsg;
432                         } else { # ->purge or ->remove
433                                 $self->{mm}->num_delete($num);
434                         }
435                         unindex_oid_remote($self, $oid, $mid);
436                 }
437         }
438
439         if (defined $mark) {
440                 my $cmt = $im->get_mark($mark);
441                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
442         }
443         if ($replace_map && scalar keys %$replace_map) {
444                 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
445                 return { rewrites => $rewrites, need_reindex => $need_reindex };
446         }
447         defined($mark) ? $removed : undef;
448 }
449
450 # public (see PublicInbox::Import->remove), but note the 3rd element
451 # (retval[2]) is not part of the stable API shared with Import->remove
452 sub remove {
453         my ($self, $eml, $cmt_msg) = @_;
454         my $r = $self->{ibx}->with_umask(\&rewrite_internal,
455                                                 $self, $eml, $cmt_msg);
456         defined($r) && defined($r->[0]) ? @$r: undef;
457 }
458
459 sub _replace ($$;$$) {
460         my ($self, $old_eml, $new_eml, $sref) = @_;
461         my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
462         my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
463                         $self, $old_eml, undef, $new_eml, $sref) or return;
464
465         my $rewrites = $rewritten->{rewrites};
466         # ->done is called if there are rewrites since we gc+prune from git
467         $self->idx_init if @$rewrites;
468
469         for my $i (0..$#$rewrites) {
470                 defined(my $cmt = $rewrites->[$i]) or next;
471                 $self->{last_commit}->[$i] = $cmt;
472         }
473         $rewritten;
474 }
475
476 # public
477 sub purge {
478         my ($self, $mime) = @_;
479         my $rewritten = _replace($self, $mime, undef, \'') or return;
480         $rewritten->{rewrites}
481 }
482
483 # returns the git object_id of $fh, does not write the object to FS
484 sub git_hash_raw ($$) {
485         my ($self, $raw) = @_;
486         # grab the expected OID we have to reindex:
487         pipe(my($in, $w)) or die "pipe: $!";
488         my $git_dir = $self->{ibx}->git->{git_dir};
489         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
490         my $r = popen_rd($cmd, undef, { 0 => $in });
491         print $w $$raw or die "print \$w: $!";
492         close $w or die "close \$w: $!";
493         local $/ = "\n";
494         chomp(my $oid = <$r>);
495         close $r or die "git hash-object failed: $?";
496         $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
497         $oid;
498 }
499
500 sub _check_mids_match ($$$) {
501         my ($old_list, $new_list, $hdrs) = @_;
502         my %old_mids = map { $_ => 1 } @$old_list;
503         my %new_mids = map { $_ => 1 } @$new_list;
504         my @old = keys %old_mids;
505         my @new = keys %new_mids;
506         my $err = "$hdrs may not be changed when replacing\n";
507         die $err if scalar(@old) != scalar(@new);
508         delete @new_mids{@old};
509         delete @old_mids{@new};
510         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
511 }
512
513 # Changing Message-IDs or References with ->replace isn't supported.
514 # The rules for dealing with messages with multiple or conflicting
515 # Message-IDs are pretty complex and rethreading hasn't been fully
516 # implemented, yet.
517 sub check_mids_match ($$) {
518         my ($old_mime, $new_mime) = @_;
519         my $old = $old_mime->header_obj;
520         my $new = $new_mime->header_obj;
521         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
522         _check_mids_match(references($old), references($new),
523                         'References/In-Reply-To');
524 }
525
526 # public
527 sub replace ($$$) {
528         my ($self, $old_mime, $new_mime) = @_;
529
530         check_mids_match($old_mime, $new_mime);
531
532         # mutt will always add Content-Length:, Status:, Lines: when editing
533         PublicInbox::Import::drop_unwanted_headers($new_mime);
534
535         my $raw = $new_mime->as_string;
536         my $expect_oid = git_hash_raw($self, \$raw);
537         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
538         my $need_reindex = $rewritten->{need_reindex};
539
540         # just in case we have bugs in deduplication code:
541         my $n = scalar(@$need_reindex);
542         if ($n > 1) {
543                 my $list = join(', ', map {
544                                         "$_->{num}: <$_->{mid}>"
545                                 } @$need_reindex);
546                 warn <<"";
547 W: rewritten $n messages matching content of original message (expected: 1).
548 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
549 W: $list
550
551         }
552
553         # make sure we really got the OID:
554         my ($blob, $type, $bytes) = $self->{ibx}->git->check($expect_oid);
555         $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
556
557         # don't leak FDs to Xapian:
558         $self->{ibx}->git->cleanup;
559
560         # reindex modified messages:
561         for my $smsg (@$need_reindex) {
562                 my $new_smsg = bless {
563                         blob => $blob,
564                         raw_bytes => $bytes,
565                         num => $smsg->{num},
566                         mid => $smsg->{mid},
567                 }, 'PublicInbox::Smsg';
568                 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
569                 $new_smsg->populate($new_mime, $sync);
570                 do_idx($self, \$raw, $new_mime, $new_smsg);
571         }
572         $rewritten->{rewrites};
573 }
574
575 sub last_epoch_commit ($$;$) {
576         my ($self, $i, $cmt) = @_;
577         my $v = PublicInbox::Search::SCHEMA_VERSION();
578         $self->{mm}->last_commit_xap($v, $i, $cmt);
579 }
580
581 sub set_last_commits ($) {
582         my ($self) = @_;
583         defined(my $epoch_max = $self->{epoch_max}) or return;
584         my $last_commit = $self->{last_commit};
585         foreach my $i (0..$epoch_max) {
586                 defined(my $cmt = $last_commit->[$i]) or next;
587                 $last_commit->[$i] = undef;
588                 last_epoch_commit($self, $i, $cmt);
589         }
590 }
591
592 sub barrier_init {
593         my ($self, $n) = @_;
594         $self->{bnote} or return;
595         --$n;
596         my $barrier = { map { $_ => 1 } (0..$n) };
597 }
598
599 sub barrier_wait {
600         my ($self, $barrier) = @_;
601         my $bnote = $self->{bnote} or return;
602         my $r = $bnote->[0];
603         while (scalar keys %$barrier) {
604                 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
605                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
606                 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
607         }
608 }
609
610 # public
611 sub checkpoint ($;$) {
612         my ($self, $wait) = @_;
613
614         if (my $im = $self->{im}) {
615                 if ($wait) {
616                         $im->barrier;
617                 } else {
618                         $im->checkpoint;
619                 }
620         }
621         my $shards = $self->{idx_shards};
622         if ($shards) {
623                 my $dbh = $self->{mm}->{dbh};
624
625                 # SQLite msgmap data is second in importance
626                 $dbh->commit;
627
628                 # SQLite overview is third
629                 $self->{over}->commit_lazy;
630
631                 # Now deal with Xapian
632                 if ($wait) {
633                         my $barrier = $self->barrier_init(scalar @$shards);
634
635                         # each shard needs to issue a barrier command
636                         $_->remote_barrier for @$shards;
637
638                         # wait for each Xapian shard
639                         $self->barrier_wait($barrier);
640                 } else {
641                         $_->remote_commit for @$shards;
642                 }
643
644                 # last_commit is special, don't commit these until
645                 # remote shards are done:
646                 $dbh->begin_work;
647                 set_last_commits($self);
648                 $dbh->commit;
649
650                 $dbh->begin_work;
651         }
652         $self->{total_bytes} += $self->{transact_bytes};
653         $self->{transact_bytes} = 0;
654 }
655
656 # issue a write barrier to ensure all data is visible to other processes
657 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
658 # public
659 sub barrier { checkpoint($_[0], 1) };
660
661 # public
662 sub done {
663         my ($self) = @_;
664         my $im = delete $self->{im};
665         $im->done if $im; # PublicInbox::Import::done
666         checkpoint($self);
667         my $mm = delete $self->{mm};
668         $mm->{dbh}->commit if $mm;
669         my $shards = delete $self->{idx_shards};
670         if ($shards) {
671                 $_->remote_close for @$shards;
672         }
673         $self->{over}->disconnect;
674         delete $self->{bnote};
675         my $nbytes = $self->{total_bytes};
676         $self->{total_bytes} = 0;
677         $self->lock_release(!!$nbytes) if $shards;
678         $self->{ibx}->git->cleanup;
679 }
680
681 sub fill_alternates ($$) {
682         my ($self, $epoch) = @_;
683
684         my $pfx = "$self->{ibx}->{inboxdir}/git";
685         my $all = "$self->{ibx}->{inboxdir}/all.git";
686         PublicInbox::Import::init_bare($all) unless -d $all;
687         my $info_dir = "$all/objects/info";
688         my $alt = "$info_dir/alternates";
689         my (%alt, $new);
690         my $mode = 0644;
691         if (-e $alt) {
692                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
693                 $mode = (stat($fh))[2] & 07777;
694
695                 # we assign a sort score to every alternate and favor
696                 # the newest (highest numbered) one because loose objects
697                 # require scanning epochs and only the latest epoch is
698                 # expected to see loose objects
699                 my $score;
700                 my $other = 0; # in case admin adds non-epoch repos
701                 %alt = map {;
702                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
703                                 $score = $1 + 0;
704                         } else {
705                                 $score = --$other;
706                         }
707                         $_ => $score;
708                 } split(/\n+/, do { local $/; <$fh> });
709         }
710
711         foreach my $i (0..$epoch) {
712                 my $dir = "../../git/$i.git/objects";
713                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
714                         $alt{$dir} = $i;
715                         $new = 1;
716                 }
717         }
718         return unless $new;
719
720         my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
721         print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
722                 or die "print $tmp: $!\n";
723         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
724         close $fh or die "close $tmp $!\n";
725         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
726 }
727
728 sub git_init {
729         my ($self, $epoch) = @_;
730         my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
731         PublicInbox::Import::init_bare($git_dir);
732         my @cmd = (qw/git config/, "--file=$git_dir/config",
733                         'include.path', '../../all.git/config');
734         PublicInbox::Import::run_die(\@cmd);
735         fill_alternates($self, $epoch);
736         $git_dir
737 }
738
739 sub git_dir_latest {
740         my ($self, $max) = @_;
741         $$max = -1;
742         my $pfx = "$self->{ibx}->{inboxdir}/git";
743         return unless -d $pfx;
744         my $latest;
745         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
746         while (defined(my $git_dir = readdir($dh))) {
747                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
748                 if ($1 > $$max) {
749                         $$max = $1;
750                         $latest = "$pfx/$git_dir";
751                 }
752         }
753         $latest;
754 }
755
756 sub importer {
757         my ($self) = @_;
758         my $im = $self->{im};
759         if ($im) {
760                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
761                         return $im;
762                 } else {
763                         $self->{im} = undef;
764                         $im->done;
765                         $im = undef;
766                         $self->checkpoint;
767                         my $git_dir = $self->git_init(++$self->{epoch_max});
768                         my $git = PublicInbox::Git->new($git_dir);
769                         return $self->import_init($git, 0);
770                 }
771         }
772         my $epoch = 0;
773         my $max;
774         my $latest = git_dir_latest($self, \$max);
775         if (defined $latest) {
776                 my $git = PublicInbox::Git->new($latest);
777                 my $packed_bytes = $git->packed_bytes;
778                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
779
780                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
781                         $epoch = $max + 1;
782                 } else {
783                         $self->{epoch_max} = $max;
784                         return $self->import_init($git, $packed_bytes);
785                 }
786         }
787         $self->{epoch_max} = $epoch;
788         $latest = $self->git_init($epoch);
789         $self->import_init(PublicInbox::Git->new($latest), 0);
790 }
791
792 sub import_init {
793         my ($self, $git, $packed_bytes, $tmp) = @_;
794         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
795         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
796         $im->{lock_path} = undef;
797         $im->{path_type} = 'v2';
798         $self->{im} = $im unless $tmp;
799         $im;
800 }
801
802 # XXX experimental
803 sub diff ($$$) {
804         my ($mid, $cur, $new) = @_;
805
806         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
807         print $ah $cur->as_string or die "print: $!";
808         close $ah or die "close: $!";
809         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
810         PublicInbox::Import::drop_unwanted_headers($new);
811         print $bh $new->as_string or die "print: $!";
812         close $bh or die "close: $!";
813         my $cmd = [ qw(diff -u), $an, $bn ];
814         print STDERR "# MID conflict <$mid>\n";
815         my $pid = spawn($cmd, undef, { 1 => 2 });
816         waitpid($pid, 0) == $pid or die "diff did not finish";
817         unlink($an, $bn);
818 }
819
820 sub get_blob ($$) {
821         my ($self, $smsg) = @_;
822         if (my $im = $self->{im}) {
823                 my $msg = $im->cat_blob($smsg->{blob});
824                 return $msg if $msg;
825         }
826         # older message, should be in alternates
827         $self->{ibx}->msg_by_smsg($smsg);
828 }
829
830 sub content_exists ($$$) {
831         my ($self, $mime, $mid) = @_;
832         my $over = $self->{over};
833         my $chashes = content_hashes($mime);
834         my ($id, $prev);
835         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
836                 my $msg = get_blob($self, $smsg);
837                 if (!defined($msg)) {
838                         warn "broken smsg for $mid\n";
839                         next;
840                 }
841                 my $cur = PublicInbox::Eml->new($msg);
842                 return 1 if content_matches($chashes, $cur);
843
844                 # XXX DEBUG_DIFF is experimental and may be removed
845                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
846         }
847         undef;
848 }
849
850 sub atfork_child {
851         my ($self) = @_;
852         if (my $shards = $self->{idx_shards}) {
853                 $_->atfork_child foreach @$shards;
854         }
855         if (my $im = $self->{im}) {
856                 $im->atfork_child;
857         }
858         die "unexpected mm" if $self->{mm};
859         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
860         $self->{bnote}->[1];
861 }
862
863 sub reindex_checkpoint ($$) {
864         my ($self, $sync) = @_;
865
866         $sync->{mm_tmp}->atfork_prepare;
867         $self->done; # release lock
868
869         if (my $pr = $sync->{-opt}->{-progress}) {
870                 $pr->(sprintf($sync->{-regen_fmt}, $sync->{nr}));
871         }
872
873         # allow -watch or -mda to write...
874         $self->idx_init; # reacquire lock
875         $sync->{mm_tmp}->atfork_parent;
876 }
877
878 sub reindex_oid ($$$) {
879         my ($self, $sync, $oid) = @_;
880         return if too_big($self, $oid);
881         my ($num, $mid0, $len);
882         my $msgref = $self->{ibx}->git->cat_file($oid, \$len);
883         return if $len == 0; # purged
884         my $mime = PublicInbox::Eml->new($$msgref);
885         my $mids = mids($mime->header_obj);
886         my $chash = content_hash($mime);
887
888         if (scalar(@$mids) == 0) {
889                 warn "E: $oid has no Message-ID, skipping\n";
890                 return;
891         }
892
893         # {unindexed} is unlikely
894         if ((my $unindexed = $self->{unindexed}) && scalar(@$mids) == 1) {
895                 $num = delete($unindexed->{$mids->[0]});
896                 if (defined $num) {
897                         $mid0 = $mids->[0];
898                         $self->{mm}->mid_set($num, $mid0);
899                         delete($self->{unindexed}) if !keys(%$unindexed);
900                 }
901         }
902         if (!defined($num)) { # reuse if reindexing (or duplicates)
903                 my $over = $self->{over};
904                 for my $mid (@$mids) {
905                         ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
906                         last if defined $num;
907                 }
908         }
909         $mid0 //= do { # is this a number we got before?
910                 $num = $sync->{mm_tmp}->num_for($mids->[0]);
911                 defined($num) ? $mids->[0] : undef;
912         };
913         if (!defined($num)) {
914                 for (my $i = $#$mids; $i >= 1; $i--) {
915                         $num = $sync->{mm_tmp}->num_for($mids->[$i]);
916                         if (defined($num)) {
917                                 $mid0 = $mids->[$i];
918                                 last;
919                         }
920                 }
921         }
922         if (defined($num)) {
923                 $sync->{mm_tmp}->num_delete($num);
924         } else { # never seen
925                 $num = $self->{mm}->mid_insert($mids->[0]);
926                 if (defined($num)) {
927                         $mid0 = $mids->[0];
928                 } else { # rare, try the rest of them, backwards
929                         for (my $i = $#$mids; $i >= 1; $i--) {
930                                 $num = $self->{mm}->mid_insert($mids->[$i]);
931                                 if (defined($num)) {
932                                         $mid0 = $mids->[$i];
933                                         last;
934                                 }
935                         }
936                 }
937         }
938         if (!defined($num)) {
939                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
940                 return;
941         }
942         $sync->{nr}++;
943         my $smsg = bless {
944                 raw_bytes => $len,
945                 num => $num,
946                 blob => $oid,
947                 mid => $mid0,
948         }, 'PublicInbox::Smsg';
949         $smsg->populate($mime, $sync);
950         if (do_idx($self, $msgref, $mime, $smsg)) {
951                 reindex_checkpoint($self, $sync);
952         }
953 }
954
955 # only update last_commit for $i on reindex iff newer than current
956 sub update_last_commit ($$$$) {
957         my ($self, $git, $i, $cmt) = @_;
958         my $last = last_epoch_commit($self, $i);
959         if (defined $last && is_ancestor($git, $last, $cmt)) {
960                 my @cmd = (qw(rev-list --count), "$last..$cmt");
961                 chomp(my $n = $git->qx(@cmd));
962                 return if $n ne '' && $n == 0;
963         }
964         last_epoch_commit($self, $i, $cmt);
965 }
966
967 sub git_dir_n ($$) { "$_[0]->{ibx}->{inboxdir}/git/$_[1].git" }
968
969 sub last_commits ($$) {
970         my ($self, $epoch_max) = @_;
971         my $heads = [];
972         for (my $i = $epoch_max; $i >= 0; $i--) {
973                 $heads->[$i] = last_epoch_commit($self, $i);
974         }
975         $heads;
976 }
977
978 # returns a revision range for git-log(1)
979 sub log_range ($$$$$) {
980         my ($self, $sync, $git, $i, $tip) = @_;
981         my $opt = $sync->{-opt};
982         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
983         my $cur = $sync->{ranges}->[$i] or do {
984                 $pr->("$i.git indexing all of $tip") if $pr;
985                 return $tip; # all of it
986         };
987
988         # fast equality check to avoid (v)fork+execve overhead
989         if ($cur eq $tip) {
990                 $sync->{ranges}->[$i] = undef;
991                 return;
992         }
993
994         my $range = "$cur..$tip";
995         $pr->("$i.git checking contiguity... ") if $pr;
996         if (is_ancestor($git, $cur, $tip)) { # common case
997                 $pr->("OK\n") if $pr;
998                 my $n = $git->qx(qw(rev-list --count), $range);
999                 chomp($n);
1000                 if ($n == 0) {
1001                         $sync->{ranges}->[$i] = undef;
1002                         $pr->("$i.git has nothing new\n") if $pr;
1003                         return; # nothing to do
1004                 }
1005                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1006         } else {
1007                 $pr->("FAIL\n") if $pr;
1008                 warn <<"";
1009 discontiguous range: $range
1010 Rewritten history? (in $git->{git_dir})
1011
1012                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1013                 if ($base) {
1014                         $range = "$base..$tip";
1015                         warn "found merge-base: $base\n"
1016                 } else {
1017                         $range = $tip;
1018                         warn "discarding history at $cur\n";
1019                 }
1020                 warn <<"";
1021 reindexing $git->{git_dir} starting at
1022 $range
1023
1024                 $sync->{unindex_range}->{$i} = "$base..$cur";
1025         }
1026         $range;
1027 }
1028
1029 sub sync_prepare ($$$) {
1030         my ($self, $sync, $epoch_max) = @_;
1031         my $pr = $sync->{-opt}->{-progress};
1032         my $regen_max = 0;
1033         my $head = $self->{ibx}->{ref_head} || 'refs/heads/master';
1034
1035         # reindex stops at the current heads and we later rerun index_sync
1036         # without {reindex}
1037         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1038
1039         for (my $i = $epoch_max; $i >= 0; $i--) {
1040                 my $git_dir = git_dir_n($self, $i);
1041                 -d $git_dir or next; # missing epochs are fine
1042                 my $git = PublicInbox::Git->new($git_dir);
1043                 if ($reindex_heads) {
1044                         $head = $reindex_heads->[$i] or next;
1045                 }
1046                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1047
1048                 next if $?; # new repo
1049                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1050                 # can't use 'rev-list --count' if we use --diff-filter
1051                 $pr->("$i.git counting $range ... ") if $pr;
1052                 # Don't bump num_highwater on --reindex by using {D}.
1053                 # We intentionally do NOT use {D} in the non-reindex case
1054                 # because we want NNTP article number gaps from unindexed
1055                 # messages to show up in mirrors, too.
1056                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1057                 my $stk = log2stack($sync, $git, $range, $self->{ibx});
1058                 my $nr = $stk ? $stk->num_records : 0;
1059                 $pr->("$nr\n") if $pr;
1060                 $sync->{stacks}->[$i] = $stk if $stk;
1061                 $regen_max += $nr;
1062         }
1063
1064         # XXX this should not happen unless somebody bypasses checks in
1065         # our code and blindly injects "d" file history into git repos
1066         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1067                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1068                 for my $oid (@leftovers) {
1069                         $oid = unpack('H*', $oid);
1070                         $self->{current_info} = "leftover $oid";
1071                         unindex_oid($self, $oid);
1072                 }
1073         }
1074         return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1075
1076         # reindex should NOT see new commits anymore, if we do,
1077         # it's a problem and we need to notice it via die()
1078         my $pad = length($regen_max) + 1;
1079         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1080         $sync->{nr} = 0;
1081         return -1 if $sync->{reindex};
1082         $regen_max + $self->{mm}->num_highwater() || 0;
1083 }
1084
1085 sub unindex_oid_remote ($$$) {
1086         my ($self, $oid, $mid) = @_;
1087         my @removed = $self->{over}->remove_oid($oid, $mid);
1088         for my $num (@removed) {
1089                 my $idx = idx_shard($self, $num % $self->{shards});
1090                 $idx->remote_remove($oid, $num);
1091         }
1092 }
1093
1094 sub unindex_oid ($$;$) {
1095         my ($self, $oid, $unindexed) = @_;
1096         my $mm = $self->{mm};
1097         my $msgref = $self->{ibx}->git->cat_file($oid);
1098         my $mime = PublicInbox::Eml->new($msgref);
1099         my $mids = mids($mime->header_obj);
1100         $mime = $msgref = undef;
1101         my $over = $self->{over};
1102         foreach my $mid (@$mids) {
1103                 my %gone;
1104                 my ($id, $prev);
1105                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1106                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1107                 }
1108                 my $n = scalar(keys(%gone)) or next;
1109                 if ($n > 1) {
1110                         warn "BUG: multiple articles linked to $oid\n",
1111                                 join(',',sort keys %gone), "\n";
1112                 }
1113                 foreach my $num (keys %gone) {
1114                         if ($unindexed) {
1115                                 my $mid0 = $mm->mid_for($num);
1116                                 $unindexed->{$mid0} = $num;
1117                         }
1118                         $mm->num_delete($num);
1119                 }
1120                 unindex_oid_remote($self, $oid, $mid);
1121         }
1122 }
1123
1124 # this is rare, it only happens when we get discontiguous history in
1125 # a mirror because the source used -purge or -edit
1126 sub unindex ($$$$) {
1127         my ($self, $sync, $git, $unindex_range) = @_;
1128         my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1129         my $before = scalar keys %$unindexed;
1130         # order does not matter, here:
1131         my @cmd = qw(log --raw -r
1132                         --no-notes --no-color --no-abbrev --no-renames);
1133         my $fh = $git->popen(@cmd, $unindex_range);
1134         while (<$fh>) {
1135                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1136                 unindex_oid($self, $1, $unindexed);
1137         }
1138         close $fh or die "git log failed: \$?=$?";
1139
1140         return unless $sync->{-opt}->{prune};
1141         my $after = scalar keys %$unindexed;
1142         return if $before == $after;
1143
1144         # ensure any blob can not longer be accessed via dumb HTTP
1145         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1146                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1147 }
1148
1149 sub sync_ranges ($$$) {
1150         my ($self, $sync, $epoch_max) = @_;
1151         my $reindex = $sync->{reindex};
1152
1153         return last_commits($self, $epoch_max) unless $reindex;
1154         return [] if ref($reindex) ne 'HASH';
1155
1156         my $ranges = $reindex->{from}; # arrayref;
1157         if (ref($ranges) ne 'ARRAY') {
1158                 die 'BUG: $reindex->{from} not an ARRAY';
1159         }
1160         $ranges;
1161 }
1162
1163 sub index_epoch ($$$) {
1164         my ($self, $sync, $i) = @_;
1165
1166         my $git_dir = git_dir_n($self, $i);
1167         -d $git_dir or return; # missing epochs are fine
1168         my $git = PublicInbox::Git->new($git_dir);
1169         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { # rare
1170                 unindex($self, $sync, $git, $unindex_range);
1171         }
1172         defined(my $stk = $sync->{stacks}->[$i]) or return;
1173         $sync->{stacks}->[$i] = undef;
1174         while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1175                 $self->{current_info} = "$i.git $oid";
1176                 if ($f eq 'm') {
1177                         $sync->{autime} = $at;
1178                         $sync->{cotime} = $ct;
1179                         reindex_oid($self, $sync, $oid);
1180                 } elsif ($f eq 'd') {
1181                         unindex_oid($self, $oid);
1182                 }
1183         }
1184         delete @$sync{qw(autime cotime)};
1185         update_last_commit($self, $git, $i, $stk->{latest_cmt});
1186 }
1187
1188 # public, called by public-inbox-index
1189 sub index_sync {
1190         my ($self, $opt) = @_;
1191         $opt ||= {};
1192         my $pr = $opt->{-progress};
1193         my $epoch_max;
1194         my $latest = git_dir_latest($self, \$epoch_max);
1195         return unless defined $latest;
1196         $self->idx_init($opt); # acquire lock
1197         fill_alternates($self, $epoch_max);
1198         $self->{over}->rethread_prepare($opt);
1199         my $sync = {
1200                 unindex_range => {}, # EPOCH => oid_old..oid_new
1201                 reindex => $opt->{reindex},
1202                 -opt => $opt
1203         };
1204         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1205         if (sync_prepare($self, $sync, $epoch_max)) {
1206                 # tmp_clone seems to fail if inside a transaction, so
1207                 # we rollback here (because we opened {mm} for reading)
1208                 # Note: we do NOT rely on DBI transactions for atomicity;
1209                 # only for batch performance.
1210                 $self->{mm}->{dbh}->rollback;
1211                 $self->{mm}->{dbh}->begin_work;
1212                 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1213         }
1214
1215         # work forwards through history
1216         index_epoch($self, $sync, $_) for (0..$epoch_max);
1217         $self->done;
1218
1219         if (my $nr = $sync->{nr}) {
1220                 my $pr = $sync->{-opt}->{-progress};
1221                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1222         }
1223         $self->{over}->rethread_done($opt);
1224
1225         # reindex does not pick up new changes, so we rerun w/o it:
1226         if ($opt->{reindex}) {
1227                 my %again = %$opt;
1228                 $sync = undef;
1229                 delete @again{qw(rethread reindex -skip_lock)};
1230                 index_sync($self, \%again);
1231         }
1232 }
1233
1234 1;