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 Fcntl qw(:flock :DEFAULT);
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,
60 # limit each repo to 1GB or so
61 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
66 # returns undef on duplicate or spam
67 # mimics Import::add and wraps it for v2
69 my ($self, $mime, $check_cb) = @_;
73 $mime = $check_cb->($mime) or return;
76 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
77 # as does SQLite 3.4.1+ (released in 2007-07-20), and
78 # Xapian 1.3.2+ (released 2015-03-15).
79 # For the most part, we can spawn git-fast-import without
80 # leaking FDs to it...
84 my $num = num_for($self, $mime, \$mid0);
85 defined $num or return; # duplicate
86 defined $mid0 or die "BUG: $mid0 undefined\n";
87 my $im = $self->importer;
88 my $cmt = $im->add($mime);
89 $cmt = $im->get_mark($cmt);
90 my ($oid, $len, $msgref) = @{$im->{last_object}};
92 my $nparts = $self->{partitions};
93 my $part = $num % $nparts;
94 my $idx = $self->idx_part($part);
95 $idx->index_raw($len, $msgref, $num, $oid, $mid0);
96 my $n = $self->{transact_bytes} += $len;
97 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
105 my ($self, $mime, $mid0) = @_;
106 my $mids = mids($mime->header_obj);
108 my $mid = $mids->[0];
109 my $num = $self->{skel}->{mm}->mid_insert($mid);
110 if (defined $num) { # common case
115 # crap, Message-ID is already known, hope somebody just resent:
116 $self->done; # write barrier, clears $self->{skel}
117 foreach my $m (@$mids) {
118 # read-only lookup now safe to do after above barrier
119 my $existing = $self->lookup_content($mime, $m);
121 warn "<$m> resent\n";
122 return; # easy, don't store duplicates
127 warn "<$mid> reused for mismatched content\n";
130 # try the rest of the mids
131 foreach my $i (1..$#$mids) {
133 $num = $self->{skel}->{mm}->mid_insert($m);
135 warn "alternative <$m> for <$mid> found\n";
141 # none of the existing Message-IDs are good, generate a new one:
142 num_for_harder($self, $mime, $mid0);
146 my ($self, $mime, $mid0) = @_;
148 my $hdr = $mime->header_obj;
149 my $dig = content_digest($mime);
150 $$mid0 = $dig->clone->hexdigest . '@localhost';
151 my $num = $self->{skel}->{mm}->mid_insert($$mid0);
152 unless (defined $num) {
153 # it's hard to spoof the last Received: header
154 my @recvd = $hdr->header_raw('Received');
155 $dig->add("Received: $_") foreach (@recvd);
156 $$mid0 = $dig->clone->hexdigest . '@localhost';
157 $num = $self->{skel}->{mm}->mid_insert($$mid0);
159 # fall back to a random Message-ID and give up determinism:
160 until (defined($num)) {
162 $$mid0 = $dig->clone->hexdigest . '@localhost';
163 warn "using random Message-ID <$$mid0> as fallback\n";
164 $num = $self->{skel}->{mm}->mid_insert($$mid0);
167 my @cur = $hdr->header_raw('Message-Id');
168 $hdr->header_set('Message-Id', "<$$mid0>", @cur);
173 my ($self, $part) = @_;
174 $self->{idx_parts}->[$part];
180 return if $self->{idx_parts};
181 my $ibx = $self->{-inbox};
183 # do not leak read-only FDs to child processes, we only have these
184 # FDs for duplicate detection so they should not be
185 # frequently activated.
186 delete $ibx->{$_} foreach (qw(git mm search));
188 # first time initialization, first we create the skeleton pipe:
189 my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
191 # need to create all parts before initializing msgmap FD
192 my $max = $self->{partitions} - 1;
193 my $idx = $self->{idx_parts} = [];
194 for my $i (0..$max) {
195 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
198 # Now that all subprocesses are up, we can open the FD for SQLite:
199 $skel->_msgmap_init->{dbh}->begin_work;
203 my ($self, $mime, $msg) = @_;
204 my $existing = $self->lookup_content($mime) or return;
206 # don't touch ghosts or already junked messages
207 return unless $existing->type eq 'mail';
209 # always write removals to the current (latest) git repo since
210 # we process chronologically
211 my $im = $self->importer;
212 my ($cmt, undef) = $im->remove($mime, $msg);
213 $cmt = $im->get_mark($cmt);
214 $self->unindex_msg($existing, $cmt);
219 my $im = delete $self->{im};
220 $im->done if $im; # PublicInbox::Import::done
221 $self->searchidx_checkpoint(0);
226 my $im = $self->{im};
227 $im->checkpoint if $im; # PublicInbox::Import::checkpoint
228 $self->searchidx_checkpoint(1);
231 sub searchidx_checkpoint {
232 my ($self, $more) = @_;
234 # order matters, we can only close {skel} after all partitions
235 # are done because the partitions also write to {skel}
236 if (my $parts = $self->{idx_parts}) {
237 foreach my $idx (@$parts) {
238 $idx->remote_commit; # propagates commit to skel
239 $idx->remote_close unless $more;
241 delete $self->{idx_parts} unless $more;
244 if (my $skel = $self->{skel}) {
245 my $dbh = $skel->{mm}->{dbh};
251 delete $self->{skel};
254 $self->{transact_bytes} = 0;
258 my ($self, $new) = @_;
259 my $pfx = "$self->{-inbox}->{mainrepo}/git";
260 my $git_dir = "$pfx/$new.git";
261 die "$git_dir exists\n" if -e $git_dir;
262 my @cmd = (qw(git init --bare -q), $git_dir);
263 PublicInbox::Import::run_die(\@cmd);
265 my $all = "$self->{-inbox}->{mainrepo}/all.git";
267 @cmd = (qw(git init --bare -q), $all);
268 PublicInbox::Import::run_die(\@cmd);
269 @cmd = (qw/git config/, "--file=$all/config",
270 'repack.writeBitmaps', 'true');
271 PublicInbox::Import::run_die(\@cmd);
274 @cmd = (qw/git config/, "--file=$git_dir/config",
275 'include.path', '../../all.git/config');
276 PublicInbox::Import::run_die(\@cmd);
278 my $alt = "$all/objects/info/alternates";
279 my $new_obj_dir = "../../git/$new.git/objects";
282 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
283 %alts = map { chomp; $_ => 1 } (<$fh>);
285 return $git_dir if $alts{$new_obj_dir};
286 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
287 print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
288 close $fh or die "close $alt: $!\n";
294 my $im = $self->{im};
296 if ($im->{bytes_added} < $self->{rotate_bytes}) {
301 $self->searchidx_checkpoint(1);
303 my $git_dir = $self->git_init(++$self->{max_git});
304 my $git = PublicInbox::Git->new($git_dir);
305 return $self->import_init($git, 0);
311 my $pfx = "$self->{-inbox}->{mainrepo}/git";
313 foreach my $git_dir (glob("$pfx/*.git")) {
314 $git_dir =~ m!/(\d+)\.git\z! or next;
322 if (defined $latest) {
323 my $git = PublicInbox::Git->new($latest);
324 my $packed_bytes = $git->packed_bytes;
325 if ($packed_bytes >= $self->{rotate_bytes}) {
328 $self->{max_git} = $max;
329 return $self->import_init($git, $packed_bytes);
332 $self->{max_git} = $new;
333 $latest = $self->git_init($new);
334 $self->import_init(PublicInbox::Git->new($latest), 0);
338 my ($self, $git, $packed_bytes) = @_;
339 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
340 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
341 $im->{want_object_info} = 1;
342 $im->{ssoma_lock} = 0;
343 $im->{path_type} = 'v2';
348 my ($self, $mime, $mid) = @_;
349 my $ibx = $self->{-inbox};
351 my $srch = $ibx->search;
352 my $cid = content_id($mime);
354 $srch->each_smsg_by_mid($mid, sub {
357 my $msg = $ibx->msg_by_smsg($smsg);
358 if (!defined($msg)) {
359 warn "broken smsg for $mid\n";
362 my $cur = PublicInbox::MIME->new($msg);
363 if (content_id($cur) eq $cid) {
364 $smsg->{mime} = $cur;
366 return 0; # break out of loop
375 if (my $parts = $self->{idx_parts}) {
376 $_->atfork_child foreach @$parts;
378 if (my $im = $self->{im}) {