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