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 $v2ibx->umask_prepare;
102 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
105 im => undef, # PublicInbox::Import
111 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
112 lock_path => "$dir/inbox.lock",
113 # limit each git repo (epoch) to 1GB or so
114 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
115 last_commit => [], # git epoch -> commit
117 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
118 $self->{shards} = count_shards($self) || nproc_shards($creat);
124 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
125 if (defined $shards) {
126 $self->{parallel} = 0 if $shards == 0;
127 $self->{shards} = $shards if $shards > 0;
130 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
132 $self->{ibx}->git_dir_latest(\$epoch_max);
133 if (defined $skip_epoch && $epoch_max == -1) {
134 $epoch_max = $skip_epoch;
136 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
140 # returns undef on duplicate or spam
141 # mimics Import::add and wraps it for v2
143 my ($self, $eml, $check_cb) = @_;
144 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
148 my ($self, $num) = @_;
149 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
152 # indexes a message, returns true if checkpointing is needed
154 my ($self, $msgref, $mime, $smsg) = @_;
155 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
156 $self->{oidx}->add_overview($mime, $smsg);
157 my $idx = idx_shard($self, $smsg->{num});
158 $idx->index_raw($msgref, $mime, $smsg);
159 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
160 $n >= $self->{batch_bytes};
164 my ($self, $mime, $check_cb) = @_;
168 $mime = $check_cb->($mime, $self->{ibx}) or return;
171 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
172 # as does SQLite 3.4.1+ (released in 2007-07-20), and
173 # Xapian 1.3.2+ (released 2015-03-15).
174 # For the most part, we can spawn git-fast-import without
175 # leaking FDs to it...
178 my ($num, $mid0) = v2_num_for($self, $mime);
179 defined $num or return; # duplicate
180 defined $mid0 or die "BUG: \$mid0 undefined\n";
181 my $im = $self->importer;
182 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
183 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
184 $cmt = $im->get_mark($cmt);
185 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
187 my $msgref = delete $smsg->{-raw_email};
188 if (do_idx($self, $msgref, $mime, $smsg)) {
196 my ($self, $mime) = @_;
197 my $mids = mids($mime);
199 my $mid = $mids->[0];
200 my $num = $self->{mm}->mid_insert($mid);
201 if (defined $num) { # common case
205 # crap, Message-ID is already known, hope somebody just resent:
206 foreach my $m (@$mids) {
207 # read-only lookup now safe to do after above barrier
208 # easy, don't store duplicates
209 # note: do not add more diagnostic info here since
210 # it gets noisy on public-inbox-watch restarts
211 return () if content_exists($self, $mime, $m);
214 # AltId may pre-populate article numbers (e.g. X-Mail-Count
215 # or NNTP article number), use that article number if it's
217 my $altid = $self->{ibx}->{altid};
218 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
219 my $num = $self->{mm}->num_for($mid);
221 if (defined $num && !$self->{oidx}->get_art($num)) {
227 warn "<$mid> reused for mismatched content\n";
229 # try the rest of the mids
230 for(my $i = $#$mids; $i >= 1; $i--) {
232 $num = $self->{mm}->mid_insert($m);
234 warn "alternative <$m> for <$mid> found\n";
239 # none of the existing Message-IDs are good, generate a new one:
240 v2_num_for_harder($self, $mime);
243 sub v2_num_for_harder {
244 my ($self, $eml) = @_;
246 my $dig = content_digest($eml);
247 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
248 my $num = $self->{mm}->mid_insert($mid0);
249 unless (defined $num) {
250 # it's hard to spoof the last Received: header
251 my @recvd = $eml->header_raw('Received');
252 $dig->add("Received: $_") foreach (@recvd);
253 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
254 $num = $self->{mm}->mid_insert($mid0);
256 # fall back to a random Message-ID and give up determinism:
257 until (defined($num)) {
259 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
260 warn "using random Message-ID <$mid0> as fallback\n";
261 $num = $self->{mm}->mid_insert($mid0);
264 PublicInbox::Import::append_mid($eml, $mid0);
268 sub _idx_init { # with_umask callback
269 my ($self, $opt) = @_;
270 $self->lock_acquire unless $opt && $opt->{-skip_lock};
271 $self->{oidx}->create;
273 # xcpdb can change shard count while -watch is idle
274 my $nshards = count_shards($self);
275 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
276 $self->{batch_bytes} = $opt->{batch_size} //
277 $PublicInbox::SearchIdx::BATCH_BYTES;
278 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
280 # need to create all shards before initializing msgmap FD
281 # idx_shards must be visible to all forked processes
282 my $max = $self->{shards} - 1;
283 my $idx = $self->{idx_shards} = [];
284 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
285 my $ibx = $self->{ibx} or return; # ExtIdxSearch
287 # Now that all subprocesses are up, we can open the FDs
289 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
290 "$ibx->{inboxdir}/msgmap.sqlite3",
291 $ibx->{-no_fsync} ? 2 : 1);
292 $mm->{dbh}->begin_work;
295 sub parallel_init ($$) {
296 my ($self, $indexlevel) = @_;
297 if (($indexlevel // 'full') eq 'basic') {
298 $self->{parallel} = 0;
300 pipe(my ($r, $w)) or die "pipe failed: $!";
301 # pipe for barrier notifications doesn't need to be big,
303 fcntl($w, 1031, 4096) if $^O eq 'linux';
304 $self->{bnote} = [ $r, $w ];
311 my ($self, $opt) = @_;
312 return if $self->{idx_shards};
313 my $ibx = $self->{ibx};
315 # do not leak read-only FDs to child processes, we only have these
316 # FDs for duplicate detection so they should not be
317 # frequently activated.
318 delete @$ibx{qw(mm search)};
321 parallel_init($self, $ibx->{indexlevel});
323 $ibx->with_umask(\&_idx_init, $self, $opt);
326 # returns an array mapping [ epoch => latest_commit ]
327 # latest_commit may be undef if nothing was done to that epoch
328 # $replace_map = { $object_id => $strref, ... }
329 sub _replace_oids ($$$) {
330 my ($self, $mime, $replace_map) = @_;
332 my $ibx = $self->{ibx};
333 my $pfx = "$ibx->{inboxdir}/git";
334 my $rewrites = []; # epoch => commit
335 my $max = $self->{epoch_max};
337 unless (defined($max)) {
338 defined(my $latest = $ibx->git_dir_latest(\$max)) or return;
339 $self->{epoch_max} = $max;
342 foreach my $i (0..$max) {
343 my $git_dir = "$pfx/$i.git";
345 my $git = PublicInbox::Git->new($git_dir);
346 my $im = $self->import_init($git, 0, 1);
347 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
353 sub content_hashes ($) {
355 my @chashes = ( content_hash($mime) );
357 # We still support Email::MIME, here, and
358 # Email::MIME->as_string doesn't always round-trip, so we may
359 # use a second content_hash
360 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
361 push @chashes, $rt if $chashes[0] ne $rt;
365 sub content_matches ($$) {
366 my ($chashes, $existing) = @_;
367 my $chash = content_hash($existing);
368 foreach (@$chashes) {
369 return 1 if $_ eq $chash
374 # used for removing or replacing (purging)
375 sub rewrite_internal ($$;$$$) {
376 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
378 my ($im, $need_reindex, $replace_map);
380 $replace_map = {}; # oid => sref
381 $need_reindex = [] if $new_eml;
383 $im = $self->importer;
385 my $oidx = $self->{oidx};
386 my $chashes = content_hashes($old_eml);
388 my $mids = mids($old_eml);
390 # We avoid introducing new blobs into git since the raw content
391 # can be slightly different, so we do not need the user-supplied
392 # message now that we have the mids and content_hash
396 foreach my $mid (@$mids) {
397 my %gone; # num => [ smsg, $mime, raw ]
399 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
400 my $msg = get_blob($self, $smsg);
401 if (!defined($msg)) {
402 warn "broken smsg for $mid\n";
406 my $cur = PublicInbox::Eml->new($msg);
407 if (content_matches($chashes, $cur)) {
408 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
411 my $n = scalar keys %gone;
414 warn "BUG: multiple articles linked to <$mid>\n",
415 join(',', sort keys %gone), "\n";
417 foreach my $num (keys %gone) {
418 my ($smsg, $mime, $orig) = @{$gone{$num}};
419 # $removed should only be set once assuming
420 # no bugs in our deduplication code:
421 $removed = [ undef, $mime, $smsg ];
422 my $oid = $smsg->{blob};
424 $replace_map->{$oid} = $sref;
426 ($mark, undef) = $im->remove($orig, $cmt_msg);
427 $removed->[0] = $mark;
430 if ($need_reindex) { # ->replace
431 push @$need_reindex, $smsg;
432 } else { # ->purge or ->remove
433 $self->{mm}->num_delete($num);
435 unindex_oid_aux($self, $oid, $mid);
440 my $cmt = $im->get_mark($mark);
441 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
443 if ($replace_map && scalar keys %$replace_map) {
444 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
445 return { rewrites => $rewrites, need_reindex => $need_reindex };
447 defined($mark) ? $removed : undef;
450 # public (see PublicInbox::Import->remove), but note the 3rd element
451 # (retval[2]) is not part of the stable API shared with Import->remove
453 my ($self, $eml, $cmt_msg) = @_;
454 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
455 $self, $eml, $cmt_msg);
456 defined($r) && defined($r->[0]) ? @$r: undef;
459 sub _replace ($$;$$) {
460 my ($self, $old_eml, $new_eml, $sref) = @_;
461 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
462 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
463 $self, $old_eml, undef, $new_eml, $sref) or return;
465 my $rewrites = $rewritten->{rewrites};
466 # ->done is called if there are rewrites since we gc+prune from git
467 $self->idx_init if @$rewrites;
469 for my $i (0..$#$rewrites) {
470 defined(my $cmt = $rewrites->[$i]) or next;
471 $self->{last_commit}->[$i] = $cmt;
478 my ($self, $mime) = @_;
479 my $rewritten = _replace($self, $mime, undef, \'') or return;
480 $rewritten->{rewrites}
483 # returns the git object_id of $fh, does not write the object to FS
484 sub git_hash_raw ($$) {
485 my ($self, $raw) = @_;
486 # grab the expected OID we have to reindex:
487 pipe(my($in, $w)) or die "pipe: $!";
488 my $git_dir = $self->git->{git_dir};
489 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
490 my $r = popen_rd($cmd, undef, { 0 => $in });
491 print $w $$raw or die "print \$w: $!";
492 close $w or die "close \$w: $!";
494 chomp(my $oid = <$r>);
495 close $r or die "git hash-object failed: $?";
496 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
500 sub _check_mids_match ($$$) {
501 my ($old_list, $new_list, $hdrs) = @_;
502 my %old_mids = map { $_ => 1 } @$old_list;
503 my %new_mids = map { $_ => 1 } @$new_list;
504 my @old = keys %old_mids;
505 my @new = keys %new_mids;
506 my $err = "$hdrs may not be changed when replacing\n";
507 die $err if scalar(@old) != scalar(@new);
508 delete @new_mids{@old};
509 delete @old_mids{@new};
510 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
513 # Changing Message-IDs or References with ->replace isn't supported.
514 # The rules for dealing with messages with multiple or conflicting
515 # Message-IDs are pretty complex and rethreading hasn't been fully
517 sub check_mids_match ($$) {
518 my ($old, $new) = @_;
519 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
520 _check_mids_match(references($old), references($new),
521 'References/In-Reply-To');
526 my ($self, $old_mime, $new_mime) = @_;
528 check_mids_match($old_mime, $new_mime);
530 # mutt will always add Content-Length:, Status:, Lines: when editing
531 PublicInbox::Import::drop_unwanted_headers($new_mime);
533 my $raw = $new_mime->as_string;
534 my $expect_oid = git_hash_raw($self, \$raw);
535 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
536 my $need_reindex = $rewritten->{need_reindex};
538 # just in case we have bugs in deduplication code:
539 my $n = scalar(@$need_reindex);
541 my $list = join(', ', map {
542 "$_->{num}: <$_->{mid}>"
545 W: rewritten $n messages matching content of original message (expected: 1).
546 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
551 # make sure we really got the OID:
552 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
553 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
555 # don't leak FDs to Xapian:
558 # reindex modified messages:
559 for my $smsg (@$need_reindex) {
560 my $new_smsg = bless {
565 }, 'PublicInbox::Smsg';
566 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
567 $new_smsg->populate($new_mime, $sync);
568 do_idx($self, \$raw, $new_mime, $new_smsg);
570 $rewritten->{rewrites};
573 sub last_epoch_commit ($$;$) {
574 my ($self, $i, $cmt) = @_;
575 my $v = PublicInbox::Search::SCHEMA_VERSION();
576 $self->{mm}->last_commit_xap($v, $i, $cmt);
579 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
581 defined(my $epoch_max = $self->{epoch_max}) or return;
582 my $last_commit = $self->{last_commit};
583 foreach my $i (0..$epoch_max) {
584 defined(my $cmt = $last_commit->[$i]) or next;
585 $last_commit->[$i] = undef;
586 last_epoch_commit($self, $i, $cmt);
592 $self->{bnote} or return;
594 my $barrier = { map { $_ => 1 } (0..$n) };
598 my ($self, $barrier) = @_;
599 my $bnote = $self->{bnote} or return;
601 while (scalar keys %$barrier) {
602 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
603 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
604 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
609 sub checkpoint ($;$) {
610 my ($self, $wait) = @_;
612 if (my $im = $self->{im}) {
619 my $shards = $self->{idx_shards};
621 my $mm = $self->{mm};
622 my $dbh = $mm->{dbh} if $mm;
624 # SQLite msgmap data is second in importance
625 $dbh->commit if $dbh;
627 # SQLite overview is third
628 $self->{oidx}->commit_lazy;
630 # Now deal with Xapian
632 my $barrier = barrier_init($self, scalar @$shards);
634 # each shard needs to issue a barrier command
635 $_->shard_barrier for @$shards;
637 # wait for each Xapian shard
638 barrier_wait($self, $barrier);
640 $_->shard_commit for @$shards;
643 my $midx = $self->{midx}; # misc index
644 $midx->commit_txn if $midx;
646 # last_commit is special, don't commit these until
647 # Xapian shards are done:
648 $dbh->begin_work if $dbh;
649 set_last_commits($self);
654 $midx->begin_txn if $midx;
656 $self->{total_bytes} += $self->{transact_bytes};
657 $self->{transact_bytes} = 0;
660 # issue a write barrier to ensure all data is visible to other processes
661 # and read-only ops. Order of data importance is: git > SQLite > Xapian
663 sub barrier { checkpoint($_[0], 1) };
665 # true if locked and active
666 sub active { !!$_[0]->{im} }
672 if (my $im = delete $self->{im}) {
673 eval { $im->done }; # PublicInbox::Import::done
674 $err .= "import done: $@\n" if $@;
677 eval { checkpoint($self) };
678 $err .= "checkpoint: $@\n" if $@;
680 if (my $mm = delete $self->{mm}) {
681 my $m = $err ? 'rollback' : 'commit';
682 eval { $mm->{dbh}->$m };
683 $err .= "msgmap $m: $@\n" if $@;
685 my $shards = delete $self->{idx_shards};
688 eval { $_->shard_close };
689 $err .= "shard close: $@\n" if $@;
692 eval { $self->{oidx}->dbh_close };
693 $err .= "over close: $@\n" if $@;
694 delete $self->{midx};
695 delete $self->{bnote};
696 my $nbytes = $self->{total_bytes};
697 $self->{total_bytes} = 0;
698 $self->lock_release(!!$nbytes) if $shards;
703 sub write_alternates ($$$) {
704 my ($info_dir, $mode, $out) = @_;
705 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
706 my $tmp = $fh->filename;
707 print $fh @$out or die "print $tmp: $!\n";
708 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
709 close $fh or die "close $tmp $!\n";
710 my $alt = "$info_dir/alternates";
711 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
712 $fh->unlink_on_destroy(0);
715 sub fill_alternates ($$) {
716 my ($self, $epoch) = @_;
718 my $pfx = "$self->{ibx}->{inboxdir}/git";
719 my $all = "$self->{ibx}->{inboxdir}/all.git";
720 PublicInbox::Import::init_bare($all) unless -d $all;
721 my $info_dir = "$all/objects/info";
722 my $alt = "$info_dir/alternates";
726 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
727 $mode = (stat($fh))[2] & 07777;
729 # we assign a sort score to every alternate and favor
730 # the newest (highest numbered) one because loose objects
731 # require scanning epochs and only the latest epoch is
732 # expected to see loose objects
734 my $other = 0; # in case admin adds non-epoch repos
736 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
742 } split(/\n+/, do { local $/; <$fh> });
745 foreach my $i (0..$epoch) {
746 my $dir = "../../git/$i.git/objects";
747 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
753 write_alternates($info_dir, $mode,
754 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
758 my ($self, $epoch) = @_;
759 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
760 PublicInbox::Import::init_bare($git_dir);
761 my @cmd = (qw/git config/, "--file=$git_dir/config",
762 'include.path', '../../all.git/config');
763 PublicInbox::Import::run_die(\@cmd);
764 fill_alternates($self, $epoch);
770 my $im = $self->{im};
772 if ($im->{bytes_added} < $self->{rotate_bytes}) {
779 my $git_dir = $self->git_init(++$self->{epoch_max});
780 my $git = PublicInbox::Git->new($git_dir);
781 return $self->import_init($git, 0);
786 my $latest = $self->{ibx}->git_dir_latest(\$max);
787 if (defined $latest) {
788 my $git = PublicInbox::Git->new($latest);
789 my $packed_bytes = $git->packed_bytes;
790 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
792 if ($unpacked_bytes >= $self->{rotate_bytes}) {
795 $self->{epoch_max} = $max;
796 return $self->import_init($git, $packed_bytes);
799 $self->{epoch_max} = $epoch;
800 $latest = $self->git_init($epoch);
801 $self->import_init(PublicInbox::Git->new($latest), 0);
805 my ($self, $git, $packed_bytes, $tmp) = @_;
806 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
807 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
808 $im->{lock_path} = undef;
809 $im->{path_type} = 'v2';
810 $self->{im} = $im unless $tmp;
816 my ($mid, $cur, $new) = @_;
818 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
819 print $ah $cur->as_string or die "print: $!";
820 $ah->flush or die "flush: $!";
821 PublicInbox::Import::drop_unwanted_headers($new);
822 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
823 print $bh $new->as_string or die "print: $!";
824 $bh->flush or die "flush: $!";
825 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
826 print STDERR "# MID conflict <$mid>\n";
827 my $pid = spawn($cmd, undef, { 1 => 2 });
828 waitpid($pid, 0) == $pid or die "diff did not finish";
832 my ($self, $smsg) = @_;
833 if (my $im = $self->{im}) {
834 my $msg = $im->cat_blob($smsg->{blob});
837 # older message, should be in alternates
838 $self->{ibx}->msg_by_smsg($smsg);
841 sub content_exists ($$$) {
842 my ($self, $mime, $mid) = @_;
843 my $oidx = $self->{oidx};
844 my $chashes = content_hashes($mime);
846 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
847 my $msg = get_blob($self, $smsg);
848 if (!defined($msg)) {
849 warn "broken smsg for $mid\n";
852 my $cur = PublicInbox::Eml->new($msg);
853 return 1 if content_matches($chashes, $cur);
855 # XXX DEBUG_DIFF is experimental and may be removed
856 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
863 if (my $shards = $self->{idx_shards}) {
864 $_->atfork_child foreach @$shards;
866 if (my $im = $self->{im}) {
869 die "unexpected mm" if $self->{mm};
870 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
874 sub reindex_checkpoint ($$) {
875 my ($self, $sync) = @_;
877 $self->git->async_wait_all;
878 $self->update_last_commit($sync);
879 ${$sync->{need_checkpoint}} = 0;
880 my $mm_tmp = $sync->{mm_tmp};
881 $mm_tmp->atfork_prepare if $mm_tmp;
882 die 'BUG: {im} during reindex' if $self->{im};
883 if ($self->{ibx_map}) {
884 checkpoint($self, 1); # no need to release lock on pure index
886 $self->done; # release lock
889 if (my $pr = $sync->{-opt}->{-progress}) {
890 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
893 # allow -watch or -mda to write...
894 $self->idx_init($sync->{-opt}); # reacquire lock
895 $mm_tmp->atfork_parent if $mm_tmp;
898 sub index_oid { # cat_async callback
899 my ($bref, $oid, $type, $size, $arg) = @_;
900 return if is_bad_blob($oid, $type, $size, $arg->{oid});
901 my $self = $arg->{self};
902 local $self->{current_info} = "$self->{current_info} $oid";
903 return if $size == 0; # purged
905 my $eml = PublicInbox::Eml->new($$bref);
906 my $mids = mids($eml);
907 my $chash = content_hash($eml);
909 if (scalar(@$mids) == 0) {
910 warn "E: $oid has no Message-ID, skipping\n";
914 # {unindexed} is unlikely
915 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
916 $num = delete($unindexed->{$mids->[0]});
919 $self->{mm}->mid_set($num, $mid0);
920 delete($arg->{unindexed}) if !keys(%$unindexed);
923 if (!defined($num)) { # reuse if reindexing (or duplicates)
924 my $oidx = $self->{oidx};
925 for my $mid (@$mids) {
926 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
927 last if defined $num;
930 $mid0 //= do { # is this a number we got before?
931 $num = $arg->{mm_tmp}->num_for($mids->[0]);
932 defined($num) ? $mids->[0] : undef;
934 if (!defined($num)) {
935 for (my $i = $#$mids; $i >= 1; $i--) {
936 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
944 $arg->{mm_tmp}->num_delete($num);
945 } else { # never seen
946 $num = $self->{mm}->mid_insert($mids->[0]);
949 } else { # rare, try the rest of them, backwards
950 for (my $i = $#$mids; $i >= 1; $i--) {
951 $num = $self->{mm}->mid_insert($mids->[$i]);
959 if (!defined($num)) {
960 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
969 }, 'PublicInbox::Smsg';
970 $smsg->populate($eml, $arg);
971 if (do_idx($self, $bref, $eml, $smsg)) {
972 ${$arg->{need_checkpoint}} = 1;
974 ${$arg->{latest_cmt}} = $arg->{cur_cmt} // die 'BUG: {cur_cmt} missing';
977 # only update last_commit for $i on reindex iff newer than current
978 sub update_last_commit {
979 my ($self, $sync, $stk) = @_;
980 my $unit = $sync->{unit} // return;
981 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
982 defined($latest_cmt) or return;
983 my $last = last_epoch_commit($self, $unit->{epoch});
984 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
985 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
986 chomp(my $n = $unit->{git}->qx(@cmd));
987 return if $n ne '' && $n == 0;
989 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
993 my ($self, $sync) = @_;
995 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
996 $heads->[$i] = last_epoch_commit($self, $i);
1001 # returns a revision range for git-log(1)
1002 sub log_range ($$$) {
1003 my ($sync, $unit, $tip) = @_;
1004 my $opt = $sync->{-opt};
1005 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1006 my $i = $unit->{epoch};
1007 my $cur = $sync->{ranges}->[$i] or do {
1008 $pr->("$i.git indexing all of $tip\n") if $pr;
1009 return $tip; # all of it
1012 # fast equality check to avoid (v)fork+execve overhead
1014 $sync->{ranges}->[$i] = undef;
1018 my $range = "$cur..$tip";
1019 $pr->("$i.git checking contiguity... ") if $pr;
1020 my $git = $unit->{git};
1021 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1022 $pr->("OK\n") if $pr;
1023 my $n = $git->qx(qw(rev-list --count), $range);
1026 $sync->{ranges}->[$i] = undef;
1027 $pr->("$i.git has nothing new\n") if $pr;
1028 return; # nothing to do
1030 $pr->("$i.git has $n changes since $cur\n") if $pr;
1032 $pr->("FAIL\n") if $pr;
1034 discontiguous range: $range
1035 Rewritten history? (in $git->{git_dir})
1037 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1039 $range = "$base..$tip";
1040 warn "found merge-base: $base\n"
1043 warn "discarding history at $cur\n";
1046 reindexing $git->{git_dir}
1049 # $cur^0 may no longer exist if pruned by git
1050 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1051 $unit->{unindex_range} = "$base..$cur";
1052 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1053 $unit->{unindex_range} = "$base..";
1055 warn "W: unable to unindex before $range\n";
1061 # overridden by ExtSearchIdx
1062 sub artnum_max { $_[0]->{mm}->num_highwater }
1064 sub sync_prepare ($$) {
1065 my ($self, $sync) = @_;
1066 $sync->{ranges} = sync_ranges($self, $sync);
1067 my $pr = $sync->{-opt}->{-progress};
1069 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1072 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1073 $pfx //= $sync->{ibx}->{inboxdir};
1077 if ($self->{ibx_map}) {
1078 # ExtSearchIdx won't index messages unless they're in
1079 # over.sqlite3 for a given inbox, so don't read beyond
1080 # what's in the per-inbox index.
1081 $reindex_heads = [];
1082 my $v = PublicInbox::Search::SCHEMA_VERSION;
1083 my $mm = $sync->{ibx}->mm;
1084 for my $i (0..$sync->{epoch_max}) {
1085 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1087 } elsif ($sync->{reindex}) { # V2 inbox
1088 # reindex stops at the current heads and we later
1089 # rerun index_sync without {reindex}
1090 $reindex_heads = $self->last_commits($sync);
1092 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1093 $sync->{index_oid} = $self->can('index_oid');
1095 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1096 my $git_dir = $sync->{ibx}->git_dir_n($i);
1097 -d $git_dir or next; # missing epochs are fine
1098 my $git = PublicInbox::Git->new($git_dir);
1099 my $unit = { git => $git, epoch => $i };
1100 if ($reindex_heads) {
1101 $head = $reindex_heads->[$i] or next;
1103 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1104 next if $?; # new repo
1106 my $range = log_range($sync, $unit, $tip) or next;
1107 # can't use 'rev-list --count' if we use --diff-filter
1108 $pr->("$pfx $i.git counting $range ... ") if $pr;
1109 # Don't bump num_highwater on --reindex by using {D}.
1110 # We intentionally do NOT use {D} in the non-reindex case
1111 # because we want NNTP article number gaps from unindexed
1112 # messages to show up in mirrors, too.
1113 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1114 my $stk = log2stack($sync, $git, $range);
1115 return 0 if $sync->{quit};
1116 my $nr = $stk ? $stk->num_records : 0;
1117 $pr->("$nr\n") if $pr;
1118 $unit->{stack} = $stk; # may be undef
1119 unshift @{$sync->{todo}}, $unit;
1122 return 0 if $sync->{quit};
1124 # XXX this should not happen unless somebody bypasses checks in
1125 # our code and blindly injects "d" file history into git repos
1126 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1127 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1128 local $self->{current_info} = 'leftover ';
1129 my $unindex_oid = $self->can('unindex_oid');
1130 for my $oid (@leftovers) {
1131 last if $sync->{quit};
1132 $oid = unpack('H*', $oid);
1133 my $req = { %$sync, oid => $oid };
1134 $self->git->cat_async($oid, $unindex_oid, $req);
1136 $self->git->cat_async_wait;
1138 return 0 if $sync->{quit};
1140 $sync->{-regen_fmt} = "%u/?\n";
1144 # reindex should NOT see new commits anymore, if we do,
1145 # it's a problem and we need to notice it via die()
1146 my $pad = length($regen_max) + 1;
1147 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1148 $sync->{nr} = \(my $nr = 0);
1149 return -1 if $sync->{reindex};
1150 $regen_max + $self->artnum_max || 0;
1153 sub unindex_oid_aux ($$$) {
1154 my ($self, $oid, $mid) = @_;
1155 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1156 for my $num (@removed) {
1157 my $idx = idx_shard($self, $num);
1158 $idx->shard_remove($num);
1162 sub unindex_oid ($$;$) { # git->cat_async callback
1163 my ($bref, $oid, $type, $size, $sync) = @_;
1164 return if is_bad_blob($oid, $type, $size, $sync->{oid});
1165 my $self = $sync->{self};
1166 local $self->{current_info} = "$self->{current_info} $oid";
1167 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1168 my $mm = $self->{mm};
1169 my $mids = mids(PublicInbox::Eml->new($bref));
1171 my $oidx = $self->{oidx};
1172 foreach my $mid (@$mids) {
1175 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1176 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1178 my $n = scalar(keys(%gone)) or next;
1180 warn "BUG: multiple articles linked to $oid\n",
1181 join(',',sort keys %gone), "\n";
1183 foreach my $num (keys %gone) {
1185 my $mid0 = $mm->mid_for($num);
1186 $unindexed->{$mid0} = $num;
1188 $mm->num_delete($num);
1190 unindex_oid_aux($self, $oid, $mid);
1194 sub git { $_[0]->{ibx}->git }
1196 # this is rare, it only happens when we get discontiguous history in
1197 # a mirror because the source used -purge or -edit
1198 sub unindex_todo ($$$) {
1199 my ($self, $sync, $unit) = @_;
1200 my $unindex_range = delete($unit->{unindex_range}) // return;
1201 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1202 my $before = scalar keys %$unindexed;
1203 # order does not matter, here:
1204 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1205 --no-abbrev --no-renames), $unindex_range);
1206 local $sync->{in_unindex} = 1;
1207 my $unindex_oid = $self->can('unindex_oid');
1209 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1210 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1212 close $fh or die "git log failed: \$?=$?";
1213 $self->git->cat_async_wait;
1215 return unless $sync->{-opt}->{prune};
1216 my $after = scalar keys %$unindexed;
1217 return if $before == $after;
1219 # ensure any blob can not longer be accessed via dumb HTTP
1220 PublicInbox::Import::run_die(['git',
1221 "--git-dir=$unit->{git}->{git_dir}",
1222 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1225 sub sync_ranges ($$) {
1226 my ($self, $sync) = @_;
1227 my $reindex = $sync->{reindex};
1228 return $self->last_commits($sync) unless $reindex;
1229 return [] if ref($reindex) ne 'HASH';
1231 my $ranges = $reindex->{from}; # arrayref;
1232 if (ref($ranges) ne 'ARRAY') {
1233 die 'BUG: $reindex->{from} not an ARRAY';
1238 sub index_xap_only { # git->cat_async callback
1239 my ($bref, $oid, $type, $size, $smsg) = @_;
1240 my $self = $smsg->{self};
1241 my $idx = idx_shard($self, $smsg->{num});
1242 $smsg->{raw_bytes} = $size;
1243 $idx->index_raw($bref, undef, $smsg);
1244 $self->{transact_bytes} += $size;
1247 sub index_xap_step ($$$;$) {
1248 my ($self, $sync, $beg, $step) = @_;
1249 my $end = $sync->{art_end};
1250 return if $beg > $end; # nothing to do
1252 $step //= $self->{shards};
1253 my $ibx = $self->{ibx};
1254 if (my $pr = $sync->{-opt}->{-progress}) {
1255 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1256 "$beg..$end (% $step)\n");
1258 for (my $num = $beg; $num <= $end; $num += $step) {
1259 last if $sync->{quit};
1260 my $smsg = $ibx->over->get_art($num) or next;
1261 $smsg->{self} = $self;
1262 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1263 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1264 ${$sync->{nr}} = $num;
1265 reindex_checkpoint($self, $sync);
1270 sub index_todo ($$$) {
1271 my ($self, $sync, $unit) = @_;
1272 return if $sync->{quit};
1273 unindex_todo($self, $sync, $unit);
1274 my $stk = delete($unit->{stack}) or return;
1275 my $all = $self->git;
1276 my $index_oid = $self->can('index_oid');
1277 my $unindex_oid = $self->can('unindex_oid');
1279 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1280 $pfx = "$1 $2"; # v2
1282 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1283 $pfx //= $unit->{git}->{git_dir};
1285 local $self->{current_info} = "$pfx ";
1286 local $sync->{latest_cmt} = \(my $latest_cmt);
1287 local $sync->{unit} = $unit;
1288 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1289 if ($sync->{quit}) {
1290 warn "waiting to quit...\n";
1291 $all->async_wait_all;
1292 $self->update_last_commit($sync);
1303 if ($sync->{max_size}) {
1304 $all->check_async($oid, \&check_size, $req);
1306 $all->cat_async($oid, $index_oid, $req);
1308 } elsif ($f eq 'd') {
1309 $all->cat_async($oid, $unindex_oid, $req);
1311 if (${$sync->{need_checkpoint}}) {
1312 reindex_checkpoint($self, $sync);
1315 $all->async_wait_all;
1316 $self->update_last_commit($sync, $stk);
1320 my ($self, $opt, $sync, $art_beg) = @_;
1321 my $seq = $opt->{sequential_shard};
1323 local $self->{parallel} = 0 if $seq;
1324 $self->idx_init($opt); # acquire lock
1325 if (my $art_end = $self->{ibx}->mm->max) {
1327 need_checkpoint => \(my $bool = 0),
1330 nr => \(my $nr = 0),
1331 -regen_fmt => "%u/?\n",
1333 $sync->{art_end} = $art_end;
1334 if ($seq || !$self->{parallel}) {
1335 my $shard_end = $self->{shards} - 1;
1336 for my $i (0..$shard_end) {
1337 last if $sync->{quit};
1338 index_xap_step($self, $sync, $art_beg + $i);
1339 if ($i != $shard_end) {
1340 reindex_checkpoint($self, $sync);
1343 } else { # parallel (maybe)
1344 index_xap_step($self, $sync, $art_beg, 1);
1347 $self->git->cat_async_wait;
1351 # public, called by public-inbox-index
1353 my ($self, $opt) = @_;
1355 return xapian_only($self, $opt) if $opt->{xapian_only};
1357 my $pr = $opt->{-progress};
1359 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max);
1360 return unless defined $latest;
1362 my $seq = $opt->{sequential_shard};
1363 my $art_beg; # the NNTP article number we start xapian_only at
1364 my $idxlevel = $self->{ibx}->{indexlevel};
1365 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1367 $self->idx_init($opt); # acquire lock
1368 fill_alternates($self, $epoch_max);
1369 $self->{oidx}->rethread_prepare($opt);
1371 need_checkpoint => \(my $bool = 0),
1372 reindex => $opt->{reindex},
1375 ibx => $self->{ibx},
1376 epoch_max => $epoch_max,
1378 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1379 local $SIG{QUIT} = $quit;
1380 local $SIG{INT} = $quit;
1381 local $SIG{TERM} = $quit;
1383 if (sync_prepare($self, $sync)) {
1384 # tmp_clone seems to fail if inside a transaction, so
1385 # we rollback here (because we opened {mm} for reading)
1386 # Note: we do NOT rely on DBI transactions for atomicity;
1387 # only for batch performance.
1388 $self->{mm}->{dbh}->rollback;
1389 $self->{mm}->{dbh}->begin_work;
1391 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1393 # xapian_only works incrementally w/o --reindex
1394 if ($seq && !$opt->{reindex}) {
1395 $art_beg = $sync->{mm_tmp}->max || -1;
1399 # work forwards through history
1400 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1401 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1404 if (my $nr = $sync->{nr}) {
1405 my $pr = $sync->{-opt}->{-progress};
1406 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1410 # deal with Xapian shards sequentially
1411 if ($seq && delete($sync->{mm_tmp})) {
1412 if ($sync->{quit}) {
1415 $self->{ibx}->{indexlevel} = $idxlevel;
1416 xapian_only($self, $opt, $sync, $art_beg);
1417 $quit_warn = 1 if $sync->{quit};
1421 # --reindex on the command-line
1422 if (!$sync->{quit} && $opt->{reindex} &&
1423 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1424 $self->lock_acquire;
1425 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1426 if (my $xdb = $s0->idx_acquire) {
1427 my $n = $xdb->get_metadata('has_threadid');
1428 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1431 $self->lock_release;
1434 # reindex does not pick up new changes, so we rerun w/o it:
1435 if ($opt->{reindex} && !$sync->{quit}) {
1438 delete @again{qw(rethread reindex -skip_lock)};
1439 index_sync($self, \%again);
1440 $opt->{quit} = $again{quit}; # propagate to caller
1442 warn <<EOF if $quit_warn;
1443 W: interrupted, --xapian-only --reindex required upon restart