X-Git-Url: http://www.git.stargrave.org/?p=public-inbox.git;a=blobdiff_plain;f=lib%2FPublicInbox%2FV2Writable.pm;h=34dd139b8ab82495296ddb9abd76847dee54b5fc;hp=87e8f3eb581a97076b5fd22ea5af917bb623306e;hb=1218a4126807951a0f47286338dc04d7f197bb78;hpb=fe86054ee1e2d93b19762a34ed1aaebe43635ff0 diff --git a/lib/PublicInbox/V2Writable.pm b/lib/PublicInbox/V2Writable.pm index 87e8f3eb..34dd139b 100644 --- a/lib/PublicInbox/V2Writable.pm +++ b/lib/PublicInbox/V2Writable.pm @@ -1,4 +1,4 @@ -# Copyright (C) 2018 all contributors +# Copyright (C) 2018-2020 all contributors # License: AGPL-3.0+ # This interface wraps and mimics PublicInbox::Import @@ -7,53 +7,92 @@ package PublicInbox::V2Writable; use strict; use warnings; use base qw(PublicInbox::Lock); -use PublicInbox::SearchIdxPart; +use 5.010_001; +use PublicInbox::SearchIdxShard; use PublicInbox::MIME; use PublicInbox::Git; use PublicInbox::Import; -use PublicInbox::MID qw(mids); +use PublicInbox::MID qw(mids references); use PublicInbox::ContentId qw(content_id content_digest); use PublicInbox::Inbox; use PublicInbox::OverIdx; use PublicInbox::Msgmap; -use PublicInbox::Spawn qw(spawn); +use PublicInbox::Spawn qw(spawn popen_rd); use PublicInbox::SearchIdx; -use IO::Handle; +use IO::Handle; # ->autoflush +use File::Temp qw(tempfile); # an estimate of the post-packed size to the raw uncompressed size my $PACKING_FACTOR = 0.4; -# assume 2 cores if GNU nproc(1) is not available -sub nproc_parts () { - my $n = int($ENV{NPROC} || `nproc 2>/dev/null` || 2); +# SATA storage lags behind what CPUs are capable of, so relying on +# nproc(1) can be misleading and having extra Xapian shards is a +# waste of FDs and space. It can also lead to excessive IO latency +# and slow things down. Users on NVME or other fast storage can +# use the NPROC env or switches in our script/public-inbox-* programs +# to increase Xapian shards +our $NPROC_MAX_DEFAULT = 4; + +sub detect_nproc () { + for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc + `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1; + } + + # getconf(1) is POSIX, but *NPROCESSORS* vars are not + for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) { + `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1; + } + + # should we bother with `sysctl hw.ncpu`? Those only give + # us total processor count, not online processor count. + undef +} + +sub nproc_shards ($) { + my ($creat_opt) = @_; + my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH'; + $n //= $ENV{NPROC}; + if (!$n) { + # assume 2 cores if not detectable or zero + state $NPROC_DETECTED = detect_nproc() || 2; + $n = $NPROC_DETECTED; + $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT; + } + # subtract for the main process and git-fast-import $n -= 1; $n < 1 ? 1 : $n; } -sub count_partitions ($) { +sub count_shards ($) { my ($self) = @_; - my $nparts = 0; + my $n = 0; my $xpfx = $self->{xpfx}; - # always load existing partitions in case core count changes: - # Also, partition count may change while -watch is running - # due to -compact + # always load existing shards in case core count changes: + # Also, shard count may change while -watch is running + # due to "xcpdb --reshard" if (-d $xpfx) { - foreach my $part (<$xpfx/*>) { - -d $part && $part =~ m!/\d+\z! or next; + require PublicInbox::Search; + PublicInbox::Search::load_xapian(); + my $XapianDatabase = $PublicInbox::Search::X{Database}; + foreach my $shard (<$xpfx/*>) { + -d $shard && $shard =~ m!/[0-9]+\z! or next; eval { - Search::Xapian::Database->new($part)->close; - $nparts++; + $XapianDatabase->new($shard)->close; + $n++; }; } } - $nparts; + $n; } sub new { + # $creat may be any true value, or 0/undef. A hashref is true, + # and $creat->{nproc} may be set to an integer my ($class, $v2ibx, $creat) = @_; - my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n"; + $v2ibx = PublicInbox::InboxWritable->new($v2ibx); + my $dir = $v2ibx->assert_usable_dir; unless (-d $dir) { if ($creat) { require File::Path; @@ -62,8 +101,6 @@ sub new { die "$dir does not exist\n"; } } - - $v2ibx = PublicInbox::InboxWritable->new($v2ibx); $v2ibx->umask_prepare; my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION; @@ -80,18 +117,22 @@ sub new { rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR), last_commit => [], # git repo -> commit }; - $self->{partitions} = count_partitions($self) || nproc_parts(); + $self->{shards} = count_shards($self) || nproc_shards($creat); bless $self, $class; } +# public (for now?) sub init_inbox { - my ($self, $parallel, $skip) = @_; - $self->{parallel} = $parallel; + my ($self, $shards, $skip_epoch) = @_; + if (defined $shards) { + $self->{parallel} = 0 if $shards == 0; + $self->{shards} = $shards if $shards > 0; + } $self->idx_init; my $epoch_max = -1; git_dir_latest($self, \$epoch_max); - if (defined $skip && $epoch_max == -1) { - $epoch_max = $skip; + if (defined $skip_epoch && $epoch_max == -1) { + $epoch_max = $skip_epoch; } $self->git_init($epoch_max >= 0 ? $epoch_max : 0); $self->done; @@ -106,6 +147,22 @@ sub add { }); } +# indexes a message, returns true if checkpointing is needed +sub do_idx ($$$$$$$) { + my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_; + my $smsg = bless { + bytes => $len, + num => $num, + blob => $oid, + mid => $mid0, + }, 'PublicInbox::Smsg'; + $self->{over}->add_overview($mime, $smsg, $self); + my $idx = idx_shard($self, $num % $self->{shards}); + $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime, $self); + my $n = $self->{transact_bytes} += $len; + $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards}); +} + sub _add { my ($self, $mime, $check_cb) = @_; @@ -121,48 +178,39 @@ sub _add { # leaking FDs to it... $self->idx_init; - my $mid0; - my $num = num_for($self, $mime, \$mid0); + my ($num, $mid0) = v2_num_for($self, $mime); defined $num or return; # duplicate defined $mid0 or die "BUG: $mid0 undefined\n"; my $im = $self->importer; - my $cmt = $im->add($mime); + my $cmt = $im->add($mime, undef, $self); # sets $self->{(au|co)time} $cmt = $im->get_mark($cmt); $self->{last_commit}->[$self->{epoch_max}] = $cmt; my ($oid, $len, $msgref) = @{$im->{last_object}}; - $self->{over}->add_overview($mime, $len, $num, $oid, $mid0); - my $nparts = $self->{partitions}; - my $part = $num % $nparts; - my $idx = $self->idx_part($part); - $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime); - my $n = $self->{transact_bytes} += $len; - if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) { + if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) { $self->checkpoint; } $cmt; } -sub num_for { - my ($self, $mime, $mid0) = @_; +sub v2_num_for { + my ($self, $mime) = @_; my $mids = mids($mime->header_obj); if (@$mids) { my $mid = $mids->[0]; my $num = $self->{mm}->mid_insert($mid); if (defined $num) { # common case - $$mid0 = $mid; - return $num; - }; + return ($num, $mid); + } # crap, Message-ID is already known, hope somebody just resent: foreach my $m (@$mids) { # read-only lookup now safe to do after above barrier - my $existing = $self->lookup_content($mime, $m); # easy, don't store duplicates # note: do not add more diagnostic info here since # it gets noisy on public-inbox-watch restarts - return if $existing; + return () if content_exists($self, $mime, $m); } # AltId may pre-populate article numbers (e.g. X-Mail-Count @@ -173,8 +221,7 @@ sub num_for { my $num = $self->{mm}->num_for($mid); if (defined $num && !$self->{over}->get_art($num)) { - $$mid0 = $mid; - return $num; + return ($num, $mid); } } @@ -187,50 +234,49 @@ sub num_for { $num = $self->{mm}->mid_insert($m); if (defined $num) { warn "alternative <$m> for <$mid> found\n"; - $$mid0 = $m; - return $num; + return ($num, $m); } } } # none of the existing Message-IDs are good, generate a new one: - num_for_harder($self, $mime, $mid0); + v2_num_for_harder($self, $mime); } -sub num_for_harder { - my ($self, $mime, $mid0) = @_; +sub v2_num_for_harder { + my ($self, $mime) = @_; my $hdr = $mime->header_obj; my $dig = content_digest($mime); - $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr); - my $num = $self->{mm}->mid_insert($$mid0); + my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr); + my $num = $self->{mm}->mid_insert($mid0); unless (defined $num) { # it's hard to spoof the last Received: header my @recvd = $hdr->header_raw('Received'); $dig->add("Received: $_") foreach (@recvd); - $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr); - $num = $self->{mm}->mid_insert($$mid0); + $mid0 = PublicInbox::Import::digest2mid($dig, $hdr); + $num = $self->{mm}->mid_insert($mid0); # fall back to a random Message-ID and give up determinism: until (defined($num)) { $dig->add(rand); - $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr); - warn "using random Message-ID <$$mid0> as fallback\n"; - $num = $self->{mm}->mid_insert($$mid0); + $mid0 = PublicInbox::Import::digest2mid($dig, $hdr); + warn "using random Message-ID <$mid0> as fallback\n"; + $num = $self->{mm}->mid_insert($mid0); } } - PublicInbox::Import::append_mid($hdr, $$mid0); - $num; + PublicInbox::Import::append_mid($hdr, $mid0); + ($num, $mid0); } -sub idx_part { - my ($self, $part) = @_; - $self->{idx_parts}->[$part]; +sub idx_shard { + my ($self, $shard_i) = @_; + $self->{idx_shards}->[$shard_i]; } # idempotent sub idx_init { - my ($self) = @_; - return if $self->{idx_parts}; + my ($self, $opt) = @_; + return if $self->{idx_shards}; my $ibx = $self->{-inbox}; # do not leak read-only FDs to child processes, we only have these @@ -255,52 +301,56 @@ sub idx_init { my $over = $self->{over}; $ibx->umask_prepare; $ibx->with_umask(sub { - $self->lock_acquire; + $self->lock_acquire unless ($opt && $opt->{-skip_lock}); $over->create; - # -compact can change partition count while -watch is idle - my $nparts = count_partitions($self); - if ($nparts && $nparts != $self->{partitions}) { - $self->{partitions} = $nparts; + # xcpdb can change shard count while -watch is idle + my $nshards = count_shards($self); + if ($nshards && $nshards != $self->{shards}) { + $self->{shards} = $nshards; } - # need to create all parts before initializing msgmap FD - my $max = $self->{partitions} - 1; + # need to create all shards before initializing msgmap FD + my $max = $self->{shards} - 1; - # idx_parts must be visible to all forked processes - my $idx = $self->{idx_parts} = []; + # idx_shards must be visible to all forked processes + my $idx = $self->{idx_shards} = []; for my $i (0..$max) { - push @$idx, PublicInbox::SearchIdxPart->new($self, $i); + push @$idx, PublicInbox::SearchIdxShard->new($self, $i); } # Now that all subprocesses are up, we can open the FDs # for SQLite: my $mm = $self->{mm} = PublicInbox::Msgmap->new_file( - "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1); + "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1); $mm->{dbh}->begin_work; }); } -sub purge_oids { - my ($self, $purge) = @_; # $purge = { $object_id => 1, ... } +# returns an array mapping [ epoch => latest_commit ] +# latest_commit may be undef if nothing was done to that epoch +# $replace_map = { $object_id => $strref, ... } +sub _replace_oids ($$$) { + my ($self, $mime, $replace_map) = @_; $self->done; - my $pfx = "$self->{-inbox}->{mainrepo}/git"; - my $purges = []; + my $pfx = "$self->{-inbox}->{inboxdir}/git"; + my $rewrites = []; # epoch => commit my $max = $self->{epoch_max}; unless (defined($max)) { defined(my $latest = git_dir_latest($self, \$max)) or return; $self->{epoch_max} = $max; } + foreach my $i (0..$max) { my $git_dir = "$pfx/$i.git"; -d $git_dir or next; my $git = PublicInbox::Git->new($git_dir); my $im = $self->import_init($git, 0, 1); - $purges->[$i] = $im->purge_oids($purge); + $rewrites->[$i] = $im->replace_oids($mime, $replace_map); $im->done; } - $purges; + $rewrites; } sub content_ids ($) { @@ -323,25 +373,30 @@ sub content_matches ($$) { 0 } -sub remove_internal { - my ($self, $mime, $cmt_msg, $purge) = @_; +# used for removing or replacing (purging) +sub rewrite_internal ($$;$$$) { + my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_; $self->idx_init; - my $im = $self->importer unless $purge; + my ($im, $need_reindex, $replace_map); + if ($sref) { + $replace_map = {}; # oid => sref + $need_reindex = [] if $new_mime; + } else { + $im = $self->importer; + } my $over = $self->{over}; - my $cids = content_ids($mime); - my $parts = $self->{idx_parts}; - my $mm = $self->{mm}; - my $removed; - my $mids = mids($mime->header_obj); + my $cids = content_ids($old_mime); + my @removed; + my $mids = mids($old_mime->header_obj); # We avoid introducing new blobs into git since the raw content # can be slightly different, so we do not need the user-supplied # message now that we have the mids and content_id - $mime = undef; + $old_mime = undef; my $mark; foreach my $mid (@$mids) { - my %gone; + my %gone; # num => [ smsg, $mime, raw ] my ($id, $prev); while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) { my $msg = get_blob($self, $smsg); @@ -352,8 +407,7 @@ sub remove_internal { my $orig = $$msg; my $cur = PublicInbox::MIME->new($msg); if (content_matches($cids, $cur)) { - $smsg->{mime} = $cur; - $gone{$smsg->{num}} = [ $smsg, \$orig ]; + $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ]; } } my $n = scalar keys %gone; @@ -363,19 +417,24 @@ sub remove_internal { join(',', sort keys %gone), "\n"; } foreach my $num (keys %gone) { - my ($smsg, $orig) = @{$gone{$num}}; - $mm->num_delete($num); - # $removed should only be set once assuming + my ($smsg, $mime, $orig) = @{$gone{$num}}; + # @removed should only be set once assuming # no bugs in our deduplication code: - $removed = $smsg; + @removed = (undef, $mime, $smsg); my $oid = $smsg->{blob}; - if ($purge) { - $purge->{$oid} = 1; + if ($replace_map) { + $replace_map->{$oid} = $sref; } else { ($mark, undef) = $im->remove($orig, $cmt_msg); + $removed[0] = $mark; } $orig = undef; - $self->unindex_oid_remote($oid, $mid); + if ($need_reindex) { # ->replace + push @$need_reindex, $smsg; + } else { # ->purge or ->remove + $self->{mm}->num_delete($num); + } + unindex_oid_remote($self, $oid, $mid); } } @@ -383,33 +442,137 @@ sub remove_internal { my $cmt = $im->get_mark($mark); $self->{last_commit}->[$self->{epoch_max}] = $cmt; } - if ($purge && scalar keys %$purge) { - return purge_oids($self, $purge); + if ($replace_map && scalar keys %$replace_map) { + my $rewrites = _replace_oids($self, $new_mime, $replace_map); + return { rewrites => $rewrites, need_reindex => $need_reindex }; } - $removed; + defined($mark) ? @removed : undef; } +# public (see PublicInbox::Import->remove), but note the 3rd element +# (retval[2]) is not part of the stable API shared with Import->remove sub remove { my ($self, $mime, $cmt_msg) = @_; + my @ret; $self->{-inbox}->with_umask(sub { - remove_internal($self, $mime, $cmt_msg); + @ret = rewrite_internal($self, $mime, $cmt_msg); }); + defined($ret[0]) ? @ret : undef; } -sub purge { - my ($self, $mime) = @_; - my $purges = $self->{-inbox}->with_umask(sub { - remove_internal($self, $mime, undef, {}); +sub _replace ($$;$$) { + my ($self, $old_mime, $new_mime, $sref) = @_; + my $rewritten = $self->{-inbox}->with_umask(sub { + rewrite_internal($self, $old_mime, undef, $new_mime, $sref); }) or return; - $self->idx_init if @$purges; # ->done is called on purges - for my $i (0..$#$purges) { - defined(my $cmt = $purges->[$i]) or next; + + my $rewrites = $rewritten->{rewrites}; + # ->done is called if there are rewrites since we gc+prune from git + $self->idx_init if @$rewrites; + + for my $i (0..$#$rewrites) { + defined(my $cmt = $rewrites->[$i]) or next; $self->{last_commit}->[$i] = $cmt; } - $purges; + $rewritten; +} + +# public +sub purge { + my ($self, $mime) = @_; + my $rewritten = _replace($self, $mime, undef, \'') or return; + $rewritten->{rewrites} +} + +# returns the git object_id of $fh, does not write the object to FS +sub git_hash_raw ($$) { + my ($self, $raw) = @_; + # grab the expected OID we have to reindex: + open my $tmp_fh, '+>', undef or die "failed to open tmp: $!"; + $tmp_fh->autoflush(1); + print $tmp_fh $$raw or die "print \$tmp_fh: $!"; + sysseek($tmp_fh, 0, 0) or die "seek failed: $!"; + + my $git_dir = $self->{-inbox}->git->{git_dir}; + my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)]; + my $r = popen_rd($cmd, undef, { 0 => $tmp_fh }); + local $/ = "\n"; + chomp(my $oid = <$r>); + close $r or die "git hash-object failed: $?"; + $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid"; + $oid; +} + +sub _check_mids_match ($$$) { + my ($old_list, $new_list, $hdrs) = @_; + my %old_mids = map { $_ => 1 } @$old_list; + my %new_mids = map { $_ => 1 } @$new_list; + my @old = keys %old_mids; + my @new = keys %new_mids; + my $err = "$hdrs may not be changed when replacing\n"; + die $err if scalar(@old) != scalar(@new); + delete @new_mids{@old}; + delete @old_mids{@new}; + die $err if (scalar(keys %old_mids) || scalar(keys %new_mids)); } -sub last_commit_part ($$;$) { +# Changing Message-IDs or References with ->replace isn't supported. +# The rules for dealing with messages with multiple or conflicting +# Message-IDs are pretty complex and rethreading hasn't been fully +# implemented, yet. +sub check_mids_match ($$) { + my ($old_mime, $new_mime) = @_; + my $old = $old_mime->header_obj; + my $new = $new_mime->header_obj; + _check_mids_match(mids($old), mids($new), 'Message-ID(s)'); + _check_mids_match(references($old), references($new), + 'References/In-Reply-To'); +} + +# public +sub replace ($$$) { + my ($self, $old_mime, $new_mime) = @_; + + check_mids_match($old_mime, $new_mime); + + # mutt will always add Content-Length:, Status:, Lines: when editing + PublicInbox::Import::drop_unwanted_headers($new_mime); + + my $raw = $new_mime->as_string; + my $expect_oid = git_hash_raw($self, \$raw); + my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return; + my $need_reindex = $rewritten->{need_reindex}; + + # just in case we have bugs in deduplication code: + my $n = scalar(@$need_reindex); + if ($n > 1) { + my $list = join(', ', map { + "$_->{num}: <$_->{mid}>" + } @$need_reindex); + warn <<""; +W: rewritten $n messages matching content of original message (expected: 1). +W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow: +W: $list + + } + + # make sure we really got the OID: + my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid); + $oid eq $expect_oid or die "BUG: $expect_oid not found after replace"; + + # don't leak FDs to Xapian: + $self->{-inbox}->git->cleanup; + + # reindex modified messages: + for my $smsg (@$need_reindex) { + my $num = $smsg->{num}; + my $mid0 = $smsg->{mid}; + do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0); + } + $rewritten->{rewrites}; +} + +sub last_epoch_commit ($$;$) { my ($self, $i, $cmt) = @_; my $v = PublicInbox::Search::SCHEMA_VERSION(); $self->{mm}->last_commit_xap($v, $i, $cmt); @@ -422,7 +585,7 @@ sub set_last_commits ($) { foreach my $i (0..$epoch_max) { defined(my $cmt = $last_commit->[$i]) or next; $last_commit->[$i] = undef; - last_commit_part($self, $i, $cmt); + last_epoch_commit($self, $i, $cmt); } } @@ -440,10 +603,11 @@ sub barrier_wait { while (scalar keys %$barrier) { defined(my $l = $r->getline) or die "EOF on barrier_wait: $!"; $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l"; - delete $barrier->{$1} or die "bad part[$1] on barrier wait"; + delete $barrier->{$1} or die "bad shard[$1] on barrier wait"; } } +# public sub checkpoint ($;$) { my ($self, $wait) = @_; @@ -454,8 +618,8 @@ sub checkpoint ($;$) { $im->checkpoint; } } - my $parts = $self->{idx_parts}; - if ($parts) { + my $shards = $self->{idx_shards}; + if ($shards) { my $dbh = $self->{mm}->{dbh}; # SQLite msgmap data is second in importance @@ -466,19 +630,19 @@ sub checkpoint ($;$) { # Now deal with Xapian if ($wait) { - my $barrier = $self->barrier_init(scalar @$parts); + my $barrier = $self->barrier_init(scalar @$shards); - # each partition needs to issue a barrier command - $_->remote_barrier for @$parts; + # each shard needs to issue a barrier command + $_->remote_barrier for @$shards; - # wait for each Xapian partition + # wait for each Xapian shard $self->barrier_wait($barrier); } else { - $_->remote_commit for @$parts; + $_->remote_commit for @$shards; } # last_commit is special, don't commit these until - # remote partitions are done: + # remote shards are done: $dbh->begin_work; set_last_commits($self); $dbh->commit; @@ -490,8 +654,10 @@ sub checkpoint ($;$) { # issue a write barrier to ensure all data is visible to other processes # and read-only ops. Order of data importance is: git > SQLite > Xapian +# public sub barrier { checkpoint($_[0], 1) }; +# public sub done { my ($self) = @_; my $im = delete $self->{im}; @@ -499,58 +665,73 @@ sub done { checkpoint($self); my $mm = delete $self->{mm}; $mm->{dbh}->commit if $mm; - my $parts = delete $self->{idx_parts}; - if ($parts) { - $_->remote_close for @$parts; + my $shards = delete $self->{idx_shards}; + if ($shards) { + $_->remote_close for @$shards; } $self->{over}->disconnect; delete $self->{bnote}; $self->{transact_bytes} = 0; - $self->lock_release if $parts; + $self->lock_release if $shards; $self->{-inbox}->git->cleanup; } sub fill_alternates ($$) { my ($self, $epoch) = @_; - my $pfx = "$self->{-inbox}->{mainrepo}/git"; - my $all = "$self->{-inbox}->{mainrepo}/all.git"; - my @cmd; + my $pfx = "$self->{-inbox}->{inboxdir}/git"; + my $all = "$self->{-inbox}->{inboxdir}/all.git"; + unless (-d $all) { - @cmd = (qw(git init --bare -q), $all); - PublicInbox::Import::run_die(\@cmd); - @cmd = (qw/git config/, "--file=$all/config", - 'repack.writeBitmaps', 'true'); - PublicInbox::Import::run_die(\@cmd); + PublicInbox::Import::init_bare($all); } - @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config", - 'include.path', '../../all.git/config'); - PublicInbox::Import::run_die(\@cmd); - - my $alt = "$all/objects/info/alternates"; - my %alts; - my @add; + my $info_dir = "$all/objects/info"; + my $alt = "$info_dir/alternates"; + my (%alt, $new); + my $mode = 0644; if (-e $alt) { open(my $fh, '<', $alt) or die "open < $alt: $!\n"; - %alts = map { chomp; $_ => 1 } (<$fh>); + $mode = (stat($fh))[2] & 07777; + + # we assign a sort score to every alternate and favor + # the newest (highest numbered) one when we + my $score; + my $other = 0; # in case admin adds non-epoch repos + %alt = map {; + if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) { + $score = $1 + 0; + } else { + $score = --$other; + } + $_ => $score; + } split(/\n+/, do { local $/; <$fh> }); } + foreach my $i (0..$epoch) { my $dir = "../../git/$i.git/objects"; - push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git"; - } - return unless @add; - open my $fh, '>>', $alt or die "open >> $alt: $!\n"; - foreach my $dir (@add) { - print $fh "$dir\n" or die "print >> $alt: $!\n"; + if (!exists($alt{$dir}) && -d "$pfx/$i.git") { + $alt{$dir} = $i; + $new = 1; + } } - close $fh or die "close $alt: $!\n"; + return unless $new; + + my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir); + print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n" + or die "print $tmp: $!\n"; + chmod($mode, $fh) or die "fchmod $tmp: $!\n"; + close $fh or die "close $tmp $!\n"; + rename($tmp, $alt) or die "rename $tmp => $alt: $!\n"; } sub git_init { my ($self, $epoch) = @_; - my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git"; + my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git"; my @cmd = (qw(git init --bare -q), $git_dir); PublicInbox::Import::run_die(\@cmd); + @cmd = (qw/git config/, "--file=$git_dir/config", + 'include.path', '../../all.git/config'); + PublicInbox::Import::run_die(\@cmd); fill_alternates($self, $epoch); $git_dir } @@ -558,12 +739,12 @@ sub git_init { sub git_dir_latest { my ($self, $max) = @_; $$max = -1; - my $pfx = "$self->{-inbox}->{mainrepo}/git"; + my $pfx = "$self->{-inbox}->{inboxdir}/git"; return unless -d $pfx; my $latest; opendir my $dh, $pfx or die "opendir $pfx: $!\n"; while (defined(my $git_dir = readdir($dh))) { - $git_dir =~ m!\A(\d+)\.git\z! or next; + $git_dir =~ m!\A([0-9]+)\.git\z! or next; if ($1 > $$max) { $$max = $1; $latest = "$pfx/$git_dir"; @@ -622,7 +803,6 @@ sub import_init { # XXX experimental sub diff ($$$) { my ($mid, $cur, $new) = @_; - use File::Temp qw(tempfile); my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1); print $ah $cur->as_string or die "print: $!"; @@ -634,7 +814,6 @@ sub diff ($$$) { my $cmd = [ qw(diff -u), $an, $bn ]; print STDERR "# MID conflict <$mid>\n"; my $pid = spawn($cmd, undef, { 1 => 2 }); - defined $pid or die "diff failed to spawn $!"; waitpid($pid, 0) == $pid or die "diff did not finish"; unlink($an, $bn); } @@ -650,7 +829,7 @@ sub get_blob ($$) { $ibx->msg_by_smsg($smsg); } -sub lookup_content { +sub content_exists ($$$) { my ($self, $mime, $mid) = @_; my $over = $self->{over}; my $cids = content_ids($mime); @@ -662,11 +841,7 @@ sub lookup_content { next; } my $cur = PublicInbox::MIME->new($msg); - if (content_matches($cids, $cur)) { - $smsg->{mime} = $cur; - return $smsg; - } - + return 1 if content_matches($cids, $cur); # XXX DEBUG_DIFF is experimental and may be removed diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF}; @@ -678,8 +853,8 @@ sub atfork_child { my ($self) = @_; my $fh = delete $self->{reindex_pipe}; close $fh if $fh; - if (my $parts = $self->{idx_parts}) { - $_->atfork_child foreach @$parts; + if (my $shards = $self->{idx_shards}) { + $_->atfork_child foreach @$shards; } if (my $im = $self->{im}) { $im->atfork_child; @@ -689,185 +864,330 @@ sub atfork_child { $self->{bnote}->[1]; } -sub mark_deleted { - my ($self, $D, $git, $oid) = @_; +sub mark_deleted ($$$$) { + my ($self, $sync, $git, $oid) = @_; my $msgref = $git->cat_file($oid); my $mime = PublicInbox::MIME->new($$msgref); my $mids = mids($mime->header_obj); my $cid = content_id($mime); foreach my $mid (@$mids) { - $D->{"$mid\0$cid"} = $oid; + $sync->{D}->{"$mid\0$cid"} = $oid; } } -sub reindex_oid { - my ($self, $mm_tmp, $D, $git, $oid, $regen, $reindex) = @_; - my $len; +sub reindex_checkpoint ($$$) { + my ($self, $sync, $git) = @_; + + $git->cleanup; + $sync->{mm_tmp}->atfork_prepare; + $self->done; # release lock + + if (my $pr = $sync->{-opt}->{-progress}) { + my ($bn) = (split('/', $git->{git_dir}))[-1]; + $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr})); + } + + # allow -watch or -mda to write... + $self->idx_init; # reacquire lock + $sync->{mm_tmp}->atfork_parent; +} + +# only for a few odd messages with multiple Message-IDs +sub reindex_oid_m ($$$$;$) { + my ($self, $sync, $git, $oid, $regen_num) = @_; + $self->{current_info} = "multi_mid $oid"; + my ($num, $mid0, $len); my $msgref = $git->cat_file($oid, \$len); my $mime = PublicInbox::MIME->new($$msgref); my $mids = mids($mime->header_obj); my $cid = content_id($mime); + die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1; - # get the NNTP article number we used before, highest number wins - # and gets deleted from mm_tmp; - my $mid0; - my $num = -1; - my $del = 0; - foreach my $mid (@$mids) { - $del += delete($D->{"$mid\0$cid"}) ? 1 : 0; - my $n = $mm_tmp->num_for($mid); - if (defined $n && $n > $num) { + for my $mid (reverse @$mids) { + delete($sync->{D}->{"$mid\0$cid"}) and + die "BUG: reindex_oid should handle <$mid> delete"; + } + my $over = $self->{over}; + for my $mid (reverse @$mids) { + ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid); + next unless defined $num; + if (defined($regen_num) && $regen_num != $num) { + die "BUG: regen(#$regen_num) != over(#$num)"; + } + } + unless (defined($num)) { + for my $mid (reverse @$mids) { + # is this a number we got before? + my $n = $sync->{mm_tmp}->num_for($mid); + next unless defined $n; + next if defined($regen_num) && $regen_num != $n; + ($num, $mid0) = ($n, $mid); + last; + } + } + if (defined($num)) { + $sync->{mm_tmp}->num_delete($num); + } elsif (defined $regen_num) { + $num = $regen_num; + for my $mid (reverse @$mids) { + $self->{mm}->mid_set($num, $mid) == 1 or next; $mid0 = $mid; - $num = $n; - $self->{mm}->mid_set($num, $mid0); - } - } - if (!defined($mid0) && $regen && !$del) { - $num = $$regen--; - die "BUG: ran out of article numbers\n" if $num <= 0; - my $mm = $self->{mm}; - foreach my $mid (reverse @$mids) { - if ($mm->mid_set($num, $mid) == 1) { - $mid0 = $mid; - last; - } + last; + } + unless (defined $mid0) { + warn "E: cannot regen #$num\n"; + return; } - if (!defined($mid0)) { - my $id = '<' . join('> <', @$mids) . '>'; - warn "Message-ID $id unusable for $num\n"; - foreach my $mid (@$mids) { - defined(my $n = $mm->num_for($mid)) or next; - warn "#$n previously mapped for <$mid>\n"; + } else { # fixup bugs in old mirrors on reindex + for my $mid (reverse @$mids) { + $num = $self->{mm}->mid_insert($mid); + next unless defined $num; + $mid0 = $mid; + last; + } + if (defined $mid0) { + if ($sync->{reindex}) { + warn "reindex added #$num <$mid0>\n"; } + } else { + warn "E: cannot find article #\n"; + return; } } + $sync->{nr}++; + if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) { + reindex_checkpoint($self, $sync, $git); + } +} - if (!defined($mid0) || $del) { - if (!defined($mid0) && $del) { # expected for deletes - $num = $$regen--; - $self->{mm}->num_highwater($num) unless $reindex; - return +sub check_unindexed ($$$) { + my ($self, $num, $mid0) = @_; + my $unindexed = $self->{unindexed} // {}; + my $n = delete($unindexed->{$mid0}); + defined $n or return; + if ($n != $num) { + die "BUG: unindexed $n != $num <$mid0>\n"; + } else { + $self->{mm}->mid_set($num, $mid0); + } +} + +# reuse Msgmap to store num => oid mapping (rather than num => mid) +sub multi_mid_q_new () { + my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1); + my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1); + $multi_mid->{dbh}->do('PRAGMA synchronous = OFF'); + # for Msgmap->DESTROY: + $multi_mid->{tmp_name} = $fn; + $multi_mid->{pid} = $$; + close $fh or die "failed to close $fn: $!"; + $multi_mid +} + +sub multi_mid_q_push ($$) { + my ($sync, $oid) = @_; + my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new(); + if ($sync->{reindex}) { # no regen on reindex + $multi_mid->mid_insert($oid); + } else { + my $num = $sync->{regen}--; + die "BUG: ran out of article numbers" if $num <= 0; + $multi_mid->mid_set($num, $oid); + } +} + +sub reindex_oid ($$$$) { + my ($self, $sync, $git, $oid) = @_; + my ($num, $mid0, $len); + my $msgref = $git->cat_file($oid, \$len); + return if $len == 0; # purged + my $mime = PublicInbox::MIME->new($$msgref); + my $mids = mids($mime->header_obj); + my $cid = content_id($mime); + + if (scalar(@$mids) == 0) { + warn "E: $oid has no Message-ID, skipping\n"; + return; + } elsif (scalar(@$mids) == 1) { + my $mid = $mids->[0]; + + # was the file previously marked as deleted?, skip if so + if (delete($sync->{D}->{"$mid\0$cid"})) { + if (!$sync->{reindex}) { + $num = $sync->{regen}--; + $self->{mm}->num_highwater($num); + } + return; } - my $id = '<' . join('> <', @$mids) . '>'; - defined($mid0) or - warn "Skipping $id, no article number found\n"; - if ($del && defined($mid0)) { - warn "$id was deleted $del " . - "time(s) but mapped to article #$num\n"; + # is this a number we got before? + $num = $sync->{mm_tmp}->num_for($mid); + if (defined $num) { + $mid0 = $mid; + check_unindexed($self, $num, $mid0); + } else { + $num = $sync->{regen}--; + die "BUG: ran out of article numbers" if $num <= 0; + if ($self->{mm}->mid_set($num, $mid) != 1) { + warn "E: unable to assign $num => <$mid>\n"; + return; + } + $mid0 = $mid; + } + } else { # multiple MIDs are a weird case: + my $del = 0; + for (@$mids) { + $del += delete($sync->{D}->{"$_\0$cid"}) // 0; + } + if ($del) { + unindex_oid_remote($self, $oid, $_) for @$mids; + # do not delete from {mm_tmp}, since another + # single-MID message may use it. + } else { # handle them at the end: + multi_mid_q_push($sync, $oid); } return; - } - $mm_tmp->mid_delete($mid0) or + $sync->{mm_tmp}->mid_delete($mid0) or die "failed to delete <$mid0> for article #$num\n"; - - $self->{over}->add_overview($mime, $len, $num, $oid, $mid0); - my $nparts = $self->{partitions}; - my $part = $num % $nparts; - my $idx = $self->idx_part($part); - $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime); - my $n = $self->{transact_bytes} += $len; - if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) { - $git->cleanup; - $mm_tmp->atfork_prepare; - $self->done; # release lock - # allow -watch or -mda to write... - $self->idx_init; # reacquire lock - $mm_tmp->atfork_parent; + $sync->{nr}++; + if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) { + reindex_checkpoint($self, $sync, $git); } } # only update last_commit for $i on reindex iff newer than current -sub update_last_commit { +sub update_last_commit ($$$$) { my ($self, $git, $i, $cmt) = @_; - my $last = last_commit_part($self, $i); + my $last = last_epoch_commit($self, $i); if (defined $last && is_ancestor($git, $last, $cmt)) { my @cmd = (qw(rev-list --count), "$last..$cmt"); chomp(my $n = $git->qx(@cmd)); return if $n ne '' && $n == 0; } - last_commit_part($self, $i, $cmt); + last_epoch_commit($self, $i, $cmt); } -sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" } +sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" } -sub last_commits { +sub last_commits ($$) { my ($self, $epoch_max) = @_; my $heads = []; for (my $i = $epoch_max; $i >= 0; $i--) { - $heads->[$i] = last_commit_part($self, $i); + $heads->[$i] = last_epoch_commit($self, $i); } $heads; } *is_ancestor = *PublicInbox::SearchIdx::is_ancestor; -sub index_prepare { - my ($self, $opts, $epoch_max, $ranges) = @_; +# returns a revision range for git-log(1) +sub log_range ($$$$$) { + my ($self, $sync, $git, $i, $tip) = @_; + my $opt = $sync->{-opt}; + my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1); + my $cur = $sync->{ranges}->[$i] or do { + $pr->("$i.git indexing all of $tip") if $pr; + return $tip; # all of it + }; + + # fast equality check to avoid (v)fork+execve overhead + if ($cur eq $tip) { + $sync->{ranges}->[$i] = undef; + return; + } + + my $range = "$cur..$tip"; + $pr->("$i.git checking contiguity... ") if $pr; + if (is_ancestor($git, $cur, $tip)) { # common case + $pr->("OK\n") if $pr; + my $n = $git->qx(qw(rev-list --count), $range); + chomp($n); + if ($n == 0) { + $sync->{ranges}->[$i] = undef; + $pr->("$i.git has nothing new\n") if $pr; + return; # nothing to do + } + $pr->("$i.git has $n changes since $cur\n") if $pr; + } else { + $pr->("FAIL\n") if $pr; + warn <<""; +discontiguous range: $range +Rewritten history? (in $git->{git_dir}) + + chomp(my $base = $git->qx('merge-base', $tip, $cur)); + if ($base) { + $range = "$base..$tip"; + warn "found merge-base: $base\n" + } else { + $range = $tip; + warn "discarding history at $cur\n"; + } + warn <<""; +reindexing $git->{git_dir} starting at +$range + + $sync->{unindex_range}->{$i} = "$base..$cur"; + } + $range; +} + +sub sync_prepare ($$$) { + my ($self, $sync, $epoch_max) = @_; + my $pr = $sync->{-opt}->{-progress}; my $regen_max = 0; my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master'; + + # reindex stops at the current heads and we later rerun index_sync + # without {reindex} + my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex}; + for (my $i = $epoch_max; $i >= 0; $i--) { - die "already indexing!\n" if $self->{index_pipe}; + die 'BUG: already indexing!' if $self->{reindex_pipe}; my $git_dir = git_dir_n($self, $i); - -d $git_dir or next; # missing parts are fine + -d $git_dir or next; # missing epochs are fine my $git = PublicInbox::Git->new($git_dir); + if ($reindex_heads) { + $head = $reindex_heads->[$i] or next; + } chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head)); - next if $?; # new repo - my $range; - if (defined(my $cur = $ranges->[$i])) { - $range = "$cur..$tip"; - if (is_ancestor($git, $cur, $tip)) { # common case - my $n = $git->qx(qw(rev-list --count), $range); - chomp($n); - if ($n == 0) { - $ranges->[$i] = undef; - next; - } - } else { - warn <<""; -discontiguous range: $range -Rewritten history? (in $git_dir) - - my $base = $git->qx('merge-base', $tip, $cur); - chomp $base; - if ($base) { - $range = "$base..$tip"; - warn "found merge-base: $base\n" - } else { - $range = $tip; - warn <<""; -discarding history at $cur - - } - warn <<""; -reindexing $git_dir starting at -$range - $self->{"unindex-range.$i"} = "$base..$cur"; - } - } else { - $range = $tip; # all of it - } - $ranges->[$i] = $range; + next if $?; # new repo + my $range = log_range($self, $sync, $git, $i, $tip) or next; + $sync->{ranges}->[$i] = $range; # can't use 'rev-list --count' if we use --diff-filter + $pr->("$i.git counting $range ... ") if $pr; + my $n = 0; my $fh = $git->popen(qw(log --pretty=tformat:%H --no-notes --no-color --no-renames --diff-filter=AM), $range, '--', 'm'); - ++$regen_max while <$fh>; + ++$n while <$fh>; + close $fh or die "git log failed: \$?=$?"; + $pr->("$n\n") if $pr; + $regen_max += $n; } - \$regen_max; + + return 0 if (!$regen_max && !keys(%{$self->{unindex_range}})); + + # reindex should NOT see new commits anymore, if we do, + # it's a problem and we need to notice it via die() + my $pad = length($regen_max) + 1; + $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n"; + $sync->{nr} = 0; + return -1 if $sync->{reindex}; + $regen_max + $self->{mm}->num_highwater() || 0; } -sub unindex_oid_remote { +sub unindex_oid_remote ($$$) { my ($self, $oid, $mid) = @_; - $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}}; + $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}}; $self->{over}->remove_oid($oid, $mid); } -sub unindex_oid { - my ($self, $git, $oid) = @_; +sub unindex_oid ($$$;$) { + my ($self, $git, $oid, $unindexed) = @_; + my $mm = $self->{mm}; my $msgref = $git->cat_file($oid); my $mime = PublicInbox::MIME->new($msgref); my $mids = mids($mime->header_obj); @@ -887,93 +1207,170 @@ sub unindex_oid { join(',',sort keys %gone), "\n"; } foreach my $num (keys %gone) { - $self->{unindexed}->{$_}++; - $self->{mm}->num_delete($num); + if ($unindexed) { + my $mid0 = $mm->mid_for($num); + $unindexed->{$mid0} = $num; + } + $mm->num_delete($num); } - $self->unindex_oid_remote($oid, $mid); + unindex_oid_remote($self, $oid, $mid); } } my $x40 = qr/[a-f0-9]{40}/; -sub unindex { - my ($self, $opts, $git, $unindex_range) = @_; - my $un = $self->{unindexed} ||= {}; # num => removal count - my $before = scalar keys %$un; +sub unindex ($$$$) { + my ($self, $sync, $git, $unindex_range) = @_; + my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num + my $before = scalar keys %$unindexed; + # order does not matter, here: my @cmd = qw(log --raw -r --no-notes --no-color --no-abbrev --no-renames); my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range); while (<$fh>) { /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next; - $self->unindex_oid($git, $1); + unindex_oid($self, $git, $1, $unindexed); } delete $self->{reindex_pipe}; - $fh = undef; + close $fh or die "git log failed: \$?=$?"; - return unless $opts->{prune}; - my $after = scalar keys %$un; + return unless $sync->{-opt}->{prune}; + my $after = scalar keys %$unindexed; return if $before == $after; # ensure any blob can not longer be accessed via dumb HTTP PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}", - qw(-c gc.reflogExpire=now gc --prune=all)]); + qw(-c gc.reflogExpire=now gc --prune=all --quiet)]); +} + +sub sync_ranges ($$$) { + my ($self, $sync, $epoch_max) = @_; + my $reindex = $sync->{reindex}; + + return last_commits($self, $epoch_max) unless $reindex; + return [] if ref($reindex) ne 'HASH'; + + my $ranges = $reindex->{from}; # arrayref; + if (ref($ranges) ne 'ARRAY') { + die 'BUG: $reindex->{from} not an ARRAY'; + } + $ranges; +} + +sub index_epoch ($$$) { + my ($self, $sync, $i) = @_; + + my $git_dir = git_dir_n($self, $i); + die 'BUG: already reindexing!' if $self->{reindex_pipe}; + -d $git_dir or return; # missing epochs are fine + fill_alternates($self, $i); + my $git = PublicInbox::Git->new($git_dir); + if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { + unindex($self, $sync, $git, $unindex_range); + } + defined(my $range = $sync->{ranges}->[$i]) or return; + if (my $pr = $sync->{-opt}->{-progress}) { + $pr->("$i.git indexing $range\n"); + } + + my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct + --no-notes --no-color --no-abbrev --no-renames); + my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range); + my $cmt; + while (<$fh>) { + chomp; + $self->{current_info} = "$i.git $_"; + if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) { + $cmt //= $1; + $self->{autime} = $2; + $self->{cotime} = $3; + } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) { + reindex_oid($self, $sync, $git, $1); + } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) { + mark_deleted($self, $sync, $git, $1); + } + } + close $fh or die "git log failed: \$?=$?"; + delete $self->{reindex_pipe}; + update_last_commit($self, $git, $i, $cmt) if defined $cmt; } +# public, called by public-inbox-index sub index_sync { - my ($self, $opts) = @_; - $opts ||= {}; + my ($self, $opt) = @_; + $opt ||= {}; + my $pr = $opt->{-progress}; my $epoch_max; my $latest = git_dir_latest($self, \$epoch_max); return unless defined $latest; - $self->idx_init; # acquire lock - my $mm_tmp = $self->{mm}->tmp_clone; - my $reindex = $opts->{reindex}; - my $ranges = $reindex ? [] : $self->last_commits($epoch_max); - - my $high = $self->{mm}->num_highwater(); - my $regen = $self->index_prepare($opts, $epoch_max, $ranges); - $$regen += $high if $high; - my $D = {}; # "$mid\0$cid" => $oid - my @cmd = qw(log --raw -r --pretty=tformat:%H - --no-notes --no-color --no-abbrev --no-renames); + $self->idx_init($opt); # acquire lock + my $sync = { + D => {}, # "$mid\0$cid" => $oid + unindex_range => {}, # EPOCH => oid_old..oid_new + reindex => $opt->{reindex}, + -opt => $opt + }; + $sync->{ranges} = sync_ranges($self, $sync, $epoch_max); + $sync->{regen} = sync_prepare($self, $sync, $epoch_max); + + if ($sync->{regen}) { + # tmp_clone seems to fail if inside a transaction, so + # we rollback here (because we opened {mm} for reading) + # Note: we do NOT rely on DBI transactions for atomicity; + # only for batch performance. + $self->{mm}->{dbh}->rollback; + $self->{mm}->{dbh}->begin_work; + $sync->{mm_tmp} = $self->{mm}->tmp_clone; + } # work backwards through history - my $last_commit = []; for (my $i = $epoch_max; $i >= 0; $i--) { - my $git_dir = git_dir_n($self, $i); - die "already reindexing!\n" if delete $self->{reindex_pipe}; - -d $git_dir or next; # missing parts are fine - fill_alternates($self, $i); - my $git = PublicInbox::Git->new($git_dir); - my $unindex = delete $self->{"unindex-range.$i"}; - $self->unindex($opts, $git, $unindex) if $unindex; - defined(my $range = $ranges->[$i]) or next; - my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range); - my $cmt; - while (<$fh>) { - chomp; - $self->{current_info} = "$i.git $_"; - if (/\A$x40$/o && !defined($cmt)) { - $cmt = $_; - } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) { - $self->reindex_oid($mm_tmp, $D, $git, $1, - $regen, $reindex); - } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) { - $self->mark_deleted($D, $git, $1); - } - } - $fh = undef; - delete $self->{reindex_pipe}; - $self->update_last_commit($git, $i, $cmt) if defined $cmt; + index_epoch($self, $sync, $i); } # unindex is required for leftovers if "deletes" affect messages # in a previous fetch+index window: - if (scalar keys %$D) { - my $git = $self->{-inbox}->git; - $self->unindex_oid($git, $_) for values %$D; - $git->cleanup; + my $git; + if (my @leftovers = values %{delete $sync->{D}}) { + $git = $self->{-inbox}->git; + for my $oid (@leftovers) { + $self->{current_info} = "leftover $oid"; + unindex_oid($self, $git, $oid); + } } + if (my $multi_mid = delete $sync->{multi_mid}) { + $git //= $self->{-inbox}->git; + my ($min, $max) = $multi_mid->minmax; + if ($sync->{reindex}) { + # we may need to create new Message-IDs if mirrors + # were initially indexed with old versions + for (my $i = $max; $i >= $min; $i--) { + my $oid = $multi_mid->mid_for($i); + next unless defined $oid; + reindex_oid_m($self, $sync, $git, $oid); + } + } else { # regen on initial index + for my $num ($min..$max) { + my $oid = $multi_mid->mid_for($num); + next unless defined $oid; + reindex_oid_m($self, $sync, $git, $oid, $num); + } + } + } + $git->cleanup if $git; $self->done; + + if (my $nr = $sync->{nr}) { + my $pr = $sync->{-opt}->{-progress}; + $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr; + } + + # reindex does not pick up new changes, so we rerun w/o it: + if ($opt->{reindex}) { + my %again = %$opt; + $sync = undef; + delete @again{qw(reindex -skip_lock)}; + index_sync($self, \%again); + } } 1;