]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: use a smaller default for Xapian partitions
[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 # Used to write to V2 inboxes (see L<public-inbox-v2-format(5)>).
6 package PublicInbox::V2Writable;
7 use strict;
8 use warnings;
9 use base qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxPart;
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 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn);
20 use PublicInbox::SearchIdx;
21 use IO::Handle;
22
23 # an estimate of the post-packed size to the raw uncompressed size
24 my $PACKING_FACTOR = 0.4;
25
26 # SATA storage lags behind what CPUs are capable of, so relying on
27 # nproc(1) can be misleading and having extra Xapian partions is a
28 # waste of FDs and space.  It can also lead to excessive IO latency
29 # and slow things down.  Users on NVME or other fast storage can
30 # use the NPROC env or switches in our script/public-inbox-* programs
31 # to increase Xapian partitions.
32 our $NPROC_MAX_DEFAULT = 4;
33
34 sub nproc_parts ($) {
35         my ($creat_opt) = @_;
36         if (ref($creat_opt) eq 'HASH') {
37                 if (defined(my $n = $creat_opt->{nproc})) {
38                         return $n
39                 }
40         }
41
42         my $n = $ENV{NPROC};
43         if (!$n) {
44                 chomp($n = `nproc 2>/dev/null`);
45                 # assume 2 cores if GNU nproc(1) is not available
46                 $n = 2 if !$n;
47                 $n = $NPROC_MAX_DEFAULT if $NPROC_MAX_DEFAULT > 4;
48         }
49
50         # subtract for the main process and git-fast-import
51         $n -= 1;
52         $n < 1 ? 1 : $n;
53 }
54
55 sub count_partitions ($) {
56         my ($self) = @_;
57         my $nparts = 0;
58         my $xpfx = $self->{xpfx};
59
60         # always load existing partitions in case core count changes:
61         # Also, partition count may change while -watch is running
62         # due to -compact
63         if (-d $xpfx) {
64                 foreach my $part (<$xpfx/*>) {
65                         -d $part && $part =~ m!/[0-9]+\z! or next;
66                         eval {
67                                 Search::Xapian::Database->new($part)->close;
68                                 $nparts++;
69                         };
70                 }
71         }
72         $nparts;
73 }
74
75 sub new {
76         # $creat may be any true value, or 0/undef.  A hashref is true,
77         # and $creat->{nproc} may be set to an integer
78         my ($class, $v2ibx, $creat) = @_;
79         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
80         unless (-d $dir) {
81                 if ($creat) {
82                         require File::Path;
83                         File::Path::mkpath($dir);
84                 } else {
85                         die "$dir does not exist\n";
86                 }
87         }
88
89         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
90         $v2ibx->umask_prepare;
91
92         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
93         my $self = {
94                 -inbox => $v2ibx,
95                 im => undef, #  PublicInbox::Import
96                 parallel => 1,
97                 transact_bytes => 0,
98                 current_info => '',
99                 xpfx => $xpfx,
100                 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
101                 lock_path => "$dir/inbox.lock",
102                 # limit each git repo (epoch) to 1GB or so
103                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
104                 last_commit => [], # git repo -> commit
105         };
106         $self->{partitions} = count_partitions($self) || nproc_parts($creat);
107         bless $self, $class;
108 }
109
110 # public (for now?)
111 sub init_inbox {
112         my ($self, $parallel, $skip_epoch) = @_;
113         $self->{parallel} = $parallel;
114         $self->idx_init;
115         my $epoch_max = -1;
116         git_dir_latest($self, \$epoch_max);
117         if (defined $skip_epoch && $epoch_max == -1) {
118                 $epoch_max = $skip_epoch;
119         }
120         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
121         $self->done;
122 }
123
124 # returns undef on duplicate or spam
125 # mimics Import::add and wraps it for v2
126 sub add {
127         my ($self, $mime, $check_cb) = @_;
128         $self->{-inbox}->with_umask(sub {
129                 _add($self, $mime, $check_cb)
130         });
131 }
132
133 sub _add {
134         my ($self, $mime, $check_cb) = @_;
135
136         # spam check:
137         if ($check_cb) {
138                 $mime = $check_cb->($mime) or return;
139         }
140
141         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
142         # as does SQLite 3.4.1+ (released in 2007-07-20), and
143         # Xapian 1.3.2+ (released 2015-03-15).
144         # For the most part, we can spawn git-fast-import without
145         # leaking FDs to it...
146         $self->idx_init;
147
148         my $mid0;
149         my $num = num_for($self, $mime, \$mid0);
150         defined $num or return; # duplicate
151         defined $mid0 or die "BUG: $mid0 undefined\n";
152         my $im = $self->importer;
153         my $cmt = $im->add($mime);
154         $cmt = $im->get_mark($cmt);
155         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
156
157         my ($oid, $len, $msgref) = @{$im->{last_object}};
158         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
159         my $nparts = $self->{partitions};
160         my $part = $num % $nparts;
161         my $idx = $self->idx_part($part);
162         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
163         my $n = $self->{transact_bytes} += $len;
164         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
165                 $self->checkpoint;
166         }
167
168         $cmt;
169 }
170
171 sub num_for {
172         my ($self, $mime, $mid0) = @_;
173         my $mids = mids($mime->header_obj);
174         if (@$mids) {
175                 my $mid = $mids->[0];
176                 my $num = $self->{mm}->mid_insert($mid);
177                 if (defined $num) { # common case
178                         $$mid0 = $mid;
179                         return $num;
180                 };
181
182                 # crap, Message-ID is already known, hope somebody just resent:
183                 foreach my $m (@$mids) {
184                         # read-only lookup now safe to do after above barrier
185                         my $existing = lookup_content($self, $mime, $m);
186                         # easy, don't store duplicates
187                         # note: do not add more diagnostic info here since
188                         # it gets noisy on public-inbox-watch restarts
189                         return if $existing;
190                 }
191
192                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
193                 # or NNTP article number), use that article number if it's
194                 # not in Over.
195                 my $altid = $self->{-inbox}->{altid};
196                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
197                         my $num = $self->{mm}->num_for($mid);
198
199                         if (defined $num && !$self->{over}->get_art($num)) {
200                                 $$mid0 = $mid;
201                                 return $num;
202                         }
203                 }
204
205                 # very unlikely:
206                 warn "<$mid> reused for mismatched content\n";
207
208                 # try the rest of the mids
209                 for(my $i = $#$mids; $i >= 1; $i--) {
210                         my $m = $mids->[$i];
211                         $num = $self->{mm}->mid_insert($m);
212                         if (defined $num) {
213                                 warn "alternative <$m> for <$mid> found\n";
214                                 $$mid0 = $m;
215                                 return $num;
216                         }
217                 }
218         }
219         # none of the existing Message-IDs are good, generate a new one:
220         num_for_harder($self, $mime, $mid0);
221 }
222
223 sub num_for_harder {
224         my ($self, $mime, $mid0) = @_;
225
226         my $hdr = $mime->header_obj;
227         my $dig = content_digest($mime);
228         $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
229         my $num = $self->{mm}->mid_insert($$mid0);
230         unless (defined $num) {
231                 # it's hard to spoof the last Received: header
232                 my @recvd = $hdr->header_raw('Received');
233                 $dig->add("Received: $_") foreach (@recvd);
234                 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
235                 $num = $self->{mm}->mid_insert($$mid0);
236
237                 # fall back to a random Message-ID and give up determinism:
238                 until (defined($num)) {
239                         $dig->add(rand);
240                         $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
241                         warn "using random Message-ID <$$mid0> as fallback\n";
242                         $num = $self->{mm}->mid_insert($$mid0);
243                 }
244         }
245         PublicInbox::Import::append_mid($hdr, $$mid0);
246         $num;
247 }
248
249 sub idx_part {
250         my ($self, $part) = @_;
251         $self->{idx_parts}->[$part];
252 }
253
254 # idempotent
255 sub idx_init {
256         my ($self, $opt) = @_;
257         return if $self->{idx_parts};
258         my $ibx = $self->{-inbox};
259
260         # do not leak read-only FDs to child processes, we only have these
261         # FDs for duplicate detection so they should not be
262         # frequently activated.
263         delete $ibx->{$_} foreach (qw(git mm search));
264
265         my $indexlevel = $ibx->{indexlevel};
266         if ($indexlevel && $indexlevel eq 'basic') {
267                 $self->{parallel} = 0;
268         }
269
270         if ($self->{parallel}) {
271                 pipe(my ($r, $w)) or die "pipe failed: $!";
272                 # pipe for barrier notifications doesn't need to be big,
273                 # 1031: F_SETPIPE_SZ
274                 fcntl($w, 1031, 4096) if $^O eq 'linux';
275                 $self->{bnote} = [ $r, $w ];
276                 $w->autoflush(1);
277         }
278
279         my $over = $self->{over};
280         $ibx->umask_prepare;
281         $ibx->with_umask(sub {
282                 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
283                 $over->create;
284
285                 # -compact can change partition count while -watch is idle
286                 my $nparts = count_partitions($self);
287                 if ($nparts && $nparts != $self->{partitions}) {
288                         $self->{partitions} = $nparts;
289                 }
290
291                 # need to create all parts before initializing msgmap FD
292                 my $max = $self->{partitions} - 1;
293
294                 # idx_parts must be visible to all forked processes
295                 my $idx = $self->{idx_parts} = [];
296                 for my $i (0..$max) {
297                         push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
298                 }
299
300                 # Now that all subprocesses are up, we can open the FDs
301                 # for SQLite:
302                 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
303                         "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
304                 $mm->{dbh}->begin_work;
305         });
306 }
307
308 sub purge_oids ($$) {
309         my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
310         $self->done;
311         my $pfx = "$self->{-inbox}->{mainrepo}/git";
312         my $purges = [];
313         my $max = $self->{epoch_max};
314
315         unless (defined($max)) {
316                 defined(my $latest = git_dir_latest($self, \$max)) or return;
317                 $self->{epoch_max} = $max;
318         }
319         foreach my $i (0..$max) {
320                 my $git_dir = "$pfx/$i.git";
321                 -d $git_dir or next;
322                 my $git = PublicInbox::Git->new($git_dir);
323                 my $im = $self->import_init($git, 0, 1);
324                 $purges->[$i] = $im->purge_oids($purge);
325                 $im->done;
326         }
327         $purges;
328 }
329
330 sub content_ids ($) {
331         my ($mime) = @_;
332         my @cids = ( content_id($mime) );
333
334         # Email::MIME->as_string doesn't always round-trip, so we may
335         # use a second content_id
336         my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
337         push @cids, $rt if $cids[0] ne $rt;
338         \@cids;
339 }
340
341 sub content_matches ($$) {
342         my ($cids, $existing) = @_;
343         my $cid = content_id($existing);
344         foreach (@$cids) {
345                 return 1 if $_ eq $cid
346         }
347         0
348 }
349
350 sub remove_internal ($$$$) {
351         my ($self, $mime, $cmt_msg, $purge) = @_;
352         $self->idx_init;
353         my $im = $self->importer unless $purge;
354         my $over = $self->{over};
355         my $cids = content_ids($mime);
356         my $parts = $self->{idx_parts};
357         my $mm = $self->{mm};
358         my $removed;
359         my $mids = mids($mime->header_obj);
360
361         # We avoid introducing new blobs into git since the raw content
362         # can be slightly different, so we do not need the user-supplied
363         # message now that we have the mids and content_id
364         $mime = undef;
365         my $mark;
366
367         foreach my $mid (@$mids) {
368                 my %gone;
369                 my ($id, $prev);
370                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
371                         my $msg = get_blob($self, $smsg);
372                         if (!defined($msg)) {
373                                 warn "broken smsg for $mid\n";
374                                 next; # continue
375                         }
376                         my $orig = $$msg;
377                         my $cur = PublicInbox::MIME->new($msg);
378                         if (content_matches($cids, $cur)) {
379                                 $smsg->{mime} = $cur;
380                                 $gone{$smsg->{num}} = [ $smsg, \$orig ];
381                         }
382                 }
383                 my $n = scalar keys %gone;
384                 next unless $n;
385                 if ($n > 1) {
386                         warn "BUG: multiple articles linked to <$mid>\n",
387                                 join(',', sort keys %gone), "\n";
388                 }
389                 foreach my $num (keys %gone) {
390                         my ($smsg, $orig) = @{$gone{$num}};
391                         $mm->num_delete($num);
392                         # $removed should only be set once assuming
393                         # no bugs in our deduplication code:
394                         $removed = $smsg;
395                         my $oid = $smsg->{blob};
396                         if ($purge) {
397                                 $purge->{$oid} = 1;
398                         } else {
399                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
400                         }
401                         $orig = undef;
402                         unindex_oid_remote($self, $oid, $mid);
403                 }
404         }
405
406         if (defined $mark) {
407                 my $cmt = $im->get_mark($mark);
408                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
409         }
410         if ($purge && scalar keys %$purge) {
411                 return purge_oids($self, $purge);
412         }
413         $removed;
414 }
415
416 # public
417 sub remove {
418         my ($self, $mime, $cmt_msg) = @_;
419         $self->{-inbox}->with_umask(sub {
420                 remove_internal($self, $mime, $cmt_msg, undef);
421         });
422 }
423
424 # public
425 sub purge {
426         my ($self, $mime) = @_;
427         my $purges = $self->{-inbox}->with_umask(sub {
428                 remove_internal($self, $mime, undef, {});
429         }) or return;
430         $self->idx_init if @$purges; # ->done is called on purges
431         for my $i (0..$#$purges) {
432                 defined(my $cmt = $purges->[$i]) or next;
433                 $self->{last_commit}->[$i] = $cmt;
434         }
435         $purges;
436 }
437
438 sub last_commit_part ($$;$) {
439         my ($self, $i, $cmt) = @_;
440         my $v = PublicInbox::Search::SCHEMA_VERSION();
441         $self->{mm}->last_commit_xap($v, $i, $cmt);
442 }
443
444 sub set_last_commits ($) {
445         my ($self) = @_;
446         defined(my $epoch_max = $self->{epoch_max}) or return;
447         my $last_commit = $self->{last_commit};
448         foreach my $i (0..$epoch_max) {
449                 defined(my $cmt = $last_commit->[$i]) or next;
450                 $last_commit->[$i] = undef;
451                 last_commit_part($self, $i, $cmt);
452         }
453 }
454
455 sub barrier_init {
456         my ($self, $n) = @_;
457         $self->{bnote} or return;
458         --$n;
459         my $barrier = { map { $_ => 1 } (0..$n) };
460 }
461
462 sub barrier_wait {
463         my ($self, $barrier) = @_;
464         my $bnote = $self->{bnote} or return;
465         my $r = $bnote->[0];
466         while (scalar keys %$barrier) {
467                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
468                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
469                 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
470         }
471 }
472
473 # public
474 sub checkpoint ($;$) {
475         my ($self, $wait) = @_;
476
477         if (my $im = $self->{im}) {
478                 if ($wait) {
479                         $im->barrier;
480                 } else {
481                         $im->checkpoint;
482                 }
483         }
484         my $parts = $self->{idx_parts};
485         if ($parts) {
486                 my $dbh = $self->{mm}->{dbh};
487
488                 # SQLite msgmap data is second in importance
489                 $dbh->commit;
490
491                 # SQLite overview is third
492                 $self->{over}->commit_lazy;
493
494                 # Now deal with Xapian
495                 if ($wait) {
496                         my $barrier = $self->barrier_init(scalar @$parts);
497
498                         # each partition needs to issue a barrier command
499                         $_->remote_barrier for @$parts;
500
501                         # wait for each Xapian partition
502                         $self->barrier_wait($barrier);
503                 } else {
504                         $_->remote_commit for @$parts;
505                 }
506
507                 # last_commit is special, don't commit these until
508                 # remote partitions are done:
509                 $dbh->begin_work;
510                 set_last_commits($self);
511                 $dbh->commit;
512
513                 $dbh->begin_work;
514         }
515         $self->{transact_bytes} = 0;
516 }
517
518 # issue a write barrier to ensure all data is visible to other processes
519 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
520 # public
521 sub barrier { checkpoint($_[0], 1) };
522
523 # public
524 sub done {
525         my ($self) = @_;
526         my $im = delete $self->{im};
527         $im->done if $im; # PublicInbox::Import::done
528         checkpoint($self);
529         my $mm = delete $self->{mm};
530         $mm->{dbh}->commit if $mm;
531         my $parts = delete $self->{idx_parts};
532         if ($parts) {
533                 $_->remote_close for @$parts;
534         }
535         $self->{over}->disconnect;
536         delete $self->{bnote};
537         $self->{transact_bytes} = 0;
538         $self->lock_release if $parts;
539         $self->{-inbox}->git->cleanup;
540 }
541
542 sub fill_alternates ($$) {
543         my ($self, $epoch) = @_;
544
545         my $pfx = "$self->{-inbox}->{mainrepo}/git";
546         my $all = "$self->{-inbox}->{mainrepo}/all.git";
547         my @cmd;
548         unless (-d $all) {
549                 PublicInbox::Import::init_bare($all);
550         }
551         @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config",
552                         'include.path', '../../all.git/config');
553         PublicInbox::Import::run_die(\@cmd);
554
555         my $alt = "$all/objects/info/alternates";
556         my %alts;
557         my @add;
558         if (-e $alt) {
559                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
560                 %alts = map { chomp; $_ => 1 } (<$fh>);
561         }
562         foreach my $i (0..$epoch) {
563                 my $dir = "../../git/$i.git/objects";
564                 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
565         }
566         return unless @add;
567         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
568         foreach my $dir (@add) {
569                 print $fh "$dir\n" or die "print >> $alt: $!\n";
570         }
571         close $fh or die "close $alt: $!\n";
572 }
573
574 sub git_init {
575         my ($self, $epoch) = @_;
576         my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git";
577         my @cmd = (qw(git init --bare -q), $git_dir);
578         PublicInbox::Import::run_die(\@cmd);
579         fill_alternates($self, $epoch);
580         $git_dir
581 }
582
583 sub git_dir_latest {
584         my ($self, $max) = @_;
585         $$max = -1;
586         my $pfx = "$self->{-inbox}->{mainrepo}/git";
587         return unless -d $pfx;
588         my $latest;
589         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
590         while (defined(my $git_dir = readdir($dh))) {
591                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
592                 if ($1 > $$max) {
593                         $$max = $1;
594                         $latest = "$pfx/$git_dir";
595                 }
596         }
597         $latest;
598 }
599
600 sub importer {
601         my ($self) = @_;
602         my $im = $self->{im};
603         if ($im) {
604                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
605                         return $im;
606                 } else {
607                         $self->{im} = undef;
608                         $im->done;
609                         $im = undef;
610                         $self->checkpoint;
611                         my $git_dir = $self->git_init(++$self->{epoch_max});
612                         my $git = PublicInbox::Git->new($git_dir);
613                         return $self->import_init($git, 0);
614                 }
615         }
616         my $epoch = 0;
617         my $max;
618         my $latest = git_dir_latest($self, \$max);
619         if (defined $latest) {
620                 my $git = PublicInbox::Git->new($latest);
621                 my $packed_bytes = $git->packed_bytes;
622                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
623
624                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
625                         $epoch = $max + 1;
626                 } else {
627                         $self->{epoch_max} = $max;
628                         return $self->import_init($git, $packed_bytes);
629                 }
630         }
631         $self->{epoch_max} = $epoch;
632         $latest = $self->git_init($epoch);
633         $self->import_init(PublicInbox::Git->new($latest), 0);
634 }
635
636 sub import_init {
637         my ($self, $git, $packed_bytes, $tmp) = @_;
638         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
639         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
640         $im->{want_object_info} = 1;
641         $im->{lock_path} = undef;
642         $im->{path_type} = 'v2';
643         $self->{im} = $im unless $tmp;
644         $im;
645 }
646
647 # XXX experimental
648 sub diff ($$$) {
649         my ($mid, $cur, $new) = @_;
650         use File::Temp qw(tempfile);
651
652         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
653         print $ah $cur->as_string or die "print: $!";
654         close $ah or die "close: $!";
655         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
656         PublicInbox::Import::drop_unwanted_headers($new);
657         print $bh $new->as_string or die "print: $!";
658         close $bh or die "close: $!";
659         my $cmd = [ qw(diff -u), $an, $bn ];
660         print STDERR "# MID conflict <$mid>\n";
661         my $pid = spawn($cmd, undef, { 1 => 2 });
662         defined $pid or die "diff failed to spawn $!";
663         waitpid($pid, 0) == $pid or die "diff did not finish";
664         unlink($an, $bn);
665 }
666
667 sub get_blob ($$) {
668         my ($self, $smsg) = @_;
669         if (my $im = $self->{im}) {
670                 my $msg = $im->cat_blob($smsg->{blob});
671                 return $msg if $msg;
672         }
673         # older message, should be in alternates
674         my $ibx = $self->{-inbox};
675         $ibx->msg_by_smsg($smsg);
676 }
677
678 sub lookup_content ($$$) {
679         my ($self, $mime, $mid) = @_;
680         my $over = $self->{over};
681         my $cids = content_ids($mime);
682         my ($id, $prev);
683         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
684                 my $msg = get_blob($self, $smsg);
685                 if (!defined($msg)) {
686                         warn "broken smsg for $mid\n";
687                         next;
688                 }
689                 my $cur = PublicInbox::MIME->new($msg);
690                 if (content_matches($cids, $cur)) {
691                         $smsg->{mime} = $cur;
692                         return $smsg;
693                 }
694
695
696                 # XXX DEBUG_DIFF is experimental and may be removed
697                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
698         }
699         undef;
700 }
701
702 sub atfork_child {
703         my ($self) = @_;
704         my $fh = delete $self->{reindex_pipe};
705         close $fh if $fh;
706         if (my $parts = $self->{idx_parts}) {
707                 $_->atfork_child foreach @$parts;
708         }
709         if (my $im = $self->{im}) {
710                 $im->atfork_child;
711         }
712         die "unexpected mm" if $self->{mm};
713         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
714         $self->{bnote}->[1];
715 }
716
717 sub mark_deleted ($$$$) {
718         my ($self, $sync, $git, $oid) = @_;
719         my $msgref = $git->cat_file($oid);
720         my $mime = PublicInbox::MIME->new($$msgref);
721         my $mids = mids($mime->header_obj);
722         my $cid = content_id($mime);
723         foreach my $mid (@$mids) {
724                 $sync->{D}->{"$mid\0$cid"} = $oid;
725         }
726 }
727
728 sub reindex_oid ($$$$) {
729         my ($self, $sync, $git, $oid) = @_;
730         my $len;
731         my $msgref = $git->cat_file($oid, \$len);
732         my $mime = PublicInbox::MIME->new($$msgref);
733         my $mids = mids($mime->header_obj);
734         my $cid = content_id($mime);
735
736         # get the NNTP article number we used before, highest number wins
737         # and gets deleted from sync->{mm_tmp};
738         my $mid0;
739         my $num = -1;
740         my $del = 0;
741         foreach my $mid (@$mids) {
742                 $del += delete($sync->{D}->{"$mid\0$cid"}) ? 1 : 0;
743                 my $n = $sync->{mm_tmp}->num_for($mid);
744                 if (defined $n && $n > $num) {
745                         $mid0 = $mid;
746                         $num = $n;
747                         $self->{mm}->mid_set($num, $mid0);
748                 }
749         }
750         if (!defined($mid0) && !$del) {
751                 $num = $sync->{regen}--;
752                 die "BUG: ran out of article numbers\n" if $num <= 0;
753                 my $mm = $self->{mm};
754                 foreach my $mid (reverse @$mids) {
755                         if ($mm->mid_set($num, $mid) == 1) {
756                                 $mid0 = $mid;
757                                 last;
758                         }
759                 }
760                 if (!defined($mid0)) {
761                         my $id = '<' . join('> <', @$mids) . '>';
762                         warn "Message-ID $id unusable for $num\n";
763                         foreach my $mid (@$mids) {
764                                 defined(my $n = $mm->num_for($mid)) or next;
765                                 warn "#$n previously mapped for <$mid>\n";
766                         }
767                 }
768         }
769
770         if (!defined($mid0) || $del) {
771                 if (!defined($mid0) && $del) { # expected for deletes
772                         $num = $sync->{regen}--;
773                         $self->{mm}->num_highwater($num) if !$sync->{reindex};
774                         return
775                 }
776
777                 my $id = '<' . join('> <', @$mids) . '>';
778                 defined($mid0) or
779                         warn "Skipping $id, no article number found\n";
780                 if ($del && defined($mid0)) {
781                         warn "$id was deleted $del " .
782                                 "time(s) but mapped to article #$num\n";
783                 }
784                 return;
785
786         }
787         $sync->{mm_tmp}->mid_delete($mid0) or
788                 die "failed to delete <$mid0> for article #$num\n";
789
790         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
791         my $nparts = $self->{partitions};
792         my $part = $num % $nparts;
793         my $idx = $self->idx_part($part);
794         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
795         my $n = $self->{transact_bytes} += $len;
796         $sync->{nr}++;
797         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
798                 $git->cleanup;
799                 $sync->{mm_tmp}->atfork_prepare;
800                 $self->done; # release lock
801
802                 if (my $pr = $sync->{-opt}->{-progress}) {
803                         my ($bn) = (split('/', $git->{git_dir}))[-1];
804                         $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
805                 }
806
807                 # allow -watch or -mda to write...
808                 $self->idx_init; # reacquire lock
809                 $sync->{mm_tmp}->atfork_parent;
810         }
811 }
812
813 # only update last_commit for $i on reindex iff newer than current
814 sub update_last_commit ($$$$) {
815         my ($self, $git, $i, $cmt) = @_;
816         my $last = last_commit_part($self, $i);
817         if (defined $last && is_ancestor($git, $last, $cmt)) {
818                 my @cmd = (qw(rev-list --count), "$last..$cmt");
819                 chomp(my $n = $git->qx(@cmd));
820                 return if $n ne '' && $n == 0;
821         }
822         last_commit_part($self, $i, $cmt);
823 }
824
825 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
826
827 sub last_commits ($$) {
828         my ($self, $epoch_max) = @_;
829         my $heads = [];
830         for (my $i = $epoch_max; $i >= 0; $i--) {
831                 $heads->[$i] = last_commit_part($self, $i);
832         }
833         $heads;
834 }
835
836 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
837
838 # returns a revision range for git-log(1)
839 sub log_range ($$$$$) {
840         my ($self, $sync, $git, $i, $tip) = @_;
841         my $opt = $sync->{-opt};
842         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
843         my $cur = $sync->{ranges}->[$i] or do {
844                 $pr->("$i.git indexing all of $tip") if $pr;
845                 return $tip; # all of it
846         };
847
848         # fast equality check to avoid (v)fork+execve overhead
849         if ($cur eq $tip) {
850                 $sync->{ranges}->[$i] = undef;
851                 return;
852         }
853
854         my $range = "$cur..$tip";
855         $pr->("$i.git checking contiguity... ") if $pr;
856         if (is_ancestor($git, $cur, $tip)) { # common case
857                 $pr->("OK\n") if $pr;
858                 my $n = $git->qx(qw(rev-list --count), $range);
859                 chomp($n);
860                 if ($n == 0) {
861                         $sync->{ranges}->[$i] = undef;
862                         $pr->("$i.git has nothing new\n") if $pr;
863                         return; # nothing to do
864                 }
865                 $pr->("$i.git has $n changes since $cur\n") if $pr;
866         } else {
867                 $pr->("FAIL\n") if $pr;
868                 warn <<"";
869 discontiguous range: $range
870 Rewritten history? (in $git->{git_dir})
871
872                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
873                 if ($base) {
874                         $range = "$base..$tip";
875                         warn "found merge-base: $base\n"
876                 } else {
877                         $range = $tip;
878                         warn "discarding history at $cur\n";
879                 }
880                 warn <<"";
881 reindexing $git->{git_dir} starting at
882 $range
883
884                 $sync->{unindex_range}->{$i} = "$base..$cur";
885         }
886         $range;
887 }
888
889 sub sync_prepare ($$$) {
890         my ($self, $sync, $epoch_max) = @_;
891         my $pr = $sync->{-opt}->{-progress};
892         my $regen_max = 0;
893         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
894
895         # reindex stops at the current heads and we later rerun index_sync
896         # without {reindex}
897         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
898
899         for (my $i = $epoch_max; $i >= 0; $i--) {
900                 die 'BUG: already indexing!' if $self->{reindex_pipe};
901                 my $git_dir = git_dir_n($self, $i);
902                 -d $git_dir or next; # missing parts are fine
903                 my $git = PublicInbox::Git->new($git_dir);
904                 if ($reindex_heads) {
905                         $head = $reindex_heads->[$i] or next;
906                 }
907                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
908
909                 next if $?; # new repo
910                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
911                 $sync->{ranges}->[$i] = $range;
912
913                 # can't use 'rev-list --count' if we use --diff-filter
914                 $pr->("$i.git counting $range ... ") if $pr;
915                 my $n = 0;
916                 my $fh = $git->popen(qw(log --pretty=tformat:%H
917                                 --no-notes --no-color --no-renames
918                                 --diff-filter=AM), $range, '--', 'm');
919                 ++$n while <$fh>;
920                 $pr->("$n\n") if $pr;
921                 $regen_max += $n;
922         }
923
924         return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
925
926         # reindex should NOT see new commits anymore, if we do,
927         # it's a problem and we need to notice it via die()
928         my $pad = length($regen_max) + 1;
929         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
930         $sync->{nr} = 0;
931         return -1 if $sync->{reindex};
932         $regen_max + $self->{mm}->num_highwater() || 0;
933 }
934
935 sub unindex_oid_remote ($$$) {
936         my ($self, $oid, $mid) = @_;
937         $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
938         $self->{over}->remove_oid($oid, $mid);
939 }
940
941 sub unindex_oid ($$$) {
942         my ($self, $git, $oid) = @_;
943         my $msgref = $git->cat_file($oid);
944         my $mime = PublicInbox::MIME->new($msgref);
945         my $mids = mids($mime->header_obj);
946         $mime = $msgref = undef;
947         my $over = $self->{over};
948         foreach my $mid (@$mids) {
949                 my %gone;
950                 my ($id, $prev);
951                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
952                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
953                         1; # continue
954                 }
955                 my $n = scalar keys %gone;
956                 next unless $n;
957                 if ($n > 1) {
958                         warn "BUG: multiple articles linked to $oid\n",
959                                 join(',',sort keys %gone), "\n";
960                 }
961                 foreach my $num (keys %gone) {
962                         $self->{unindexed}->{$_}++;
963                         $self->{mm}->num_delete($num);
964                 }
965                 unindex_oid_remote($self, $oid, $mid);
966         }
967 }
968
969 my $x40 = qr/[a-f0-9]{40}/;
970 sub unindex ($$$$) {
971         my ($self, $sync, $git, $unindex_range) = @_;
972         my $un = $self->{unindexed} ||= {}; # num => removal count
973         my $before = scalar keys %$un;
974         my @cmd = qw(log --raw -r
975                         --no-notes --no-color --no-abbrev --no-renames);
976         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
977         while (<$fh>) {
978                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
979                 unindex_oid($self, $git, $1);
980         }
981         delete $self->{reindex_pipe};
982         $fh = undef;
983
984         return unless $sync->{-opt}->{prune};
985         my $after = scalar keys %$un;
986         return if $before == $after;
987
988         # ensure any blob can not longer be accessed via dumb HTTP
989         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
990                 qw(-c gc.reflogExpire=now gc --prune=all)]);
991 }
992
993 sub sync_ranges ($$$) {
994         my ($self, $sync, $epoch_max) = @_;
995         my $reindex = $sync->{reindex};
996
997         return last_commits($self, $epoch_max) unless $reindex;
998         return [] if ref($reindex) ne 'HASH';
999
1000         my $ranges = $reindex->{from}; # arrayref;
1001         if (ref($ranges) ne 'ARRAY') {
1002                 die 'BUG: $reindex->{from} not an ARRAY';
1003         }
1004         $ranges;
1005 }
1006
1007 sub index_epoch ($$$) {
1008         my ($self, $sync, $i) = @_;
1009
1010         my $git_dir = git_dir_n($self, $i);
1011         die 'BUG: already reindexing!' if $self->{reindex_pipe};
1012         -d $git_dir or return; # missing parts are fine
1013         fill_alternates($self, $i);
1014         my $git = PublicInbox::Git->new($git_dir);
1015         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1016                 unindex($self, $sync, $git, $unindex_range);
1017         }
1018         defined(my $range = $sync->{ranges}->[$i]) or return;
1019         if (my $pr = $sync->{-opt}->{-progress}) {
1020                 $pr->("$i.git indexing $range\n");
1021         }
1022
1023         my @cmd = qw(log --raw -r --pretty=tformat:%H
1024                         --no-notes --no-color --no-abbrev --no-renames);
1025         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1026         my $cmt;
1027         while (<$fh>) {
1028                 chomp;
1029                 $self->{current_info} = "$i.git $_";
1030                 if (/\A$x40$/o && !defined($cmt)) {
1031                         $cmt = $_;
1032                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1033                         reindex_oid($self, $sync, $git, $1);
1034                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1035                         mark_deleted($self, $sync, $git, $1);
1036                 }
1037         }
1038         $fh = undef;
1039         delete $self->{reindex_pipe};
1040         update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1041 }
1042
1043 # public, called by public-inbox-index
1044 sub index_sync {
1045         my ($self, $opt) = @_;
1046         $opt ||= {};
1047         my $pr = $opt->{-progress};
1048         my $epoch_max;
1049         my $latest = git_dir_latest($self, \$epoch_max);
1050         return unless defined $latest;
1051         $self->idx_init($opt); # acquire lock
1052         my $sync = {
1053                 D => {}, # "$mid\0$cid" => $oid
1054                 unindex_range => {}, # EPOCH => oid_old..oid_new
1055                 reindex => $opt->{reindex},
1056                 -opt => $opt
1057         };
1058         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1059         $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1060
1061         if ($sync->{regen}) {
1062                 # tmp_clone seems to fail if inside a transaction, so
1063                 # we rollback here (because we opened {mm} for reading)
1064                 # Note: we do NOT rely on DBI transactions for atomicity;
1065                 # only for batch performance.
1066                 $self->{mm}->{dbh}->rollback;
1067                 $self->{mm}->{dbh}->begin_work;
1068                 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1069         }
1070
1071         # work backwards through history
1072         for (my $i = $epoch_max; $i >= 0; $i--) {
1073                 index_epoch($self, $sync, $i);
1074         }
1075
1076         # unindex is required for leftovers if "deletes" affect messages
1077         # in a previous fetch+index window:
1078         if (my @leftovers = values %{delete $sync->{D}}) {
1079                 my $git = $self->{-inbox}->git;
1080                 unindex_oid($self, $git, $_) for @leftovers;
1081                 $git->cleanup;
1082         }
1083         $self->done;
1084
1085         if (my $nr = $sync->{nr}) {
1086                 my $pr = $sync->{-opt}->{-progress};
1087                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1088         }
1089
1090         # reindex does not pick up new changes, so we rerun w/o it:
1091         if ($opt->{reindex}) {
1092                 my %again = %$opt;
1093                 $sync = undef;
1094                 delete @again{qw(reindex -skip_lock)};
1095                 index_sync($self, \%again);
1096         }
1097 }
1098
1099 1;