]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: DEBUG_DIFF respects $TMPDIR
[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
227         # We avoid introducing new blobs into git since the raw content
228         # can be slightly different, so we do not need the user-supplied
229         # message now that we have the mids and content_id
230         $mime = undef;
231
232         foreach my $mid (@$mids) {
233                 $srch->reopen->each_smsg_by_mid($mid, sub {
234                         my ($smsg) = @_;
235                         $smsg->load_expand;
236                         my $msg = $ibx->msg_by_smsg($smsg);
237                         if (!defined($msg)) {
238                                 warn "broken smsg for $mid\n";
239                                 return 1; # continue
240                         }
241                         my $orig = $$msg;
242                         my $cur = PublicInbox::MIME->new($msg);
243                         if (content_id($cur) eq $cid) {
244                                 $mm->num_delete($smsg->num);
245                                 # $removed should only be set once assuming
246                                 # no bugs in our deduplication code:
247                                 $removed = $smsg;
248                                 $removed->{mime} = $cur;
249                                 $im->remove(\$orig, $cmt_msg);
250                                 $orig = undef;
251                                 $removed->num; # memoize this for callers
252
253                                 my $oid = $smsg->{blob};
254                                 foreach my $idx (@$parts, $skel) {
255                                         $idx->remote_remove($oid, $mid);
256                                 }
257                         }
258                         1; # continue
259                 });
260                 $self->barrier;
261         }
262         $removed;
263 }
264
265 sub done {
266         my ($self) = @_;
267         my $locked = defined $self->{idx_parts};
268         my $im = delete $self->{im};
269         $im->done if $im; # PublicInbox::Import::done
270         $self->searchidx_checkpoint(0);
271         $self->lock_release if $locked;
272 }
273
274 sub checkpoint {
275         my ($self) = @_;
276         my $im = $self->{im};
277         $im->checkpoint if $im; # PublicInbox::Import::checkpoint
278         $self->searchidx_checkpoint(1);
279 }
280
281 # issue a write barrier to ensure all data is visible to other processes
282 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
283 sub barrier {
284         my ($self) = @_;
285
286         if (my $im = $self->{im}) {
287                 $im->barrier;
288         }
289         my $skel = $self->{skel};
290         my $parts = $self->{idx_parts};
291         if ($parts && $skel) {
292                 my $dbh = $skel->{mm}->{dbh};
293                 $dbh->commit; # SQLite data is second in importance
294
295                 # Now deal with Xapian
296                 $skel->barrier_init(scalar(@$parts));
297                 # each partition needs to issue a barrier command to skel:
298                 $_->remote_barrier foreach @$parts;
299
300                 $skel->barrier_wait; # wait for each Xapian partition
301
302                 $dbh->begin_work;
303         }
304         $self->{transact_bytes} = 0;
305 }
306
307 sub searchidx_checkpoint {
308         my ($self, $more) = @_;
309
310         # order matters, we can only close {skel} after all partitions
311         # are done because the partitions also write to {skel}
312         if (my $parts = $self->{idx_parts}) {
313                 foreach my $idx (@$parts) {
314                         $idx->remote_commit; # propagates commit to skel
315                         $idx->remote_close unless $more;
316                 }
317                 delete $self->{idx_parts} unless $more;
318         }
319
320         if (my $skel = $self->{skel}) {
321                 my $dbh = $skel->{mm}->{dbh};
322                 $dbh->commit;
323                 if ($more) {
324                         $dbh->begin_work;
325                 } else {
326                         $skel->remote_close;
327                         delete $self->{skel};
328                 }
329         }
330         $self->{transact_bytes} = 0;
331 }
332
333 sub git_init {
334         my ($self, $new) = @_;
335         my $pfx = "$self->{-inbox}->{mainrepo}/git";
336         my $git_dir = "$pfx/$new.git";
337         die "$git_dir exists\n" if -e $git_dir;
338         my @cmd = (qw(git init --bare -q), $git_dir);
339         PublicInbox::Import::run_die(\@cmd);
340
341         my $all = "$self->{-inbox}->{mainrepo}/all.git";
342         unless (-d $all) {
343                 @cmd = (qw(git init --bare -q), $all);
344                 PublicInbox::Import::run_die(\@cmd);
345                 @cmd = (qw/git config/, "--file=$all/config",
346                                 'repack.writeBitmaps', 'true');
347                 PublicInbox::Import::run_die(\@cmd);
348         }
349
350         @cmd = (qw/git config/, "--file=$git_dir/config",
351                         'include.path', '../../all.git/config');
352         PublicInbox::Import::run_die(\@cmd);
353
354         my $alt = "$all/objects/info/alternates";
355         my $new_obj_dir = "../../git/$new.git/objects";
356         my %alts;
357         if (-e $alt) {
358                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
359                 %alts = map { chomp; $_ => 1 } (<$fh>);
360         }
361         return $git_dir if $alts{$new_obj_dir};
362         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
363         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
364         close $fh or die "close $alt: $!\n";
365         $git_dir
366 }
367
368 sub git_dir_latest {
369         my ($self, $max) = @_;
370         $$max = -1;
371         my $pfx = "$self->{-inbox}->{mainrepo}/git";
372         return unless -d $pfx;
373         my $latest;
374         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
375         while (defined(my $git_dir = readdir($dh))) {
376                 $git_dir =~ m!\A(\d+)\.git\z! or next;
377                 if ($1 > $$max) {
378                         $$max = $1;
379                         $latest = "$pfx/$git_dir";
380                 }
381         }
382         $latest;
383 }
384
385 sub importer {
386         my ($self) = @_;
387         my $im = $self->{im};
388         if ($im) {
389                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
390                         return $im;
391                 } else {
392                         $self->{im} = undef;
393                         $im->done;
394                         $self->searchidx_checkpoint(1);
395                         $im = undef;
396                         my $git_dir = $self->git_init(++$self->{max_git});
397                         my $git = PublicInbox::Git->new($git_dir);
398                         return $self->import_init($git, 0);
399                 }
400         }
401         my $new = 0;
402         my $max;
403         my $latest = git_dir_latest($self, \$max);
404         if (defined $latest) {
405                 my $git = PublicInbox::Git->new($latest);
406                 my $packed_bytes = $git->packed_bytes;
407                 if ($packed_bytes >= $self->{rotate_bytes}) {
408                         $new = $max + 1;
409                 } else {
410                         $self->{max_git} = $max;
411                         return $self->import_init($git, $packed_bytes);
412                 }
413         }
414         $self->{max_git} = $new;
415         $latest = $self->git_init($new);
416         $self->import_init(PublicInbox::Git->new($latest), 0);
417 }
418
419 sub import_init {
420         my ($self, $git, $packed_bytes) = @_;
421         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
422         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
423         $im->{want_object_info} = 1;
424         $im->{lock_path} = undef;
425         $im->{path_type} = 'v2';
426         $self->{im} = $im;
427 }
428
429 # XXX experimental
430 sub diff ($$$) {
431         my ($mid, $cur, $new) = @_;
432         use File::Temp qw(tempfile);
433         use PublicInbox::Spawn qw(spawn);
434
435         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
436         print $ah $cur->as_string or die "print: $!";
437         close $ah or die "close: $!";
438         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
439         PublicInbox::Import::drop_unwanted_headers($new);
440         print $bh $new->as_string or die "print: $!";
441         close $bh or die "close: $!";
442         my $cmd = [ qw(diff -u), $an, $bn ];
443         print STDERR "# MID conflict <$mid>\n";
444         my $pid = spawn($cmd, undef, { 1 => 2 });
445         defined $pid or die "diff failed to spawn $!";
446         waitpid($pid, 0) == $pid or die "diff did not finish";
447         unlink($an, $bn);
448 }
449
450 sub lookup_content {
451         my ($self, $mime, $mid) = @_;
452         my $ibx = $self->{-inbox};
453
454         my $srch = $ibx->search->reopen;
455         my $cid = content_id($mime);
456         my $found;
457         $srch->each_smsg_by_mid($mid, sub {
458                 my ($smsg) = @_;
459                 $smsg->load_expand;
460                 my $msg = $ibx->msg_by_smsg($smsg);
461                 if (!defined($msg)) {
462                         warn "broken smsg for $mid\n";
463                         return 1; # continue
464                 }
465                 my $cur = PublicInbox::MIME->new($msg);
466                 if (content_id($cur) eq $cid) {
467                         $smsg->{mime} = $cur;
468                         $found = $smsg;
469                         return 0; # break out of loop
470                 }
471
472                 # XXX DEBUG_DIFF is experimental and may be removed
473                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
474
475                 1; # continue
476         });
477         $found;
478 }
479
480 sub atfork_child {
481         my ($self) = @_;
482         my $fh = delete $self->{reindex_pipe};
483         close $fh if $fh;
484         if (my $parts = $self->{idx_parts}) {
485                 $_->atfork_child foreach @$parts;
486         }
487         if (my $im = $self->{im}) {
488                 $im->atfork_child;
489         }
490 }
491
492 sub mark_deleted {
493         my ($self, $D, $git, $oid) = @_;
494         my $msgref = $git->cat_file($oid);
495         my $mime = PublicInbox::MIME->new($$msgref);
496         my $mids = mids($mime->header_obj);
497         my $cid = content_id($mime);
498         foreach my $mid (@$mids) {
499                 $D->{$mid.$cid} = 1;
500         }
501 }
502
503 sub reindex_oid {
504         my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
505         my $len;
506         my $msgref = $git->cat_file($oid, \$len);
507         my $mime = PublicInbox::MIME->new($$msgref);
508         my $mids = mids($mime->header_obj);
509         my $cid = content_id($mime);
510
511         # get the NNTP article number we used before, highest number wins
512         # and gets deleted from mm_tmp;
513         my $mid0;
514         my $num = -1;
515         my $del = 0;
516         foreach my $mid (@$mids) {
517                 $del += (delete $D->{$mid.$cid} || 0);
518                 my $n = $mm_tmp->num_for($mid);
519                 if (defined $n && $n > $num) {
520                         $mid0 = $mid;
521                         $num = $n;
522                 }
523         }
524         if (!defined($mid0) && $regen && !$del) {
525                 $num = $$regen--;
526                 die "BUG: ran out of article numbers\n" if $num <= 0;
527                 my $mm = $self->{skel}->{mm};
528                 foreach my $mid (@$mids) {
529                         if ($mm->mid_set($num, $mid) == 1) {
530                                 $mid0 = $mid;
531                                 last;
532                         }
533                 }
534                 if (!defined($mid0)) {
535                         my $id = '<' . join('> <', @$mids) . '>';
536                         warn "Message-Id $id unusable for $num\n";
537                 }
538         }
539
540         if (!defined($mid0) || $del) {
541                 if (!defined($mid0) && $del) { # expected for deletes
542                         $$regen--;
543                         return
544                 }
545
546                 my $id = '<' . join('> <', @$mids) . '>';
547                 defined($mid0) or
548                         warn "Skipping $id, no article number found\n";
549                 if ($del && defined($mid0)) {
550                         warn "$id was deleted $del " .
551                                 "time(s) but mapped to article #$num\n";
552                 }
553                 return;
554
555         }
556         $mm_tmp->mid_delete($mid0) or
557                 die "failed to delete <$mid0> for article #$num\n";
558
559         my $nparts = $self->{partitions};
560         my $part = $num % $nparts;
561         my $idx = $self->idx_part($part);
562         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
563         my $n = $self->{transact_bytes} += $len;
564         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
565                 $git->cleanup;
566                 $mm_tmp->atfork_prepare;
567                 $self->done; # release lock
568                 # allow -watch or -mda to write...
569                 $self->idx_init; # reacquire lock
570                 $mm_tmp->atfork_parent;
571         }
572 }
573
574 sub reindex {
575         my ($self, $regen) = @_;
576         my $ibx = $self->{-inbox};
577         my $pfx = "$ibx->{mainrepo}/git";
578         my $max_git;
579         my $latest = git_dir_latest($self, \$max_git);
580         return unless defined $latest;
581         my $head = $ibx->{ref_head} || 'refs/heads/master';
582         $self->idx_init; # acquire lock
583         my $x40 = qr/[a-f0-9]{40}/;
584         my $mm_tmp = $self->{skel}->{mm}->tmp_clone;
585         if (!$regen) {
586                 my (undef, $max) = $mm_tmp->minmax;
587                 unless (defined $max) {
588                         $regen = 1;
589                         warn
590 "empty msgmap.sqlite3, regenerating article numbers\n";
591                 }
592         }
593         my $tip; # latest commit out of all git repos
594         if ($regen) {
595                 my $regen_max = 0;
596                 for (my $cur = $max_git; $cur >= 0; $cur--) {
597                         die "already reindexing!\n" if $self->{reindex_pipe};
598                         my $git = PublicInbox::Git->new("$pfx/$cur.git");
599                         chomp($tip = $git->qx('rev-parse', $head)) unless $tip;
600                         my $h = $cur == $max_git ? $tip : $head;
601                         my @count = ('rev-list', '--count', $h, '--', 'm');
602                         $regen_max += $git->qx(@count);
603                 }
604                 die "No messages found in $pfx/*.git, bug?\n" unless $regen_max;
605                 $regen = \$regen_max;
606         }
607         my $D = {};
608         my @cmd = qw(log --raw -r --pretty=tformat:%h
609                         --no-notes --no-color --no-abbrev);
610
611         # if we are regenerating, we must not use a newer tip commit than what
612         # the regeneration counter used:
613         $tip ||= $head;
614
615         # work backwards through history
616         for (my $cur = $max_git; $cur >= 0; $cur--) {
617                 die "already reindexing!\n" if delete $self->{reindex_pipe};
618                 my $cmt;
619                 my $git_dir = "$pfx/$cur.git";
620                 my $git = PublicInbox::Git->new($git_dir);
621                 my $h = $cur == $max_git ? $tip : $head;
622                 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $h);
623                 while (<$fh>) {
624                         if (/\A$x40$/o) {
625                                 chomp($cmt = $_);
626                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
627                                 $self->reindex_oid($mm_tmp, $D, $git, $1,
628                                                 $regen);
629                         } elsif (m!\A:\d{6} 100644 $x40 ($x40) [AM]\t_/D$!o) {
630                                 $self->mark_deleted($D, $git, $1);
631                         }
632                 }
633                 delete $self->{reindex_pipe};
634         }
635         my ($min, $max) = $mm_tmp->minmax;
636         defined $max and die "leftover article numbers at $min..$max\n";
637 }
638
639 1;