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);
55 im => undef, # PublicInbox::Import
56 partitions => $nparts,
59 lock_path => "$dir/inbox.lock",
60 # limit each repo to 1GB or so
61 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
67 my ($self, $parallel) = @_;
68 $self->{parallel} = $parallel;
74 # returns undef on duplicate or spam
75 # mimics Import::add and wraps it for v2
77 my ($self, $mime, $check_cb) = @_;
81 $mime = $check_cb->($mime) or return;
84 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
85 # as does SQLite 3.4.1+ (released in 2007-07-20), and
86 # Xapian 1.3.2+ (released 2015-03-15).
87 # For the most part, we can spawn git-fast-import without
88 # leaking FDs to it...
92 my $num = num_for($self, $mime, \$mid0);
93 defined $num or return; # duplicate
94 defined $mid0 or die "BUG: $mid0 undefined\n";
95 my $im = $self->importer;
96 my $cmt = $im->add($mime);
97 $cmt = $im->get_mark($cmt);
98 my ($oid, $len, $msgref) = @{$im->{last_object}};
100 my $nparts = $self->{partitions};
101 my $part = $num % $nparts;
102 my $idx = $self->idx_part($part);
103 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
104 my $n = $self->{transact_bytes} += $len;
105 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
113 my ($self, $mime, $mid0) = @_;
114 my $mids = mids($mime->header_obj);
116 my $mid = $mids->[0];
117 my $num = $self->{skel}->{mm}->mid_insert($mid);
118 if (defined $num) { # common case
123 # crap, Message-ID is already known, hope somebody just resent:
125 foreach my $m (@$mids) {
126 # read-only lookup now safe to do after above barrier
127 my $existing = $self->lookup_content($mime, $m);
128 # easy, don't store duplicates
129 # note: do not add more diagnostic info here since
130 # it gets noisy on public-inbox-watch restarts
135 warn "<$mid> reused for mismatched content\n";
137 # try the rest of the mids
138 foreach my $i (1..$#$mids) {
140 $num = $self->{skel}->{mm}->mid_insert($m);
142 warn "alternative <$m> for <$mid> found\n";
148 # none of the existing Message-IDs are good, generate a new one:
149 num_for_harder($self, $mime, $mid0);
153 my ($self, $mime, $mid0) = @_;
155 my $hdr = $mime->header_obj;
156 my $dig = content_digest($mime);
157 $$mid0 = PublicInbox::Import::digest2mid($dig);
158 my $num = $self->{skel}->{mm}->mid_insert($$mid0);
159 unless (defined $num) {
160 # it's hard to spoof the last Received: header
161 my @recvd = $hdr->header_raw('Received');
162 $dig->add("Received: $_") foreach (@recvd);
163 $$mid0 = PublicInbox::Import::digest2mid($dig);
164 $num = $self->{skel}->{mm}->mid_insert($$mid0);
166 # fall back to a random Message-ID and give up determinism:
167 until (defined($num)) {
169 $$mid0 = PublicInbox::Import::digest2mid($dig);
170 warn "using random Message-ID <$$mid0> as fallback\n";
171 $num = $self->{skel}->{mm}->mid_insert($$mid0);
174 PublicInbox::Import::append_mid($hdr, $$mid0);
179 my ($self, $part) = @_;
180 $self->{idx_parts}->[$part];
186 return if $self->{idx_parts};
187 my $ibx = $self->{-inbox};
189 # do not leak read-only FDs to child processes, we only have these
190 # FDs for duplicate detection so they should not be
191 # frequently activated.
192 delete $ibx->{$_} foreach (qw(git mm search));
196 # first time initialization, first we create the skeleton pipe:
197 my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
199 # need to create all parts before initializing msgmap FD
200 my $max = $self->{partitions} - 1;
201 my $idx = $self->{idx_parts} = [];
202 for my $i (0..$max) {
203 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
206 # Now that all subprocesses are up, we can open the FD for SQLite:
207 $skel->_msgmap_init->{dbh}->begin_work;
211 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
213 my $pfx = "$self->{-inbox}->{mainrepo}/git";
214 foreach my $i (0..$self->{max_git}) {
215 my $git = PublicInbox::Git->new("$pfx/$i.git");
216 my $im = $self->import_init($git, 0);
217 $im->purge_oids($purge);
221 sub remove_internal {
222 my ($self, $mime, $cmt_msg, $purge) = @_;
225 my $im = $self->importer unless $purge;
226 my $ibx = $self->{-inbox};
227 my $srch = $ibx->search;
228 my $cid = content_id($mime);
229 my $skel = $self->{skel};
230 my $parts = $self->{idx_parts};
231 my $mm = $skel->{mm};
233 my $mids = mids($mime->header_obj);
235 # We avoid introducing new blobs into git since the raw content
236 # can be slightly different, so we do not need the user-supplied
237 # message now that we have the mids and content_id
240 foreach my $mid (@$mids) {
241 $srch->reopen->each_smsg_by_mid($mid, sub {
244 my $msg = $ibx->msg_by_smsg($smsg);
245 if (!defined($msg)) {
246 warn "broken smsg for $mid\n";
250 my $cur = PublicInbox::MIME->new($msg);
251 if (content_id($cur) eq $cid) {
252 $mm->num_delete($smsg->num);
253 # $removed should only be set once assuming
254 # no bugs in our deduplication code:
256 $removed->{mime} = $cur;
257 my $oid = $smsg->{blob};
261 $im->remove(\$orig, $cmt_msg);
264 $removed->num; # memoize this for callers
266 foreach my $idx (@$parts, $skel) {
267 $idx->remote_remove($oid, $mid);
274 if ($purge && scalar keys %$purge) {
275 purge_oids($self, $purge);
281 my ($self, $mime, $cmt_msg) = @_;
282 remove_internal($self, $mime, $cmt_msg);
286 my ($self, $mime) = @_;
287 remove_internal($self, $mime, undef, {});
293 my $locked = defined $self->{idx_parts};
294 my $im = delete $self->{im};
295 $im->done if $im; # PublicInbox::Import::done
296 $self->searchidx_checkpoint(0);
297 $self->lock_release if $locked;
302 my $im = $self->{im};
303 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
304 $self->searchidx_checkpoint(1);
307 # issue a write barrier to ensure all data is visible to other processes
308 # and read-only ops. Order of data importance is: git > SQLite > Xapian
312 if (my $im = $self->{im}) {
315 my $skel = $self->{skel};
316 my $parts = $self->{idx_parts};
317 if ($parts && $skel) {
318 my $dbh = $skel->{mm}->{dbh};
319 $dbh->commit; # SQLite data is second in importance
321 # Now deal with Xapian
322 $skel->barrier_init(scalar(@$parts));
323 # each partition needs to issue a barrier command to skel:
324 $_->remote_barrier foreach @$parts;
326 $skel->barrier_wait; # wait for each Xapian partition
330 $self->{transact_bytes} = 0;
333 sub searchidx_checkpoint {
334 my ($self, $more) = @_;
336 # order matters, we can only close {skel} after all partitions
337 # are done because the partitions also write to {skel}
338 if (my $parts = $self->{idx_parts}) {
339 foreach my $idx (@$parts) {
340 $idx->remote_commit; # propagates commit to skel
341 $idx->remote_close unless $more;
343 delete $self->{idx_parts} unless $more;
346 if (my $skel = $self->{skel}) {
347 my $dbh = $skel->{mm}->{dbh};
353 delete $self->{skel};
356 $self->{transact_bytes} = 0;
360 my ($self, $new) = @_;
361 my $pfx = "$self->{-inbox}->{mainrepo}/git";
362 my $git_dir = "$pfx/$new.git";
363 die "$git_dir exists\n" if -e $git_dir;
364 my @cmd = (qw(git init --bare -q), $git_dir);
365 PublicInbox::Import::run_die(\@cmd);
367 my $all = "$self->{-inbox}->{mainrepo}/all.git";
369 @cmd = (qw(git init --bare -q), $all);
370 PublicInbox::Import::run_die(\@cmd);
371 @cmd = (qw/git config/, "--file=$all/config",
372 'repack.writeBitmaps', 'true');
373 PublicInbox::Import::run_die(\@cmd);
376 @cmd = (qw/git config/, "--file=$git_dir/config",
377 'include.path', '../../all.git/config');
378 PublicInbox::Import::run_die(\@cmd);
380 my $alt = "$all/objects/info/alternates";
381 my $new_obj_dir = "../../git/$new.git/objects";
384 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
385 %alts = map { chomp; $_ => 1 } (<$fh>);
387 return $git_dir if $alts{$new_obj_dir};
388 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
389 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
390 close $fh or die "close $alt: $!\n";
395 my ($self, $max) = @_;
397 my $pfx = "$self->{-inbox}->{mainrepo}/git";
398 return unless -d $pfx;
400 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
401 while (defined(my $git_dir = readdir($dh))) {
402 $git_dir =~ m!\A(\d+)\.git\z! or next;
405 $latest = "$pfx/$git_dir";
413 my $im = $self->{im};
415 if ($im->{bytes_added} < $self->{rotate_bytes}) {
420 $self->searchidx_checkpoint(1);
422 my $git_dir = $self->git_init(++$self->{max_git});
423 my $git = PublicInbox::Git->new($git_dir);
424 return $self->import_init($git, 0);
429 my $latest = git_dir_latest($self, \$max);
430 if (defined $latest) {
431 my $git = PublicInbox::Git->new($latest);
432 my $packed_bytes = $git->packed_bytes;
433 if ($packed_bytes >= $self->{rotate_bytes}) {
436 $self->{max_git} = $max;
437 return $self->import_init($git, $packed_bytes);
440 $self->{max_git} = $new;
441 $latest = $self->git_init($new);
442 $self->import_init(PublicInbox::Git->new($latest), 0);
446 my ($self, $git, $packed_bytes) = @_;
447 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
448 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
449 $im->{want_object_info} = 1;
450 $im->{lock_path} = undef;
451 $im->{path_type} = 'v2';
457 my ($mid, $cur, $new) = @_;
458 use File::Temp qw(tempfile);
459 use PublicInbox::Spawn qw(spawn);
461 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
462 print $ah $cur->as_string or die "print: $!";
463 close $ah or die "close: $!";
464 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
465 PublicInbox::Import::drop_unwanted_headers($new);
466 print $bh $new->as_string or die "print: $!";
467 close $bh or die "close: $!";
468 my $cmd = [ qw(diff -u), $an, $bn ];
469 print STDERR "# MID conflict <$mid>\n";
470 my $pid = spawn($cmd, undef, { 1 => 2 });
471 defined $pid or die "diff failed to spawn $!";
472 waitpid($pid, 0) == $pid or die "diff did not finish";
477 my ($self, $mime, $mid) = @_;
478 my $ibx = $self->{-inbox};
480 my $srch = $ibx->search->reopen;
481 my $cid = content_id($mime);
483 $srch->each_smsg_by_mid($mid, sub {
486 my $msg = $ibx->msg_by_smsg($smsg);
487 if (!defined($msg)) {
488 warn "broken smsg for $mid\n";
491 my $cur = PublicInbox::MIME->new($msg);
492 if (content_id($cur) eq $cid) {
493 $smsg->{mime} = $cur;
495 return 0; # break out of loop
498 # XXX DEBUG_DIFF is experimental and may be removed
499 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
508 my $fh = delete $self->{reindex_pipe};
510 if (my $parts = $self->{idx_parts}) {
511 $_->atfork_child foreach @$parts;
513 if (my $im = $self->{im}) {
519 my ($self, $D, $git, $oid) = @_;
520 my $msgref = $git->cat_file($oid);
521 my $mime = PublicInbox::MIME->new($$msgref);
522 my $mids = mids($mime->header_obj);
523 my $cid = content_id($mime);
524 foreach my $mid (@$mids) {
525 $D->{"$mid\0$cid"} = 1;
530 my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
532 my $msgref = $git->cat_file($oid, \$len);
533 my $mime = PublicInbox::MIME->new($$msgref);
534 my $mids = mids($mime->header_obj);
535 my $cid = content_id($mime);
537 # get the NNTP article number we used before, highest number wins
538 # and gets deleted from mm_tmp;
542 foreach my $mid (@$mids) {
543 $del += (delete $D->{"$mid\0$cid"} || 0);
544 my $n = $mm_tmp->num_for($mid);
545 if (defined $n && $n > $num) {
550 if (!defined($mid0) && $regen && !$del) {
552 die "BUG: ran out of article numbers\n" if $num <= 0;
553 my $mm = $self->{skel}->{mm};
554 foreach my $mid (@$mids) {
555 if ($mm->mid_set($num, $mid) == 1) {
560 if (!defined($mid0)) {
561 my $id = '<' . join('> <', @$mids) . '>';
562 warn "Message-Id $id unusable for $num\n";
566 if (!defined($mid0) || $del) {
567 if (!defined($mid0) && $del) { # expected for deletes
572 my $id = '<' . join('> <', @$mids) . '>';
574 warn "Skipping $id, no article number found\n";
575 if ($del && defined($mid0)) {
576 warn "$id was deleted $del " .
577 "time(s) but mapped to article #$num\n";
582 $mm_tmp->mid_delete($mid0) or
583 die "failed to delete <$mid0> for article #$num\n";
585 my $nparts = $self->{partitions};
586 my $part = $num % $nparts;
587 my $idx = $self->idx_part($part);
588 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
589 my $n = $self->{transact_bytes} += $len;
590 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
592 $mm_tmp->atfork_prepare;
593 $self->done; # release lock
594 # allow -watch or -mda to write...
595 $self->idx_init; # reacquire lock
596 $mm_tmp->atfork_parent;
601 my ($self, $regen) = @_;
602 my $ibx = $self->{-inbox};
603 my $pfx = "$ibx->{mainrepo}/git";
605 my $latest = git_dir_latest($self, \$max_git);
606 return unless defined $latest;
607 my $head = $ibx->{ref_head} || 'refs/heads/master';
608 $self->idx_init; # acquire lock
609 my $x40 = qr/[a-f0-9]{40}/;
610 my $mm_tmp = $self->{skel}->{mm}->tmp_clone;
612 my (undef, $max) = $mm_tmp->minmax;
613 unless (defined $max) {
616 "empty msgmap.sqlite3, regenerating article numbers\n";
619 my $tip; # latest commit out of all git repos
622 for (my $cur = $max_git; $cur >= 0; $cur--) {
623 die "already reindexing!\n" if $self->{reindex_pipe};
624 my $git = PublicInbox::Git->new("$pfx/$cur.git");
625 chomp($tip = $git->qx('rev-parse', $head)) unless $tip;
626 my $h = $cur == $max_git ? $tip : $head;
627 my @count = ('rev-list', '--count', $h, '--', 'm');
628 $regen_max += $git->qx(@count);
630 die "No messages found in $pfx/*.git, bug?\n" unless $regen_max;
631 $regen = \$regen_max;
634 my @cmd = qw(log --raw -r --pretty=tformat:%h
635 --no-notes --no-color --no-abbrev);
637 # if we are regenerating, we must not use a newer tip commit than what
638 # the regeneration counter used:
641 # work backwards through history
642 for (my $cur = $max_git; $cur >= 0; $cur--) {
643 die "already reindexing!\n" if delete $self->{reindex_pipe};
645 my $git_dir = "$pfx/$cur.git";
646 my $git = PublicInbox::Git->new($git_dir);
647 my $h = $cur == $max_git ? $tip : $head;
648 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $h);
652 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
653 $self->reindex_oid($mm_tmp, $D, $git, $1,
655 } elsif (m!\A:\d{6} 100644 $x40 ($x40) [AM]\t_/D$!o) {
656 $self->mark_deleted($D, $git, $1);
659 delete $self->{reindex_pipe};
661 my ($min, $max) = $mm_tmp->minmax;
662 defined $max and die "leftover article numbers at $min..$max\n";
663 my @d = sort keys %$D;
665 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
667 my ($mid, undef) = split(/\0/, $_, 2);