]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
InboxWritable: add mbox/maildir parsing + import logic
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This interface wraps and mimics PublicInbox::Import
5 package PublicInbox::V2Writable;
6 use strict;
7 use warnings;
8 use base qw(PublicInbox::Lock);
9 use PublicInbox::SearchIdxPart;
10 use PublicInbox::SearchIdxSkeleton;
11 use PublicInbox::MIME;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids);
15 use PublicInbox::ContentId qw(content_id content_digest);
16 use PublicInbox::Inbox;
17
18 # an estimate of the post-packed size to the raw uncompressed size
19 my $PACKING_FACTOR = 0.4;
20
21 # assume 2 cores if GNU nproc(1) is not available
22 sub nproc () {
23         int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
24 }
25
26 sub new {
27         my ($class, $v2ibx, $creat) = @_;
28         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
29         unless (-d $dir) {
30                 if ($creat) {
31                         require File::Path;
32                         File::Path::mkpath($dir);
33                 } else {
34                         die "$dir does not exist\n";
35                 }
36         }
37
38         my $nparts = 0;
39         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
40
41         # always load existing partitions in case core count changes:
42         if (-d $xpfx) {
43                 foreach my $part (<$xpfx/*>) {
44                         -d $part && $part =~ m!/\d+\z! or next;
45                         eval {
46                                 Search::Xapian::Database->new($part)->close;
47                                 $nparts++;
48                         };
49                 }
50         }
51         $nparts = nproc() if ($nparts == 0);
52
53         my $self = {
54                 -inbox => $v2ibx,
55                 im => undef, #  PublicInbox::Import
56                 xap_rw => undef, # PublicInbox::V2SearchIdx
57                 xap_ro => undef,
58                 partitions => $nparts,
59                 parallel => 1,
60                 transact_bytes => 0,
61                 lock_path => "$dir/inbox.lock",
62                 # limit each repo to 1GB or so
63                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
64         };
65         bless $self, $class;
66 }
67
68 sub init_inbox {
69         my ($self, $parallel) = @_;
70         $self->{parallel} = $parallel;
71         $self->idx_init;
72         $self->git_init(0);
73         $self->done;
74 }
75
76 # returns undef on duplicate or spam
77 # mimics Import::add and wraps it for v2
78 sub add {
79         my ($self, $mime, $check_cb) = @_;
80
81         # spam check:
82         if ($check_cb) {
83                 $mime = $check_cb->($mime) or return;
84         }
85
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...
91         $self->idx_init;
92
93         my $mid0;
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}};
101
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)) {
108                 $self->checkpoint;
109         }
110
111         $mime;
112 }
113
114 sub num_for {
115         my ($self, $mime, $mid0) = @_;
116         my $mids = mids($mime->header_obj);
117         if (@$mids) {
118                 my $mid = $mids->[0];
119                 my $num = $self->{skel}->{mm}->mid_insert($mid);
120                 if (defined $num) { # common case
121                         $$mid0 = $mid;
122                         return $num;
123                 };
124
125                 # crap, Message-ID is already known, hope somebody just resent:
126                 $self->barrier;
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
133                         return if $existing;
134                 }
135
136                 # very unlikely:
137                 warn "<$mid> reused for mismatched content\n";
138
139                 # try the rest of the mids
140                 foreach my $i (1..$#$mids) {
141                         my $m = $mids->[$i];
142                         $num = $self->{skel}->{mm}->mid_insert($m);
143                         if (defined $num) {
144                                 warn "alternative <$m> for <$mid> found\n";
145                                 $$mid0 = $m;
146                                 return $num;
147                         }
148                 }
149         }
150         # none of the existing Message-IDs are good, generate a new one:
151         num_for_harder($self, $mime, $mid0);
152 }
153
154 sub num_for_harder {
155         my ($self, $mime, $mid0) = @_;
156
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);
167
168                 # fall back to a random Message-ID and give up determinism:
169                 until (defined($num)) {
170                         $dig->add(rand);
171                         $$mid0 = PublicInbox::Import::digest2mid($dig);
172                         warn "using random Message-ID <$$mid0> as fallback\n";
173                         $num = $self->{skel}->{mm}->mid_insert($$mid0);
174                 }
175         }
176         my @cur = $hdr->header_raw('Message-Id');
177         $hdr->header_set('Message-Id', "<$$mid0>", @cur);
178         $num;
179 }
180
181 sub idx_part {
182         my ($self, $part) = @_;
183         $self->{idx_parts}->[$part];
184 }
185
186 # idempotent
187 sub idx_init {
188         my ($self) = @_;
189         return if $self->{idx_parts};
190         my $ibx = $self->{-inbox};
191
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));
196
197         $self->lock_acquire;
198
199         # first time initialization, first we create the skeleton pipe:
200         my $skel = $self->{skel} = PublicInbox::SearchIdxSkeleton->new($self);
201
202         # need to create all parts before initializing msgmap FD
203         my $max = $self->{partitions} - 1;
204         my $idx = $self->{idx_parts} = [];
205         for my $i (0..$max) {
206                 push @$idx, PublicInbox::SearchIdxPart->new($self, $i, $skel);
207         }
208
209         # Now that all subprocesses are up, we can open the FD for SQLite:
210         $skel->_msgmap_init->{dbh}->begin_work;
211 }
212
213 sub remove {
214         my ($self, $mime, $cmt_msg) = @_;
215         $self->barrier;
216         $self->idx_init;
217         my $im = $self->importer;
218         my $ibx = $self->{-inbox};
219         my $srch = $ibx->search;
220         my $cid = content_id($mime);
221         my $skel = $self->{skel};
222         my $parts = $self->{idx_parts};
223         my $mm = $skel->{mm};
224         my $removed;
225         my $mids = mids($mime->header_obj);
226         foreach my $mid (@$mids) {
227                 $srch->reopen->each_smsg_by_mid($mid, sub {
228                         my ($smsg) = @_;
229                         $smsg->load_expand;
230                         my $msg = $ibx->msg_by_smsg($smsg);
231                         if (!defined($msg)) {
232                                 warn "broken smsg for $mid\n";
233                                 return 1; # continue
234                         }
235                         my $orig = $$msg;
236                         my $cur = PublicInbox::MIME->new($msg);
237                         if (content_id($cur) eq $cid) {
238                                 $mm->num_delete($smsg->num);
239                                 # $removed should only be set once assuming
240                                 # no bugs in our deduplication code:
241                                 $removed = $smsg;
242                                 $removed->{mime} = $cur;
243                                 $im->remove(\$orig, $cmt_msg);
244                                 $orig = undef;
245                                 $removed->num; # memoize this for callers
246
247                                 my $oid = $smsg->{blob};
248                                 foreach my $idx (@$parts, $skel) {
249                                         $idx->remote_remove($oid, $mid);
250                                 }
251                         }
252                         1; # continue
253                 });
254                 $self->barrier;
255         }
256         $removed;
257 }
258
259 sub done {
260         my ($self) = @_;
261         my $locked = defined $self->{idx_parts};
262         my $im = delete $self->{im};
263         $im->done if $im; # PublicInbox::Import::done
264         $self->searchidx_checkpoint(0);
265         $self->lock_release if $locked;
266 }
267
268 sub checkpoint {
269         my ($self) = @_;
270         my $im = $self->{im};
271         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
272         $self->searchidx_checkpoint(1);
273 }
274
275 # issue a write barrier to ensure all data is visible to other processes
276 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
277 sub barrier {
278         my ($self) = @_;
279
280         if (my $im = $self->{im}) {
281                 $im->barrier;
282         }
283         my $skel = $self->{skel};
284         my $parts = $self->{idx_parts};
285         if ($parts && $skel) {
286                 my $dbh = $skel->{mm}->{dbh};
287                 $dbh->commit; # SQLite data is second in importance
288
289                 # Now deal with Xapian
290                 $skel->barrier_init(scalar(@$parts));
291                 # each partition needs to issue a barrier command to skel:
292                 $_->remote_barrier foreach @$parts;
293
294                 $skel->barrier_wait; # wait for each Xapian partition
295
296                 $dbh->begin_work;
297         }
298         $self->{transact_bytes} = 0;
299 }
300
301 sub searchidx_checkpoint {
302         my ($self, $more) = @_;
303
304         # order matters, we can only close {skel} after all partitions
305         # are done because the partitions also write to {skel}
306         if (my $parts = $self->{idx_parts}) {
307                 foreach my $idx (@$parts) {
308                         $idx->remote_commit; # propagates commit to skel
309                         $idx->remote_close unless $more;
310                 }
311                 delete $self->{idx_parts} unless $more;
312         }
313
314         if (my $skel = $self->{skel}) {
315                 my $dbh = $skel->{mm}->{dbh};
316                 $dbh->commit;
317                 if ($more) {
318                         $dbh->begin_work;
319                 } else {
320                         $skel->remote_close;
321                         delete $self->{skel};
322                 }
323         }
324         $self->{transact_bytes} = 0;
325 }
326
327 sub git_init {
328         my ($self, $new) = @_;
329         my $pfx = "$self->{-inbox}->{mainrepo}/git";
330         my $git_dir = "$pfx/$new.git";
331         die "$git_dir exists\n" if -e $git_dir;
332         my @cmd = (qw(git init --bare -q), $git_dir);
333         PublicInbox::Import::run_die(\@cmd);
334
335         my $all = "$self->{-inbox}->{mainrepo}/all.git";
336         unless (-d $all) {
337                 @cmd = (qw(git init --bare -q), $all);
338                 PublicInbox::Import::run_die(\@cmd);
339                 @cmd = (qw/git config/, "--file=$all/config",
340                                 'repack.writeBitmaps', 'true');
341                 PublicInbox::Import::run_die(\@cmd);
342         }
343
344         @cmd = (qw/git config/, "--file=$git_dir/config",
345                         'include.path', '../../all.git/config');
346         PublicInbox::Import::run_die(\@cmd);
347
348         my $alt = "$all/objects/info/alternates";
349         my $new_obj_dir = "../../git/$new.git/objects";
350         my %alts;
351         if (-e $alt) {
352                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
353                 %alts = map { chomp; $_ => 1 } (<$fh>);
354         }
355         return $git_dir if $alts{$new_obj_dir};
356         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
357         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
358         close $fh or die "close $alt: $!\n";
359         $git_dir
360 }
361
362 sub importer {
363         my ($self) = @_;
364         my $im = $self->{im};
365         if ($im) {
366                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
367                         return $im;
368                 } else {
369                         $self->{im} = undef;
370                         $im->done;
371                         $self->searchidx_checkpoint(1);
372                         $im = undef;
373                         my $git_dir = $self->git_init(++$self->{max_git});
374                         my $git = PublicInbox::Git->new($git_dir);
375                         return $self->import_init($git, 0);
376                 }
377         }
378         my $latest;
379         my $max = -1;
380         my $new = 0;
381         my $pfx = "$self->{-inbox}->{mainrepo}/git";
382         if (-d $pfx) {
383                 foreach my $git_dir (glob("$pfx/*.git")) {
384                         $git_dir =~ m!/(\d+)\.git\z! or next;
385                         my $n = $1;
386                         if ($n > $max) {
387                                 $max = $n;
388                                 $latest = $git_dir;
389                         }
390                 }
391         }
392         if (defined $latest) {
393                 my $git = PublicInbox::Git->new($latest);
394                 my $packed_bytes = $git->packed_bytes;
395                 if ($packed_bytes >= $self->{rotate_bytes}) {
396                         $new = $max + 1;
397                 } else {
398                         $self->{max_git} = $max;
399                         return $self->import_init($git, $packed_bytes);
400                 }
401         }
402         $self->{max_git} = $new;
403         $latest = $self->git_init($new);
404         $self->import_init(PublicInbox::Git->new($latest), 0);
405 }
406
407 sub import_init {
408         my ($self, $git, $packed_bytes) = @_;
409         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
410         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
411         $im->{want_object_info} = 1;
412         $im->{lock_path} = undef;
413         $im->{path_type} = 'v2';
414         $self->{im} = $im;
415 }
416
417 # XXX experimental
418 sub diff ($$$) {
419         my ($mid, $cur, $new) = @_;
420         use File::Temp qw(tempfile);
421         use PublicInbox::Spawn qw(spawn);
422
423         my ($ah, $an) = tempfile('email-cur-XXXXXXXX');
424         print $ah $cur->as_string or die "print: $!";
425         close $ah or die "close: $!";
426         my ($bh, $bn) = tempfile('email-new-XXXXXXXX');
427         print $bh $new->as_string or die "print: $!";
428         close $bh or die "close: $!";
429         my $cmd = [ qw(diff -u), $an, $bn ];
430         print STDERR "# MID conflict <$mid>\n";
431         my $pid = spawn($cmd, undef, { 1 => 2 });
432         defined $pid or die "diff failed to spawn $!";
433         waitpid($pid, 0) == $pid or die "diff did not finish";
434         unlink($an, $bn);
435 }
436
437 sub lookup_content {
438         my ($self, $mime, $mid) = @_;
439         my $ibx = $self->{-inbox};
440
441         my $srch = $ibx->search->reopen;
442         my $cid = content_id($mime);
443         my $found;
444         $srch->each_smsg_by_mid($mid, sub {
445                 my ($smsg) = @_;
446                 $smsg->load_expand;
447                 my $msg = $ibx->msg_by_smsg($smsg);
448                 if (!defined($msg)) {
449                         warn "broken smsg for $mid\n";
450                         return 1; # continue
451                 }
452                 my $cur = PublicInbox::MIME->new($msg);
453                 if (content_id($cur) eq $cid) {
454                         $smsg->{mime} = $cur;
455                         $found = $smsg;
456                         return 0; # break out of loop
457                 }
458
459                 # XXX DEBUG_DIFF is experimental and may be removed
460                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
461
462                 1; # continue
463         });
464         $found;
465 }
466
467 sub atfork_child {
468         my ($self) = @_;
469         if (my $parts = $self->{idx_parts}) {
470                 $_->atfork_child foreach @$parts;
471         }
472         if (my $im = $self->{im}) {
473                 $im->atfork_child;
474         }
475 }
476
477 1;