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;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentHash qw(content_hash content_digest);
16 use PublicInbox::InboxWritable;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd);
20 use PublicInbox::SearchIdx qw(log2stack crlf_adjust is_ancestor check_size
22 use IO::Handle; # ->autoflush
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 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
39 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
40 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
42 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
43 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
46 # should we bother with `sysctl hw.ncpu`? Those only give
47 # us total processor count, not online processor count.
51 sub nproc_shards ($) {
53 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
56 # assume 2 cores if not detectable or zero
57 state $NPROC_DETECTED = detect_nproc() || 2;
59 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
62 # subtract for the main process and git-fast-import
67 sub count_shards ($) {
69 if (my $ibx = $self->{ibx}) {
70 # always load existing shards in case core count changes:
71 # Also, shard count may change while -watch is running
72 my $srch = $ibx->search or return 0;
73 delete $ibx->{search};
75 } else { # ExtSearchIdx
76 $self->{nshard} // do {
77 if ($self->xdb_sharded) {
78 $self->{nshard} // die 'BUG: {nshard} unset';
87 # $creat may be any true value, or 0/undef. A hashref is true,
88 # and $creat->{nproc} may be set to an integer
89 my ($class, $v2ibx, $creat) = @_;
90 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
91 my $dir = $v2ibx->assert_usable_dir;
95 File::Path::mkpath($dir);
97 die "$dir does not exist\n";
100 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
103 im => undef, # PublicInbox::Import
109 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
110 lock_path => "$dir/inbox.lock",
111 # limit each git repo (epoch) to 1GB or so
112 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
113 last_commit => [], # git epoch -> commit
115 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
116 $self->{shards} = count_shards($self) || nproc_shards($creat);
122 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
123 if (defined $shards) {
124 $self->{parallel} = 0 if $shards == 0;
125 $self->{shards} = $shards if $shards > 0;
128 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
129 my $max = $self->{ibx}->max_git_epoch;
130 $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
131 $self->git_init($max // 0);
135 # returns undef on duplicate or spam
136 # mimics Import::add and wraps it for v2
138 my ($self, $eml, $check_cb) = @_;
139 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
143 my ($self, $num) = @_;
144 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
147 # indexes a message, returns true if checkpointing is needed
149 my ($self, $msgref, $mime, $smsg) = @_;
150 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
151 $self->{oidx}->add_overview($mime, $smsg);
152 my $idx = idx_shard($self, $smsg->{num});
153 $idx->index_raw($msgref, $mime, $smsg);
154 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
155 $n >= $self->{batch_bytes};
159 my ($self, $mime, $check_cb) = @_;
163 $mime = $check_cb->($mime, $self->{ibx}) or return;
166 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
167 # as does SQLite 3.4.1+ (released in 2007-07-20), and
168 # Xapian 1.3.2+ (released 2015-03-15).
169 # For the most part, we can spawn git-fast-import without
170 # leaking FDs to it...
173 my ($num, $mid0) = v2_num_for($self, $mime);
174 defined $num or return; # duplicate
175 defined $mid0 or die "BUG: \$mid0 undefined\n";
176 my $im = $self->importer;
177 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
178 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
179 $cmt = $im->get_mark($cmt);
180 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
182 my $msgref = delete $smsg->{-raw_email};
183 if (do_idx($self, $msgref, $mime, $smsg)) {
191 my ($self, $mime) = @_;
192 my $mids = mids($mime);
194 my $mid = $mids->[0];
195 my $num = $self->{mm}->mid_insert($mid);
196 if (defined $num) { # common case
200 # crap, Message-ID is already known, hope somebody just resent:
201 foreach my $m (@$mids) {
202 # read-only lookup now safe to do after above barrier
203 # easy, don't store duplicates
204 # note: do not add more diagnostic info here since
205 # it gets noisy on public-inbox-watch restarts
206 return () if content_exists($self, $mime, $m);
209 # AltId may pre-populate article numbers (e.g. X-Mail-Count
210 # or NNTP article number), use that article number if it's
212 my $altid = $self->{ibx}->{altid};
213 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
214 my $num = $self->{mm}->num_for($mid);
216 if (defined $num && !$self->{oidx}->get_art($num)) {
222 warn "<$mid> reused for mismatched content\n";
224 # try the rest of the mids
225 for(my $i = $#$mids; $i >= 1; $i--) {
227 $num = $self->{mm}->mid_insert($m);
229 warn "alternative <$m> for <$mid> found\n";
234 # none of the existing Message-IDs are good, generate a new one:
235 v2_num_for_harder($self, $mime);
238 sub v2_num_for_harder {
239 my ($self, $eml) = @_;
241 my $dig = content_digest($eml);
242 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
243 my $num = $self->{mm}->mid_insert($mid0);
244 unless (defined $num) {
245 # it's hard to spoof the last Received: header
246 my @recvd = $eml->header_raw('Received');
247 $dig->add("Received: $_") foreach (@recvd);
248 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
249 $num = $self->{mm}->mid_insert($mid0);
251 # fall back to a random Message-ID and give up determinism:
252 until (defined($num)) {
254 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
255 warn "using random Message-ID <$mid0> as fallback\n";
256 $num = $self->{mm}->mid_insert($mid0);
259 PublicInbox::Import::append_mid($eml, $mid0);
263 sub _idx_init { # with_umask callback
264 my ($self, $opt) = @_;
265 $self->lock_acquire unless $opt && $opt->{-skip_lock};
266 $self->{oidx}->create;
268 # xcpdb can change shard count while -watch is idle
269 my $nshards = count_shards($self);
270 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
271 $self->{batch_bytes} = $opt->{batch_size} //
272 $PublicInbox::SearchIdx::BATCH_BYTES;
274 # need to create all shards before initializing msgmap FD
275 # idx_shards must be visible to all forked processes
276 my $max = $self->{shards} - 1;
277 my $idx = $self->{idx_shards} = [];
278 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
280 # SearchIdxShard may do their own flushing, so don't scale
281 # until after forking
282 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
284 my $ibx = $self->{ibx} or return; # ExtIdxSearch
286 # Now that all subprocesses are up, we can open the FDs
288 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
289 "$ibx->{inboxdir}/msgmap.sqlite3",
290 $ibx->{-no_fsync} ? 2 : 1);
291 $mm->{dbh}->begin_work;
294 sub parallel_init ($$) {
295 my ($self, $indexlevel) = @_;
296 if (($indexlevel // 'full') eq 'basic') {
297 $self->{parallel} = 0;
299 pipe(my ($r, $w)) or die "pipe failed: $!";
300 # pipe for barrier notifications doesn't need to be big,
302 fcntl($w, 1031, 4096) if $^O eq 'linux';
303 $self->{bnote} = [ $r, $w ];
310 my ($self, $opt) = @_;
311 return if $self->{idx_shards};
312 my $ibx = $self->{ibx};
314 # do not leak read-only FDs to child processes, we only have these
315 # FDs for duplicate detection so they should not be
316 # frequently activated.
317 delete @$ibx{qw(mm search)};
320 parallel_init($self, $ibx->{indexlevel});
321 $ibx->with_umask(\&_idx_init, $self, $opt);
324 # returns an array mapping [ epoch => latest_commit ]
325 # latest_commit may be undef if nothing was done to that epoch
326 # $replace_map = { $object_id => $strref, ... }
327 sub _replace_oids ($$$) {
328 my ($self, $mime, $replace_map) = @_;
330 my $ibx = $self->{ibx};
331 my $pfx = "$ibx->{inboxdir}/git";
332 my $rewrites = []; # epoch => commit
333 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
335 foreach my $i (0..$max) {
336 my $git_dir = "$pfx/$i.git";
338 my $git = PublicInbox::Git->new($git_dir);
339 my $im = $self->import_init($git, 0, 1);
340 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
346 sub content_hashes ($) {
348 my @chashes = ( content_hash($mime) );
350 # We still support Email::MIME, here, and
351 # Email::MIME->as_string doesn't always round-trip, so we may
352 # use a second content_hash
353 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
354 push @chashes, $rt if $chashes[0] ne $rt;
358 sub content_matches ($$) {
359 my ($chashes, $existing) = @_;
360 my $chash = content_hash($existing);
361 foreach (@$chashes) {
362 return 1 if $_ eq $chash
367 # used for removing or replacing (purging)
368 sub rewrite_internal ($$;$$$) {
369 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
371 my ($im, $need_reindex, $replace_map);
373 $replace_map = {}; # oid => sref
374 $need_reindex = [] if $new_eml;
376 $im = $self->importer;
378 my $oidx = $self->{oidx};
379 my $chashes = content_hashes($old_eml);
381 my $mids = mids($old_eml);
383 # We avoid introducing new blobs into git since the raw content
384 # can be slightly different, so we do not need the user-supplied
385 # message now that we have the mids and content_hash
389 foreach my $mid (@$mids) {
390 my %gone; # num => [ smsg, $mime, raw ]
392 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
393 my $msg = get_blob($self, $smsg);
394 if (!defined($msg)) {
395 warn "broken smsg for $mid\n";
399 my $cur = PublicInbox::Eml->new($msg);
400 if (content_matches($chashes, $cur)) {
401 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
404 my $n = scalar keys %gone;
407 warn "BUG: multiple articles linked to <$mid>\n",
408 join(',', sort keys %gone), "\n";
410 foreach my $num (keys %gone) {
411 my ($smsg, $mime, $orig) = @{$gone{$num}};
412 # $removed should only be set once assuming
413 # no bugs in our deduplication code:
414 $removed = [ undef, $mime, $smsg ];
415 my $oid = $smsg->{blob};
417 $replace_map->{$oid} = $sref;
419 ($mark, undef) = $im->remove($orig, $cmt_msg);
420 $removed->[0] = $mark;
423 if ($need_reindex) { # ->replace
424 push @$need_reindex, $smsg;
425 } else { # ->purge or ->remove
426 $self->{mm}->num_delete($num);
428 unindex_oid_aux($self, $oid, $mid);
433 my $cmt = $im->get_mark($mark);
434 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
436 if ($replace_map && scalar keys %$replace_map) {
437 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
438 return { rewrites => $rewrites, need_reindex => $need_reindex };
440 defined($mark) ? $removed : undef;
443 # public (see PublicInbox::Import->remove), but note the 3rd element
444 # (retval[2]) is not part of the stable API shared with Import->remove
446 my ($self, $eml, $cmt_msg) = @_;
447 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
448 $self, $eml, $cmt_msg);
449 defined($r) && defined($r->[0]) ? @$r: undef;
452 sub _replace ($$;$$) {
453 my ($self, $old_eml, $new_eml, $sref) = @_;
454 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
455 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
456 $self, $old_eml, undef, $new_eml, $sref) or return;
458 my $rewrites = $rewritten->{rewrites};
459 # ->done is called if there are rewrites since we gc+prune from git
460 $self->idx_init if @$rewrites;
462 for my $i (0..$#$rewrites) {
463 defined(my $cmt = $rewrites->[$i]) or next;
464 $self->{last_commit}->[$i] = $cmt;
471 my ($self, $mime) = @_;
472 my $rewritten = _replace($self, $mime, undef, \'') or return;
473 $rewritten->{rewrites}
476 # returns the git object_id of $fh, does not write the object to FS
477 sub git_hash_raw ($$) {
478 my ($self, $raw) = @_;
479 # grab the expected OID we have to reindex:
480 pipe(my($in, $w)) or die "pipe: $!";
481 my $git_dir = $self->git->{git_dir};
482 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
483 my $r = popen_rd($cmd, undef, { 0 => $in });
484 print $w $$raw or die "print \$w: $!";
485 close $w or die "close \$w: $!";
487 chomp(my $oid = <$r>);
488 close $r or die "git hash-object failed: $?";
489 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
493 sub _check_mids_match ($$$) {
494 my ($old_list, $new_list, $hdrs) = @_;
495 my %old_mids = map { $_ => 1 } @$old_list;
496 my %new_mids = map { $_ => 1 } @$new_list;
497 my @old = keys %old_mids;
498 my @new = keys %new_mids;
499 my $err = "$hdrs may not be changed when replacing\n";
500 die $err if scalar(@old) != scalar(@new);
501 delete @new_mids{@old};
502 delete @old_mids{@new};
503 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
506 # Changing Message-IDs or References with ->replace isn't supported.
507 # The rules for dealing with messages with multiple or conflicting
508 # Message-IDs are pretty complex and rethreading hasn't been fully
510 sub check_mids_match ($$) {
511 my ($old, $new) = @_;
512 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
513 _check_mids_match(references($old), references($new),
514 'References/In-Reply-To');
519 my ($self, $old_mime, $new_mime) = @_;
521 check_mids_match($old_mime, $new_mime);
523 # mutt will always add Content-Length:, Status:, Lines: when editing
524 PublicInbox::Import::drop_unwanted_headers($new_mime);
526 my $raw = $new_mime->as_string;
527 my $expect_oid = git_hash_raw($self, \$raw);
528 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
529 my $need_reindex = $rewritten->{need_reindex};
531 # just in case we have bugs in deduplication code:
532 my $n = scalar(@$need_reindex);
534 my $list = join(', ', map {
535 "$_->{num}: <$_->{mid}>"
538 W: rewritten $n messages matching content of original message (expected: 1).
539 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
544 # make sure we really got the OID:
545 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
546 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
548 # don't leak FDs to Xapian:
551 # reindex modified messages:
552 for my $smsg (@$need_reindex) {
553 my $new_smsg = bless {
558 }, 'PublicInbox::Smsg';
559 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
560 $new_smsg->populate($new_mime, $sync);
561 do_idx($self, \$raw, $new_mime, $new_smsg);
563 $rewritten->{rewrites};
566 sub last_epoch_commit ($$;$) {
567 my ($self, $i, $cmt) = @_;
568 my $v = PublicInbox::Search::SCHEMA_VERSION();
569 $self->{mm}->last_commit_xap($v, $i, $cmt);
572 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
574 defined(my $epoch_max = $self->{epoch_max}) or return;
575 my $last_commit = $self->{last_commit};
576 foreach my $i (0..$epoch_max) {
577 defined(my $cmt = $last_commit->[$i]) or next;
578 $last_commit->[$i] = undef;
579 last_epoch_commit($self, $i, $cmt);
585 $self->{bnote} or return;
587 my $barrier = { map { $_ => 1 } (0..$n) };
591 my ($self, $barrier) = @_;
592 my $bnote = $self->{bnote} or return;
594 while (scalar keys %$barrier) {
595 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
596 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
597 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
602 sub checkpoint ($;$) {
603 my ($self, $wait) = @_;
605 if (my $im = $self->{im}) {
612 my $shards = $self->{idx_shards};
614 my $mm = $self->{mm};
615 my $dbh = $mm->{dbh} if $mm;
617 # SQLite msgmap data is second in importance
618 $dbh->commit if $dbh;
620 # SQLite overview is third
621 $self->{oidx}->commit_lazy;
623 # Now deal with Xapian
625 my $barrier = barrier_init($self, scalar @$shards);
627 # each shard needs to issue a barrier command
628 $_->shard_barrier for @$shards;
630 # wait for each Xapian shard
631 barrier_wait($self, $barrier);
633 $_->shard_commit for @$shards;
636 my $midx = $self->{midx}; # misc index
637 $midx->commit_txn if $midx;
639 # last_commit is special, don't commit these until
640 # Xapian shards are done:
641 $dbh->begin_work if $dbh;
642 set_last_commits($self);
647 $midx->begin_txn if $midx;
649 $self->{total_bytes} += $self->{transact_bytes};
650 $self->{transact_bytes} = 0;
653 # issue a write barrier to ensure all data is visible to other processes
654 # and read-only ops. Order of data importance is: git > SQLite > Xapian
656 sub barrier { checkpoint($_[0], 1) };
658 # true if locked and active
659 sub active { !!$_[0]->{im} }
665 if (my $im = delete $self->{im}) {
666 eval { $im->done }; # PublicInbox::Import::done
667 $err .= "import done: $@\n" if $@;
670 eval { checkpoint($self) };
671 $err .= "checkpoint: $@\n" if $@;
673 if (my $mm = delete $self->{mm}) {
674 my $m = $err ? 'rollback' : 'commit';
675 eval { $mm->{dbh}->$m };
676 $err .= "msgmap $m: $@\n" if $@;
678 my $shards = delete $self->{idx_shards};
681 eval { $_->shard_close };
682 $err .= "shard close: $@\n" if $@;
685 eval { $self->{oidx}->dbh_close };
686 $err .= "over close: $@\n" if $@;
687 delete $self->{midx};
688 delete $self->{bnote};
689 my $nbytes = $self->{total_bytes};
690 $self->{total_bytes} = 0;
691 $self->lock_release(!!$nbytes) if $shards;
696 sub write_alternates ($$$) {
697 my ($info_dir, $mode, $out) = @_;
698 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
699 my $tmp = $fh->filename;
700 print $fh @$out or die "print $tmp: $!\n";
701 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
702 close $fh or die "close $tmp $!\n";
703 my $alt = "$info_dir/alternates";
704 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
705 $fh->unlink_on_destroy(0);
708 sub fill_alternates ($$) {
709 my ($self, $epoch) = @_;
711 my $pfx = "$self->{ibx}->{inboxdir}/git";
712 my $all = "$self->{ibx}->{inboxdir}/all.git";
713 PublicInbox::Import::init_bare($all) unless -d $all;
714 my $info_dir = "$all/objects/info";
715 my $alt = "$info_dir/alternates";
719 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
720 $mode = (stat($fh))[2] & 07777;
722 # we assign a sort score to every alternate and favor
723 # the newest (highest numbered) one because loose objects
724 # require scanning epochs and only the latest epoch is
725 # expected to see loose objects
727 my $other = 0; # in case admin adds non-epoch repos
729 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
735 } split(/\n+/, do { local $/; <$fh> });
738 foreach my $i (0..$epoch) {
739 my $dir = "../../git/$i.git/objects";
740 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
746 write_alternates($info_dir, $mode,
747 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
751 my ($self, $epoch) = @_;
752 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
753 PublicInbox::Import::init_bare($git_dir);
754 my @cmd = (qw/git config/, "--file=$git_dir/config",
755 'include.path', '../../all.git/config');
756 PublicInbox::Import::run_die(\@cmd);
757 fill_alternates($self, $epoch);
763 my $im = $self->{im};
765 if ($im->{bytes_added} < $self->{rotate_bytes}) {
772 my $git_dir = $self->git_init(++$self->{epoch_max});
773 my $git = PublicInbox::Git->new($git_dir);
774 return $self->import_init($git, 0);
779 my $latest = $self->{ibx}->git_dir_latest(\$max);
780 if (defined $latest) {
781 my $git = PublicInbox::Git->new($latest);
782 my $packed_bytes = $git->packed_bytes;
783 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
785 if ($unpacked_bytes >= $self->{rotate_bytes}) {
788 $self->{epoch_max} = $max;
789 return $self->import_init($git, $packed_bytes);
792 $self->{epoch_max} = $epoch;
793 $latest = $self->git_init($epoch);
794 $self->import_init(PublicInbox::Git->new($latest), 0);
798 my ($self, $git, $packed_bytes, $tmp) = @_;
799 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
800 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
801 $im->{lock_path} = undef;
802 $im->{path_type} = 'v2';
803 $self->{im} = $im unless $tmp;
809 my ($mid, $cur, $new) = @_;
811 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
812 print $ah $cur->as_string or die "print: $!";
813 $ah->flush or die "flush: $!";
814 PublicInbox::Import::drop_unwanted_headers($new);
815 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
816 print $bh $new->as_string or die "print: $!";
817 $bh->flush or die "flush: $!";
818 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
819 print STDERR "# MID conflict <$mid>\n";
820 my $pid = spawn($cmd, undef, { 1 => 2 });
821 waitpid($pid, 0) == $pid or die "diff did not finish";
825 my ($self, $smsg) = @_;
826 if (my $im = $self->{im}) {
827 my $msg = $im->cat_blob($smsg->{blob});
830 # older message, should be in alternates
831 $self->{ibx}->msg_by_smsg($smsg);
834 sub content_exists ($$$) {
835 my ($self, $mime, $mid) = @_;
836 my $oidx = $self->{oidx};
837 my $chashes = content_hashes($mime);
839 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
840 my $msg = get_blob($self, $smsg);
841 if (!defined($msg)) {
842 warn "broken smsg for $mid\n";
845 my $cur = PublicInbox::Eml->new($msg);
846 return 1 if content_matches($chashes, $cur);
848 # XXX DEBUG_DIFF is experimental and may be removed
849 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
856 if (my $shards = $self->{idx_shards}) {
857 $_->atfork_child foreach @$shards;
859 if (my $im = $self->{im}) {
862 die "unexpected mm" if $self->{mm};
863 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
867 sub reindex_checkpoint ($$) {
868 my ($self, $sync) = @_;
870 $self->git->async_wait_all;
871 $self->update_last_commit($sync);
872 ${$sync->{need_checkpoint}} = 0;
873 my $mm_tmp = $sync->{mm_tmp};
874 $mm_tmp->atfork_prepare if $mm_tmp;
875 die 'BUG: {im} during reindex' if $self->{im};
876 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
877 checkpoint($self, 1); # no need to release lock on pure index
879 $self->done; # release lock
882 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
883 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
886 # allow -watch or -mda to write...
887 $self->idx_init($sync->{-opt}); # reacquire lock
888 if (my $intvl = $sync->{check_intvl}) { # eidx
889 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
891 $mm_tmp->atfork_parent if $mm_tmp;
894 sub index_finalize ($$) {
895 my ($arg, $index) = @_;
896 ++$arg->{self}->{nidx};
897 if (defined(my $cur = $arg->{cur_cmt})) {
898 ${$arg->{latest_cmt}} = $cur;
900 die 'BUG: {cur_cmt} missing';
901 } # else { unindexing @leftovers doesn't set {cur_cmt}
904 sub index_oid { # cat_async callback
905 my ($bref, $oid, $type, $size, $arg) = @_;
906 is_bad_blob($oid, $type, $size, $arg->{oid}) and
907 return index_finalize($arg, 1); # size == 0 purged returns here
908 my $self = $arg->{self};
909 local $self->{current_info} = "$self->{current_info} $oid";
911 my $eml = PublicInbox::Eml->new($$bref);
912 my $mids = mids($eml);
913 my $chash = content_hash($eml);
915 if (scalar(@$mids) == 0) {
916 warn "E: $oid has no Message-ID, skipping\n";
920 # {unindexed} is unlikely
921 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
922 $num = delete($unindexed->{$mids->[0]});
925 $self->{mm}->mid_set($num, $mid0);
926 delete($arg->{unindexed}) if !keys(%$unindexed);
929 if (!defined($num)) { # reuse if reindexing (or duplicates)
930 my $oidx = $self->{oidx};
931 for my $mid (@$mids) {
932 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
933 last if defined $num;
936 $mid0 //= do { # is this a number we got before?
937 $num = $arg->{mm_tmp}->num_for($mids->[0]);
938 defined($num) ? $mids->[0] : undef;
940 if (!defined($num)) {
941 for (my $i = $#$mids; $i >= 1; $i--) {
942 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
950 $arg->{mm_tmp}->num_delete($num);
951 } else { # never seen
952 $num = $self->{mm}->mid_insert($mids->[0]);
955 } else { # rare, try the rest of them, backwards
956 for (my $i = $#$mids; $i >= 1; $i--) {
957 $num = $self->{mm}->mid_insert($mids->[$i]);
965 if (!defined($num)) {
966 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
975 }, 'PublicInbox::Smsg';
976 $smsg->populate($eml, $arg);
977 if (do_idx($self, $bref, $eml, $smsg)) {
978 ${$arg->{need_checkpoint}} = 1;
980 index_finalize($arg, 1);
983 # only update last_commit for $i on reindex iff newer than current
984 sub update_last_commit {
985 my ($self, $sync, $stk) = @_;
986 my $unit = $sync->{unit} // return;
987 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
988 defined($latest_cmt) or return;
989 my $last = last_epoch_commit($self, $unit->{epoch});
990 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
991 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
992 chomp(my $n = $unit->{git}->qx(@cmd));
993 return if $n ne '' && $n == 0;
995 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
999 my ($self, $sync) = @_;
1001 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1002 $heads->[$i] = last_epoch_commit($self, $i);
1007 # returns a revision range for git-log(1)
1008 sub log_range ($$$) {
1009 my ($sync, $unit, $tip) = @_;
1010 my $opt = $sync->{-opt};
1011 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1012 my $i = $unit->{epoch};
1013 my $cur = $sync->{ranges}->[$i] or do {
1014 $pr->("$i.git indexing all of $tip\n") if $pr;
1015 return $tip; # all of it
1018 # fast equality check to avoid (v)fork+execve overhead
1020 $sync->{ranges}->[$i] = undef;
1024 my $range = "$cur..$tip";
1025 $pr->("$i.git checking contiguity... ") if $pr;
1026 my $git = $unit->{git};
1027 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1028 $pr->("OK\n") if $pr;
1029 my $n = $git->qx(qw(rev-list --count), $range);
1032 $sync->{ranges}->[$i] = undef;
1033 $pr->("$i.git has nothing new\n") if $pr;
1034 return; # nothing to do
1036 $pr->("$i.git has $n changes since $cur\n") if $pr;
1038 $pr->("FAIL\n") if $pr;
1040 discontiguous range: $range
1041 Rewritten history? (in $git->{git_dir})
1043 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1045 $range = "$base..$tip";
1046 warn "found merge-base: $base\n"
1049 warn "discarding history at $cur\n";
1052 reindexing $git->{git_dir}
1055 # $cur^0 may no longer exist if pruned by git
1056 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1057 $unit->{unindex_range} = "$base..$cur";
1058 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1059 $unit->{unindex_range} = "$base..";
1061 warn "W: unable to unindex before $range\n";
1067 # overridden by ExtSearchIdx
1068 sub artnum_max { $_[0]->{mm}->num_highwater }
1070 sub sync_prepare ($$) {
1071 my ($self, $sync) = @_;
1072 $sync->{ranges} = sync_ranges($self, $sync);
1073 my $pr = $sync->{-opt}->{-progress};
1075 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1078 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1079 $pfx //= $sync->{ibx}->{inboxdir};
1083 if ($self->{ibx_map}) {
1084 # ExtSearchIdx won't index messages unless they're in
1085 # over.sqlite3 for a given inbox, so don't read beyond
1086 # what's in the per-inbox index.
1087 $reindex_heads = [];
1088 my $v = PublicInbox::Search::SCHEMA_VERSION;
1089 my $mm = $sync->{ibx}->mm;
1090 for my $i (0..$sync->{epoch_max}) {
1091 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1093 } elsif ($sync->{reindex}) { # V2 inbox
1094 # reindex stops at the current heads and we later
1095 # rerun index_sync without {reindex}
1096 $reindex_heads = $self->last_commits($sync);
1098 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1099 $sync->{index_oid} = $self->can('index_oid');
1101 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1102 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1103 my $git_dir = "$git_pfx/$i.git";
1104 -d $git_dir or next; # missing epochs are fine
1105 my $git = PublicInbox::Git->new($git_dir);
1106 my $unit = { git => $git, epoch => $i };
1108 if ($reindex_heads) {
1109 $tip = $head = $reindex_heads->[$i] or next;
1111 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1112 next if $?; # new repo
1115 my $range = log_range($sync, $unit, $tip) or next;
1116 # can't use 'rev-list --count' if we use --diff-filter
1117 $pr->("$pfx $i.git counting $range ... ") if $pr;
1118 # Don't bump num_highwater on --reindex by using {D}.
1119 # We intentionally do NOT use {D} in the non-reindex case
1120 # because we want NNTP article number gaps from unindexed
1121 # messages to show up in mirrors, too.
1122 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1123 my $stk = log2stack($sync, $git, $range);
1124 return 0 if $sync->{quit};
1125 my $nr = $stk ? $stk->num_records : 0;
1126 $pr->("$nr\n") if $pr;
1127 $unit->{stack} = $stk; # may be undef
1128 unshift @{$sync->{todo}}, $unit;
1131 return 0 if $sync->{quit};
1133 # XXX this should not happen unless somebody bypasses checks in
1134 # our code and blindly injects "d" file history into git repos
1135 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1136 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1137 local $self->{current_info} = 'leftover ';
1138 my $unindex_oid = $self->can('unindex_oid');
1139 for my $oid (@leftovers) {
1140 last if $sync->{quit};
1141 $oid = unpack('H*', $oid);
1142 my $req = { %$sync, oid => $oid };
1143 $self->git->cat_async($oid, $unindex_oid, $req);
1145 $self->git->cat_async_wait;
1147 return 0 if $sync->{quit};
1149 $sync->{-regen_fmt} = "%u/?\n";
1153 # reindex should NOT see new commits anymore, if we do,
1154 # it's a problem and we need to notice it via die()
1155 my $pad = length($regen_max) + 1;
1156 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1157 $sync->{nr} = \(my $nr = 0);
1158 return -1 if $sync->{reindex};
1159 $regen_max + $self->artnum_max || 0;
1162 sub unindex_oid_aux ($$$) {
1163 my ($self, $oid, $mid) = @_;
1164 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1165 for my $num (@removed) {
1166 my $idx = idx_shard($self, $num);
1167 $idx->shard_remove($num);
1171 sub unindex_oid ($$;$) { # git->cat_async callback
1172 my ($bref, $oid, $type, $size, $arg) = @_;
1173 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1174 return index_finalize($arg, 0);
1175 my $self = $arg->{self};
1176 local $self->{current_info} = "$self->{current_info} $oid";
1177 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1178 my $mm = $self->{mm};
1179 my $mids = mids(PublicInbox::Eml->new($bref));
1181 my $oidx = $self->{oidx};
1182 foreach my $mid (@$mids) {
1185 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1186 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1188 my $n = scalar(keys(%gone)) or next;
1190 warn "BUG: multiple articles linked to $oid\n",
1191 join(',',sort keys %gone), "\n";
1193 foreach my $num (keys %gone) {
1195 my $mid0 = $mm->mid_for($num);
1196 $unindexed->{$mid0} = $num;
1198 $mm->num_delete($num);
1200 unindex_oid_aux($self, $oid, $mid);
1202 index_finalize($arg, 0);
1205 sub git { $_[0]->{ibx}->git }
1207 # this is rare, it only happens when we get discontiguous history in
1208 # a mirror because the source used -purge or -edit
1209 sub unindex_todo ($$$) {
1210 my ($self, $sync, $unit) = @_;
1211 my $unindex_range = delete($unit->{unindex_range}) // return;
1212 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1213 my $before = scalar keys %$unindexed;
1214 # order does not matter, here:
1215 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1216 --no-abbrev --no-renames), $unindex_range);
1217 local $sync->{in_unindex} = 1;
1218 my $unindex_oid = $self->can('unindex_oid');
1220 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1221 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1223 close $fh or die "git log failed: \$?=$?";
1224 $self->git->cat_async_wait;
1226 return unless $sync->{-opt}->{prune};
1227 my $after = scalar keys %$unindexed;
1228 return if $before == $after;
1230 # ensure any blob can not longer be accessed via dumb HTTP
1231 PublicInbox::Import::run_die(['git',
1232 "--git-dir=$unit->{git}->{git_dir}",
1233 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1236 sub sync_ranges ($$) {
1237 my ($self, $sync) = @_;
1238 my $reindex = $sync->{reindex};
1239 return $self->last_commits($sync) unless $reindex;
1240 return [] if ref($reindex) ne 'HASH';
1242 my $ranges = $reindex->{from}; # arrayref;
1243 if (ref($ranges) ne 'ARRAY') {
1244 die 'BUG: $reindex->{from} not an ARRAY';
1249 sub index_xap_only { # git->cat_async callback
1250 my ($bref, $oid, $type, $size, $smsg) = @_;
1251 my $self = $smsg->{self};
1252 my $idx = idx_shard($self, $smsg->{num});
1253 $smsg->{raw_bytes} = $size;
1254 $idx->index_raw($bref, undef, $smsg);
1255 $self->{transact_bytes} += $size;
1258 sub index_xap_step ($$$;$) {
1259 my ($self, $sync, $beg, $step) = @_;
1260 my $end = $sync->{art_end};
1261 return if $beg > $end; # nothing to do
1263 $step //= $self->{shards};
1264 my $ibx = $self->{ibx};
1265 if (my $pr = $sync->{-opt}->{-progress}) {
1266 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1267 "$beg..$end (% $step)\n");
1269 for (my $num = $beg; $num <= $end; $num += $step) {
1270 last if $sync->{quit};
1271 my $smsg = $ibx->over->get_art($num) or next;
1272 $smsg->{self} = $self;
1273 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1274 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1275 ${$sync->{nr}} = $num;
1276 reindex_checkpoint($self, $sync);
1281 sub index_todo ($$$) {
1282 my ($self, $sync, $unit) = @_;
1283 return if $sync->{quit};
1284 unindex_todo($self, $sync, $unit);
1285 my $stk = delete($unit->{stack}) or return;
1286 my $all = $self->git;
1287 my $index_oid = $self->can('index_oid');
1288 my $unindex_oid = $self->can('unindex_oid');
1290 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1291 $pfx = "$1 $2"; # v2
1293 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1294 $pfx //= $unit->{git}->{git_dir};
1296 local $self->{current_info} = "$pfx ";
1297 local $sync->{latest_cmt} = \(my $latest_cmt);
1298 local $sync->{unit} = $unit;
1299 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1300 if ($sync->{quit}) {
1301 warn "waiting to quit...\n";
1302 $all->async_wait_all;
1303 $self->update_last_commit($sync);
1314 if ($sync->{max_size}) {
1315 $all->check_async($oid, \&check_size, $req);
1317 $all->cat_async($oid, $index_oid, $req);
1319 } elsif ($f eq 'd') {
1320 $all->cat_async($oid, $unindex_oid, $req);
1322 if (${$sync->{need_checkpoint}}) {
1323 reindex_checkpoint($self, $sync);
1326 $all->async_wait_all;
1327 $self->update_last_commit($sync, $stk);
1331 my ($self, $opt, $sync, $art_beg) = @_;
1332 my $seq = $opt->{sequential_shard};
1334 local $self->{parallel} = 0 if $seq;
1335 $self->idx_init($opt); # acquire lock
1336 if (my $art_end = $self->{ibx}->mm->max) {
1338 need_checkpoint => \(my $bool = 0),
1341 nr => \(my $nr = 0),
1342 -regen_fmt => "%u/?\n",
1344 $sync->{art_end} = $art_end;
1345 if ($seq || !$self->{parallel}) {
1346 my $shard_end = $self->{shards} - 1;
1347 for my $i (0..$shard_end) {
1348 last if $sync->{quit};
1349 index_xap_step($self, $sync, $art_beg + $i);
1350 if ($i != $shard_end) {
1351 reindex_checkpoint($self, $sync);
1354 } else { # parallel (maybe)
1355 index_xap_step($self, $sync, $art_beg, 1);
1358 $self->git->cat_async_wait;
1362 # public, called by public-inbox-index
1364 my ($self, $opt) = @_;
1366 return xapian_only($self, $opt) if $opt->{xapian_only};
1369 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1370 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1371 use Time::HiRes qw(stat);
1372 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1373 my $c = $mm[10]; # 10 = ctime (nsec NV)
1374 my @hd = stat("$latest/refs/heads");
1375 my @pr = stat("$latest/packed-refs");
1376 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1380 my $pr = $opt->{-progress};
1381 my $seq = $opt->{sequential_shard};
1382 my $art_beg; # the NNTP article number we start xapian_only at
1383 my $idxlevel = $self->{ibx}->{indexlevel};
1384 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1386 $self->idx_init($opt); # acquire lock
1387 fill_alternates($self, $epoch_max);
1388 $self->{oidx}->rethread_prepare($opt);
1390 need_checkpoint => \(my $bool = 0),
1391 reindex => $opt->{reindex},
1394 ibx => $self->{ibx},
1395 epoch_max => $epoch_max,
1397 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1398 local $SIG{QUIT} = $quit;
1399 local $SIG{INT} = $quit;
1400 local $SIG{TERM} = $quit;
1402 if (sync_prepare($self, $sync)) {
1403 # tmp_clone seems to fail if inside a transaction, so
1404 # we rollback here (because we opened {mm} for reading)
1405 # Note: we do NOT rely on DBI transactions for atomicity;
1406 # only for batch performance.
1407 $self->{mm}->{dbh}->rollback;
1408 $self->{mm}->{dbh}->begin_work;
1410 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1412 # xapian_only works incrementally w/o --reindex
1413 if ($seq && !$opt->{reindex}) {
1414 $art_beg = $sync->{mm_tmp}->max || -1;
1418 # work forwards through history
1419 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1420 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1423 if (my $nr = $sync->{nr}) {
1424 my $pr = $sync->{-opt}->{-progress};
1425 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1429 # deal with Xapian shards sequentially
1430 if ($seq && delete($sync->{mm_tmp})) {
1431 if ($sync->{quit}) {
1434 $self->{ibx}->{indexlevel} = $idxlevel;
1435 xapian_only($self, $opt, $sync, $art_beg);
1436 $quit_warn = 1 if $sync->{quit};
1440 # --reindex on the command-line
1441 if (!$sync->{quit} && $opt->{reindex} &&
1442 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1443 $self->lock_acquire;
1444 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1445 if (my $xdb = $s0->idx_acquire) {
1446 my $n = $xdb->get_metadata('has_threadid');
1447 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1450 $self->lock_release;
1453 # reindex does not pick up new changes, so we rerun w/o it:
1454 if ($opt->{reindex} && !$sync->{quit}) {
1457 delete @again{qw(rethread reindex -skip_lock)};
1458 index_sync($self, \%again);
1459 $opt->{quit} = $again{quit}; # propagate to caller
1461 warn <<EOF if $quit_warn;
1462 W: interrupted, --xapian-only --reindex required upon restart