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 xap_rw => undef, # PublicInbox::V2SearchIdx
58 partitions => $nparts,
61 lock_path => "$dir/inbox.lock",
62 # limit each repo to 1GB or so
63 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
69 my ($self, $parallel) = @_;
70 $self->{parallel} = $parallel;
76 # returns undef on duplicate or spam
77 # mimics Import::add and wraps it for v2
79 my ($self, $mime, $check_cb) = @_;
83 $mime = $check_cb->($mime) or return;
86 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
87 # as does SQLite 3.4.1+ (released in 2007-07-20), and
88 # Xapian 1.3.2+ (released 2015-03-15).
89 # For the most part, we can spawn git-fast-import without
90 # leaking FDs to it...
94 my $num = num_for($self, $mime, \$mid0);
95 defined $num or return; # duplicate
96 defined $mid0 or die "BUG: $mid0 undefined\n";
97 my $im = $self->importer;
98 my $cmt = $im->add($mime);
99 $cmt = $im->get_mark($cmt);
100 my ($oid, $len, $msgref) = @{$im->{last_object}};
102 my $nparts = $self->{partitions};
103 my $part = $num % $nparts;
104 my $idx = $self->idx_part($part);
105 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
106 my $n = $self->{transact_bytes} += $len;
107 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
115 my ($self, $mime, $mid0) = @_;
116 my $mids = mids($mime->header_obj);
118 my $mid = $mids->[0];
119 my $num = $self->{skel}->{mm}->mid_insert($mid);
120 if (defined $num) { # common case
125 # crap, Message-ID is already known, hope somebody just resent:
127 foreach my $m (@$mids) {
128 # read-only lookup now safe to do after above barrier
129 my $existing = $self->lookup_content($mime, $m);
130 # easy, don't store duplicates
131 # note: do not add more diagnostic info here since
132 # it gets noisy on public-inbox-watch restarts
137 warn "<$mid> reused for mismatched content\n";
139 # try the rest of the mids
140 foreach my $i (1..$#$mids) {
142 $num = $self->{skel}->{mm}->mid_insert($m);
144 warn "alternative <$m> for <$mid> found\n";
150 # none of the existing Message-IDs are good, generate a new one:
151 num_for_harder($self, $mime, $mid0);
155 my ($self, $mime, $mid0) = @_;
157 my $hdr = $mime->header_obj;
158 my $dig = content_digest($mime);
159 $$mid0 = PublicInbox::Import::digest2mid($dig);
160 my $num = $self->{skel}->{mm}->mid_insert($$mid0);
161 unless (defined $num) {
162 # it's hard to spoof the last Received: header
163 my @recvd = $hdr->header_raw('Received');
164 $dig->add("Received: $_") foreach (@recvd);
165 $$mid0 = PublicInbox::Import::digest2mid($dig);
166 $num = $self->{skel}->{mm}->mid_insert($$mid0);
168 # fall back to a random Message-ID and give up determinism:
169 until (defined($num)) {
171 $$mid0 = PublicInbox::Import::digest2mid($dig);
172 warn "using random Message-ID <$$mid0> as fallback\n";
173 $num = $self->{skel}->{mm}->mid_insert($$mid0);
176 PublicInbox::Import::append_mid($hdr, $$mid0);
181 my ($self, $part) = @_;
182 $self->{idx_parts}->[$part];
188 return if $self->{idx_parts};
189 my $ibx = $self->{-inbox};
191 # do not leak read-only FDs to child processes, we only have these
192 # FDs for duplicate detection so they should not be
193 # frequently activated.
194 delete $ibx->{$_} foreach (qw(git mm search));
198 # first time initialization, first we create the skeleton pipe:
199 my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
201 # need to create all parts before initializing msgmap FD
202 my $max = $self->{partitions} - 1;
203 my $idx = $self->{idx_parts} = [];
204 for my $i (0..$max) {
205 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
208 # Now that all subprocesses are up, we can open the FD for SQLite:
209 $skel->_msgmap_init->{dbh}->begin_work;
213 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
215 my $pfx = "$self->{-inbox}->{mainrepo}/git";
216 foreach my $i (0..$self->{max_git}) {
217 my $git = PublicInbox::Git->new("$pfx/$i.git");
218 my $im = $self->import_init($git, 0);
219 $im->purge_oids($purge);
223 sub remove_internal {
224 my ($self, $mime, $cmt_msg, $purge) = @_;
227 my $im = $self->importer unless $purge;
228 my $ibx = $self->{-inbox};
229 my $srch = $ibx->search;
230 my $cid = content_id($mime);
231 my $skel = $self->{skel};
232 my $parts = $self->{idx_parts};
233 my $mm = $skel->{mm};
235 my $mids = mids($mime->header_obj);
237 # We avoid introducing new blobs into git since the raw content
238 # can be slightly different, so we do not need the user-supplied
239 # message now that we have the mids and content_id
242 foreach my $mid (@$mids) {
243 $srch->reopen->each_smsg_by_mid($mid, sub {
246 my $msg = $ibx->msg_by_smsg($smsg);
247 if (!defined($msg)) {
248 warn "broken smsg for $mid\n";
252 my $cur = PublicInbox::MIME->new($msg);
253 if (content_id($cur) eq $cid) {
254 $mm->num_delete($smsg->num);
255 # $removed should only be set once assuming
256 # no bugs in our deduplication code:
258 $removed->{mime} = $cur;
259 my $oid = $smsg->{blob};
263 $im->remove(\$orig, $cmt_msg);
266 $removed->num; # memoize this for callers
268 foreach my $idx (@$parts, $skel) {
269 $idx->remote_remove($oid, $mid);
276 if ($purge && scalar keys %$purge) {
277 purge_oids($self, $purge);
283 my ($self, $mime, $cmt_msg) = @_;
284 remove_internal($self, $mime, $cmt_msg);
288 my ($self, $mime) = @_;
289 remove_internal($self, $mime, undef, {});
295 my $locked = defined $self->{idx_parts};
296 my $im = delete $self->{im};
297 $im->done if $im; # PublicInbox::Import::done
298 $self->searchidx_checkpoint(0);
299 $self->lock_release if $locked;
304 my $im = $self->{im};
305 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
306 $self->searchidx_checkpoint(1);
309 # issue a write barrier to ensure all data is visible to other processes
310 # and read-only ops. Order of data importance is: git > SQLite > Xapian
314 if (my $im = $self->{im}) {
317 my $skel = $self->{skel};
318 my $parts = $self->{idx_parts};
319 if ($parts && $skel) {
320 my $dbh = $skel->{mm}->{dbh};
321 $dbh->commit; # SQLite data is second in importance
323 # Now deal with Xapian
324 $skel->barrier_init(scalar(@$parts));
325 # each partition needs to issue a barrier command to skel:
326 $_->remote_barrier foreach @$parts;
328 $skel->barrier_wait; # wait for each Xapian partition
332 $self->{transact_bytes} = 0;
335 sub searchidx_checkpoint {
336 my ($self, $more) = @_;
338 # order matters, we can only close {skel} after all partitions
339 # are done because the partitions also write to {skel}
340 if (my $parts = $self->{idx_parts}) {
341 foreach my $idx (@$parts) {
342 $idx->remote_commit; # propagates commit to skel
343 $idx->remote_close unless $more;
345 delete $self->{idx_parts} unless $more;
348 if (my $skel = $self->{skel}) {
349 my $dbh = $skel->{mm}->{dbh};
355 delete $self->{skel};
358 $self->{transact_bytes} = 0;
362 my ($self, $new) = @_;
363 my $pfx = "$self->{-inbox}->{mainrepo}/git";
364 my $git_dir = "$pfx/$new.git";
365 die "$git_dir exists\n" if -e $git_dir;
366 my @cmd = (qw(git init --bare -q), $git_dir);
367 PublicInbox::Import::run_die(\@cmd);
369 my $all = "$self->{-inbox}->{mainrepo}/all.git";
371 @cmd = (qw(git init --bare -q), $all);
372 PublicInbox::Import::run_die(\@cmd);
373 @cmd = (qw/git config/, "--file=$all/config",
374 'repack.writeBitmaps', 'true');
375 PublicInbox::Import::run_die(\@cmd);
378 @cmd = (qw/git config/, "--file=$git_dir/config",
379 'include.path', '../../all.git/config');
380 PublicInbox::Import::run_die(\@cmd);
382 my $alt = "$all/objects/info/alternates";
383 my $new_obj_dir = "../../git/$new.git/objects";
386 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
387 %alts = map { chomp; $_ => 1 } (<$fh>);
389 return $git_dir if $alts{$new_obj_dir};
390 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
391 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
392 close $fh or die "close $alt: $!\n";
397 my ($self, $max) = @_;
399 my $pfx = "$self->{-inbox}->{mainrepo}/git";
400 return unless -d $pfx;
402 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
403 while (defined(my $git_dir = readdir($dh))) {
404 $git_dir =~ m!\A(\d+)\.git\z! or next;
407 $latest = "$pfx/$git_dir";
415 my $im = $self->{im};
417 if ($im->{bytes_added} < $self->{rotate_bytes}) {
422 $self->searchidx_checkpoint(1);
424 my $git_dir = $self->git_init(++$self->{max_git});
425 my $git = PublicInbox::Git->new($git_dir);
426 return $self->import_init($git, 0);
431 my $latest = git_dir_latest($self, \$max);
432 if (defined $latest) {
433 my $git = PublicInbox::Git->new($latest);
434 my $packed_bytes = $git->packed_bytes;
435 if ($packed_bytes >= $self->{rotate_bytes}) {
438 $self->{max_git} = $max;
439 return $self->import_init($git, $packed_bytes);
442 $self->{max_git} = $new;
443 $latest = $self->git_init($new);
444 $self->import_init(PublicInbox::Git->new($latest), 0);
448 my ($self, $git, $packed_bytes) = @_;
449 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
450 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
451 $im->{want_object_info} = 1;
452 $im->{lock_path} = undef;
453 $im->{path_type} = 'v2';
459 my ($mid, $cur, $new) = @_;
460 use File::Temp qw(tempfile);
461 use PublicInbox::Spawn qw(spawn);
463 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
464 print $ah $cur->as_string or die "print: $!";
465 close $ah or die "close: $!";
466 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
467 PublicInbox::Import::drop_unwanted_headers($new);
468 print $bh $new->as_string or die "print: $!";
469 close $bh or die "close: $!";
470 my $cmd = [ qw(diff -u), $an, $bn ];
471 print STDERR "# MID conflict <$mid>\n";
472 my $pid = spawn($cmd, undef, { 1 => 2 });
473 defined $pid or die "diff failed to spawn $!";
474 waitpid($pid, 0) == $pid or die "diff did not finish";
479 my ($self, $mime, $mid) = @_;
480 my $ibx = $self->{-inbox};
482 my $srch = $ibx->search->reopen;
483 my $cid = content_id($mime);
485 $srch->each_smsg_by_mid($mid, sub {
488 my $msg = $ibx->msg_by_smsg($smsg);
489 if (!defined($msg)) {
490 warn "broken smsg for $mid\n";
493 my $cur = PublicInbox::MIME->new($msg);
494 if (content_id($cur) eq $cid) {
495 $smsg->{mime} = $cur;
497 return 0; # break out of loop
500 # XXX DEBUG_DIFF is experimental and may be removed
501 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
510 my $fh = delete $self->{reindex_pipe};
512 if (my $parts = $self->{idx_parts}) {
513 $_->atfork_child foreach @$parts;
515 if (my $im = $self->{im}) {
521 my ($self, $D, $git, $oid) = @_;
522 my $msgref = $git->cat_file($oid);
523 my $mime = PublicInbox::MIME->new($$msgref);
524 my $mids = mids($mime->header_obj);
525 my $cid = content_id($mime);
526 foreach my $mid (@$mids) {
527 $D->{"$mid\0$cid"} = 1;
532 my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
534 my $msgref = $git->cat_file($oid, \$len);
535 my $mime = PublicInbox::MIME->new($$msgref);
536 my $mids = mids($mime->header_obj);
537 my $cid = content_id($mime);
539 # get the NNTP article number we used before, highest number wins
540 # and gets deleted from mm_tmp;
544 foreach my $mid (@$mids) {
545 $del += (delete $D->{"$mid\0$cid"} || 0);
546 my $n = $mm_tmp->num_for($mid);
547 if (defined $n && $n > $num) {
552 if (!defined($mid0) && $regen && !$del) {
554 die "BUG: ran out of article numbers\n" if $num <= 0;
555 my $mm = $self->{skel}->{mm};
556 foreach my $mid (@$mids) {
557 if ($mm->mid_set($num, $mid) == 1) {
562 if (!defined($mid0)) {
563 my $id = '<' . join('> <', @$mids) . '>';
564 warn "Message-Id $id unusable for $num\n";
568 if (!defined($mid0) || $del) {
569 if (!defined($mid0) && $del) { # expected for deletes
574 my $id = '<' . join('> <', @$mids) . '>';
576 warn "Skipping $id, no article number found\n";
577 if ($del && defined($mid0)) {
578 warn "$id was deleted $del " .
579 "time(s) but mapped to article #$num\n";
584 $mm_tmp->mid_delete($mid0) or
585 die "failed to delete <$mid0> for article #$num\n";
587 my $nparts = $self->{partitions};
588 my $part = $num % $nparts;
589 my $idx = $self->idx_part($part);
590 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
591 my $n = $self->{transact_bytes} += $len;
592 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
594 $mm_tmp->atfork_prepare;
595 $self->done; # release lock
596 # allow -watch or -mda to write...
597 $self->idx_init; # reacquire lock
598 $mm_tmp->atfork_parent;
603 my ($self, $regen) = @_;
604 my $ibx = $self->{-inbox};
605 my $pfx = "$ibx->{mainrepo}/git";
607 my $latest = git_dir_latest($self, \$max_git);
608 return unless defined $latest;
609 my $head = $ibx->{ref_head} || 'refs/heads/master';
610 $self->idx_init; # acquire lock
611 my $x40 = qr/[a-f0-9]{40}/;
612 my $mm_tmp = $self->{skel}->{mm}->tmp_clone;
614 my (undef, $max) = $mm_tmp->minmax;
615 unless (defined $max) {
618 "empty msgmap.sqlite3, regenerating article numbers\n";
621 my $tip; # latest commit out of all git repos
624 for (my $cur = $max_git; $cur >= 0; $cur--) {
625 die "already reindexing!\n" if $self->{reindex_pipe};
626 my $git = PublicInbox::Git->new("$pfx/$cur.git");
627 chomp($tip = $git->qx('rev-parse', $head)) unless $tip;
628 my $h = $cur == $max_git ? $tip : $head;
629 my @count = ('rev-list', '--count', $h, '--', 'm');
630 $regen_max += $git->qx(@count);
632 die "No messages found in $pfx/*.git, bug?\n" unless $regen_max;
633 $regen = \$regen_max;
636 my @cmd = qw(log --raw -r --pretty=tformat:%h
637 --no-notes --no-color --no-abbrev);
639 # if we are regenerating, we must not use a newer tip commit than what
640 # the regeneration counter used:
643 # work backwards through history
644 for (my $cur = $max_git; $cur >= 0; $cur--) {
645 die "already reindexing!\n" if delete $self->{reindex_pipe};
647 my $git_dir = "$pfx/$cur.git";
648 my $git = PublicInbox::Git->new($git_dir);
649 my $h = $cur == $max_git ? $tip : $head;
650 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $h);
654 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
655 $self->reindex_oid($mm_tmp, $D, $git, $1,
657 } elsif (m!\A:\d{6} 100644 $x40 ($x40) [AM]\t_/D$!o) {
658 $self->mark_deleted($D, $git, $1);
661 delete $self->{reindex_pipe};
663 my ($min, $max) = $mm_tmp->minmax;
664 defined $max and die "leftover article numbers at $min..$max\n";
665 my @d = sort keys %$D;
667 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
669 my ($mid, undef) = split(/\0/, $_, 2);