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 our $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} ||= scalar($self->xdb_shards_flat);
81 # $creat may be any true value, or 0/undef. A hashref is true,
82 # and $creat->{nproc} may be set to an integer
83 my ($class, $v2ibx, $creat) = @_;
84 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
85 my $dir = $v2ibx->assert_usable_dir;
89 File::Path::mkpath($dir);
91 die "$dir does not exist\n";
94 $v2ibx->umask_prepare;
96 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
99 im => undef, # PublicInbox::Import
105 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
106 lock_path => "$dir/inbox.lock",
107 # limit each git repo (epoch) to 1GB or so
108 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
109 last_commit => [], # git epoch -> commit
111 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
112 $self->{shards} = count_shards($self) || nproc_shards($creat);
118 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
119 if (defined $shards) {
120 $self->{parallel} = 0 if $shards == 0;
121 $self->{shards} = $shards if $shards > 0;
124 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
125 my $max = $self->{ibx}->max_git_epoch;
126 $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
127 $self->git_init($max // 0);
131 # returns undef on duplicate or spam
132 # mimics Import::add and wraps it for v2
134 my ($self, $eml, $check_cb) = @_;
135 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
139 my ($self, $num) = @_;
140 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
143 # indexes a message, returns true if checkpointing is needed
145 my ($self, $msgref, $mime, $smsg) = @_;
146 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
147 $self->{oidx}->add_overview($mime, $smsg);
148 my $idx = idx_shard($self, $smsg->{num});
149 $idx->index_raw($msgref, $mime, $smsg);
150 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
151 $n >= $self->{batch_bytes};
155 my ($self, $mime, $check_cb) = @_;
159 $mime = $check_cb->($mime, $self->{ibx}) or return;
162 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
163 # as does SQLite 3.4.1+ (released in 2007-07-20), and
164 # Xapian 1.3.2+ (released 2015-03-15).
165 # For the most part, we can spawn git-fast-import without
166 # leaking FDs to it...
169 my ($num, $mid0) = v2_num_for($self, $mime);
170 defined $num or return; # duplicate
171 defined $mid0 or die "BUG: \$mid0 undefined\n";
172 my $im = $self->importer;
173 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
174 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
175 $cmt = $im->get_mark($cmt);
176 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
178 my $msgref = delete $smsg->{-raw_email};
179 if (do_idx($self, $msgref, $mime, $smsg)) {
187 my ($self, $mime) = @_;
188 my $mids = mids($mime);
190 my $mid = $mids->[0];
191 my $num = $self->{mm}->mid_insert($mid);
192 if (defined $num) { # common case
196 # crap, Message-ID is already known, hope somebody just resent:
197 foreach my $m (@$mids) {
198 # read-only lookup now safe to do after above barrier
199 # easy, don't store duplicates
200 # note: do not add more diagnostic info here since
201 # it gets noisy on public-inbox-watch restarts
202 return () if content_exists($self, $mime, $m);
205 # AltId may pre-populate article numbers (e.g. X-Mail-Count
206 # or NNTP article number), use that article number if it's
208 my $altid = $self->{ibx}->{altid};
209 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
210 my $num = $self->{mm}->num_for($mid);
212 if (defined $num && !$self->{oidx}->get_art($num)) {
218 warn "<$mid> reused for mismatched content\n";
220 # try the rest of the mids
221 for(my $i = $#$mids; $i >= 1; $i--) {
223 $num = $self->{mm}->mid_insert($m);
225 warn "alternative <$m> for <$mid> found\n";
230 # none of the existing Message-IDs are good, generate a new one:
231 v2_num_for_harder($self, $mime);
234 sub v2_num_for_harder {
235 my ($self, $eml) = @_;
237 my $dig = content_digest($eml);
238 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
239 my $num = $self->{mm}->mid_insert($mid0);
240 unless (defined $num) {
241 # it's hard to spoof the last Received: header
242 my @recvd = $eml->header_raw('Received');
243 $dig->add("Received: $_") foreach (@recvd);
244 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
245 $num = $self->{mm}->mid_insert($mid0);
247 # fall back to a random Message-ID and give up determinism:
248 until (defined($num)) {
250 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
251 warn "using random Message-ID <$mid0> as fallback\n";
252 $num = $self->{mm}->mid_insert($mid0);
255 PublicInbox::Import::append_mid($eml, $mid0);
259 sub _idx_init { # with_umask callback
260 my ($self, $opt) = @_;
261 $self->lock_acquire unless $opt && $opt->{-skip_lock};
262 $self->{oidx}->create;
264 # xcpdb can change shard count while -watch is idle
265 my $nshards = count_shards($self);
266 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
267 $self->{batch_bytes} = $opt->{batch_size} //
268 $PublicInbox::SearchIdx::BATCH_BYTES;
270 # need to create all shards before initializing msgmap FD
271 # idx_shards must be visible to all forked processes
272 my $max = $self->{shards} - 1;
273 my $idx = $self->{idx_shards} = [];
274 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
276 # SearchIdxShard may do their own flushing, so don't scale
277 # until after forking
278 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
280 my $ibx = $self->{ibx} or return; # ExtIdxSearch
282 # Now that all subprocesses are up, we can open the FDs
284 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
285 "$ibx->{inboxdir}/msgmap.sqlite3",
286 $ibx->{-no_fsync} ? 2 : 1);
287 $mm->{dbh}->begin_work;
290 sub parallel_init ($$) {
291 my ($self, $indexlevel) = @_;
292 if (($indexlevel // 'full') eq 'basic') {
293 $self->{parallel} = 0;
295 pipe(my ($r, $w)) or die "pipe failed: $!";
296 # pipe for barrier notifications doesn't need to be big,
298 fcntl($w, 1031, 4096) if $^O eq 'linux';
299 $self->{bnote} = [ $r, $w ];
306 my ($self, $opt) = @_;
307 return if $self->{idx_shards};
308 my $ibx = $self->{ibx};
310 # do not leak read-only FDs to child processes, we only have these
311 # FDs for duplicate detection so they should not be
312 # frequently activated.
313 delete @$ibx{qw(mm search)};
316 parallel_init($self, $ibx->{indexlevel});
318 $ibx->with_umask(\&_idx_init, $self, $opt);
321 # returns an array mapping [ epoch => latest_commit ]
322 # latest_commit may be undef if nothing was done to that epoch
323 # $replace_map = { $object_id => $strref, ... }
324 sub _replace_oids ($$$) {
325 my ($self, $mime, $replace_map) = @_;
327 my $ibx = $self->{ibx};
328 my $pfx = "$ibx->{inboxdir}/git";
329 my $rewrites = []; # epoch => commit
330 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
332 foreach my $i (0..$max) {
333 my $git_dir = "$pfx/$i.git";
335 my $git = PublicInbox::Git->new($git_dir);
336 my $im = $self->import_init($git, 0, 1);
337 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
343 sub content_hashes ($) {
345 my @chashes = ( content_hash($mime) );
347 # We still support Email::MIME, here, and
348 # Email::MIME->as_string doesn't always round-trip, so we may
349 # use a second content_hash
350 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
351 push @chashes, $rt if $chashes[0] ne $rt;
355 sub content_matches ($$) {
356 my ($chashes, $existing) = @_;
357 my $chash = content_hash($existing);
358 foreach (@$chashes) {
359 return 1 if $_ eq $chash
364 # used for removing or replacing (purging)
365 sub rewrite_internal ($$;$$$) {
366 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
368 my ($im, $need_reindex, $replace_map);
370 $replace_map = {}; # oid => sref
371 $need_reindex = [] if $new_eml;
373 $im = $self->importer;
375 my $oidx = $self->{oidx};
376 my $chashes = content_hashes($old_eml);
378 my $mids = mids($old_eml);
380 # We avoid introducing new blobs into git since the raw content
381 # can be slightly different, so we do not need the user-supplied
382 # message now that we have the mids and content_hash
386 foreach my $mid (@$mids) {
387 my %gone; # num => [ smsg, $mime, raw ]
389 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
390 my $msg = get_blob($self, $smsg);
391 if (!defined($msg)) {
392 warn "broken smsg for $mid\n";
396 my $cur = PublicInbox::Eml->new($msg);
397 if (content_matches($chashes, $cur)) {
398 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
401 my $n = scalar keys %gone;
404 warn "BUG: multiple articles linked to <$mid>\n",
405 join(',', sort keys %gone), "\n";
407 foreach my $num (keys %gone) {
408 my ($smsg, $mime, $orig) = @{$gone{$num}};
409 # $removed should only be set once assuming
410 # no bugs in our deduplication code:
411 $removed = [ undef, $mime, $smsg ];
412 my $oid = $smsg->{blob};
414 $replace_map->{$oid} = $sref;
416 ($mark, undef) = $im->remove($orig, $cmt_msg);
417 $removed->[0] = $mark;
420 if ($need_reindex) { # ->replace
421 push @$need_reindex, $smsg;
422 } else { # ->purge or ->remove
423 $self->{mm}->num_delete($num);
425 unindex_oid_aux($self, $oid, $mid);
430 my $cmt = $im->get_mark($mark);
431 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
433 if ($replace_map && scalar keys %$replace_map) {
434 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
435 return { rewrites => $rewrites, need_reindex => $need_reindex };
437 defined($mark) ? $removed : undef;
440 # public (see PublicInbox::Import->remove), but note the 3rd element
441 # (retval[2]) is not part of the stable API shared with Import->remove
443 my ($self, $eml, $cmt_msg) = @_;
444 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
445 $self, $eml, $cmt_msg);
446 defined($r) && defined($r->[0]) ? @$r: undef;
449 sub _replace ($$;$$) {
450 my ($self, $old_eml, $new_eml, $sref) = @_;
451 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
452 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
453 $self, $old_eml, undef, $new_eml, $sref) or return;
455 my $rewrites = $rewritten->{rewrites};
456 # ->done is called if there are rewrites since we gc+prune from git
457 $self->idx_init if @$rewrites;
459 for my $i (0..$#$rewrites) {
460 defined(my $cmt = $rewrites->[$i]) or next;
461 $self->{last_commit}->[$i] = $cmt;
468 my ($self, $mime) = @_;
469 my $rewritten = _replace($self, $mime, undef, \'') or return;
470 $rewritten->{rewrites}
473 # returns the git object_id of $fh, does not write the object to FS
474 sub git_hash_raw ($$) {
475 my ($self, $raw) = @_;
476 # grab the expected OID we have to reindex:
477 pipe(my($in, $w)) or die "pipe: $!";
478 my $git_dir = $self->git->{git_dir};
479 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
480 my $r = popen_rd($cmd, undef, { 0 => $in });
481 print $w $$raw or die "print \$w: $!";
482 close $w or die "close \$w: $!";
484 chomp(my $oid = <$r>);
485 close $r or die "git hash-object failed: $?";
486 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
490 sub _check_mids_match ($$$) {
491 my ($old_list, $new_list, $hdrs) = @_;
492 my %old_mids = map { $_ => 1 } @$old_list;
493 my %new_mids = map { $_ => 1 } @$new_list;
494 my @old = keys %old_mids;
495 my @new = keys %new_mids;
496 my $err = "$hdrs may not be changed when replacing\n";
497 die $err if scalar(@old) != scalar(@new);
498 delete @new_mids{@old};
499 delete @old_mids{@new};
500 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
503 # Changing Message-IDs or References with ->replace isn't supported.
504 # The rules for dealing with messages with multiple or conflicting
505 # Message-IDs are pretty complex and rethreading hasn't been fully
507 sub check_mids_match ($$) {
508 my ($old, $new) = @_;
509 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
510 _check_mids_match(references($old), references($new),
511 'References/In-Reply-To');
516 my ($self, $old_mime, $new_mime) = @_;
518 check_mids_match($old_mime, $new_mime);
520 # mutt will always add Content-Length:, Status:, Lines: when editing
521 PublicInbox::Import::drop_unwanted_headers($new_mime);
523 my $raw = $new_mime->as_string;
524 my $expect_oid = git_hash_raw($self, \$raw);
525 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
526 my $need_reindex = $rewritten->{need_reindex};
528 # just in case we have bugs in deduplication code:
529 my $n = scalar(@$need_reindex);
531 my $list = join(', ', map {
532 "$_->{num}: <$_->{mid}>"
535 W: rewritten $n messages matching content of original message (expected: 1).
536 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
541 # make sure we really got the OID:
542 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
543 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
545 # don't leak FDs to Xapian:
548 # reindex modified messages:
549 for my $smsg (@$need_reindex) {
550 my $new_smsg = bless {
555 }, 'PublicInbox::Smsg';
556 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
557 $new_smsg->populate($new_mime, $sync);
558 do_idx($self, \$raw, $new_mime, $new_smsg);
560 $rewritten->{rewrites};
563 sub last_epoch_commit ($$;$) {
564 my ($self, $i, $cmt) = @_;
565 my $v = PublicInbox::Search::SCHEMA_VERSION();
566 $self->{mm}->last_commit_xap($v, $i, $cmt);
569 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
571 defined(my $epoch_max = $self->{epoch_max}) or return;
572 my $last_commit = $self->{last_commit};
573 foreach my $i (0..$epoch_max) {
574 defined(my $cmt = $last_commit->[$i]) or next;
575 $last_commit->[$i] = undef;
576 last_epoch_commit($self, $i, $cmt);
582 $self->{bnote} or return;
584 my $barrier = { map { $_ => 1 } (0..$n) };
588 my ($self, $barrier) = @_;
589 my $bnote = $self->{bnote} or return;
591 while (scalar keys %$barrier) {
592 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
593 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
594 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
599 sub checkpoint ($;$) {
600 my ($self, $wait) = @_;
602 if (my $im = $self->{im}) {
609 my $shards = $self->{idx_shards};
611 my $mm = $self->{mm};
612 my $dbh = $mm->{dbh} if $mm;
614 # SQLite msgmap data is second in importance
615 $dbh->commit if $dbh;
617 # SQLite overview is third
618 $self->{oidx}->commit_lazy;
620 # Now deal with Xapian
622 my $barrier = barrier_init($self, scalar @$shards);
624 # each shard needs to issue a barrier command
625 $_->shard_barrier for @$shards;
627 # wait for each Xapian shard
628 barrier_wait($self, $barrier);
630 $_->shard_commit for @$shards;
633 my $midx = $self->{midx}; # misc index
634 $midx->commit_txn if $midx;
636 # last_commit is special, don't commit these until
637 # Xapian shards are done:
638 $dbh->begin_work if $dbh;
639 set_last_commits($self);
644 $midx->begin_txn if $midx;
646 $self->{total_bytes} += $self->{transact_bytes};
647 $self->{transact_bytes} = 0;
650 # issue a write barrier to ensure all data is visible to other processes
651 # and read-only ops. Order of data importance is: git > SQLite > Xapian
653 sub barrier { checkpoint($_[0], 1) };
655 # true if locked and active
656 sub active { !!$_[0]->{im} }
662 if (my $im = delete $self->{im}) {
663 eval { $im->done }; # PublicInbox::Import::done
664 $err .= "import done: $@\n" if $@;
667 eval { checkpoint($self) };
668 $err .= "checkpoint: $@\n" if $@;
670 if (my $mm = delete $self->{mm}) {
671 my $m = $err ? 'rollback' : 'commit';
672 eval { $mm->{dbh}->$m };
673 $err .= "msgmap $m: $@\n" if $@;
675 my $shards = delete $self->{idx_shards};
678 eval { $_->shard_close };
679 $err .= "shard close: $@\n" if $@;
682 eval { $self->{oidx}->dbh_close };
683 $err .= "over close: $@\n" if $@;
684 delete $self->{midx};
685 delete $self->{bnote};
686 my $nbytes = $self->{total_bytes};
687 $self->{total_bytes} = 0;
688 $self->lock_release(!!$nbytes) if $shards;
693 sub write_alternates ($$$) {
694 my ($info_dir, $mode, $out) = @_;
695 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
696 my $tmp = $fh->filename;
697 print $fh @$out or die "print $tmp: $!\n";
698 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
699 close $fh or die "close $tmp $!\n";
700 my $alt = "$info_dir/alternates";
701 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
702 $fh->unlink_on_destroy(0);
705 sub fill_alternates ($$) {
706 my ($self, $epoch) = @_;
708 my $pfx = "$self->{ibx}->{inboxdir}/git";
709 my $all = "$self->{ibx}->{inboxdir}/all.git";
710 PublicInbox::Import::init_bare($all) unless -d $all;
711 my $info_dir = "$all/objects/info";
712 my $alt = "$info_dir/alternates";
716 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
717 $mode = (stat($fh))[2] & 07777;
719 # we assign a sort score to every alternate and favor
720 # the newest (highest numbered) one because loose objects
721 # require scanning epochs and only the latest epoch is
722 # expected to see loose objects
724 my $other = 0; # in case admin adds non-epoch repos
726 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
732 } split(/\n+/, do { local $/; <$fh> });
735 foreach my $i (0..$epoch) {
736 my $dir = "../../git/$i.git/objects";
737 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
743 write_alternates($info_dir, $mode,
744 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
748 my ($self, $epoch) = @_;
749 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
750 PublicInbox::Import::init_bare($git_dir);
751 my @cmd = (qw/git config/, "--file=$git_dir/config",
752 'include.path', '../../all.git/config');
753 PublicInbox::Import::run_die(\@cmd);
754 fill_alternates($self, $epoch);
760 my $im = $self->{im};
762 if ($im->{bytes_added} < $self->{rotate_bytes}) {
769 my $git_dir = $self->git_init(++$self->{epoch_max});
770 my $git = PublicInbox::Git->new($git_dir);
771 return $self->import_init($git, 0);
776 my $latest = $self->{ibx}->git_dir_latest(\$max);
777 if (defined $latest) {
778 my $git = PublicInbox::Git->new($latest);
779 my $packed_bytes = $git->packed_bytes;
780 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
782 if ($unpacked_bytes >= $self->{rotate_bytes}) {
785 $self->{epoch_max} = $max;
786 return $self->import_init($git, $packed_bytes);
789 $self->{epoch_max} = $epoch;
790 $latest = $self->git_init($epoch);
791 $self->import_init(PublicInbox::Git->new($latest), 0);
795 my ($self, $git, $packed_bytes, $tmp) = @_;
796 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
797 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
798 $im->{lock_path} = undef;
799 $im->{path_type} = 'v2';
800 $self->{im} = $im unless $tmp;
806 my ($mid, $cur, $new) = @_;
808 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
809 print $ah $cur->as_string or die "print: $!";
810 $ah->flush or die "flush: $!";
811 PublicInbox::Import::drop_unwanted_headers($new);
812 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
813 print $bh $new->as_string or die "print: $!";
814 $bh->flush or die "flush: $!";
815 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
816 print STDERR "# MID conflict <$mid>\n";
817 my $pid = spawn($cmd, undef, { 1 => 2 });
818 waitpid($pid, 0) == $pid or die "diff did not finish";
822 my ($self, $smsg) = @_;
823 if (my $im = $self->{im}) {
824 my $msg = $im->cat_blob($smsg->{blob});
827 # older message, should be in alternates
828 $self->{ibx}->msg_by_smsg($smsg);
831 sub content_exists ($$$) {
832 my ($self, $mime, $mid) = @_;
833 my $oidx = $self->{oidx};
834 my $chashes = content_hashes($mime);
836 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
837 my $msg = get_blob($self, $smsg);
838 if (!defined($msg)) {
839 warn "broken smsg for $mid\n";
842 my $cur = PublicInbox::Eml->new($msg);
843 return 1 if content_matches($chashes, $cur);
845 # XXX DEBUG_DIFF is experimental and may be removed
846 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
853 if (my $shards = $self->{idx_shards}) {
854 $_->atfork_child foreach @$shards;
856 if (my $im = $self->{im}) {
859 die "unexpected mm" if $self->{mm};
860 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
864 sub reindex_checkpoint ($$) {
865 my ($self, $sync) = @_;
867 $self->git->async_wait_all;
868 $self->update_last_commit($sync);
869 ${$sync->{need_checkpoint}} = 0;
870 my $mm_tmp = $sync->{mm_tmp};
871 $mm_tmp->atfork_prepare if $mm_tmp;
872 die 'BUG: {im} during reindex' if $self->{im};
873 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
874 checkpoint($self, 1); # no need to release lock on pure index
876 $self->done; # release lock
879 if (my $pr = $sync->{-opt}->{-progress}) {
880 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
883 # allow -watch or -mda to write...
884 $self->idx_init($sync->{-opt}); # reacquire lock
885 if (my $intvl = $sync->{check_intvl}) { # eidx
886 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
888 $mm_tmp->atfork_parent if $mm_tmp;
891 sub index_oid { # cat_async callback
892 my ($bref, $oid, $type, $size, $arg) = @_;
893 return if is_bad_blob($oid, $type, $size, $arg->{oid});
894 my $self = $arg->{self};
895 local $self->{current_info} = "$self->{current_info} $oid";
896 return if $size == 0; # purged
898 my $eml = PublicInbox::Eml->new($$bref);
899 my $mids = mids($eml);
900 my $chash = content_hash($eml);
902 if (scalar(@$mids) == 0) {
903 warn "E: $oid has no Message-ID, skipping\n";
907 # {unindexed} is unlikely
908 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
909 $num = delete($unindexed->{$mids->[0]});
912 $self->{mm}->mid_set($num, $mid0);
913 delete($arg->{unindexed}) if !keys(%$unindexed);
916 if (!defined($num)) { # reuse if reindexing (or duplicates)
917 my $oidx = $self->{oidx};
918 for my $mid (@$mids) {
919 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
920 last if defined $num;
923 $mid0 //= do { # is this a number we got before?
924 $num = $arg->{mm_tmp}->num_for($mids->[0]);
925 defined($num) ? $mids->[0] : undef;
927 if (!defined($num)) {
928 for (my $i = $#$mids; $i >= 1; $i--) {
929 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
937 $arg->{mm_tmp}->num_delete($num);
938 } else { # never seen
939 $num = $self->{mm}->mid_insert($mids->[0]);
942 } else { # rare, try the rest of them, backwards
943 for (my $i = $#$mids; $i >= 1; $i--) {
944 $num = $self->{mm}->mid_insert($mids->[$i]);
952 if (!defined($num)) {
953 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
962 }, 'PublicInbox::Smsg';
963 $smsg->populate($eml, $arg);
964 if (do_idx($self, $bref, $eml, $smsg)) {
965 ${$arg->{need_checkpoint}} = 1;
967 ${$arg->{latest_cmt}} = $arg->{cur_cmt} // die 'BUG: {cur_cmt} missing';
970 # only update last_commit for $i on reindex iff newer than current
971 sub update_last_commit {
972 my ($self, $sync, $stk) = @_;
973 my $unit = $sync->{unit} // return;
974 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
975 defined($latest_cmt) or return;
976 my $last = last_epoch_commit($self, $unit->{epoch});
977 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
978 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
979 chomp(my $n = $unit->{git}->qx(@cmd));
980 return if $n ne '' && $n == 0;
982 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
986 my ($self, $sync) = @_;
988 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
989 $heads->[$i] = last_epoch_commit($self, $i);
994 # returns a revision range for git-log(1)
995 sub log_range ($$$) {
996 my ($sync, $unit, $tip) = @_;
997 my $opt = $sync->{-opt};
998 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
999 my $i = $unit->{epoch};
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 my $git = $unit->{git};
1014 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1015 $pr->("OK\n") if $pr;
1016 my $n = $git->qx(qw(rev-list --count), $range);
1019 $sync->{ranges}->[$i] = undef;
1020 $pr->("$i.git has nothing new\n") if $pr;
1021 return; # nothing to do
1023 $pr->("$i.git has $n changes since $cur\n") if $pr;
1025 $pr->("FAIL\n") if $pr;
1027 discontiguous range: $range
1028 Rewritten history? (in $git->{git_dir})
1030 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1032 $range = "$base..$tip";
1033 warn "found merge-base: $base\n"
1036 warn "discarding history at $cur\n";
1039 reindexing $git->{git_dir}
1042 # $cur^0 may no longer exist if pruned by git
1043 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1044 $unit->{unindex_range} = "$base..$cur";
1045 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1046 $unit->{unindex_range} = "$base..";
1048 warn "W: unable to unindex before $range\n";
1054 # overridden by ExtSearchIdx
1055 sub artnum_max { $_[0]->{mm}->num_highwater }
1057 sub sync_prepare ($$) {
1058 my ($self, $sync) = @_;
1059 $sync->{ranges} = sync_ranges($self, $sync);
1060 my $pr = $sync->{-opt}->{-progress};
1062 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1065 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1066 $pfx //= $sync->{ibx}->{inboxdir};
1070 if ($self->{ibx_map}) {
1071 # ExtSearchIdx won't index messages unless they're in
1072 # over.sqlite3 for a given inbox, so don't read beyond
1073 # what's in the per-inbox index.
1074 $reindex_heads = [];
1075 my $v = PublicInbox::Search::SCHEMA_VERSION;
1076 my $mm = $sync->{ibx}->mm;
1077 for my $i (0..$sync->{epoch_max}) {
1078 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1080 } elsif ($sync->{reindex}) { # V2 inbox
1081 # reindex stops at the current heads and we later
1082 # rerun index_sync without {reindex}
1083 $reindex_heads = $self->last_commits($sync);
1085 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1086 $sync->{index_oid} = $self->can('index_oid');
1088 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1089 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1090 my $git_dir = "$git_pfx/$i.git";
1091 -d $git_dir or next; # missing epochs are fine
1092 my $git = PublicInbox::Git->new($git_dir);
1093 my $unit = { git => $git, epoch => $i };
1094 if ($reindex_heads) {
1095 $head = $reindex_heads->[$i] or next;
1097 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1098 next if $?; # new repo
1100 my $range = log_range($sync, $unit, $tip) or next;
1101 # can't use 'rev-list --count' if we use --diff-filter
1102 $pr->("$pfx $i.git counting $range ... ") if $pr;
1103 # Don't bump num_highwater on --reindex by using {D}.
1104 # We intentionally do NOT use {D} in the non-reindex case
1105 # because we want NNTP article number gaps from unindexed
1106 # messages to show up in mirrors, too.
1107 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1108 my $stk = log2stack($sync, $git, $range);
1109 return 0 if $sync->{quit};
1110 my $nr = $stk ? $stk->num_records : 0;
1111 $pr->("$nr\n") if $pr;
1112 $unit->{stack} = $stk; # may be undef
1113 unshift @{$sync->{todo}}, $unit;
1116 return 0 if $sync->{quit};
1118 # XXX this should not happen unless somebody bypasses checks in
1119 # our code and blindly injects "d" file history into git repos
1120 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1121 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1122 local $self->{current_info} = 'leftover ';
1123 my $unindex_oid = $self->can('unindex_oid');
1124 for my $oid (@leftovers) {
1125 last if $sync->{quit};
1126 $oid = unpack('H*', $oid);
1127 my $req = { %$sync, oid => $oid };
1128 $self->git->cat_async($oid, $unindex_oid, $req);
1130 $self->git->cat_async_wait;
1132 return 0 if $sync->{quit};
1134 $sync->{-regen_fmt} = "%u/?\n";
1138 # reindex should NOT see new commits anymore, if we do,
1139 # it's a problem and we need to notice it via die()
1140 my $pad = length($regen_max) + 1;
1141 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1142 $sync->{nr} = \(my $nr = 0);
1143 return -1 if $sync->{reindex};
1144 $regen_max + $self->artnum_max || 0;
1147 sub unindex_oid_aux ($$$) {
1148 my ($self, $oid, $mid) = @_;
1149 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1150 for my $num (@removed) {
1151 my $idx = idx_shard($self, $num);
1152 $idx->shard_remove($num);
1156 sub unindex_oid ($$;$) { # git->cat_async callback
1157 my ($bref, $oid, $type, $size, $sync) = @_;
1158 return if is_bad_blob($oid, $type, $size, $sync->{oid});
1159 my $self = $sync->{self};
1160 local $self->{current_info} = "$self->{current_info} $oid";
1161 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1162 my $mm = $self->{mm};
1163 my $mids = mids(PublicInbox::Eml->new($bref));
1165 my $oidx = $self->{oidx};
1166 foreach my $mid (@$mids) {
1169 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1170 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1172 my $n = scalar(keys(%gone)) or next;
1174 warn "BUG: multiple articles linked to $oid\n",
1175 join(',',sort keys %gone), "\n";
1177 foreach my $num (keys %gone) {
1179 my $mid0 = $mm->mid_for($num);
1180 $unindexed->{$mid0} = $num;
1182 $mm->num_delete($num);
1184 unindex_oid_aux($self, $oid, $mid);
1188 sub git { $_[0]->{ibx}->git }
1190 # this is rare, it only happens when we get discontiguous history in
1191 # a mirror because the source used -purge or -edit
1192 sub unindex_todo ($$$) {
1193 my ($self, $sync, $unit) = @_;
1194 my $unindex_range = delete($unit->{unindex_range}) // return;
1195 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1196 my $before = scalar keys %$unindexed;
1197 # order does not matter, here:
1198 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1199 --no-abbrev --no-renames), $unindex_range);
1200 local $sync->{in_unindex} = 1;
1201 my $unindex_oid = $self->can('unindex_oid');
1203 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1204 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1206 close $fh or die "git log failed: \$?=$?";
1207 $self->git->cat_async_wait;
1209 return unless $sync->{-opt}->{prune};
1210 my $after = scalar keys %$unindexed;
1211 return if $before == $after;
1213 # ensure any blob can not longer be accessed via dumb HTTP
1214 PublicInbox::Import::run_die(['git',
1215 "--git-dir=$unit->{git}->{git_dir}",
1216 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1219 sub sync_ranges ($$) {
1220 my ($self, $sync) = @_;
1221 my $reindex = $sync->{reindex};
1222 return $self->last_commits($sync) unless $reindex;
1223 return [] if ref($reindex) ne 'HASH';
1225 my $ranges = $reindex->{from}; # arrayref;
1226 if (ref($ranges) ne 'ARRAY') {
1227 die 'BUG: $reindex->{from} not an ARRAY';
1232 sub index_xap_only { # git->cat_async callback
1233 my ($bref, $oid, $type, $size, $smsg) = @_;
1234 my $self = $smsg->{self};
1235 my $idx = idx_shard($self, $smsg->{num});
1236 $smsg->{raw_bytes} = $size;
1237 $idx->index_raw($bref, undef, $smsg);
1238 $self->{transact_bytes} += $size;
1241 sub index_xap_step ($$$;$) {
1242 my ($self, $sync, $beg, $step) = @_;
1243 my $end = $sync->{art_end};
1244 return if $beg > $end; # nothing to do
1246 $step //= $self->{shards};
1247 my $ibx = $self->{ibx};
1248 if (my $pr = $sync->{-opt}->{-progress}) {
1249 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1250 "$beg..$end (% $step)\n");
1252 for (my $num = $beg; $num <= $end; $num += $step) {
1253 last if $sync->{quit};
1254 my $smsg = $ibx->over->get_art($num) or next;
1255 $smsg->{self} = $self;
1256 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1257 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1258 ${$sync->{nr}} = $num;
1259 reindex_checkpoint($self, $sync);
1264 sub index_todo ($$$) {
1265 my ($self, $sync, $unit) = @_;
1266 return if $sync->{quit};
1267 unindex_todo($self, $sync, $unit);
1268 my $stk = delete($unit->{stack}) or return;
1269 my $all = $self->git;
1270 my $index_oid = $self->can('index_oid');
1271 my $unindex_oid = $self->can('unindex_oid');
1273 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1274 $pfx = "$1 $2"; # v2
1276 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1277 $pfx //= $unit->{git}->{git_dir};
1279 local $self->{current_info} = "$pfx ";
1280 local $sync->{latest_cmt} = \(my $latest_cmt);
1281 local $sync->{unit} = $unit;
1282 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1283 if ($sync->{quit}) {
1284 warn "waiting to quit...\n";
1285 $all->async_wait_all;
1286 $self->update_last_commit($sync);
1297 if ($sync->{max_size}) {
1298 $all->check_async($oid, \&check_size, $req);
1300 $all->cat_async($oid, $index_oid, $req);
1302 } elsif ($f eq 'd') {
1303 $all->cat_async($oid, $unindex_oid, $req);
1305 if (${$sync->{need_checkpoint}}) {
1306 reindex_checkpoint($self, $sync);
1309 $all->async_wait_all;
1310 $self->update_last_commit($sync, $stk);
1314 my ($self, $opt, $sync, $art_beg) = @_;
1315 my $seq = $opt->{sequential_shard};
1317 local $self->{parallel} = 0 if $seq;
1318 $self->idx_init($opt); # acquire lock
1319 if (my $art_end = $self->{ibx}->mm->max) {
1321 need_checkpoint => \(my $bool = 0),
1324 nr => \(my $nr = 0),
1325 -regen_fmt => "%u/?\n",
1327 $sync->{art_end} = $art_end;
1328 if ($seq || !$self->{parallel}) {
1329 my $shard_end = $self->{shards} - 1;
1330 for my $i (0..$shard_end) {
1331 last if $sync->{quit};
1332 index_xap_step($self, $sync, $art_beg + $i);
1333 if ($i != $shard_end) {
1334 reindex_checkpoint($self, $sync);
1337 } else { # parallel (maybe)
1338 index_xap_step($self, $sync, $art_beg, 1);
1341 $self->git->cat_async_wait;
1345 # public, called by public-inbox-index
1347 my ($self, $opt) = @_;
1349 return xapian_only($self, $opt) if $opt->{xapian_only};
1351 my $pr = $opt->{-progress};
1353 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max);
1354 return unless defined $latest;
1356 my $seq = $opt->{sequential_shard};
1357 my $art_beg; # the NNTP article number we start xapian_only at
1358 my $idxlevel = $self->{ibx}->{indexlevel};
1359 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1361 $self->idx_init($opt); # acquire lock
1362 fill_alternates($self, $epoch_max);
1363 $self->{oidx}->rethread_prepare($opt);
1365 need_checkpoint => \(my $bool = 0),
1366 reindex => $opt->{reindex},
1369 ibx => $self->{ibx},
1370 epoch_max => $epoch_max,
1372 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1373 local $SIG{QUIT} = $quit;
1374 local $SIG{INT} = $quit;
1375 local $SIG{TERM} = $quit;
1377 if (sync_prepare($self, $sync)) {
1378 # tmp_clone seems to fail if inside a transaction, so
1379 # we rollback here (because we opened {mm} for reading)
1380 # Note: we do NOT rely on DBI transactions for atomicity;
1381 # only for batch performance.
1382 $self->{mm}->{dbh}->rollback;
1383 $self->{mm}->{dbh}->begin_work;
1385 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1387 # xapian_only works incrementally w/o --reindex
1388 if ($seq && !$opt->{reindex}) {
1389 $art_beg = $sync->{mm_tmp}->max || -1;
1393 # work forwards through history
1394 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1395 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1398 if (my $nr = $sync->{nr}) {
1399 my $pr = $sync->{-opt}->{-progress};
1400 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1404 # deal with Xapian shards sequentially
1405 if ($seq && delete($sync->{mm_tmp})) {
1406 if ($sync->{quit}) {
1409 $self->{ibx}->{indexlevel} = $idxlevel;
1410 xapian_only($self, $opt, $sync, $art_beg);
1411 $quit_warn = 1 if $sync->{quit};
1415 # --reindex on the command-line
1416 if (!$sync->{quit} && $opt->{reindex} &&
1417 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1418 $self->lock_acquire;
1419 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1420 if (my $xdb = $s0->idx_acquire) {
1421 my $n = $xdb->get_metadata('has_threadid');
1422 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1425 $self->lock_release;
1428 # reindex does not pick up new changes, so we rerun w/o it:
1429 if ($opt->{reindex} && !$sync->{quit}) {
1432 delete @again{qw(rethread reindex -skip_lock)};
1433 index_sync($self, \%again);
1434 $opt->{quit} = $again{quit}; # propagate to caller
1436 warn <<EOF if $quit_warn;
1437 W: interrupted, --xapian-only --reindex required upon restart