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";
227 foreach my $i (0..$self->{max_git}) {
228 my $git = PublicInbox::Git->new("$pfx/$i.git");
229 my $im = $self->import_init($git, 0);
230 $im->purge_oids($purge);
234 sub remove_internal {
235 my ($self, $mime, $cmt_msg, $purge) = @_;
238 my $im = $self->importer unless $purge;
239 my $ibx = $self->{-inbox};
240 my $srch = $ibx->search;
241 my $cid = content_id($mime);
242 my $parts = $self->{idx_parts};
243 my $mm = $self->{mm};
245 my $mids = mids($mime->header_obj);
247 # We avoid introducing new blobs into git since the raw content
248 # can be slightly different, so we do not need the user-supplied
249 # message now that we have the mids and content_id
252 foreach my $mid (@$mids) {
253 $srch->reopen->each_smsg_by_mid($mid, sub {
256 my $msg = $ibx->msg_by_smsg($smsg);
257 if (!defined($msg)) {
258 warn "broken smsg for $mid\n";
262 my $cur = PublicInbox::MIME->new($msg);
263 if (content_id($cur) eq $cid) {
264 $mm->num_delete($smsg->num);
265 # $removed should only be set once assuming
266 # no bugs in our deduplication code:
268 $removed->{mime} = $cur;
269 my $oid = $smsg->{blob};
273 $im->remove(\$orig, $cmt_msg);
276 $removed->num; # memoize this for callers
278 foreach my $idx (@$parts) {
279 $idx->remote_remove($oid, $mid);
281 $self->{over}->remove_oid($oid, $mid);
287 if ($purge && scalar keys %$purge) {
288 purge_oids($self, $purge);
294 my ($self, $mime, $cmt_msg) = @_;
295 remove_internal($self, $mime, $cmt_msg);
299 my ($self, $mime) = @_;
300 remove_internal($self, $mime, undef, {});
306 my $im = delete $self->{im};
307 $im->done if $im; # PublicInbox::Import::done
309 if (my $mm = delete $self->{mm}) {
313 # order matters, we can only close {over} after all partitions
314 # are done because the partitions also write to {over}
315 my $parts = delete $self->{idx_parts};
317 $_->remote_commit for @$parts;
318 $_->remote_close for @$parts;
321 my $over = $self->{over};
322 $over->remote_commit;
324 $self->{transact_bytes} = 0;
325 $self->lock_release if $parts;
330 my $im = $self->{im};
331 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
335 # issue a write barrier to ensure all data is visible to other processes
336 # and read-only ops. Order of data importance is: git > SQLite > Xapian
338 my ($self, $fsync) = @_;
340 if (my $im = $self->{im}) {
343 my $parts = $self->{idx_parts};
345 my $dbh = $self->{mm}->{dbh};
346 $dbh->commit; # SQLite msgmap data is second in importance
348 my $over = $self->{over};
350 # Now deal with Xapian and overview DB
351 $over->barrier_init(scalar(@$parts));
353 # each partition needs to issue a barrier command to over
354 $_->remote_barrier foreach @$parts;
356 $over->barrier_wait; # wait for each Xapian partition
357 $over->commit_fsync if $fsync;
361 $self->{transact_bytes} = 0;
365 my ($self, $new) = @_;
366 my $pfx = "$self->{-inbox}->{mainrepo}/git";
367 my $git_dir = "$pfx/$new.git";
368 my @cmd = (qw(git init --bare -q), $git_dir);
369 PublicInbox::Import::run_die(\@cmd);
371 my $all = "$self->{-inbox}->{mainrepo}/all.git";
373 @cmd = (qw(git init --bare -q), $all);
374 PublicInbox::Import::run_die(\@cmd);
375 @cmd = (qw/git config/, "--file=$all/config",
376 'repack.writeBitmaps', 'true');
377 PublicInbox::Import::run_die(\@cmd);
380 @cmd = (qw/git config/, "--file=$git_dir/config",
381 'include.path', '../../all.git/config');
382 PublicInbox::Import::run_die(\@cmd);
384 my $alt = "$all/objects/info/alternates";
385 my $new_obj_dir = "../../git/$new.git/objects";
388 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
389 %alts = map { chomp; $_ => 1 } (<$fh>);
391 return $git_dir if $alts{$new_obj_dir};
392 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
393 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
394 close $fh or die "close $alt: $!\n";
399 my ($self, $max) = @_;
401 my $pfx = "$self->{-inbox}->{mainrepo}/git";
402 return unless -d $pfx;
404 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
405 while (defined(my $git_dir = readdir($dh))) {
406 $git_dir =~ m!\A(\d+)\.git\z! or next;
409 $latest = "$pfx/$git_dir";
417 my $im = $self->{im};
419 if ($im->{bytes_added} < $self->{rotate_bytes}) {
426 my $git_dir = $self->git_init(++$self->{max_git});
427 my $git = PublicInbox::Git->new($git_dir);
428 return $self->import_init($git, 0);
433 my $latest = git_dir_latest($self, \$max);
434 if (defined $latest) {
435 my $git = PublicInbox::Git->new($latest);
436 my $packed_bytes = $git->packed_bytes;
437 if ($packed_bytes >= $self->{rotate_bytes}) {
440 $self->{max_git} = $max;
441 return $self->import_init($git, $packed_bytes);
444 $self->{max_git} = $new;
445 $latest = $self->git_init($new);
446 $self->import_init(PublicInbox::Git->new($latest), 0);
450 my ($self, $git, $packed_bytes) = @_;
451 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
452 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
453 $im->{want_object_info} = 1;
454 $im->{lock_path} = undef;
455 $im->{path_type} = 'v2';
461 my ($mid, $cur, $new) = @_;
462 use File::Temp qw(tempfile);
463 use PublicInbox::Spawn qw(spawn);
465 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
466 print $ah $cur->as_string or die "print: $!";
467 close $ah or die "close: $!";
468 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
469 PublicInbox::Import::drop_unwanted_headers($new);
470 print $bh $new->as_string or die "print: $!";
471 close $bh or die "close: $!";
472 my $cmd = [ qw(diff -u), $an, $bn ];
473 print STDERR "# MID conflict <$mid>\n";
474 my $pid = spawn($cmd, undef, { 1 => 2 });
475 defined $pid or die "diff failed to spawn $!";
476 waitpid($pid, 0) == $pid or die "diff did not finish";
481 my ($self, $mime, $mid) = @_;
482 my $ibx = $self->{-inbox};
484 my $srch = $ibx->search->reopen;
485 my $cid = content_id($mime);
487 $srch->each_smsg_by_mid($mid, sub {
490 my $msg = $ibx->msg_by_smsg($smsg);
491 if (!defined($msg)) {
492 warn "broken smsg for $mid\n";
495 my $cur = PublicInbox::MIME->new($msg);
496 if (content_id($cur) eq $cid) {
497 $smsg->{mime} = $cur;
499 return 0; # break out of loop
502 # XXX DEBUG_DIFF is experimental and may be removed
503 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
512 my $fh = delete $self->{reindex_pipe};
514 if (my $parts = $self->{idx_parts}) {
515 $_->atfork_child foreach @$parts;
517 if (my $im = $self->{im}) {
520 die "unexpected mm" if $self->{mm};
524 my ($self, $D, $git, $oid) = @_;
525 my $msgref = $git->cat_file($oid);
526 my $mime = PublicInbox::MIME->new($$msgref);
527 my $mids = mids($mime->header_obj);
528 my $cid = content_id($mime);
529 foreach my $mid (@$mids) {
530 $D->{"$mid\0$cid"} = 1;
535 my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
537 my $msgref = $git->cat_file($oid, \$len);
538 my $mime = PublicInbox::MIME->new($$msgref);
539 my $mids = mids($mime->header_obj);
540 my $cid = content_id($mime);
542 # get the NNTP article number we used before, highest number wins
543 # and gets deleted from mm_tmp;
547 foreach my $mid (@$mids) {
548 $del += (delete $D->{"$mid\0$cid"} || 0);
549 my $n = $mm_tmp->num_for($mid);
550 if (defined $n && $n > $num) {
555 if (!defined($mid0) && $regen && !$del) {
557 die "BUG: ran out of article numbers\n" if $num <= 0;
558 my $mm = $self->{mm};
559 foreach my $mid (reverse @$mids) {
560 if ($mm->mid_set($num, $mid) == 1) {
565 if (!defined($mid0)) {
566 my $id = '<' . join('> <', @$mids) . '>';
567 warn "Message-ID $id unusable for $num\n";
568 foreach my $mid (@$mids) {
569 defined(my $n = $mm->num_for($mid)) or next;
570 warn "#$n previously mapped for <$mid>\n";
575 if (!defined($mid0) || $del) {
576 if (!defined($mid0) && $del) { # expected for deletes
581 my $id = '<' . join('> <', @$mids) . '>';
583 warn "Skipping $id, no article number found\n";
584 if ($del && defined($mid0)) {
585 warn "$id was deleted $del " .
586 "time(s) but mapped to article #$num\n";
591 $mm_tmp->mid_delete($mid0) or
592 die "failed to delete <$mid0> for article #$num\n";
594 my $nparts = $self->{partitions};
595 my $part = $num % $nparts;
596 my $idx = $self->idx_part($part);
597 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
598 my $n = $self->{transact_bytes} += $len;
599 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
601 $mm_tmp->atfork_prepare;
602 $self->done; # release lock
603 # allow -watch or -mda to write...
604 $self->idx_init; # reacquire lock
605 $mm_tmp->atfork_parent;
610 my ($self, $regen) = @_;
611 my $ibx = $self->{-inbox};
612 my $pfx = "$ibx->{mainrepo}/git";
614 my $latest = git_dir_latest($self, \$max_git);
615 return unless defined $latest;
616 my $head = $ibx->{ref_head} || 'refs/heads/master';
617 $self->idx_init; # acquire lock
618 my $x40 = qr/[a-f0-9]{40}/;
619 my $mm_tmp = $self->{mm}->tmp_clone;
621 my (undef, $max) = $mm_tmp->minmax;
622 unless (defined $max) {
625 "empty msgmap.sqlite3, regenerating article numbers\n";
628 my $tip; # latest commit out of all git repos
631 for (my $cur = $max_git; $cur >= 0; $cur--) {
632 die "already reindexing!\n" if $self->{reindex_pipe};
633 my $git = PublicInbox::Git->new("$pfx/$cur.git");
634 -d $git->{git_dir} or next; # missing parts are fine
635 chomp($tip = $git->qx('rev-parse', $head)) unless $tip;
636 my $h = $cur == $max_git ? $tip : $head;
638 # can't use 'rev-list --count' if we use --diff-filter
639 my $fh = $git->popen(qw(log --pretty=tformat:%h
640 --no-notes --no-color --no-renames
641 --diff-filter=AM), $h, '--', 'm');
642 ++$regen_max while <$fh>;
644 die "No messages found in $pfx/*.git, bug?\n" unless $regen_max;
645 $regen = \$regen_max;
648 my @cmd = qw(log --raw -r --pretty=tformat:%h
649 --no-notes --no-color --no-abbrev --no-renames);
651 # if we are regenerating, we must not use a newer tip commit than what
652 # the regeneration counter used:
655 # work backwards through history
656 for (my $cur = $max_git; $cur >= 0; $cur--) {
657 die "already reindexing!\n" if delete $self->{reindex_pipe};
659 my $git_dir = "$pfx/$cur.git";
660 -d $git_dir or next; # missing parts are fine
661 my $git = PublicInbox::Git->new($git_dir);
662 my $h = $cur == $max_git ? $tip : $head;
663 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $h);
667 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
668 $self->reindex_oid($mm_tmp, $D, $git, $1,
670 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
671 $self->mark_deleted($D, $git, $1);
674 delete $self->{reindex_pipe};
677 if ($regen && $$regen != 0) {
678 warn "W: leftover article number ($$regen)\n";
681 my ($min, $max) = $mm_tmp->minmax;
683 warn "W: leftover article numbers at $min..$max\n";
686 warn "W: were old git partitions deleted?\n" if $gaps;
687 my @d = sort keys %$D;
689 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
691 my ($mid, undef) = split(/\0/, $_, 2);