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);
21 use IO::Handle; # ->autoflush
24 my $OID = qr/[a-f0-9]{40,}/;
25 # an estimate of the post-packed size to the raw uncompressed size
26 my $PACKING_FACTOR = 0.4;
28 # SATA storage lags behind what CPUs are capable of, so relying on
29 # nproc(1) can be misleading and having extra Xapian shards is a
30 # waste of FDs and space. It can also lead to excessive IO latency
31 # and slow things down. Users on NVME or other fast storage can
32 # use the NPROC env or switches in our script/public-inbox-* programs
33 # to increase Xapian shards
34 our $NPROC_MAX_DEFAULT = 4;
37 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
38 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
39 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
41 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
42 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
45 # should we bother with `sysctl hw.ncpu`? Those only give
46 # us total processor count, not online processor count.
50 sub nproc_shards ($) {
52 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
55 # assume 2 cores if not detectable or zero
56 state $NPROC_DETECTED = detect_nproc() || 2;
58 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
61 # subtract for the main process and git-fast-import
66 sub count_shards ($) {
69 my $xpfx = $self->{xpfx};
71 # always load existing shards in case core count changes:
72 # Also, shard count may change while -watch is running
73 # due to "xcpdb --reshard"
76 foreach my $shard (<$xpfx/*>) {
77 -d $shard && $shard =~ m!/[0-9]+\z! or next;
78 $XapianDatabase //= do {
79 require PublicInbox::Search;
80 PublicInbox::Search::load_xapian();
81 $PublicInbox::Search::X{Database};
84 $XapianDatabase->new($shard)->close;
93 # $creat may be any true value, or 0/undef. A hashref is true,
94 # and $creat->{nproc} may be set to an integer
95 my ($class, $v2ibx, $creat) = @_;
96 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
97 my $dir = $v2ibx->assert_usable_dir;
101 File::Path::mkpath($dir);
103 die "$dir does not exist\n";
106 $v2ibx->umask_prepare;
108 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
111 im => undef, # PublicInbox::Import
117 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
118 lock_path => "$dir/inbox.lock",
119 # limit each git repo (epoch) to 1GB or so
120 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
121 last_commit => [], # git epoch -> commit
123 $self->{over}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
124 $self->{shards} = count_shards($self) || nproc_shards($creat);
130 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
131 if (defined $shards) {
132 $self->{parallel} = 0 if $shards == 0;
133 $self->{shards} = $shards if $shards > 0;
136 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
138 git_dir_latest($self, \$epoch_max);
139 if (defined $skip_epoch && $epoch_max == -1) {
140 $epoch_max = $skip_epoch;
142 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
146 # returns undef on duplicate or spam
147 # mimics Import::add and wraps it for v2
149 my ($self, $eml, $check_cb) = @_;
150 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
153 # indexes a message, returns true if checkpointing is needed
155 my ($self, $msgref, $mime, $smsg) = @_;
156 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
157 $self->{over}->add_overview($mime, $smsg);
158 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
159 $idx->index_raw($msgref, $mime, $smsg);
160 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
161 $n >= $self->{batch_bytes};
165 my ($self, $mime, $check_cb) = @_;
169 $mime = $check_cb->($mime, $self->{ibx}) or return;
172 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
173 # as does SQLite 3.4.1+ (released in 2007-07-20), and
174 # Xapian 1.3.2+ (released 2015-03-15).
175 # For the most part, we can spawn git-fast-import without
176 # leaking FDs to it...
179 my ($num, $mid0) = v2_num_for($self, $mime);
180 defined $num or return; # duplicate
181 defined $mid0 or die "BUG: \$mid0 undefined\n";
182 my $im = $self->importer;
183 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
184 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
185 $cmt = $im->get_mark($cmt);
186 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
188 my $msgref = delete $smsg->{-raw_email};
189 if (do_idx($self, $msgref, $mime, $smsg)) {
197 my ($self, $mime) = @_;
198 my $mids = mids($mime);
200 my $mid = $mids->[0];
201 my $num = $self->{mm}->mid_insert($mid);
202 if (defined $num) { # common case
206 # crap, Message-ID is already known, hope somebody just resent:
207 foreach my $m (@$mids) {
208 # read-only lookup now safe to do after above barrier
209 # easy, don't store duplicates
210 # note: do not add more diagnostic info here since
211 # it gets noisy on public-inbox-watch restarts
212 return () if content_exists($self, $mime, $m);
215 # AltId may pre-populate article numbers (e.g. X-Mail-Count
216 # or NNTP article number), use that article number if it's
218 my $altid = $self->{ibx}->{altid};
219 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
220 my $num = $self->{mm}->num_for($mid);
222 if (defined $num && !$self->{over}->get_art($num)) {
228 warn "<$mid> reused for mismatched content\n";
230 # try the rest of the mids
231 for(my $i = $#$mids; $i >= 1; $i--) {
233 $num = $self->{mm}->mid_insert($m);
235 warn "alternative <$m> for <$mid> found\n";
240 # none of the existing Message-IDs are good, generate a new one:
241 v2_num_for_harder($self, $mime);
244 sub v2_num_for_harder {
245 my ($self, $eml) = @_;
247 my $dig = content_digest($eml);
248 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
249 my $num = $self->{mm}->mid_insert($mid0);
250 unless (defined $num) {
251 # it's hard to spoof the last Received: header
252 my @recvd = $eml->header_raw('Received');
253 $dig->add("Received: $_") foreach (@recvd);
254 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
255 $num = $self->{mm}->mid_insert($mid0);
257 # fall back to a random Message-ID and give up determinism:
258 until (defined($num)) {
260 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
261 warn "using random Message-ID <$mid0> as fallback\n";
262 $num = $self->{mm}->mid_insert($mid0);
265 PublicInbox::Import::append_mid($eml, $mid0);
270 my ($self, $shard_i) = @_;
271 $self->{idx_shards}->[$shard_i];
274 sub _idx_init { # with_umask callback
275 my ($self, $opt) = @_;
276 $self->lock_acquire unless $opt && $opt->{-skip_lock};
277 $self->{over}->create;
279 # xcpdb can change shard count while -watch is idle
280 my $nshards = count_shards($self);
281 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
282 $self->{batch_bytes} = $opt->{batch_size} //
283 $PublicInbox::SearchIdx::BATCH_BYTES;
284 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
286 # need to create all shards before initializing msgmap FD
287 # idx_shards must be visible to all forked processes
288 my $max = $self->{shards} - 1;
289 my $idx = $self->{idx_shards} = [];
290 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
292 # Now that all subprocesses are up, we can open the FDs
294 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
295 "$self->{ibx}->{inboxdir}/msgmap.sqlite3",
296 $self->{ibx}->{-no_fsync} ? 2 : 1);
297 $mm->{dbh}->begin_work;
302 my ($self, $opt) = @_;
303 return if $self->{idx_shards};
304 my $ibx = $self->{ibx};
306 # do not leak read-only FDs to child processes, we only have these
307 # FDs for duplicate detection so they should not be
308 # frequently activated.
309 delete @$ibx{qw(mm search)};
312 $self->{parallel} = 0 if ($ibx->{indexlevel}//'') eq 'basic';
313 if ($self->{parallel}) {
314 pipe(my ($r, $w)) or die "pipe failed: $!";
315 # pipe for barrier notifications doesn't need to be big,
317 fcntl($w, 1031, 4096) if $^O eq 'linux';
318 $self->{bnote} = [ $r, $w ];
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 $pfx = "$self->{ibx}->{inboxdir}/git";
333 my $rewrites = []; # epoch => commit
334 my $max = $self->{epoch_max};
336 unless (defined($max)) {
337 defined(my $latest = git_dir_latest($self, \$max)) or return;
338 $self->{epoch_max} = $max;
341 foreach my $i (0..$max) {
342 my $git_dir = "$pfx/$i.git";
344 my $git = PublicInbox::Git->new($git_dir);
345 my $im = $self->import_init($git, 0, 1);
346 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
352 sub content_hashes ($) {
354 my @chashes = ( content_hash($mime) );
356 # We still support Email::MIME, here, and
357 # Email::MIME->as_string doesn't always round-trip, so we may
358 # use a second content_hash
359 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
360 push @chashes, $rt if $chashes[0] ne $rt;
364 sub content_matches ($$) {
365 my ($chashes, $existing) = @_;
366 my $chash = content_hash($existing);
367 foreach (@$chashes) {
368 return 1 if $_ eq $chash
373 # used for removing or replacing (purging)
374 sub rewrite_internal ($$;$$$) {
375 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
377 my ($im, $need_reindex, $replace_map);
379 $replace_map = {}; # oid => sref
380 $need_reindex = [] if $new_eml;
382 $im = $self->importer;
384 my $over = $self->{over};
385 my $chashes = content_hashes($old_eml);
387 my $mids = mids($old_eml);
389 # We avoid introducing new blobs into git since the raw content
390 # can be slightly different, so we do not need the user-supplied
391 # message now that we have the mids and content_hash
395 foreach my $mid (@$mids) {
396 my %gone; # num => [ smsg, $mime, raw ]
398 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
399 my $msg = get_blob($self, $smsg);
400 if (!defined($msg)) {
401 warn "broken smsg for $mid\n";
405 my $cur = PublicInbox::Eml->new($msg);
406 if (content_matches($chashes, $cur)) {
407 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
410 my $n = scalar keys %gone;
413 warn "BUG: multiple articles linked to <$mid>\n",
414 join(',', sort keys %gone), "\n";
416 foreach my $num (keys %gone) {
417 my ($smsg, $mime, $orig) = @{$gone{$num}};
418 # $removed should only be set once assuming
419 # no bugs in our deduplication code:
420 $removed = [ undef, $mime, $smsg ];
421 my $oid = $smsg->{blob};
423 $replace_map->{$oid} = $sref;
425 ($mark, undef) = $im->remove($orig, $cmt_msg);
426 $removed->[0] = $mark;
429 if ($need_reindex) { # ->replace
430 push @$need_reindex, $smsg;
431 } else { # ->purge or ->remove
432 $self->{mm}->num_delete($num);
434 unindex_oid_remote($self, $oid, $mid);
439 my $cmt = $im->get_mark($mark);
440 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
442 if ($replace_map && scalar keys %$replace_map) {
443 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
444 return { rewrites => $rewrites, need_reindex => $need_reindex };
446 defined($mark) ? $removed : undef;
449 # public (see PublicInbox::Import->remove), but note the 3rd element
450 # (retval[2]) is not part of the stable API shared with Import->remove
452 my ($self, $eml, $cmt_msg) = @_;
453 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
454 $self, $eml, $cmt_msg);
455 defined($r) && defined($r->[0]) ? @$r: undef;
458 sub _replace ($$;$$) {
459 my ($self, $old_eml, $new_eml, $sref) = @_;
460 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
461 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
462 $self, $old_eml, undef, $new_eml, $sref) or return;
464 my $rewrites = $rewritten->{rewrites};
465 # ->done is called if there are rewrites since we gc+prune from git
466 $self->idx_init if @$rewrites;
468 for my $i (0..$#$rewrites) {
469 defined(my $cmt = $rewrites->[$i]) or next;
470 $self->{last_commit}->[$i] = $cmt;
477 my ($self, $mime) = @_;
478 my $rewritten = _replace($self, $mime, undef, \'') or return;
479 $rewritten->{rewrites}
482 # returns the git object_id of $fh, does not write the object to FS
483 sub git_hash_raw ($$) {
484 my ($self, $raw) = @_;
485 # grab the expected OID we have to reindex:
486 pipe(my($in, $w)) or die "pipe: $!";
487 my $git_dir = $self->{ibx}->git->{git_dir};
488 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
489 my $r = popen_rd($cmd, undef, { 0 => $in });
490 print $w $$raw or die "print \$w: $!";
491 close $w or die "close \$w: $!";
493 chomp(my $oid = <$r>);
494 close $r or die "git hash-object failed: $?";
495 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
499 sub _check_mids_match ($$$) {
500 my ($old_list, $new_list, $hdrs) = @_;
501 my %old_mids = map { $_ => 1 } @$old_list;
502 my %new_mids = map { $_ => 1 } @$new_list;
503 my @old = keys %old_mids;
504 my @new = keys %new_mids;
505 my $err = "$hdrs may not be changed when replacing\n";
506 die $err if scalar(@old) != scalar(@new);
507 delete @new_mids{@old};
508 delete @old_mids{@new};
509 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
512 # Changing Message-IDs or References with ->replace isn't supported.
513 # The rules for dealing with messages with multiple or conflicting
514 # Message-IDs are pretty complex and rethreading hasn't been fully
516 sub check_mids_match ($$) {
517 my ($old, $new) = @_;
518 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
519 _check_mids_match(references($old), references($new),
520 'References/In-Reply-To');
525 my ($self, $old_mime, $new_mime) = @_;
527 check_mids_match($old_mime, $new_mime);
529 # mutt will always add Content-Length:, Status:, Lines: when editing
530 PublicInbox::Import::drop_unwanted_headers($new_mime);
532 my $raw = $new_mime->as_string;
533 my $expect_oid = git_hash_raw($self, \$raw);
534 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
535 my $need_reindex = $rewritten->{need_reindex};
537 # just in case we have bugs in deduplication code:
538 my $n = scalar(@$need_reindex);
540 my $list = join(', ', map {
541 "$_->{num}: <$_->{mid}>"
544 W: rewritten $n messages matching content of original message (expected: 1).
545 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
550 # make sure we really got the OID:
551 my ($blob, $type, $bytes) = $self->{ibx}->git->check($expect_oid);
552 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
554 # don't leak FDs to Xapian:
555 $self->{ibx}->git->cleanup;
557 # reindex modified messages:
558 for my $smsg (@$need_reindex) {
559 my $new_smsg = bless {
564 }, 'PublicInbox::Smsg';
565 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
566 $new_smsg->populate($new_mime, $sync);
567 do_idx($self, \$raw, $new_mime, $new_smsg);
569 $rewritten->{rewrites};
572 sub last_epoch_commit ($$;$) {
573 my ($self, $i, $cmt) = @_;
574 my $v = PublicInbox::Search::SCHEMA_VERSION();
575 $self->{mm}->last_commit_xap($v, $i, $cmt);
578 sub set_last_commits ($) {
580 defined(my $epoch_max = $self->{epoch_max}) or return;
581 my $last_commit = $self->{last_commit};
582 foreach my $i (0..$epoch_max) {
583 defined(my $cmt = $last_commit->[$i]) or next;
584 $last_commit->[$i] = undef;
585 last_epoch_commit($self, $i, $cmt);
591 $self->{bnote} or return;
593 my $barrier = { map { $_ => 1 } (0..$n) };
597 my ($self, $barrier) = @_;
598 my $bnote = $self->{bnote} or return;
600 while (scalar keys %$barrier) {
601 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
602 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
603 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
608 sub checkpoint ($;$) {
609 my ($self, $wait) = @_;
611 if (my $im = $self->{im}) {
618 my $shards = $self->{idx_shards};
620 my $dbh = $self->{mm}->{dbh};
622 # SQLite msgmap data is second in importance
625 # SQLite overview is third
626 $self->{over}->commit_lazy;
628 # Now deal with Xapian
630 my $barrier = $self->barrier_init(scalar @$shards);
632 # each shard needs to issue a barrier command
633 $_->shard_barrier for @$shards;
635 # wait for each Xapian shard
636 $self->barrier_wait($barrier);
638 $_->shard_commit for @$shards;
641 # last_commit is special, don't commit these until
642 # remote shards are done:
644 set_last_commits($self);
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->{over}->dbh_close };
686 $err .= "over close: $@\n" if $@;
687 delete $self->{bnote};
688 my $nbytes = $self->{total_bytes};
689 $self->{total_bytes} = 0;
690 $self->lock_release(!!$nbytes) if $shards;
691 $self->{ibx}->git->cleanup;
695 sub fill_alternates ($$) {
696 my ($self, $epoch) = @_;
698 my $pfx = "$self->{ibx}->{inboxdir}/git";
699 my $all = "$self->{ibx}->{inboxdir}/all.git";
700 PublicInbox::Import::init_bare($all) unless -d $all;
701 my $info_dir = "$all/objects/info";
702 my $alt = "$info_dir/alternates";
706 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
707 $mode = (stat($fh))[2] & 07777;
709 # we assign a sort score to every alternate and favor
710 # the newest (highest numbered) one because loose objects
711 # require scanning epochs and only the latest epoch is
712 # expected to see loose objects
714 my $other = 0; # in case admin adds non-epoch repos
716 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
722 } split(/\n+/, do { local $/; <$fh> });
725 foreach my $i (0..$epoch) {
726 my $dir = "../../git/$i.git/objects";
727 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
734 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
735 my $tmp = $fh->filename;
736 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
737 or die "print $tmp: $!\n";
738 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
739 close $fh or die "close $tmp $!\n";
740 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
741 $fh->unlink_on_destroy(0);
745 my ($self, $epoch) = @_;
746 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
747 PublicInbox::Import::init_bare($git_dir);
748 my @cmd = (qw/git config/, "--file=$git_dir/config",
749 'include.path', '../../all.git/config');
750 PublicInbox::Import::run_die(\@cmd);
751 fill_alternates($self, $epoch);
756 my ($self, $max) = @_;
758 my $pfx = "$self->{ibx}->{inboxdir}/git";
759 return unless -d $pfx;
761 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
762 while (defined(my $git_dir = readdir($dh))) {
763 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
766 $latest = "$pfx/$git_dir";
774 my $im = $self->{im};
776 if ($im->{bytes_added} < $self->{rotate_bytes}) {
783 my $git_dir = $self->git_init(++$self->{epoch_max});
784 my $git = PublicInbox::Git->new($git_dir);
785 return $self->import_init($git, 0);
790 my $latest = git_dir_latest($self, \$max);
791 if (defined $latest) {
792 my $git = PublicInbox::Git->new($latest);
793 my $packed_bytes = $git->packed_bytes;
794 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
796 if ($unpacked_bytes >= $self->{rotate_bytes}) {
799 $self->{epoch_max} = $max;
800 return $self->import_init($git, $packed_bytes);
803 $self->{epoch_max} = $epoch;
804 $latest = $self->git_init($epoch);
805 $self->import_init(PublicInbox::Git->new($latest), 0);
809 my ($self, $git, $packed_bytes, $tmp) = @_;
810 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
811 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
812 $im->{lock_path} = undef;
813 $im->{path_type} = 'v2';
814 $self->{im} = $im unless $tmp;
820 my ($mid, $cur, $new) = @_;
822 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
823 print $ah $cur->as_string or die "print: $!";
824 $ah->flush or die "flush: $!";
825 PublicInbox::Import::drop_unwanted_headers($new);
826 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
827 print $bh $new->as_string or die "print: $!";
828 $bh->flush or die "flush: $!";
829 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
830 print STDERR "# MID conflict <$mid>\n";
831 my $pid = spawn($cmd, undef, { 1 => 2 });
832 waitpid($pid, 0) == $pid or die "diff did not finish";
836 my ($self, $smsg) = @_;
837 if (my $im = $self->{im}) {
838 my $msg = $im->cat_blob($smsg->{blob});
841 # older message, should be in alternates
842 $self->{ibx}->msg_by_smsg($smsg);
845 sub content_exists ($$$) {
846 my ($self, $mime, $mid) = @_;
847 my $over = $self->{over};
848 my $chashes = content_hashes($mime);
850 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
851 my $msg = get_blob($self, $smsg);
852 if (!defined($msg)) {
853 warn "broken smsg for $mid\n";
856 my $cur = PublicInbox::Eml->new($msg);
857 return 1 if content_matches($chashes, $cur);
859 # XXX DEBUG_DIFF is experimental and may be removed
860 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
867 if (my $shards = $self->{idx_shards}) {
868 $_->atfork_child foreach @$shards;
870 if (my $im = $self->{im}) {
873 die "unexpected mm" if $self->{mm};
874 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
878 sub reindex_checkpoint ($$) {
879 my ($self, $sync) = @_;
881 $self->{ibx}->git->cleanup; # *async_wait
882 ${$sync->{need_checkpoint}} = 0;
883 my $mm_tmp = $sync->{mm_tmp};
884 $mm_tmp->atfork_prepare if $mm_tmp;
885 $self->done; # release lock
887 if (my $pr = $sync->{-opt}->{-progress}) {
888 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
891 # allow -watch or -mda to write...
892 $self->idx_init($sync->{-opt}); # reacquire lock
893 $mm_tmp->atfork_parent if $mm_tmp;
896 sub index_oid { # cat_async callback
897 my ($bref, $oid, $type, $size, $arg) = @_;
898 return if $size == 0; # purged
900 my $eml = PublicInbox::Eml->new($$bref);
901 my $mids = mids($eml);
902 my $chash = content_hash($eml);
903 my $self = $arg->{v2w};
905 if (scalar(@$mids) == 0) {
906 warn "E: $oid has no Message-ID, skipping\n";
910 # {unindexed} is unlikely
911 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
912 $num = delete($unindexed->{$mids->[0]});
915 $self->{mm}->mid_set($num, $mid0);
916 delete($arg->{unindexed}) if !keys(%$unindexed);
919 if (!defined($num)) { # reuse if reindexing (or duplicates)
920 my $over = $self->{over};
921 for my $mid (@$mids) {
922 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
923 last if defined $num;
926 $mid0 //= do { # is this a number we got before?
927 $num = $arg->{mm_tmp}->num_for($mids->[0]);
928 defined($num) ? $mids->[0] : undef;
930 if (!defined($num)) {
931 for (my $i = $#$mids; $i >= 1; $i--) {
932 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
940 $arg->{mm_tmp}->num_delete($num);
941 } else { # never seen
942 $num = $self->{mm}->mid_insert($mids->[0]);
945 } else { # rare, try the rest of them, backwards
946 for (my $i = $#$mids; $i >= 1; $i--) {
947 $num = $self->{mm}->mid_insert($mids->[$i]);
955 if (!defined($num)) {
956 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
965 }, 'PublicInbox::Smsg';
966 $smsg->populate($eml, $arg);
967 if (do_idx($self, $bref, $eml, $smsg)) {
968 ${$arg->{need_checkpoint}} = 1;
972 # only update last_commit for $i on reindex iff newer than current
973 sub update_last_commit ($$$$) {
974 my ($self, $git, $i, $cmt) = @_;
975 my $last = last_epoch_commit($self, $i);
976 if (defined $last && is_ancestor($git, $last, $cmt)) {
977 my @cmd = (qw(rev-list --count), "$last..$cmt");
978 chomp(my $n = $git->qx(@cmd));
979 return if $n ne '' && $n == 0;
981 last_epoch_commit($self, $i, $cmt);
984 sub git_dir_n ($$) { "$_[0]->{ibx}->{inboxdir}/git/$_[1].git" }
986 sub last_commits ($$) {
987 my ($self, $epoch_max) = @_;
989 for (my $i = $epoch_max; $i >= 0; $i--) {
990 $heads->[$i] = last_epoch_commit($self, $i);
995 # returns a revision range for git-log(1)
996 sub log_range ($$$$$) {
997 my ($self, $sync, $git, $i, $tip) = @_;
998 my $opt = $sync->{-opt};
999 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1000 my $cur = $sync->{ranges}->[$i] or do {
1001 $pr->("$i.git indexing all of $tip\n") if $pr;
1002 return $tip; # all of it
1005 # fast equality check to avoid (v)fork+execve overhead
1007 $sync->{ranges}->[$i] = undef;
1011 my $range = "$cur..$tip";
1012 $pr->("$i.git checking contiguity... ") if $pr;
1013 if (is_ancestor($git, $cur, $tip)) { # common case
1014 $pr->("OK\n") if $pr;
1015 my $n = $git->qx(qw(rev-list --count), $range);
1018 $sync->{ranges}->[$i] = undef;
1019 $pr->("$i.git has nothing new\n") if $pr;
1020 return; # nothing to do
1022 $pr->("$i.git has $n changes since $cur\n") if $pr;
1024 $pr->("FAIL\n") if $pr;
1026 discontiguous range: $range
1027 Rewritten history? (in $git->{git_dir})
1029 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1031 $range = "$base..$tip";
1032 warn "found merge-base: $base\n"
1035 warn "discarding history at $cur\n";
1038 reindexing $git->{git_dir} starting at
1041 $sync->{unindex_range}->{$i} = "$base..$cur";
1046 sub sync_prepare ($$$) {
1047 my ($self, $sync, $epoch_max) = @_;
1048 my $pr = $sync->{-opt}->{-progress};
1050 my $head = $self->{ibx}->{ref_head} || 'refs/heads/master';
1052 # reindex stops at the current heads and we later rerun index_sync
1054 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1056 for (my $i = $epoch_max; $i >= 0; $i--) {
1057 my $git_dir = git_dir_n($self, $i);
1058 -d $git_dir or next; # missing epochs are fine
1059 my $git = PublicInbox::Git->new($git_dir);
1060 if ($reindex_heads) {
1061 $head = $reindex_heads->[$i] or next;
1063 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1065 next if $?; # new repo
1066 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1067 # can't use 'rev-list --count' if we use --diff-filter
1068 $pr->("$i.git counting $range ... ") if $pr;
1069 # Don't bump num_highwater on --reindex by using {D}.
1070 # We intentionally do NOT use {D} in the non-reindex case
1071 # because we want NNTP article number gaps from unindexed
1072 # messages to show up in mirrors, too.
1073 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1074 my $stk = log2stack($sync, $git, $range, $self->{ibx});
1075 my $nr = $stk ? $stk->num_records : 0;
1076 $pr->("$nr\n") if $pr;
1077 $sync->{stacks}->[$i] = $stk if $stk;
1081 # XXX this should not happen unless somebody bypasses checks in
1082 # our code and blindly injects "d" file history into git repos
1083 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1084 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1085 my $arg = { v2w => $self };
1086 my $all = $self->{ibx}->git;
1087 for my $oid (@leftovers) {
1088 $oid = unpack('H*', $oid);
1089 $self->{current_info} = "leftover $oid";
1090 $all->cat_async($oid, \&unindex_oid, $arg);
1092 $all->cat_async_wait;
1094 if (!$regen_max && !keys(%{$self->{unindex_range}})) {
1095 $sync->{-regen_fmt} = "%u/?\n";
1099 # reindex should NOT see new commits anymore, if we do,
1100 # it's a problem and we need to notice it via die()
1101 my $pad = length($regen_max) + 1;
1102 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1103 $sync->{nr} = \(my $nr = 0);
1104 return -1 if $sync->{reindex};
1105 $regen_max + $self->{mm}->num_highwater() || 0;
1108 sub unindex_oid_remote ($$$) {
1109 my ($self, $oid, $mid) = @_;
1110 my @removed = $self->{over}->remove_oid($oid, $mid);
1111 for my $num (@removed) {
1112 my $idx = idx_shard($self, $num % $self->{shards});
1113 $idx->shard_remove($oid, $num);
1117 sub unindex_oid ($$;$) { # git->cat_async callback
1118 my ($bref, $oid, $type, $size, $sync) = @_;
1119 my $self = $sync->{v2w};
1120 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1121 my $mm = $self->{mm};
1122 my $mids = mids(PublicInbox::Eml->new($bref));
1124 my $over = $self->{over};
1125 foreach my $mid (@$mids) {
1128 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1129 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1131 my $n = scalar(keys(%gone)) or next;
1133 warn "BUG: multiple articles linked to $oid\n",
1134 join(',',sort keys %gone), "\n";
1136 foreach my $num (keys %gone) {
1138 my $mid0 = $mm->mid_for($num);
1139 $unindexed->{$mid0} = $num;
1141 $mm->num_delete($num);
1143 unindex_oid_remote($self, $oid, $mid);
1147 # this is rare, it only happens when we get discontiguous history in
1148 # a mirror because the source used -purge or -edit
1149 sub unindex ($$$$) {
1150 my ($self, $sync, $git, $unindex_range) = @_;
1151 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1152 my $before = scalar keys %$unindexed;
1153 # order does not matter, here:
1154 my @cmd = qw(log --raw -r
1155 --no-notes --no-color --no-abbrev --no-renames);
1156 my $fh = $git->popen(@cmd, $unindex_range);
1157 my $all = $self->{ibx}->git;
1158 local $sync->{in_unindex} = 1;
1160 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1161 $all->cat_async($1, \&unindex_oid, $sync);
1163 close $fh or die "git log failed: \$?=$?";
1164 $all->cat_async_wait;
1166 return unless $sync->{-opt}->{prune};
1167 my $after = scalar keys %$unindexed;
1168 return if $before == $after;
1170 # ensure any blob can not longer be accessed via dumb HTTP
1171 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1172 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1175 sub sync_ranges ($$$) {
1176 my ($self, $sync, $epoch_max) = @_;
1177 my $reindex = $sync->{reindex};
1179 return last_commits($self, $epoch_max) unless $reindex;
1180 return [] if ref($reindex) ne 'HASH';
1182 my $ranges = $reindex->{from}; # arrayref;
1183 if (ref($ranges) ne 'ARRAY') {
1184 die 'BUG: $reindex->{from} not an ARRAY';
1189 sub index_xap_only { # git->cat_async callback
1190 my ($bref, $oid, $type, $size, $smsg) = @_;
1191 my $self = $smsg->{v2w};
1192 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
1193 $smsg->{raw_bytes} = $size;
1194 $idx->index_raw($bref, undef, $smsg);
1195 $self->{transact_bytes} += $size;
1198 sub index_xap_step ($$$;$) {
1199 my ($self, $sync, $beg, $step) = @_;
1200 my $end = $sync->{art_end};
1201 return if $beg > $end; # nothing to do
1203 $step //= $self->{shards};
1204 my $ibx = $self->{ibx};
1205 if (my $pr = $sync->{-opt}->{-progress}) {
1206 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1207 "$beg..$end (% $step)\n");
1209 for (my $num = $beg; $num <= $end; $num += $step) {
1210 my $smsg = $ibx->over->get_art($num) or next;
1211 $smsg->{v2w} = $self;
1212 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1213 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1214 ${$sync->{nr}} = $num;
1215 reindex_checkpoint($self, $sync);
1220 sub index_epoch ($$$) {
1221 my ($self, $sync, $i) = @_;
1223 my $git_dir = git_dir_n($self, $i);
1224 -d $git_dir or return; # missing epochs are fine
1225 my $git = PublicInbox::Git->new($git_dir);
1226 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { # rare
1227 unindex($self, $sync, $git, $unindex_range);
1229 defined(my $stk = $sync->{stacks}->[$i]) or return;
1230 $sync->{stacks}->[$i] = undef;
1231 my $all = $self->{ibx}->git;
1232 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1233 $self->{current_info} = "$i.git $oid";
1235 my $arg = { %$sync, autime => $at, cotime => $ct };
1236 if ($sync->{max_size}) {
1237 $all->check_async($oid, \&check_size, $arg);
1239 $all->cat_async($oid, \&index_oid, $arg);
1241 } elsif ($f eq 'd') {
1242 $all->cat_async($oid, \&unindex_oid, $sync);
1244 if (${$sync->{need_checkpoint}}) {
1245 reindex_checkpoint($self, $sync);
1248 $all->check_async_wait;
1249 $all->cat_async_wait;
1250 update_last_commit($self, $git, $i, $stk->{latest_cmt});
1254 my ($self, $opt, $sync, $art_beg) = @_;
1255 my $seq = $opt->{sequential_shard};
1257 local $self->{parallel} = 0 if $seq;
1258 $self->idx_init($opt); # acquire lock
1259 if (my $art_end = $self->{ibx}->mm->max) {
1261 need_checkpoint => \(my $bool = 0),
1264 nr => \(my $nr = 0),
1265 -regen_fmt => "%u/?\n",
1267 $sync->{art_end} = $art_end;
1268 if ($seq || !$self->{parallel}) {
1269 my $shard_end = $self->{shards} - 1;
1270 for my $i (0..$shard_end) {
1271 index_xap_step($self, $sync, $art_beg + $i);
1272 if ($i != $shard_end) {
1273 reindex_checkpoint($self, $sync);
1276 } else { # parallel (maybe)
1277 index_xap_step($self, $sync, $art_beg, 1);
1280 $self->{ibx}->git->cat_async_wait;
1284 # public, called by public-inbox-index
1286 my ($self, $opt) = @_;
1287 $opt //= $_[1] //= {};
1288 goto \&xapian_only if $opt->{xapian_only};
1290 my $pr = $opt->{-progress};
1292 my $latest = git_dir_latest($self, \$epoch_max);
1293 return unless defined $latest;
1295 my $seq = $opt->{sequential_shard};
1296 my $art_beg; # the NNTP article number we start xapian_only at
1297 my $idxlevel = $self->{ibx}->{indexlevel};
1298 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1300 $self->idx_init($opt); # acquire lock
1301 fill_alternates($self, $epoch_max);
1302 $self->{over}->rethread_prepare($opt);
1304 need_checkpoint => \(my $bool = 0),
1305 unindex_range => {}, # EPOCH => oid_old..oid_new
1306 reindex => $opt->{reindex},
1310 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1311 if (sync_prepare($self, $sync, $epoch_max)) {
1312 # tmp_clone seems to fail if inside a transaction, so
1313 # we rollback here (because we opened {mm} for reading)
1314 # Note: we do NOT rely on DBI transactions for atomicity;
1315 # only for batch performance.
1316 $self->{mm}->{dbh}->rollback;
1317 $self->{mm}->{dbh}->begin_work;
1319 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1321 # xapian_only works incrementally w/o --reindex
1322 if ($seq && !$opt->{reindex}) {
1323 $art_beg = $sync->{mm_tmp}->max;
1324 $art_beg++ if defined($art_beg);
1327 if ($sync->{max_size} = $opt->{max_size}) {
1328 $sync->{index_oid} = \&index_oid;
1330 # work forwards through history
1331 index_epoch($self, $sync, $_) for (0..$epoch_max);
1332 $self->{over}->rethread_done($opt);
1335 if (my $nr = $sync->{nr}) {
1336 my $pr = $sync->{-opt}->{-progress};
1337 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1340 # deal with Xapian shards sequentially
1341 if ($seq && delete($sync->{mm_tmp})) {
1342 $self->{ibx}->{indexlevel} = $idxlevel;
1343 xapian_only($self, $opt, $sync, $art_beg);
1346 # --reindex on the command-line
1347 if ($opt->{reindex} && !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1348 $self->lock_acquire;
1349 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1350 if (my $xdb = $s0->idx_acquire) {
1351 my $n = $xdb->get_metadata('has_threadid');
1352 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1355 $self->lock_release;
1358 # reindex does not pick up new changes, so we rerun w/o it:
1359 if ($opt->{reindex}) {
1362 delete @again{qw(rethread reindex -skip_lock)};
1363 index_sync($self, \%again);