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>
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;
9 use parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::IdxStack;
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(log2stack crlf_adjust is_ancestor check_size);
22 use IO::Handle; # ->autoflush
23 use File::Temp qw(tempfile);
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;
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;
38 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
39 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
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;
47 # should we bother with `sysctl hw.ncpu`? Those only give
48 # us total processor count, not online processor count.
52 sub nproc_shards ($) {
54 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
57 # assume 2 cores if not detectable or zero
58 state $NPROC_DETECTED = detect_nproc() || 2;
60 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
63 # subtract for the main process and git-fast-import
68 sub count_shards ($) {
71 my $xpfx = $self->{xpfx};
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"
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};
86 $XapianDatabase->new($shard)->close;
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;
103 File::Path::mkpath($dir);
105 die "$dir does not exist\n";
108 $v2ibx->umask_prepare;
110 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
113 im => undef, # PublicInbox::Import
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
125 $self->{over}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
126 $self->{shards} = count_shards($self) || nproc_shards($creat);
132 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
133 if (defined $shards) {
134 $self->{parallel} = 0 if $shards == 0;
135 $self->{shards} = $shards if $shards > 0;
138 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
140 git_dir_latest($self, \$epoch_max);
141 if (defined $skip_epoch && $epoch_max == -1) {
142 $epoch_max = $skip_epoch;
144 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
148 # returns undef on duplicate or spam
149 # mimics Import::add and wraps it for v2
151 my ($self, $eml, $check_cb) = @_;
152 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
155 sub batch_bytes ($) {
157 ($self->{parallel} ? $self->{shards} : 1) *
158 $PublicInbox::SearchIdx::BATCH_BYTES;
161 # indexes a message, returns true if checkpointing is needed
163 my ($self, $msgref, $mime, $smsg) = @_;
164 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
165 $self->{over}->add_overview($mime, $smsg);
166 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
167 $idx->index_raw($msgref, $mime, $smsg);
168 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
169 $n >= batch_bytes($self);
173 my ($self, $mime, $check_cb) = @_;
177 $mime = $check_cb->($mime, $self->{ibx}) or return;
180 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
181 # as does SQLite 3.4.1+ (released in 2007-07-20), and
182 # Xapian 1.3.2+ (released 2015-03-15).
183 # For the most part, we can spawn git-fast-import without
184 # leaking FDs to it...
187 my ($num, $mid0) = v2_num_for($self, $mime);
188 defined $num or return; # duplicate
189 defined $mid0 or die "BUG: \$mid0 undefined\n";
190 my $im = $self->importer;
191 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
192 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
193 $cmt = $im->get_mark($cmt);
194 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
196 my $msgref = delete $smsg->{-raw_email};
197 if (do_idx($self, $msgref, $mime, $smsg)) {
205 my ($self, $mime) = @_;
206 my $mids = mids($mime);
208 my $mid = $mids->[0];
209 my $num = $self->{mm}->mid_insert($mid);
210 if (defined $num) { # common case
214 # crap, Message-ID is already known, hope somebody just resent:
215 foreach my $m (@$mids) {
216 # read-only lookup now safe to do after above barrier
217 # easy, don't store duplicates
218 # note: do not add more diagnostic info here since
219 # it gets noisy on public-inbox-watch restarts
220 return () if content_exists($self, $mime, $m);
223 # AltId may pre-populate article numbers (e.g. X-Mail-Count
224 # or NNTP article number), use that article number if it's
226 my $altid = $self->{ibx}->{altid};
227 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
228 my $num = $self->{mm}->num_for($mid);
230 if (defined $num && !$self->{over}->get_art($num)) {
236 warn "<$mid> reused for mismatched content\n";
238 # try the rest of the mids
239 for(my $i = $#$mids; $i >= 1; $i--) {
241 $num = $self->{mm}->mid_insert($m);
243 warn "alternative <$m> for <$mid> found\n";
248 # none of the existing Message-IDs are good, generate a new one:
249 v2_num_for_harder($self, $mime);
252 sub v2_num_for_harder {
253 my ($self, $eml) = @_;
255 my $dig = content_digest($eml);
256 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
257 my $num = $self->{mm}->mid_insert($mid0);
258 unless (defined $num) {
259 # it's hard to spoof the last Received: header
260 my @recvd = $eml->header_raw('Received');
261 $dig->add("Received: $_") foreach (@recvd);
262 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
263 $num = $self->{mm}->mid_insert($mid0);
265 # fall back to a random Message-ID and give up determinism:
266 until (defined($num)) {
268 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
269 warn "using random Message-ID <$mid0> as fallback\n";
270 $num = $self->{mm}->mid_insert($mid0);
273 PublicInbox::Import::append_mid($eml, $mid0);
278 my ($self, $shard_i) = @_;
279 $self->{idx_shards}->[$shard_i];
282 sub _idx_init { # with_umask callback
283 my ($self, $opt) = @_;
284 $self->lock_acquire unless $opt && $opt->{-skip_lock};
285 $self->{over}->create;
287 # xcpdb can change shard count while -watch is idle
288 my $nshards = count_shards($self);
289 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
291 # need to create all shards before initializing msgmap FD
292 # idx_shards must be visible to all forked processes
293 my $max = $self->{shards} - 1;
294 my $idx = $self->{idx_shards} = [];
295 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
297 # Now that all subprocesses are up, we can open the FDs
299 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
300 "$self->{ibx}->{inboxdir}/msgmap.sqlite3",
301 $self->{ibx}->{-no_fsync} ? 2 : 1);
302 $mm->{dbh}->begin_work;
307 my ($self, $opt) = @_;
308 return if $self->{idx_shards};
309 my $ibx = $self->{ibx};
311 # do not leak read-only FDs to child processes, we only have these
312 # FDs for duplicate detection so they should not be
313 # frequently activated.
314 delete @$ibx{qw(mm search)};
317 $self->{parallel} = 0 if ($ibx->{indexlevel}//'') eq 'basic';
318 if ($self->{parallel}) {
319 pipe(my ($r, $w)) or die "pipe failed: $!";
320 # pipe for barrier notifications doesn't need to be big,
322 fcntl($w, 1031, 4096) if $^O eq 'linux';
323 $self->{bnote} = [ $r, $w ];
328 $ibx->with_umask(\&_idx_init, $self, $opt);
331 # returns an array mapping [ epoch => latest_commit ]
332 # latest_commit may be undef if nothing was done to that epoch
333 # $replace_map = { $object_id => $strref, ... }
334 sub _replace_oids ($$$) {
335 my ($self, $mime, $replace_map) = @_;
337 my $pfx = "$self->{ibx}->{inboxdir}/git";
338 my $rewrites = []; # epoch => commit
339 my $max = $self->{epoch_max};
341 unless (defined($max)) {
342 defined(my $latest = git_dir_latest($self, \$max)) or return;
343 $self->{epoch_max} = $max;
346 foreach my $i (0..$max) {
347 my $git_dir = "$pfx/$i.git";
349 my $git = PublicInbox::Git->new($git_dir);
350 my $im = $self->import_init($git, 0, 1);
351 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
357 sub content_hashes ($) {
359 my @chashes = ( content_hash($mime) );
361 # We still support Email::MIME, here, and
362 # Email::MIME->as_string doesn't always round-trip, so we may
363 # use a second content_hash
364 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
365 push @chashes, $rt if $chashes[0] ne $rt;
369 sub content_matches ($$) {
370 my ($chashes, $existing) = @_;
371 my $chash = content_hash($existing);
372 foreach (@$chashes) {
373 return 1 if $_ eq $chash
378 # used for removing or replacing (purging)
379 sub rewrite_internal ($$;$$$) {
380 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
382 my ($im, $need_reindex, $replace_map);
384 $replace_map = {}; # oid => sref
385 $need_reindex = [] if $new_eml;
387 $im = $self->importer;
389 my $over = $self->{over};
390 my $chashes = content_hashes($old_eml);
392 my $mids = mids($old_eml);
394 # We avoid introducing new blobs into git since the raw content
395 # can be slightly different, so we do not need the user-supplied
396 # message now that we have the mids and content_hash
400 foreach my $mid (@$mids) {
401 my %gone; # num => [ smsg, $mime, raw ]
403 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
404 my $msg = get_blob($self, $smsg);
405 if (!defined($msg)) {
406 warn "broken smsg for $mid\n";
410 my $cur = PublicInbox::Eml->new($msg);
411 if (content_matches($chashes, $cur)) {
412 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
415 my $n = scalar keys %gone;
418 warn "BUG: multiple articles linked to <$mid>\n",
419 join(',', sort keys %gone), "\n";
421 foreach my $num (keys %gone) {
422 my ($smsg, $mime, $orig) = @{$gone{$num}};
423 # $removed should only be set once assuming
424 # no bugs in our deduplication code:
425 $removed = [ undef, $mime, $smsg ];
426 my $oid = $smsg->{blob};
428 $replace_map->{$oid} = $sref;
430 ($mark, undef) = $im->remove($orig, $cmt_msg);
431 $removed->[0] = $mark;
434 if ($need_reindex) { # ->replace
435 push @$need_reindex, $smsg;
436 } else { # ->purge or ->remove
437 $self->{mm}->num_delete($num);
439 unindex_oid_remote($self, $oid, $mid);
444 my $cmt = $im->get_mark($mark);
445 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
447 if ($replace_map && scalar keys %$replace_map) {
448 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
449 return { rewrites => $rewrites, need_reindex => $need_reindex };
451 defined($mark) ? $removed : undef;
454 # public (see PublicInbox::Import->remove), but note the 3rd element
455 # (retval[2]) is not part of the stable API shared with Import->remove
457 my ($self, $eml, $cmt_msg) = @_;
458 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
459 $self, $eml, $cmt_msg);
460 defined($r) && defined($r->[0]) ? @$r: undef;
463 sub _replace ($$;$$) {
464 my ($self, $old_eml, $new_eml, $sref) = @_;
465 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
466 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
467 $self, $old_eml, undef, $new_eml, $sref) or return;
469 my $rewrites = $rewritten->{rewrites};
470 # ->done is called if there are rewrites since we gc+prune from git
471 $self->idx_init if @$rewrites;
473 for my $i (0..$#$rewrites) {
474 defined(my $cmt = $rewrites->[$i]) or next;
475 $self->{last_commit}->[$i] = $cmt;
482 my ($self, $mime) = @_;
483 my $rewritten = _replace($self, $mime, undef, \'') or return;
484 $rewritten->{rewrites}
487 # returns the git object_id of $fh, does not write the object to FS
488 sub git_hash_raw ($$) {
489 my ($self, $raw) = @_;
490 # grab the expected OID we have to reindex:
491 pipe(my($in, $w)) or die "pipe: $!";
492 my $git_dir = $self->{ibx}->git->{git_dir};
493 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
494 my $r = popen_rd($cmd, undef, { 0 => $in });
495 print $w $$raw or die "print \$w: $!";
496 close $w or die "close \$w: $!";
498 chomp(my $oid = <$r>);
499 close $r or die "git hash-object failed: $?";
500 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
504 sub _check_mids_match ($$$) {
505 my ($old_list, $new_list, $hdrs) = @_;
506 my %old_mids = map { $_ => 1 } @$old_list;
507 my %new_mids = map { $_ => 1 } @$new_list;
508 my @old = keys %old_mids;
509 my @new = keys %new_mids;
510 my $err = "$hdrs may not be changed when replacing\n";
511 die $err if scalar(@old) != scalar(@new);
512 delete @new_mids{@old};
513 delete @old_mids{@new};
514 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
517 # Changing Message-IDs or References with ->replace isn't supported.
518 # The rules for dealing with messages with multiple or conflicting
519 # Message-IDs are pretty complex and rethreading hasn't been fully
521 sub check_mids_match ($$) {
522 my ($old, $new) = @_;
523 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
524 _check_mids_match(references($old), references($new),
525 'References/In-Reply-To');
530 my ($self, $old_mime, $new_mime) = @_;
532 check_mids_match($old_mime, $new_mime);
534 # mutt will always add Content-Length:, Status:, Lines: when editing
535 PublicInbox::Import::drop_unwanted_headers($new_mime);
537 my $raw = $new_mime->as_string;
538 my $expect_oid = git_hash_raw($self, \$raw);
539 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
540 my $need_reindex = $rewritten->{need_reindex};
542 # just in case we have bugs in deduplication code:
543 my $n = scalar(@$need_reindex);
545 my $list = join(', ', map {
546 "$_->{num}: <$_->{mid}>"
549 W: rewritten $n messages matching content of original message (expected: 1).
550 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
555 # make sure we really got the OID:
556 my ($blob, $type, $bytes) = $self->{ibx}->git->check($expect_oid);
557 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
559 # don't leak FDs to Xapian:
560 $self->{ibx}->git->cleanup;
562 # reindex modified messages:
563 for my $smsg (@$need_reindex) {
564 my $new_smsg = bless {
569 }, 'PublicInbox::Smsg';
570 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
571 $new_smsg->populate($new_mime, $sync);
572 do_idx($self, \$raw, $new_mime, $new_smsg);
574 $rewritten->{rewrites};
577 sub last_epoch_commit ($$;$) {
578 my ($self, $i, $cmt) = @_;
579 my $v = PublicInbox::Search::SCHEMA_VERSION();
580 $self->{mm}->last_commit_xap($v, $i, $cmt);
583 sub set_last_commits ($) {
585 defined(my $epoch_max = $self->{epoch_max}) or return;
586 my $last_commit = $self->{last_commit};
587 foreach my $i (0..$epoch_max) {
588 defined(my $cmt = $last_commit->[$i]) or next;
589 $last_commit->[$i] = undef;
590 last_epoch_commit($self, $i, $cmt);
596 $self->{bnote} or return;
598 my $barrier = { map { $_ => 1 } (0..$n) };
602 my ($self, $barrier) = @_;
603 my $bnote = $self->{bnote} or return;
605 while (scalar keys %$barrier) {
606 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
607 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
608 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
613 sub checkpoint ($;$) {
614 my ($self, $wait) = @_;
616 if (my $im = $self->{im}) {
623 my $shards = $self->{idx_shards};
625 my $dbh = $self->{mm}->{dbh};
627 # SQLite msgmap data is second in importance
630 # SQLite overview is third
631 $self->{over}->commit_lazy;
633 # Now deal with Xapian
635 my $barrier = $self->barrier_init(scalar @$shards);
637 # each shard needs to issue a barrier command
638 $_->remote_barrier for @$shards;
640 # wait for each Xapian shard
641 $self->barrier_wait($barrier);
643 $_->remote_commit for @$shards;
646 # last_commit is special, don't commit these until
647 # remote shards are done:
649 set_last_commits($self);
654 $self->{total_bytes} += $self->{transact_bytes};
655 $self->{transact_bytes} = 0;
658 # issue a write barrier to ensure all data is visible to other processes
659 # and read-only ops. Order of data importance is: git > SQLite > Xapian
661 sub barrier { checkpoint($_[0], 1) };
667 if (my $im = delete $self->{im}) {
668 eval { $im->done }; # PublicInbox::Import::done
669 $err .= "import done: $@\n" if $@;
672 eval { checkpoint($self) };
673 $err .= "checkpoint: $@\n" if $@;
675 if (my $mm = delete $self->{mm}) {
676 my $m = $err ? 'rollback' : 'commit';
677 eval { $mm->{dbh}->$m };
678 $err .= "msgmap $m: $@\n" if $@;
680 my $shards = delete $self->{idx_shards};
683 eval { $_->remote_close };
684 $err .= "shard close: $@\n" if $@;
687 eval { $self->{over}->disconnect };
688 $err .= "over disconnect: $@\n" if $@;
689 delete $self->{bnote};
690 my $nbytes = $self->{total_bytes};
691 $self->{total_bytes} = 0;
692 $self->lock_release(!!$nbytes) if $shards;
693 $self->{ibx}->git->cleanup;
697 sub fill_alternates ($$) {
698 my ($self, $epoch) = @_;
700 my $pfx = "$self->{ibx}->{inboxdir}/git";
701 my $all = "$self->{ibx}->{inboxdir}/all.git";
702 PublicInbox::Import::init_bare($all) unless -d $all;
703 my $info_dir = "$all/objects/info";
704 my $alt = "$info_dir/alternates";
708 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
709 $mode = (stat($fh))[2] & 07777;
711 # we assign a sort score to every alternate and favor
712 # the newest (highest numbered) one because loose objects
713 # require scanning epochs and only the latest epoch is
714 # expected to see loose objects
716 my $other = 0; # in case admin adds non-epoch repos
718 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
724 } split(/\n+/, do { local $/; <$fh> });
727 foreach my $i (0..$epoch) {
728 my $dir = "../../git/$i.git/objects";
729 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
736 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
737 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
738 or die "print $tmp: $!\n";
739 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
740 close $fh or die "close $tmp $!\n";
741 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
745 my ($self, $epoch) = @_;
746 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
747 PublicInbox::Import::init_bare($git_dir);
748 my @cmd = (qw/git config/, "--file=$git_dir/config",
749 'include.path', '../../all.git/config');
750 PublicInbox::Import::run_die(\@cmd);
751 fill_alternates($self, $epoch);
756 my ($self, $max) = @_;
758 my $pfx = "$self->{ibx}->{inboxdir}/git";
759 return unless -d $pfx;
761 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
762 while (defined(my $git_dir = readdir($dh))) {
763 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
766 $latest = "$pfx/$git_dir";
774 my $im = $self->{im};
776 if ($im->{bytes_added} < $self->{rotate_bytes}) {
783 my $git_dir = $self->git_init(++$self->{epoch_max});
784 my $git = PublicInbox::Git->new($git_dir);
785 return $self->import_init($git, 0);
790 my $latest = git_dir_latest($self, \$max);
791 if (defined $latest) {
792 my $git = PublicInbox::Git->new($latest);
793 my $packed_bytes = $git->packed_bytes;
794 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
796 if ($unpacked_bytes >= $self->{rotate_bytes}) {
799 $self->{epoch_max} = $max;
800 return $self->import_init($git, $packed_bytes);
803 $self->{epoch_max} = $epoch;
804 $latest = $self->git_init($epoch);
805 $self->import_init(PublicInbox::Git->new($latest), 0);
809 my ($self, $git, $packed_bytes, $tmp) = @_;
810 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
811 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
812 $im->{lock_path} = undef;
813 $im->{path_type} = 'v2';
814 $self->{im} = $im unless $tmp;
820 my ($mid, $cur, $new) = @_;
822 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
823 print $ah $cur->as_string or die "print: $!";
824 close $ah or die "close: $!";
825 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
826 PublicInbox::Import::drop_unwanted_headers($new);
827 print $bh $new->as_string or die "print: $!";
828 close $bh or die "close: $!";
829 my $cmd = [ qw(diff -u), $an, $bn ];
830 print STDERR "# MID conflict <$mid>\n";
831 my $pid = spawn($cmd, undef, { 1 => 2 });
832 waitpid($pid, 0) == $pid or die "diff did not finish";
837 my ($self, $smsg) = @_;
838 if (my $im = $self->{im}) {
839 my $msg = $im->cat_blob($smsg->{blob});
842 # older message, should be in alternates
843 $self->{ibx}->msg_by_smsg($smsg);
846 sub content_exists ($$$) {
847 my ($self, $mime, $mid) = @_;
848 my $over = $self->{over};
849 my $chashes = content_hashes($mime);
851 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
852 my $msg = get_blob($self, $smsg);
853 if (!defined($msg)) {
854 warn "broken smsg for $mid\n";
857 my $cur = PublicInbox::Eml->new($msg);
858 return 1 if content_matches($chashes, $cur);
860 # XXX DEBUG_DIFF is experimental and may be removed
861 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
868 if (my $shards = $self->{idx_shards}) {
869 $_->atfork_child foreach @$shards;
871 if (my $im = $self->{im}) {
874 die "unexpected mm" if $self->{mm};
875 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
879 sub reindex_checkpoint ($$) {
880 my ($self, $sync) = @_;
882 $self->{ibx}->git->cleanup; # *async_wait
883 ${$sync->{need_checkpoint}} = 0;
884 my $mm_tmp = $sync->{mm_tmp};
885 $mm_tmp->atfork_prepare if $mm_tmp;
886 $self->done; # release lock
888 if (my $pr = $sync->{-opt}->{-progress}) {
889 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
892 # allow -watch or -mda to write...
893 $self->idx_init; # reacquire lock
894 $mm_tmp->atfork_parent if $mm_tmp;
897 sub index_oid { # cat_async callback
898 my ($bref, $oid, $type, $size, $arg) = @_;
899 return if $size == 0; # purged
901 my $eml = PublicInbox::Eml->new($$bref);
902 my $mids = mids($eml);
903 my $chash = content_hash($eml);
904 my $self = $arg->{v2w};
906 if (scalar(@$mids) == 0) {
907 warn "E: $oid has no Message-ID, skipping\n";
911 # {unindexed} is unlikely
912 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
913 $num = delete($unindexed->{$mids->[0]});
916 $self->{mm}->mid_set($num, $mid0);
917 delete($arg->{unindexed}) if !keys(%$unindexed);
920 if (!defined($num)) { # reuse if reindexing (or duplicates)
921 my $over = $self->{over};
922 for my $mid (@$mids) {
923 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
924 last if defined $num;
927 $mid0 //= do { # is this a number we got before?
928 $num = $arg->{mm_tmp}->num_for($mids->[0]);
929 defined($num) ? $mids->[0] : undef;
931 if (!defined($num)) {
932 for (my $i = $#$mids; $i >= 1; $i--) {
933 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
941 $arg->{mm_tmp}->num_delete($num);
942 } else { # never seen
943 $num = $self->{mm}->mid_insert($mids->[0]);
946 } else { # rare, try the rest of them, backwards
947 for (my $i = $#$mids; $i >= 1; $i--) {
948 $num = $self->{mm}->mid_insert($mids->[$i]);
956 if (!defined($num)) {
957 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
966 }, 'PublicInbox::Smsg';
967 $smsg->populate($eml, $arg);
968 if (do_idx($self, $bref, $eml, $smsg)) {
969 ${$arg->{need_checkpoint}} = 1;
973 # only update last_commit for $i on reindex iff newer than current
974 sub update_last_commit ($$$$) {
975 my ($self, $git, $i, $cmt) = @_;
976 my $last = last_epoch_commit($self, $i);
977 if (defined $last && is_ancestor($git, $last, $cmt)) {
978 my @cmd = (qw(rev-list --count), "$last..$cmt");
979 chomp(my $n = $git->qx(@cmd));
980 return if $n ne '' && $n == 0;
982 last_epoch_commit($self, $i, $cmt);
985 sub git_dir_n ($$) { "$_[0]->{ibx}->{inboxdir}/git/$_[1].git" }
987 sub last_commits ($$) {
988 my ($self, $epoch_max) = @_;
990 for (my $i = $epoch_max; $i >= 0; $i--) {
991 $heads->[$i] = last_epoch_commit($self, $i);
996 # returns a revision range for git-log(1)
997 sub log_range ($$$$$) {
998 my ($self, $sync, $git, $i, $tip) = @_;
999 my $opt = $sync->{-opt};
1000 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1001 my $cur = $sync->{ranges}->[$i] or do {
1002 $pr->("$i.git indexing all of $tip") if $pr;
1003 return $tip; # all of it
1006 # fast equality check to avoid (v)fork+execve overhead
1008 $sync->{ranges}->[$i] = undef;
1012 my $range = "$cur..$tip";
1013 $pr->("$i.git checking contiguity... ") if $pr;
1014 if (is_ancestor($git, $cur, $tip)) { # common case
1015 $pr->("OK\n") if $pr;
1016 my $n = $git->qx(qw(rev-list --count), $range);
1019 $sync->{ranges}->[$i] = undef;
1020 $pr->("$i.git has nothing new\n") if $pr;
1021 return; # nothing to do
1023 $pr->("$i.git has $n changes since $cur\n") if $pr;
1025 $pr->("FAIL\n") if $pr;
1027 discontiguous range: $range
1028 Rewritten history? (in $git->{git_dir})
1030 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1032 $range = "$base..$tip";
1033 warn "found merge-base: $base\n"
1036 warn "discarding history at $cur\n";
1039 reindexing $git->{git_dir} starting at
1042 $sync->{unindex_range}->{$i} = "$base..$cur";
1047 sub sync_prepare ($$$) {
1048 my ($self, $sync, $epoch_max) = @_;
1049 my $pr = $sync->{-opt}->{-progress};
1051 my $head = $self->{ibx}->{ref_head} || 'refs/heads/master';
1053 # reindex stops at the current heads and we later rerun index_sync
1055 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1057 for (my $i = $epoch_max; $i >= 0; $i--) {
1058 my $git_dir = git_dir_n($self, $i);
1059 -d $git_dir or next; # missing epochs are fine
1060 my $git = PublicInbox::Git->new($git_dir);
1061 if ($reindex_heads) {
1062 $head = $reindex_heads->[$i] or next;
1064 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1066 next if $?; # new repo
1067 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1068 # can't use 'rev-list --count' if we use --diff-filter
1069 $pr->("$i.git counting $range ... ") if $pr;
1070 # Don't bump num_highwater on --reindex by using {D}.
1071 # We intentionally do NOT use {D} in the non-reindex case
1072 # because we want NNTP article number gaps from unindexed
1073 # messages to show up in mirrors, too.
1074 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1075 my $stk = log2stack($sync, $git, $range, $self->{ibx});
1076 my $nr = $stk ? $stk->num_records : 0;
1077 $pr->("$nr\n") if $pr;
1078 $sync->{stacks}->[$i] = $stk if $stk;
1082 # XXX this should not happen unless somebody bypasses checks in
1083 # our code and blindly injects "d" file history into git repos
1084 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1085 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1086 my $arg = { v2w => $self };
1087 my $all = $self->{ibx}->git;
1088 for my $oid (@leftovers) {
1089 $oid = unpack('H*', $oid);
1090 $self->{current_info} = "leftover $oid";
1091 $all->cat_async($oid, \&unindex_oid, $arg);
1093 $all->cat_async_wait;
1095 if (!$regen_max && !keys(%{$self->{unindex_range}})) {
1096 $sync->{-regen_fmt} = "%u/?\n";
1100 # reindex should NOT see new commits anymore, if we do,
1101 # it's a problem and we need to notice it via die()
1102 my $pad = length($regen_max) + 1;
1103 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1104 $sync->{nr} = \(my $nr = 0);
1105 return -1 if $sync->{reindex};
1106 $regen_max + $self->{mm}->num_highwater() || 0;
1109 sub unindex_oid_remote ($$$) {
1110 my ($self, $oid, $mid) = @_;
1111 my @removed = $self->{over}->remove_oid($oid, $mid);
1112 for my $num (@removed) {
1113 my $idx = idx_shard($self, $num % $self->{shards});
1114 $idx->remote_remove($oid, $num);
1118 sub unindex_oid ($$;$) { # git->cat_async callback
1119 my ($bref, $oid, $type, $size, $sync) = @_;
1120 my $self = $sync->{v2w};
1121 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1122 my $mm = $self->{mm};
1123 my $mids = mids(PublicInbox::Eml->new($bref));
1125 my $over = $self->{over};
1126 foreach my $mid (@$mids) {
1129 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1130 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1132 my $n = scalar(keys(%gone)) or next;
1134 warn "BUG: multiple articles linked to $oid\n",
1135 join(',',sort keys %gone), "\n";
1137 foreach my $num (keys %gone) {
1139 my $mid0 = $mm->mid_for($num);
1140 $unindexed->{$mid0} = $num;
1142 $mm->num_delete($num);
1144 unindex_oid_remote($self, $oid, $mid);
1148 # this is rare, it only happens when we get discontiguous history in
1149 # a mirror because the source used -purge or -edit
1150 sub unindex ($$$$) {
1151 my ($self, $sync, $git, $unindex_range) = @_;
1152 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1153 my $before = scalar keys %$unindexed;
1154 # order does not matter, here:
1155 my @cmd = qw(log --raw -r
1156 --no-notes --no-color --no-abbrev --no-renames);
1157 my $fh = $git->popen(@cmd, $unindex_range);
1158 my $all = $self->{ibx}->git;
1159 local $sync->{in_unindex} = 1;
1161 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1162 $all->cat_async($1, \&unindex_oid, $sync);
1164 close $fh or die "git log failed: \$?=$?";
1165 $all->cat_async_wait;
1167 return unless $sync->{-opt}->{prune};
1168 my $after = scalar keys %$unindexed;
1169 return if $before == $after;
1171 # ensure any blob can not longer be accessed via dumb HTTP
1172 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1173 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1176 sub sync_ranges ($$$) {
1177 my ($self, $sync, $epoch_max) = @_;
1178 my $reindex = $sync->{reindex};
1180 return last_commits($self, $epoch_max) unless $reindex;
1181 return [] if ref($reindex) ne 'HASH';
1183 my $ranges = $reindex->{from}; # arrayref;
1184 if (ref($ranges) ne 'ARRAY') {
1185 die 'BUG: $reindex->{from} not an ARRAY';
1190 sub index_xap_only { # git->cat_async callback
1191 my ($bref, $oid, $type, $size, $smsg) = @_;
1192 my $self = $smsg->{v2w};
1193 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
1194 $smsg->{raw_bytes} = $size;
1195 $idx->index_raw($bref, undef, $smsg);
1196 $self->{transact_bytes} += $size;
1199 sub index_xap_step ($$$;$) {
1200 my ($self, $sync, $beg, $step) = @_;
1201 my $ibx = $self->{ibx};
1202 my $all = $ibx->git;
1203 my $over = $ibx->over;
1204 my $batch_bytes = batch_bytes($self);
1205 $step //= $self->{shards};
1206 my $end = $sync->{art_end};
1207 if (my $pr = $sync->{-opt}->{-progress}) {
1208 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1209 "$beg..$end (% $step)\n");
1211 for (my $num = $beg; $num <= $end; $num += $step) {
1212 my $smsg = $over->get_art($num) or next;
1213 $smsg->{v2w} = $self;
1214 $all->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1215 if ($self->{transact_bytes} >= $batch_bytes) {
1216 ${$sync->{nr}} = $num;
1217 reindex_checkpoint($self, $sync);
1222 sub index_epoch ($$$) {
1223 my ($self, $sync, $i) = @_;
1225 my $git_dir = git_dir_n($self, $i);
1226 -d $git_dir or return; # missing epochs are fine
1227 my $git = PublicInbox::Git->new($git_dir);
1228 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { # rare
1229 unindex($self, $sync, $git, $unindex_range);
1231 defined(my $stk = $sync->{stacks}->[$i]) or return;
1232 $sync->{stacks}->[$i] = undef;
1233 my $all = $self->{ibx}->git;
1234 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1235 $self->{current_info} = "$i.git $oid";
1237 my $arg = { %$sync, autime => $at, cotime => $ct };
1238 if ($sync->{index_max_size}) {
1239 $all->check_async($oid, \&check_size, $arg);
1241 $all->cat_async($oid, \&index_oid, $arg);
1243 } elsif ($f eq 'd') {
1244 $all->cat_async($oid, \&unindex_oid, $sync);
1246 if (${$sync->{need_checkpoint}}) {
1247 reindex_checkpoint($self, $sync);
1250 $all->check_async_wait;
1251 $all->cat_async_wait;
1252 update_last_commit($self, $git, $i, $stk->{latest_cmt});
1256 my ($self, $opt, $sync) = @_;
1257 my $seq = $opt->{sequentialshard};
1258 local $self->{parallel} = 0 if $seq;
1259 $self->idx_init($opt); # acquire lock
1260 if (my $art_end = $self->{ibx}->mm->max) {
1262 need_checkpoint => \(my $bool = 0),
1265 nr => \(my $nr = 0),
1266 -regen_fmt => "%u/?\n",
1268 $sync->{art_end} = $art_end;
1269 if ($seq || !$self->{parallel}) {
1270 my $shard_end = $self->{shards} - 1;
1271 index_xap_step($self, $sync, $_) for (0..$shard_end);
1272 } else { # parallel (maybe)
1273 index_xap_step($self, $sync, 0, 1);
1276 $self->{ibx}->git->cat_async_wait;
1280 # public, called by public-inbox-index
1282 my ($self, $opt) = @_;
1283 $opt //= $_[1] //= {};
1284 goto \&xapian_only if $opt->{xapianonly};
1286 my $pr = $opt->{-progress};
1288 my $latest = git_dir_latest($self, \$epoch_max);
1289 return unless defined $latest;
1291 my $seq = $opt->{sequentialshard};
1292 my $idxlevel = $self->{ibx}->{indexlevel};
1293 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1295 $self->idx_init($opt); # acquire lock
1296 fill_alternates($self, $epoch_max);
1297 $self->{over}->rethread_prepare($opt);
1299 need_checkpoint => \(my $bool = 0),
1300 unindex_range => {}, # EPOCH => oid_old..oid_new
1301 reindex => $opt->{reindex},
1305 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1306 if (sync_prepare($self, $sync, $epoch_max)) {
1307 # tmp_clone seems to fail if inside a transaction, so
1308 # we rollback here (because we opened {mm} for reading)
1309 # Note: we do NOT rely on DBI transactions for atomicity;
1310 # only for batch performance.
1311 $self->{mm}->{dbh}->rollback;
1312 $self->{mm}->{dbh}->begin_work;
1314 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1316 if ($sync->{index_max_size} = $self->{ibx}->{index_max_size}) {
1317 $sync->{index_oid} = \&index_oid;
1319 # work forwards through history
1320 index_epoch($self, $sync, $_) for (0..$epoch_max);
1321 $self->{over}->rethread_done($opt);
1324 if (my $nr = $sync->{nr}) {
1325 my $pr = $sync->{-opt}->{-progress};
1326 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1329 if ($seq) { # deal with Xapian shards sequentially
1330 $self->{ibx}->{indexlevel} = $idxlevel;
1331 delete $sync->{mm_tmp};
1332 xapian_only($self, $opt, $sync);
1335 # reindex does not pick up new changes, so we rerun w/o it:
1336 if ($opt->{reindex}) {
1339 delete @again{qw(rethread reindex -skip_lock)};
1340 index_sync($self, \%again);