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::SearchIdxSkeleton;
11 use PublicInbox::MIME;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids);
15 use PublicInbox::ContentId qw(content_id content_digest);
16 use PublicInbox::Inbox;
18 # an estimate of the post-packed size to the raw uncompressed size
19 my $PACKING_FACTOR = 0.4;
21 # assume 2 cores if GNU nproc(1) is not available
23 int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
27 my ($class, $v2ibx, $creat) = @_;
28 my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
32 File::Path::mkpath($dir);
34 die "$dir does not exist\n";
39 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
41 # always load existing partitions in case core count changes:
43 foreach my $part (<$xpfx/*>) {
44 -d $part && $part =~ m!/\d+\z! or next;
46 Search::Xapian::Database->new($part)->close;
51 $nparts = nproc() if ($nparts == 0);
53 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
56 im => undef, # PublicInbox::Import
57 partitions => $nparts,
60 lock_path => "$dir/inbox.lock",
61 # limit each repo to 1GB or so
62 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
68 my ($self, $parallel) = @_;
69 $self->{parallel} = $parallel;
72 git_dir_latest($self, \$max_git);
73 $self->git_init($max_git >= 0 ? $max_git : 0);
77 # returns undef on duplicate or spam
78 # mimics Import::add and wraps it for v2
80 my ($self, $mime, $check_cb) = @_;
84 $mime = $check_cb->($mime) or return;
87 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
88 # as does SQLite 3.4.1+ (released in 2007-07-20), and
89 # Xapian 1.3.2+ (released 2015-03-15).
90 # For the most part, we can spawn git-fast-import without
91 # leaking FDs to it...
95 my $num = num_for($self, $mime, \$mid0);
96 defined $num or return; # duplicate
97 defined $mid0 or die "BUG: $mid0 undefined\n";
98 my $im = $self->importer;
99 my $cmt = $im->add($mime);
100 $cmt = $im->get_mark($cmt);
101 my ($oid, $len, $msgref) = @{$im->{last_object}};
103 my $nparts = $self->{partitions};
104 my $part = $num % $nparts;
105 my $idx = $self->idx_part($part);
106 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
107 my $n = $self->{transact_bytes} += $len;
108 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
116 my ($self, $mime, $mid0) = @_;
117 my $mids = mids($mime->header_obj);
119 my $mid = $mids->[0];
120 my $num = $self->{skel}->{mm}->mid_insert($mid);
121 if (defined $num) { # common case
126 # crap, Message-ID is already known, hope somebody just resent:
128 foreach my $m (@$mids) {
129 # read-only lookup now safe to do after above barrier
130 my $existing = $self->lookup_content($mime, $m);
131 # easy, don't store duplicates
132 # note: do not add more diagnostic info here since
133 # it gets noisy on public-inbox-watch restarts
138 warn "<$mid> reused for mismatched content\n";
140 # try the rest of the mids
141 for(my $i = $#$mids; $i >= 1; $i--) {
143 $num = $self->{skel}->{mm}->mid_insert($m);
145 warn "alternative <$m> for <$mid> found\n";
151 # none of the existing Message-IDs are good, generate a new one:
152 num_for_harder($self, $mime, $mid0);
156 my ($self, $mime, $mid0) = @_;
158 my $hdr = $mime->header_obj;
159 my $dig = content_digest($mime);
160 $$mid0 = PublicInbox::Import::digest2mid($dig);
161 my $num = $self->{skel}->{mm}->mid_insert($$mid0);
162 unless (defined $num) {
163 # it's hard to spoof the last Received: header
164 my @recvd = $hdr->header_raw('Received');
165 $dig->add("Received: $_") foreach (@recvd);
166 $$mid0 = PublicInbox::Import::digest2mid($dig);
167 $num = $self->{skel}->{mm}->mid_insert($$mid0);
169 # fall back to a random Message-ID and give up determinism:
170 until (defined($num)) {
172 $$mid0 = PublicInbox::Import::digest2mid($dig);
173 warn "using random Message-ID <$$mid0> as fallback\n";
174 $num = $self->{skel}->{mm}->mid_insert($$mid0);
177 PublicInbox::Import::append_mid($hdr, $$mid0);
182 my ($self, $part) = @_;
183 $self->{idx_parts}->[$part];
189 return if $self->{idx_parts};
190 my $ibx = $self->{-inbox};
192 # do not leak read-only FDs to child processes, we only have these
193 # FDs for duplicate detection so they should not be
194 # frequently activated.
195 delete $ibx->{$_} foreach (qw(git mm search));
198 $ibx->with_umask(sub {
201 # first time initialization, first we create the skeleton pipe:
202 my $skel = PublicInbox::SearchIdxSkeleton->new($self);
203 $self->{skel} = $skel;
205 # need to create all parts before initializing msgmap FD
206 my $max = $self->{partitions} - 1;
207 @{$self->{idx_parts}} = map {
208 PublicInbox::SearchIdxPart->new($self, $_, $skel);
211 # Now that all subprocesses are up, we can open the FD for SQLite:
212 $skel->_msgmap_init->{dbh}->begin_work;
217 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
219 my $pfx = "$self->{-inbox}->{mainrepo}/git";
220 foreach my $i (0..$self->{max_git}) {
221 my $git = PublicInbox::Git->new("$pfx/$i.git");
222 my $im = $self->import_init($git, 0);
223 $im->purge_oids($purge);
227 sub remove_internal {
228 my ($self, $mime, $cmt_msg, $purge) = @_;
231 my $im = $self->importer unless $purge;
232 my $ibx = $self->{-inbox};
233 my $srch = $ibx->search;
234 my $cid = content_id($mime);
235 my $skel = $self->{skel};
236 my $parts = $self->{idx_parts};
237 my $mm = $skel->{mm};
239 my $mids = mids($mime->header_obj);
241 # We avoid introducing new blobs into git since the raw content
242 # can be slightly different, so we do not need the user-supplied
243 # message now that we have the mids and content_id
246 foreach my $mid (@$mids) {
247 $srch->reopen->each_smsg_by_mid($mid, sub {
250 my $msg = $ibx->msg_by_smsg($smsg);
251 if (!defined($msg)) {
252 warn "broken smsg for $mid\n";
256 my $cur = PublicInbox::MIME->new($msg);
257 if (content_id($cur) eq $cid) {
258 $mm->num_delete($smsg->num);
259 # $removed should only be set once assuming
260 # no bugs in our deduplication code:
262 $removed->{mime} = $cur;
263 my $oid = $smsg->{blob};
267 $im->remove(\$orig, $cmt_msg);
270 $removed->num; # memoize this for callers
272 foreach my $idx (@$parts, $skel) {
273 $idx->remote_remove($oid, $mid);
280 if ($purge && scalar keys %$purge) {
281 purge_oids($self, $purge);
287 my ($self, $mime, $cmt_msg) = @_;
288 remove_internal($self, $mime, $cmt_msg);
292 my ($self, $mime) = @_;
293 remove_internal($self, $mime, undef, {});
299 my $locked = defined $self->{idx_parts};
300 my $im = delete $self->{im};
301 $im->done if $im; # PublicInbox::Import::done
302 $self->searchidx_checkpoint(0);
303 $self->lock_release if $locked;
308 my $im = $self->{im};
309 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
310 $self->searchidx_checkpoint(1);
313 # issue a write barrier to ensure all data is visible to other processes
314 # and read-only ops. Order of data importance is: git > SQLite > Xapian
318 if (my $im = $self->{im}) {
321 my $skel = $self->{skel};
322 my $parts = $self->{idx_parts};
323 if ($parts && $skel) {
324 my $dbh = $skel->{mm}->{dbh};
325 $dbh->commit; # SQLite data is second in importance
327 # Now deal with Xapian
328 $skel->barrier_init(scalar(@$parts));
329 # each partition needs to issue a barrier command to skel:
330 $_->remote_barrier foreach @$parts;
332 $skel->barrier_wait; # wait for each Xapian partition
336 $self->{transact_bytes} = 0;
339 sub searchidx_checkpoint {
340 my ($self, $more) = @_;
342 # order matters, we can only close {skel} after all partitions
343 # are done because the partitions also write to {skel}
344 if (my $parts = $self->{idx_parts}) {
345 foreach my $idx (@$parts) {
346 $idx->remote_commit; # propagates commit to skel
347 $idx->remote_close unless $more;
349 delete $self->{idx_parts} unless $more;
352 if (my $skel = $self->{skel}) {
353 my $dbh = $skel->{mm}->{dbh};
359 delete $self->{skel};
362 $self->{transact_bytes} = 0;
366 my ($self, $new) = @_;
367 my $pfx = "$self->{-inbox}->{mainrepo}/git";
368 my $git_dir = "$pfx/$new.git";
369 my @cmd = (qw(git init --bare -q), $git_dir);
370 PublicInbox::Import::run_die(\@cmd);
372 my $all = "$self->{-inbox}->{mainrepo}/all.git";
374 @cmd = (qw(git init --bare -q), $all);
375 PublicInbox::Import::run_die(\@cmd);
376 @cmd = (qw/git config/, "--file=$all/config",
377 'repack.writeBitmaps', 'true');
378 PublicInbox::Import::run_die(\@cmd);
381 @cmd = (qw/git config/, "--file=$git_dir/config",
382 'include.path', '../../all.git/config');
383 PublicInbox::Import::run_die(\@cmd);
385 my $alt = "$all/objects/info/alternates";
386 my $new_obj_dir = "../../git/$new.git/objects";
389 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
390 %alts = map { chomp; $_ => 1 } (<$fh>);
392 return $git_dir if $alts{$new_obj_dir};
393 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
394 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
395 close $fh or die "close $alt: $!\n";
400 my ($self, $max) = @_;
402 my $pfx = "$self->{-inbox}->{mainrepo}/git";
403 return unless -d $pfx;
405 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
406 while (defined(my $git_dir = readdir($dh))) {
407 $git_dir =~ m!\A(\d+)\.git\z! or next;
410 $latest = "$pfx/$git_dir";
418 my $im = $self->{im};
420 if ($im->{bytes_added} < $self->{rotate_bytes}) {
425 $self->searchidx_checkpoint(1);
427 my $git_dir = $self->git_init(++$self->{max_git});
428 my $git = PublicInbox::Git->new($git_dir);
429 return $self->import_init($git, 0);
434 my $latest = git_dir_latest($self, \$max);
435 if (defined $latest) {
436 my $git = PublicInbox::Git->new($latest);
437 my $packed_bytes = $git->packed_bytes;
438 if ($packed_bytes >= $self->{rotate_bytes}) {
441 $self->{max_git} = $max;
442 return $self->import_init($git, $packed_bytes);
445 $self->{max_git} = $new;
446 $latest = $self->git_init($new);
447 $self->import_init(PublicInbox::Git->new($latest), 0);
451 my ($self, $git, $packed_bytes) = @_;
452 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
453 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
454 $im->{want_object_info} = 1;
455 $im->{lock_path} = undef;
456 $im->{path_type} = 'v2';
462 my ($mid, $cur, $new) = @_;
463 use File::Temp qw(tempfile);
464 use PublicInbox::Spawn qw(spawn);
466 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
467 print $ah $cur->as_string or die "print: $!";
468 close $ah or die "close: $!";
469 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
470 PublicInbox::Import::drop_unwanted_headers($new);
471 print $bh $new->as_string or die "print: $!";
472 close $bh or die "close: $!";
473 my $cmd = [ qw(diff -u), $an, $bn ];
474 print STDERR "# MID conflict <$mid>\n";
475 my $pid = spawn($cmd, undef, { 1 => 2 });
476 defined $pid or die "diff failed to spawn $!";
477 waitpid($pid, 0) == $pid or die "diff did not finish";
482 my ($self, $mime, $mid) = @_;
483 my $ibx = $self->{-inbox};
485 my $srch = $ibx->search->reopen;
486 my $cid = content_id($mime);
488 $srch->each_smsg_by_mid($mid, sub {
491 my $msg = $ibx->msg_by_smsg($smsg);
492 if (!defined($msg)) {
493 warn "broken smsg for $mid\n";
496 my $cur = PublicInbox::MIME->new($msg);
497 if (content_id($cur) eq $cid) {
498 $smsg->{mime} = $cur;
500 return 0; # break out of loop
503 # XXX DEBUG_DIFF is experimental and may be removed
504 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
513 my $fh = delete $self->{reindex_pipe};
515 if (my $parts = $self->{idx_parts}) {
516 $_->atfork_child foreach @$parts;
518 if (my $im = $self->{im}) {
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->{skel}->{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->{skel}->{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;
637 my @count = ('rev-list', '--count', $h, '--', 'm');
638 $regen_max += $git->qx(@count);
640 die "No messages found in $pfx/*.git, bug?\n" unless $regen_max;
641 $regen = \$regen_max;
644 my @cmd = qw(log --raw -r --pretty=tformat:%h
645 --no-notes --no-color --no-abbrev);
647 # if we are regenerating, we must not use a newer tip commit than what
648 # the regeneration counter used:
651 # work backwards through history
652 for (my $cur = $max_git; $cur >= 0; $cur--) {
653 die "already reindexing!\n" if delete $self->{reindex_pipe};
655 my $git_dir = "$pfx/$cur.git";
656 -d $git_dir or next; # missing parts are fine
657 my $git = PublicInbox::Git->new($git_dir);
658 my $h = $cur == $max_git ? $tip : $head;
659 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $h);
663 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
664 $self->reindex_oid($mm_tmp, $D, $git, $1,
666 } elsif (m!\A:\d{6} 100644 $x40 ($x40) [AM]\t_/D$!o) {
667 $self->mark_deleted($D, $git, $1);
670 delete $self->{reindex_pipe};
673 if ($regen && $$regen != 0) {
674 warn "W: leftover article number ($$regen)\n";
677 my ($min, $max) = $mm_tmp->minmax;
679 warn "W: leftover article numbers at $min..$max\n";
682 warn "W: were old git partitions deleted?\n" if $gaps;
683 my @d = sort keys %$D;
685 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
687 my ($mid, undef) = split(/\0/, $_, 2);