1 # Copyright (C) 2018 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 package PublicInbox::V2Writable;
8 use base qw(PublicInbox::Lock);
9 use PublicInbox::SearchIdxPart;
10 use PublicInbox::MIME;
12 use PublicInbox::Import;
13 use PublicInbox::MID qw(mids);
14 use PublicInbox::ContentId qw(content_id content_digest);
15 use PublicInbox::Inbox;
16 use PublicInbox::OverIdxFork;
17 use PublicInbox::Msgmap;
18 use PublicInbox::Spawn;
21 # an estimate of the post-packed size to the raw uncompressed size
22 my $PACKING_FACTOR = 0.4;
24 # assume 2 cores if GNU nproc(1) is not available
26 int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
30 my ($class, $v2ibx, $creat) = @_;
31 my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
35 File::Path::mkpath($dir);
37 die "$dir does not exist\n";
42 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
44 # always load existing partitions in case core count changes:
46 foreach my $part (<$xpfx/*>) {
47 -d $part && $part =~ m!/\d+\z! or next;
49 Search::Xapian::Database->new($part)->close;
54 $nparts = nproc() if ($nparts == 0);
56 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
59 im => undef, # PublicInbox::Import
60 partitions => $nparts,
63 over => PublicInbox::OverIdxFork->new("$xpfx/over.sqlite3"),
64 lock_path => "$dir/inbox.lock",
65 # limit each repo to 1GB or so
66 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
73 my ($self, $parallel) = @_;
74 $self->{parallel} = $parallel;
77 git_dir_latest($self, \$max_git);
78 $self->git_init($max_git >= 0 ? $max_git : 0);
82 # returns undef on duplicate or spam
83 # mimics Import::add and wraps it for v2
85 my ($self, $mime, $check_cb) = @_;
89 $mime = $check_cb->($mime) or return;
92 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
93 # as does SQLite 3.4.1+ (released in 2007-07-20), and
94 # Xapian 1.3.2+ (released 2015-03-15).
95 # For the most part, we can spawn git-fast-import without
96 # leaking FDs to it...
100 my $num = num_for($self, $mime, \$mid0);
101 defined $num or return; # duplicate
102 defined $mid0 or die "BUG: $mid0 undefined\n";
103 my $im = $self->importer;
104 my $cmt = $im->add($mime);
105 $cmt = $im->get_mark($cmt);
106 my ($oid, $len, $msgref) = @{$im->{last_object}};
108 my $nparts = $self->{partitions};
109 my $part = $num % $nparts;
110 $self->{last_commit}->[$self->{max_git}] = $cmt;
111 my $idx = $self->idx_part($part);
112 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
113 my $n = $self->{transact_bytes} += $len;
114 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
122 my ($self, $mime, $mid0) = @_;
123 my $mids = mids($mime->header_obj);
125 my $mid = $mids->[0];
126 my $num = $self->{mm}->mid_insert($mid);
127 if (defined $num) { # common case
132 # crap, Message-ID is already known, hope somebody just resent:
134 foreach my $m (@$mids) {
135 # read-only lookup now safe to do after above barrier
136 my $existing = $self->lookup_content($mime, $m);
137 # easy, don't store duplicates
138 # note: do not add more diagnostic info here since
139 # it gets noisy on public-inbox-watch restarts
144 warn "<$mid> reused for mismatched content\n";
146 # try the rest of the mids
147 for(my $i = $#$mids; $i >= 1; $i--) {
149 $num = $self->{mm}->mid_insert($m);
151 warn "alternative <$m> for <$mid> found\n";
157 # none of the existing Message-IDs are good, generate a new one:
158 num_for_harder($self, $mime, $mid0);
162 my ($self, $mime, $mid0) = @_;
164 my $hdr = $mime->header_obj;
165 my $dig = content_digest($mime);
166 $$mid0 = PublicInbox::Import::digest2mid($dig);
167 my $num = $self->{mm}->mid_insert($$mid0);
168 unless (defined $num) {
169 # it's hard to spoof the last Received: header
170 my @recvd = $hdr->header_raw('Received');
171 $dig->add("Received: $_") foreach (@recvd);
172 $$mid0 = PublicInbox::Import::digest2mid($dig);
173 $num = $self->{mm}->mid_insert($$mid0);
175 # fall back to a random Message-ID and give up determinism:
176 until (defined($num)) {
178 $$mid0 = PublicInbox::Import::digest2mid($dig);
179 warn "using random Message-ID <$$mid0> as fallback\n";
180 $num = $self->{mm}->mid_insert($$mid0);
183 PublicInbox::Import::append_mid($hdr, $$mid0);
188 my ($self, $part) = @_;
189 $self->{idx_parts}->[$part];
195 return if $self->{idx_parts};
196 my $ibx = $self->{-inbox};
198 # do not leak read-only FDs to child processes, we only have these
199 # FDs for duplicate detection so they should not be
200 # frequently activated.
201 delete $ibx->{$_} foreach (qw(git mm search));
203 my $over = $self->{over};
205 $ibx->with_umask(sub {
207 $over->create($self);
209 # need to create all parts before initializing msgmap FD
210 my $max = $self->{partitions} - 1;
212 # idx_parts must be visible to all forked processes
213 my $idx = $self->{idx_parts} = [];
214 for my $i (0..$max) {
215 push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
218 # Now that all subprocesses are up, we can open the FDs
220 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
221 "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
222 $mm->{dbh}->begin_work;
227 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
229 my $pfx = "$self->{-inbox}->{mainrepo}/git";
231 foreach my $i (0..$self->{max_git}) {
232 my $git = PublicInbox::Git->new("$pfx/$i.git");
233 my $im = $self->import_init($git, 0, 1);
234 $purges->[$i] = $im->purge_oids($purge);
239 sub remove_internal {
240 my ($self, $mime, $cmt_msg, $purge) = @_;
243 my $im = $self->importer unless $purge;
244 my $ibx = $self->{-inbox};
245 my $srch = $ibx->search;
246 my $cid = content_id($mime);
247 my $parts = $self->{idx_parts};
248 my $mm = $self->{mm};
250 my $mids = mids($mime->header_obj);
252 # We avoid introducing new blobs into git since the raw content
253 # can be slightly different, so we do not need the user-supplied
254 # message now that we have the mids and content_id
258 foreach my $mid (@$mids) {
259 $srch->reopen->each_smsg_by_mid($mid, sub {
262 my $msg = $ibx->msg_by_smsg($smsg);
263 if (!defined($msg)) {
264 warn "broken smsg for $mid\n";
268 my $cur = PublicInbox::MIME->new($msg);
269 if (content_id($cur) eq $cid) {
270 $mm->num_delete($smsg->num);
271 # $removed should only be set once assuming
272 # no bugs in our deduplication code:
274 $removed->{mime} = $cur;
275 my $oid = $smsg->{blob};
280 $im->remove(\$orig, $cmt_msg);
283 $removed->num; # memoize this for callers
285 foreach my $idx (@$parts) {
286 $idx->remote_remove($oid, $mid);
288 $self->{over}->remove_oid($oid, $mid);
296 my $cmt = $im->get_mark($mark);
297 $self->{last_commit}->[$self->{max_git}] = $cmt;
299 if ($purge && scalar keys %$purge) {
300 return purge_oids($self, $purge);
306 my ($self, $mime, $cmt_msg) = @_;
307 remove_internal($self, $mime, $cmt_msg);
311 my ($self, $mime) = @_;
312 my $purges = remove_internal($self, $mime, undef, {});
313 $self->idx_init if @$purges; # ->done is called on purges
314 for my $i (0..$#$purges) {
315 defined(my $cmt = $purges->[$i]) or next;
316 $self->{last_commit}->[$i] = $cmt;
321 sub set_last_commits ($) {
323 defined(my $max_git = $self->{max_git}) or return;
324 my $mm = $self->{mm};
325 my $last_commit = $self->{last_commit};
326 foreach my $i (0..$max_git) {
327 defined(my $cmt = $last_commit->[$i]) or next;
328 $last_commit->[$i] = undef;
329 $mm->last_commit_n($i, $cmt);
335 my $im = delete $self->{im};
336 $im->done if $im; # PublicInbox::Import::done
338 my $mm = $self->{mm};
339 $mm->{dbh}->commit if $mm;
341 # order matters, we can only close {over} after all partitions
342 # are done because the partitions also write to {over}
343 my $parts = delete $self->{idx_parts};
345 $_->remote_commit for @$parts;
346 $_->remote_close for @$parts;
349 my $over = $self->{over};
350 $over->remote_commit;
354 $mm->{dbh}->begin_work;
355 set_last_commits($self);
360 $self->{transact_bytes} = 0;
361 $self->lock_release if $parts;
366 my $im = $self->{im};
367 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
371 # issue a write barrier to ensure all data is visible to other processes
372 # and read-only ops. Order of data importance is: git > SQLite > Xapian
374 my ($self, $fsync) = @_;
376 if (my $im = $self->{im}) {
379 my $parts = $self->{idx_parts};
381 my $dbh = $self->{mm}->{dbh};
382 $dbh->commit; # SQLite msgmap data is second in importance
384 my $over = $self->{over};
386 # Now deal with Xapian and overview DB
387 $over->barrier_init(scalar(@$parts));
389 # each partition needs to issue a barrier command to over
390 $_->remote_barrier foreach @$parts;
392 $over->barrier_wait; # wait for each Xapian partition
393 $over->commit_fsync if $fsync;
395 # last_commit is special, don't commit these until
396 # remote partitions are done:
398 set_last_commits($self);
403 $self->{transact_bytes} = 0;
407 my ($self, $new) = @_;
408 my $pfx = "$self->{-inbox}->{mainrepo}/git";
409 my $git_dir = "$pfx/$new.git";
410 my @cmd = (qw(git init --bare -q), $git_dir);
411 PublicInbox::Import::run_die(\@cmd);
413 my $all = "$self->{-inbox}->{mainrepo}/all.git";
415 @cmd = (qw(git init --bare -q), $all);
416 PublicInbox::Import::run_die(\@cmd);
417 @cmd = (qw/git config/, "--file=$all/config",
418 'repack.writeBitmaps', 'true');
419 PublicInbox::Import::run_die(\@cmd);
422 @cmd = (qw/git config/, "--file=$git_dir/config",
423 'include.path', '../../all.git/config');
424 PublicInbox::Import::run_die(\@cmd);
426 my $alt = "$all/objects/info/alternates";
427 my $new_obj_dir = "../../git/$new.git/objects";
430 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
431 %alts = map { chomp; $_ => 1 } (<$fh>);
433 return $git_dir if $alts{$new_obj_dir};
434 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
435 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
436 close $fh or die "close $alt: $!\n";
441 my ($self, $max) = @_;
443 my $pfx = "$self->{-inbox}->{mainrepo}/git";
444 return unless -d $pfx;
446 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
447 while (defined(my $git_dir = readdir($dh))) {
448 $git_dir =~ m!\A(\d+)\.git\z! or next;
451 $latest = "$pfx/$git_dir";
459 my $im = $self->{im};
461 if ($im->{bytes_added} < $self->{rotate_bytes}) {
468 my $git_dir = $self->git_init(++$self->{max_git});
469 my $git = PublicInbox::Git->new($git_dir);
470 return $self->import_init($git, 0);
475 my $latest = git_dir_latest($self, \$max);
476 if (defined $latest) {
477 my $git = PublicInbox::Git->new($latest);
478 my $packed_bytes = $git->packed_bytes;
479 if ($packed_bytes >= $self->{rotate_bytes}) {
482 $self->{max_git} = $max;
483 return $self->import_init($git, $packed_bytes);
486 $self->{max_git} = $new;
487 $latest = $self->git_init($new);
488 $self->import_init(PublicInbox::Git->new($latest), 0);
492 my ($self, $git, $packed_bytes, $tmp) = @_;
493 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
494 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
495 $im->{want_object_info} = 1;
496 $im->{lock_path} = undef;
497 $im->{path_type} = 'v2';
498 $self->{im} = $im unless $tmp;
504 my ($mid, $cur, $new) = @_;
505 use File::Temp qw(tempfile);
506 use PublicInbox::Spawn qw(spawn);
508 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
509 print $ah $cur->as_string or die "print: $!";
510 close $ah or die "close: $!";
511 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
512 PublicInbox::Import::drop_unwanted_headers($new);
513 print $bh $new->as_string or die "print: $!";
514 close $bh or die "close: $!";
515 my $cmd = [ qw(diff -u), $an, $bn ];
516 print STDERR "# MID conflict <$mid>\n";
517 my $pid = spawn($cmd, undef, { 1 => 2 });
518 defined $pid or die "diff failed to spawn $!";
519 waitpid($pid, 0) == $pid or die "diff did not finish";
524 my ($self, $mime, $mid) = @_;
525 my $ibx = $self->{-inbox};
527 my $srch = $ibx->search->reopen;
528 my $cid = content_id($mime);
530 $srch->each_smsg_by_mid($mid, sub {
533 my $msg = $ibx->msg_by_smsg($smsg);
534 if (!defined($msg)) {
535 warn "broken smsg for $mid\n";
538 my $cur = PublicInbox::MIME->new($msg);
539 if (content_id($cur) eq $cid) {
540 $smsg->{mime} = $cur;
542 return 0; # break out of loop
545 # XXX DEBUG_DIFF is experimental and may be removed
546 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
555 my $fh = delete $self->{reindex_pipe};
557 if (my $parts = $self->{idx_parts}) {
558 $_->atfork_child foreach @$parts;
560 if (my $im = $self->{im}) {
563 die "unexpected mm" if $self->{mm};
567 my ($self, $D, $git, $oid) = @_;
568 my $msgref = $git->cat_file($oid);
569 my $mime = PublicInbox::MIME->new($$msgref);
570 my $mids = mids($mime->header_obj);
571 my $cid = content_id($mime);
572 foreach my $mid (@$mids) {
573 $D->{"$mid\0$cid"} = 1;
578 my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
580 my $msgref = $git->cat_file($oid, \$len);
581 my $mime = PublicInbox::MIME->new($$msgref);
582 my $mids = mids($mime->header_obj);
583 my $cid = content_id($mime);
585 # get the NNTP article number we used before, highest number wins
586 # and gets deleted from mm_tmp;
590 foreach my $mid (@$mids) {
591 $del += (delete $D->{"$mid\0$cid"} || 0);
592 my $n = $mm_tmp->num_for($mid);
593 if (defined $n && $n > $num) {
598 if (!defined($mid0) && $regen && !$del) {
600 die "BUG: ran out of article numbers\n" if $num <= 0;
601 my $mm = $self->{mm};
602 foreach my $mid (reverse @$mids) {
603 if ($mm->mid_set($num, $mid) == 1) {
608 if (!defined($mid0)) {
609 my $id = '<' . join('> <', @$mids) . '>';
610 warn "Message-ID $id unusable for $num\n";
611 foreach my $mid (@$mids) {
612 defined(my $n = $mm->num_for($mid)) or next;
613 warn "#$n previously mapped for <$mid>\n";
618 if (!defined($mid0) || $del) {
619 if (!defined($mid0) && $del) { # expected for deletes
624 my $id = '<' . join('> <', @$mids) . '>';
626 warn "Skipping $id, no article number found\n";
627 if ($del && defined($mid0)) {
628 warn "$id was deleted $del " .
629 "time(s) but mapped to article #$num\n";
634 $mm_tmp->mid_delete($mid0) or
635 die "failed to delete <$mid0> for article #$num\n";
637 my $nparts = $self->{partitions};
638 my $part = $num % $nparts;
639 my $idx = $self->idx_part($part);
640 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
641 my $n = $self->{transact_bytes} += $len;
642 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
644 $mm_tmp->atfork_prepare;
645 $self->done; # release lock
646 # allow -watch or -mda to write...
647 $self->idx_init; # reacquire lock
648 $mm_tmp->atfork_parent;
652 # only update last_commit for $i on reindex iff newer than current
653 sub update_last_commit {
654 my ($self, $git, $i, $cmt) = @_;
655 my $last = $self->{mm}->last_commit_n($i);
656 if (defined $last && is_ancestor($git, $last, $cmt)) {
657 my @cmd = (qw(rev-list --count), "$last..$cmt");
658 chomp(my $n = $git->qx(@cmd));
659 return if $n ne '' && $n == 0;
661 $self->{mm}->last_commit_n($i, $cmt);
664 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
667 my ($self, $max_git) = @_;
669 for (my $i = $max_git; $i >= 0; $i--) {
670 $heads->[$i] = $self->{mm}->last_commit_n($i);
675 sub is_ancestor ($$$) {
676 my ($git, $cur, $tip) = @_;
677 return 0 unless $git->check($cur);
678 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
679 qw(merge-base --is-ancestor), $cur, $tip ];
680 my $pid = spawn($cmd);
681 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
682 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
687 my ($self, $opts, $max_git, $ranges) = @_;
689 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
690 for (my $i = $max_git; $i >= 0; $i--) {
691 die "already indexing!\n" if $self->{index_pipe};
692 my $git_dir = git_dir_n($self, $i);
693 -d $git_dir or next; # missing parts are fine
694 my $git = PublicInbox::Git->new($git_dir);
695 chomp(my $tip = $git->qx('rev-parse', $head));
697 if (defined(my $cur = $ranges->[$i])) {
698 $range = "$cur..$tip";
699 if (is_ancestor($git, $cur, $tip)) { # common case
700 my $n = $git->qx(qw(rev-list --count), $range);
703 $ranges->[$i] = undef;
708 discontiguous range: $range
709 Rewritten history? (in $git_dir)
711 my $base = $git->qx('merge-base', $tip, $cur);
714 $range = "$base..$tip";
715 warn "found merge-base: $base\n"
719 discarding history at $cur
723 reindexing $git_dir starting at
726 $self->{"unindex-range.$i"} = "$base..$cur";
729 $range = $tip; # all of it
731 $ranges->[$i] = $range;
733 # can't use 'rev-list --count' if we use --diff-filter
734 my $fh = $git->popen(qw(log --pretty=tformat:%h
735 --no-notes --no-color --no-renames
736 --diff-filter=AM), $range, '--', 'm');
737 ++$regen_max while <$fh>;
743 my ($self, $git, $oid) = @_;
744 my $msgref = $git->cat_file($oid);
745 my $mime = PublicInbox::MIME->new($msgref);
746 my $mids = mids($mime->header_obj);
747 $mime = $msgref = undef;
749 foreach my $mid (@$mids) {
751 $self->{-inbox}->search->reopen->each_smsg_by_mid($mid, sub {
754 $gone{$smsg->num} = 1 if $oid eq $smsg->{blob};
757 my $n = scalar keys %gone;
760 warn "BUG: multiple articles linked to $oid\n",
761 join(',',sort keys %gone), "\n";
763 $self->{unindexed}->{$_}++ foreach keys %gone;
764 $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
765 $self->{over}->remove_oid($oid, $mid);
770 my $x40 = qr/[a-f0-9]{40}/;
772 my ($self, $opts, $git, $unindex_range) = @_;
773 my $un = $self->{unindexed} ||= {}; # num => removal count
775 my $before = scalar keys %$un;
776 my @cmd = qw(log --raw -r
777 --no-notes --no-color --no-abbrev --no-renames);
778 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
780 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
781 $self->unindex_oid($git, $1);
783 delete $self->{reindex_pipe};
786 return unless $opts->{prune};
787 my $after = scalar keys %$un;
788 return if $before == $after;
790 # ensure any blob can not longer be accessed via dumb HTTP
791 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
792 qw(-c gc.reflogExpire=now gc --prune=all)]);
796 my ($self, $opts) = @_;
798 my $ibx = $self->{-inbox};
800 my $latest = git_dir_latest($self, \$max_git);
801 return unless defined $latest;
802 $self->idx_init; # acquire lock
803 my $mm_tmp = $self->{mm}->tmp_clone;
804 my $ranges = $opts->{reindex} ? [] : $self->last_commits($max_git);
806 my ($min, $max) = $mm_tmp->minmax;
807 my $regen = $self->index_prepare($opts, $max_git, $ranges);
808 $$regen += $max if $max;
810 my @cmd = qw(log --raw -r --pretty=tformat:%h
811 --no-notes --no-color --no-abbrev --no-renames);
813 # work backwards through history
814 my $last_commit = [];
815 for (my $i = $max_git; $i >= 0; $i--) {
816 my $git_dir = git_dir_n($self, $i);
817 die "already reindexing!\n" if delete $self->{reindex_pipe};
818 -d $git_dir or next; # missing parts are fine
819 my $git = PublicInbox::Git->new($git_dir);
820 my $unindex = delete $self->{"unindex-range.$i"};
821 $self->unindex($opts, $git, $unindex) if $unindex;
822 defined(my $range = $ranges->[$i]) or next;
823 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
826 if (/\A$x40$/o && !defined($cmt)) {
828 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
829 $self->reindex_oid($mm_tmp, $D, $git, $1,
831 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
832 $self->mark_deleted($D, $git, $1);
836 delete $self->{reindex_pipe};
837 $self->update_last_commit($git, $i, $cmt) if defined $cmt;
839 my @d = sort keys %$D;
841 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
843 my ($mid, undef) = split(/\0/, $_, 2);