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;
20 # an estimate of the post-packed size to the raw uncompressed size
21 my $PACKING_FACTOR = 0.4;
23 # assume 2 cores if GNU nproc(1) is not available
25 int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
29 my ($class, $v2ibx, $creat) = @_;
30 my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
34 File::Path::mkpath($dir);
36 die "$dir does not exist\n";
41 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
43 # always load existing partitions in case core count changes:
45 foreach my $part (<$xpfx/*>) {
46 -d $part && $part =~ m!/\d+\z! or next;
48 Search::Xapian::Database->new($part)->close;
53 $nparts = nproc() if ($nparts == 0);
55 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
58 im => undef, # PublicInbox::Import
59 partitions => $nparts,
62 over => PublicInbox::OverIdxFork->new("$xpfx/over.sqlite3"),
63 lock_path => "$dir/inbox.lock",
64 # limit each repo to 1GB or so
65 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
71 my ($self, $parallel) = @_;
72 $self->{parallel} = $parallel;
75 git_dir_latest($self, \$max_git);
76 $self->git_init($max_git >= 0 ? $max_git : 0);
80 # returns undef on duplicate or spam
81 # mimics Import::add and wraps it for v2
83 my ($self, $mime, $check_cb) = @_;
87 $mime = $check_cb->($mime) or return;
90 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
91 # as does SQLite 3.4.1+ (released in 2007-07-20), and
92 # Xapian 1.3.2+ (released 2015-03-15).
93 # For the most part, we can spawn git-fast-import without
94 # leaking FDs to it...
98 my $num = num_for($self, $mime, \$mid0);
99 defined $num or return; # duplicate
100 defined $mid0 or die "BUG: $mid0 undefined\n";
101 my $im = $self->importer;
102 my $cmt = $im->add($mime);
103 $cmt = $im->get_mark($cmt);
104 my ($oid, $len, $msgref) = @{$im->{last_object}};
106 my $nparts = $self->{partitions};
107 my $part = $num % $nparts;
108 my $idx = $self->idx_part($part);
109 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
110 my $n = $self->{transact_bytes} += $len;
111 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
119 my ($self, $mime, $mid0) = @_;
120 my $mids = mids($mime->header_obj);
122 my $mid = $mids->[0];
123 my $num = $self->{mm}->mid_insert($mid);
124 if (defined $num) { # common case
129 # crap, Message-ID is already known, hope somebody just resent:
131 foreach my $m (@$mids) {
132 # read-only lookup now safe to do after above barrier
133 my $existing = $self->lookup_content($mime, $m);
134 # easy, don't store duplicates
135 # note: do not add more diagnostic info here since
136 # it gets noisy on public-inbox-watch restarts
141 warn "<$mid> reused for mismatched content\n";
143 # try the rest of the mids
144 for(my $i = $#$mids; $i >= 1; $i--) {
146 $num = $self->{mm}->mid_insert($m);
148 warn "alternative <$m> for <$mid> found\n";
154 # none of the existing Message-IDs are good, generate a new one:
155 num_for_harder($self, $mime, $mid0);
159 my ($self, $mime, $mid0) = @_;
161 my $hdr = $mime->header_obj;
162 my $dig = content_digest($mime);
163 $$mid0 = PublicInbox::Import::digest2mid($dig);
164 my $num = $self->{mm}->mid_insert($$mid0);
165 unless (defined $num) {
166 # it's hard to spoof the last Received: header
167 my @recvd = $hdr->header_raw('Received');
168 $dig->add("Received: $_") foreach (@recvd);
169 $$mid0 = PublicInbox::Import::digest2mid($dig);
170 $num = $self->{mm}->mid_insert($$mid0);
172 # fall back to a random Message-ID and give up determinism:
173 until (defined($num)) {
175 $$mid0 = PublicInbox::Import::digest2mid($dig);
176 warn "using random Message-ID <$$mid0> as fallback\n";
177 $num = $self->{mm}->mid_insert($$mid0);
180 PublicInbox::Import::append_mid($hdr, $$mid0);
185 my ($self, $part) = @_;
186 $self->{idx_parts}->[$part];
192 return if $self->{idx_parts};
193 my $ibx = $self->{-inbox};
195 # do not leak read-only FDs to child processes, we only have these
196 # FDs for duplicate detection so they should not be
197 # frequently activated.
198 delete $ibx->{$_} foreach (qw(git mm search));
200 my $over = $self->{over};
202 $ibx->with_umask(sub {
204 $over->create($self);
206 # need to create all parts before initializing msgmap FD
207 my $max = $self->{partitions} - 1;
209 # idx_parts must be visible to all forked processes
210 my $idx = $self->{idx_parts} = [];
211 for my $i (0..$max) {
212 push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
215 # Now that all subprocesses are up, we can open the FDs
217 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
218 "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
219 $mm->{dbh}->begin_work;
224 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
226 my $pfx = "$self->{-inbox}->{mainrepo}/git";
228 foreach my $i (0..$self->{max_git}) {
229 my $git = PublicInbox::Git->new("$pfx/$i.git");
230 my $im = $self->import_init($git, 0);
231 $purges->[$i] = $im->purge_oids($purge);
236 sub remove_internal {
237 my ($self, $mime, $cmt_msg, $purge) = @_;
240 my $im = $self->importer unless $purge;
241 my $ibx = $self->{-inbox};
242 my $srch = $ibx->search;
243 my $cid = content_id($mime);
244 my $parts = $self->{idx_parts};
245 my $mm = $self->{mm};
247 my $mids = mids($mime->header_obj);
249 # We avoid introducing new blobs into git since the raw content
250 # can be slightly different, so we do not need the user-supplied
251 # message now that we have the mids and content_id
254 foreach my $mid (@$mids) {
255 $srch->reopen->each_smsg_by_mid($mid, sub {
258 my $msg = $ibx->msg_by_smsg($smsg);
259 if (!defined($msg)) {
260 warn "broken smsg for $mid\n";
264 my $cur = PublicInbox::MIME->new($msg);
265 if (content_id($cur) eq $cid) {
266 $mm->num_delete($smsg->num);
267 # $removed should only be set once assuming
268 # no bugs in our deduplication code:
270 $removed->{mime} = $cur;
271 my $oid = $smsg->{blob};
275 $im->remove(\$orig, $cmt_msg);
278 $removed->num; # memoize this for callers
280 foreach my $idx (@$parts) {
281 $idx->remote_remove($oid, $mid);
283 $self->{over}->remove_oid($oid, $mid);
289 if ($purge && scalar keys %$purge) {
290 return purge_oids($self, $purge);
296 my ($self, $mime, $cmt_msg) = @_;
297 remove_internal($self, $mime, $cmt_msg);
301 my ($self, $mime) = @_;
302 remove_internal($self, $mime, undef, {});
308 my $im = delete $self->{im};
309 $im->done if $im; # PublicInbox::Import::done
311 if (my $mm = delete $self->{mm}) {
315 # order matters, we can only close {over} after all partitions
316 # are done because the partitions also write to {over}
317 my $parts = delete $self->{idx_parts};
319 $_->remote_commit for @$parts;
320 $_->remote_close for @$parts;
323 my $over = $self->{over};
324 $over->remote_commit;
326 $self->{transact_bytes} = 0;
327 $self->lock_release if $parts;
332 my $im = $self->{im};
333 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
337 # issue a write barrier to ensure all data is visible to other processes
338 # and read-only ops. Order of data importance is: git > SQLite > Xapian
340 my ($self, $fsync) = @_;
342 if (my $im = $self->{im}) {
345 my $parts = $self->{idx_parts};
347 my $dbh = $self->{mm}->{dbh};
348 $dbh->commit; # SQLite msgmap data is second in importance
350 my $over = $self->{over};
352 # Now deal with Xapian and overview DB
353 $over->barrier_init(scalar(@$parts));
355 # each partition needs to issue a barrier command to over
356 $_->remote_barrier foreach @$parts;
358 $over->barrier_wait; # wait for each Xapian partition
359 $over->commit_fsync if $fsync;
363 $self->{transact_bytes} = 0;
367 my ($self, $new) = @_;
368 my $pfx = "$self->{-inbox}->{mainrepo}/git";
369 my $git_dir = "$pfx/$new.git";
370 my @cmd = (qw(git init --bare -q), $git_dir);
371 PublicInbox::Import::run_die(\@cmd);
373 my $all = "$self->{-inbox}->{mainrepo}/all.git";
375 @cmd = (qw(git init --bare -q), $all);
376 PublicInbox::Import::run_die(\@cmd);
377 @cmd = (qw/git config/, "--file=$all/config",
378 'repack.writeBitmaps', 'true');
379 PublicInbox::Import::run_die(\@cmd);
382 @cmd = (qw/git config/, "--file=$git_dir/config",
383 'include.path', '../../all.git/config');
384 PublicInbox::Import::run_die(\@cmd);
386 my $alt = "$all/objects/info/alternates";
387 my $new_obj_dir = "../../git/$new.git/objects";
390 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
391 %alts = map { chomp; $_ => 1 } (<$fh>);
393 return $git_dir if $alts{$new_obj_dir};
394 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
395 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
396 close $fh or die "close $alt: $!\n";
401 my ($self, $max) = @_;
403 my $pfx = "$self->{-inbox}->{mainrepo}/git";
404 return unless -d $pfx;
406 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
407 while (defined(my $git_dir = readdir($dh))) {
408 $git_dir =~ m!\A(\d+)\.git\z! or next;
411 $latest = "$pfx/$git_dir";
419 my $im = $self->{im};
421 if ($im->{bytes_added} < $self->{rotate_bytes}) {
428 my $git_dir = $self->git_init(++$self->{max_git});
429 my $git = PublicInbox::Git->new($git_dir);
430 return $self->import_init($git, 0);
435 my $latest = git_dir_latest($self, \$max);
436 if (defined $latest) {
437 my $git = PublicInbox::Git->new($latest);
438 my $packed_bytes = $git->packed_bytes;
439 if ($packed_bytes >= $self->{rotate_bytes}) {
442 $self->{max_git} = $max;
443 return $self->import_init($git, $packed_bytes);
446 $self->{max_git} = $new;
447 $latest = $self->git_init($new);
448 $self->import_init(PublicInbox::Git->new($latest), 0);
452 my ($self, $git, $packed_bytes) = @_;
453 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
454 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
455 $im->{want_object_info} = 1;
456 $im->{lock_path} = undef;
457 $im->{path_type} = 'v2';
463 my ($mid, $cur, $new) = @_;
464 use File::Temp qw(tempfile);
465 use PublicInbox::Spawn qw(spawn);
467 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
468 print $ah $cur->as_string or die "print: $!";
469 close $ah or die "close: $!";
470 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
471 PublicInbox::Import::drop_unwanted_headers($new);
472 print $bh $new->as_string or die "print: $!";
473 close $bh or die "close: $!";
474 my $cmd = [ qw(diff -u), $an, $bn ];
475 print STDERR "# MID conflict <$mid>\n";
476 my $pid = spawn($cmd, undef, { 1 => 2 });
477 defined $pid or die "diff failed to spawn $!";
478 waitpid($pid, 0) == $pid or die "diff did not finish";
483 my ($self, $mime, $mid) = @_;
484 my $ibx = $self->{-inbox};
486 my $srch = $ibx->search->reopen;
487 my $cid = content_id($mime);
489 $srch->each_smsg_by_mid($mid, sub {
492 my $msg = $ibx->msg_by_smsg($smsg);
493 if (!defined($msg)) {
494 warn "broken smsg for $mid\n";
497 my $cur = PublicInbox::MIME->new($msg);
498 if (content_id($cur) eq $cid) {
499 $smsg->{mime} = $cur;
501 return 0; # break out of loop
504 # XXX DEBUG_DIFF is experimental and may be removed
505 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
514 my $fh = delete $self->{reindex_pipe};
516 if (my $parts = $self->{idx_parts}) {
517 $_->atfork_child foreach @$parts;
519 if (my $im = $self->{im}) {
522 die "unexpected mm" if $self->{mm};
526 my ($self, $D, $git, $oid) = @_;
527 my $msgref = $git->cat_file($oid);
528 my $mime = PublicInbox::MIME->new($$msgref);
529 my $mids = mids($mime->header_obj);
530 my $cid = content_id($mime);
531 foreach my $mid (@$mids) {
532 $D->{"$mid\0$cid"} = 1;
537 my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
539 my $msgref = $git->cat_file($oid, \$len);
540 my $mime = PublicInbox::MIME->new($$msgref);
541 my $mids = mids($mime->header_obj);
542 my $cid = content_id($mime);
544 # get the NNTP article number we used before, highest number wins
545 # and gets deleted from mm_tmp;
549 foreach my $mid (@$mids) {
550 $del += (delete $D->{"$mid\0$cid"} || 0);
551 my $n = $mm_tmp->num_for($mid);
552 if (defined $n && $n > $num) {
557 if (!defined($mid0) && $regen && !$del) {
559 die "BUG: ran out of article numbers\n" if $num <= 0;
560 my $mm = $self->{mm};
561 foreach my $mid (reverse @$mids) {
562 if ($mm->mid_set($num, $mid) == 1) {
567 if (!defined($mid0)) {
568 my $id = '<' . join('> <', @$mids) . '>';
569 warn "Message-ID $id unusable for $num\n";
570 foreach my $mid (@$mids) {
571 defined(my $n = $mm->num_for($mid)) or next;
572 warn "#$n previously mapped for <$mid>\n";
577 if (!defined($mid0) || $del) {
578 if (!defined($mid0) && $del) { # expected for deletes
583 my $id = '<' . join('> <', @$mids) . '>';
585 warn "Skipping $id, no article number found\n";
586 if ($del && defined($mid0)) {
587 warn "$id was deleted $del " .
588 "time(s) but mapped to article #$num\n";
593 $mm_tmp->mid_delete($mid0) or
594 die "failed to delete <$mid0> for article #$num\n";
596 my $nparts = $self->{partitions};
597 my $part = $num % $nparts;
598 my $idx = $self->idx_part($part);
599 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
600 my $n = $self->{transact_bytes} += $len;
601 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
603 $mm_tmp->atfork_prepare;
604 $self->done; # release lock
605 # allow -watch or -mda to write...
606 $self->idx_init; # reacquire lock
607 $mm_tmp->atfork_parent;
612 my ($self, $regen) = @_;
613 my $ibx = $self->{-inbox};
614 my $pfx = "$ibx->{mainrepo}/git";
616 my $latest = git_dir_latest($self, \$max_git);
617 return unless defined $latest;
618 my $head = $ibx->{ref_head} || 'refs/heads/master';
619 $self->idx_init; # acquire lock
620 my $x40 = qr/[a-f0-9]{40}/;
621 my $mm_tmp = $self->{mm}->tmp_clone;
623 my (undef, $max) = $mm_tmp->minmax;
624 unless (defined $max) {
627 "empty msgmap.sqlite3, regenerating article numbers\n";
630 my $tip; # latest commit out of all git repos
633 for (my $cur = $max_git; $cur >= 0; $cur--) {
634 die "already reindexing!\n" if $self->{reindex_pipe};
635 my $git = PublicInbox::Git->new("$pfx/$cur.git");
636 -d $git->{git_dir} or next; # missing parts are fine
637 chomp($tip = $git->qx('rev-parse', $head)) unless $tip;
638 my $h = $cur == $max_git ? $tip : $head;
640 # can't use 'rev-list --count' if we use --diff-filter
641 my $fh = $git->popen(qw(log --pretty=tformat:%h
642 --no-notes --no-color --no-renames
643 --diff-filter=AM), $h, '--', 'm');
644 ++$regen_max while <$fh>;
646 die "No messages found in $pfx/*.git, bug?\n" unless $regen_max;
647 $regen = \$regen_max;
650 my @cmd = qw(log --raw -r --pretty=tformat:%h
651 --no-notes --no-color --no-abbrev --no-renames);
653 # if we are regenerating, we must not use a newer tip commit than what
654 # the regeneration counter used:
657 # work backwards through history
658 for (my $cur = $max_git; $cur >= 0; $cur--) {
659 die "already reindexing!\n" if delete $self->{reindex_pipe};
661 my $git_dir = "$pfx/$cur.git";
662 -d $git_dir or next; # missing parts are fine
663 my $git = PublicInbox::Git->new($git_dir);
664 my $h = $cur == $max_git ? $tip : $head;
665 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $h);
669 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
670 $self->reindex_oid($mm_tmp, $D, $git, $1,
672 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
673 $self->mark_deleted($D, $git, $1);
676 delete $self->{reindex_pipe};
679 if ($regen && $$regen != 0) {
680 warn "W: leftover article number ($$regen)\n";
683 my ($min, $max) = $mm_tmp->minmax;
685 warn "W: leftover article numbers at $min..$max\n";
688 warn "W: were old git partitions deleted?\n" if $gaps;
689 my @d = sort keys %$D;
691 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
693 my ($mid, undef) = split(/\0/, $_, 2);