]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
ipc: switch to one-way pipes
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018-2021 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 v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::Eml;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentHash qw(content_hash content_digest);
16 use PublicInbox::InboxWritable;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd run_die);
20 use PublicInbox::SearchIdx qw(log2stack is_ancestor check_size is_bad_blob);
21 use IO::Handle; # ->autoflush
22 use File::Temp ();
23
24 my $OID = qr/[a-f0-9]{40,}/;
25 # an estimate of the post-packed size to the raw uncompressed size
26 our $PACKING_FACTOR = 0.4;
27
28 # SATA storage lags behind what CPUs are capable of, so relying on
29 # nproc(1) can be misleading and having extra Xapian shards is a
30 # waste of FDs and space.  It can also lead to excessive IO latency
31 # and slow things down.  Users on NVME or other fast storage can
32 # use the NPROC env or switches in our script/public-inbox-* programs
33 # to increase Xapian shards
34 our $NPROC_MAX_DEFAULT = 4;
35
36 sub detect_nproc () {
37         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
38         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
39                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
40         }
41         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
42                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
43         }
44
45         # should we bother with `sysctl hw.ncpu`?  Those only give
46         # us total processor count, not online processor count.
47         undef
48 }
49
50 sub nproc_shards ($) {
51         my ($creat_opt) = @_;
52         my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
53         $n //= $ENV{NPROC};
54         if (!$n) {
55                 # assume 2 cores if not detectable or zero
56                 state $NPROC_DETECTED = detect_nproc() || 2;
57                 $n = $NPROC_DETECTED;
58                 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
59         }
60
61         # subtract for the main process and git-fast-import
62         $n -= 1;
63         $n < 1 ? 1 : $n;
64 }
65
66 sub count_shards ($) {
67         my ($self) = @_;
68         if (my $ibx = $self->{ibx}) {
69                 # always load existing shards in case core count changes:
70                 # Also, shard count may change while -watch is running
71                 my $srch = $ibx->search or return 0;
72                 delete $ibx->{search};
73                 $srch->{nshard} // 0
74         } else { # ExtSearchIdx
75                 $self->{nshard} ||= scalar($self->xdb_shards_flat);
76         }
77 }
78
79 sub new {
80         # $creat may be any true value, or 0/undef.  A hashref is true,
81         # and $creat->{nproc} may be set to an integer
82         my ($class, $v2ibx, $creat) = @_;
83         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
84         my $dir = $v2ibx->assert_usable_dir;
85         unless (-d $dir) {
86                 if ($creat) {
87                         require File::Path;
88                         File::Path::mkpath($dir);
89                 } else {
90                         die "$dir does not exist\n";
91                 }
92         }
93         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
94         my $self = {
95                 ibx => $v2ibx,
96                 im => undef, #  PublicInbox::Import
97                 parallel => 1,
98                 transact_bytes => 0,
99                 total_bytes => 0,
100                 current_info => '',
101                 xpfx => $xpfx,
102                 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
103                 lock_path => "$dir/inbox.lock",
104                 # limit each git repo (epoch) to 1GB or so
105                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
106                 last_commit => [], # git epoch -> commit
107         };
108         $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
109         $self->{shards} = count_shards($self) || nproc_shards($creat);
110         bless $self, $class;
111 }
112
113 # public (for now?)
114 sub init_inbox {
115         my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
116         if (defined $shards) {
117                 $self->{parallel} = 0 if $shards == 0;
118                 $self->{shards} = $shards if $shards > 0;
119         }
120         $self->idx_init;
121         $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
122         my $max = $self->{ibx}->max_git_epoch;
123         $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
124         $self->git_init($max // 0);
125         $self->done;
126 }
127
128 # returns undef on duplicate or spam
129 # mimics Import::add and wraps it for v2
130 sub add {
131         my ($self, $eml, $check_cb) = @_;
132         $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
133 }
134
135 sub idx_shard ($$) {
136         my ($self, $num) = @_;
137         $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
138 }
139
140 # indexes a message, returns true if checkpointing is needed
141 sub do_idx ($$$) {
142         my ($self, $eml, $smsg) = @_;
143         $self->{oidx}->add_overview($eml, $smsg);
144         my $idx = idx_shard($self, $smsg->{num});
145         $idx->index_eml($eml, $smsg);
146         my $n = $self->{transact_bytes} += $smsg->{bytes};
147         $n >= $self->{batch_bytes};
148 }
149
150 sub _add {
151         my ($self, $mime, $check_cb) = @_;
152
153         # spam check:
154         if ($check_cb) {
155                 $mime = $check_cb->($mime, $self->{ibx}) or return;
156         }
157
158         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
159         # as does SQLite 3.4.1+ (released in 2007-07-20), and
160         # Xapian 1.3.2+ (released 2015-03-15).
161         # For the most part, we can spawn git-fast-import without
162         # leaking FDs to it...
163         $self->idx_init;
164
165         my ($num, $mid0) = v2_num_for($self, $mime);
166         defined $num or return; # duplicate
167         defined $mid0 or die "BUG: \$mid0 undefined\n";
168         my $im = $self->importer;
169         my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
170         my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
171         $cmt = $im->get_mark($cmt);
172         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
173
174         if (do_idx($self, $mime, $smsg)) {
175                 $self->checkpoint;
176         }
177
178         $cmt;
179 }
180
181 sub v2_num_for {
182         my ($self, $mime) = @_;
183         my $mids = mids($mime);
184         if (@$mids) {
185                 my $mid = $mids->[0];
186                 my $num = $self->{mm}->mid_insert($mid);
187                 if (defined $num) { # common case
188                         return ($num, $mid);
189                 }
190
191                 # crap, Message-ID is already known, hope somebody just resent:
192                 foreach my $m (@$mids) {
193                         # read-only lookup now safe to do after above barrier
194                         # easy, don't store duplicates
195                         # note: do not add more diagnostic info here since
196                         # it gets noisy on public-inbox-watch restarts
197                         return () if content_exists($self, $mime, $m);
198                 }
199
200                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
201                 # or NNTP article number), use that article number if it's
202                 # not in Over.
203                 my $altid = $self->{ibx}->{altid};
204                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
205                         my $num = $self->{mm}->num_for($mid);
206
207                         if (defined $num && !$self->{oidx}->get_art($num)) {
208                                 return ($num, $mid);
209                         }
210                 }
211
212                 # very unlikely:
213                 warn "<$mid> reused for mismatched content\n";
214
215                 # try the rest of the mids
216                 for(my $i = $#$mids; $i >= 1; $i--) {
217                         my $m = $mids->[$i];
218                         $num = $self->{mm}->mid_insert($m);
219                         if (defined $num) {
220                                 warn "alternative <$m> for <$mid> found\n";
221                                 return ($num, $m);
222                         }
223                 }
224         }
225         # none of the existing Message-IDs are good, generate a new one:
226         v2_num_for_harder($self, $mime);
227 }
228
229 sub v2_num_for_harder {
230         my ($self, $eml) = @_;
231
232         my $dig = content_digest($eml);
233         my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
234         my $num = $self->{mm}->mid_insert($mid0);
235         unless (defined $num) {
236                 # it's hard to spoof the last Received: header
237                 my @recvd = $eml->header_raw('Received');
238                 $dig->add("Received: $_") foreach (@recvd);
239                 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
240                 $num = $self->{mm}->mid_insert($mid0);
241
242                 # fall back to a random Message-ID and give up determinism:
243                 until (defined($num)) {
244                         $dig->add(rand);
245                         $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
246                         warn "using random Message-ID <$mid0> as fallback\n";
247                         $num = $self->{mm}->mid_insert($mid0);
248                 }
249         }
250         PublicInbox::Import::append_mid($eml, $mid0);
251         ($num, $mid0);
252 }
253
254 sub _idx_init { # with_umask callback
255         my ($self, $opt) = @_;
256         $self->lock_acquire unless $opt && $opt->{-skip_lock};
257         $self->{oidx}->create;
258
259         # xcpdb can change shard count while -watch is idle
260         my $nshards = count_shards($self);
261         $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
262         $self->{batch_bytes} = $opt->{batch_size} //
263                                 $PublicInbox::SearchIdx::BATCH_BYTES;
264
265         # need to create all shards before initializing msgmap FD
266         # idx_shards must be visible to all forked processes
267         my $max = $self->{shards} - 1;
268         my $idx = $self->{idx_shards} = [];
269         push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
270
271         # SearchIdxShard may do their own flushing, so don't scale
272         # until after forking
273         $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
274
275         my $ibx = $self->{ibx} or return; # ExtIdxSearch
276
277         # Now that all subprocesses are up, we can open the FDs
278         # for SQLite:
279         my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
280                                 "$ibx->{inboxdir}/msgmap.sqlite3",
281                                 $ibx->{-no_fsync} ? 2 : 1);
282         $mm->{dbh}->begin_work;
283 }
284
285 sub parallel_init ($$) {
286         my ($self, $indexlevel) = @_;
287         $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
288 }
289
290 # idempotent
291 sub idx_init {
292         my ($self, $opt) = @_;
293         return if $self->{idx_shards};
294         my $ibx = $self->{ibx};
295
296         # do not leak read-only FDs to child processes, we only have these
297         # FDs for duplicate detection so they should not be
298         # frequently activated.
299         delete @$ibx{qw(mm search)};
300         $ibx->git->cleanup;
301
302         parallel_init($self, $ibx->{indexlevel});
303         $ibx->with_umask(\&_idx_init, $self, $opt);
304 }
305
306 # returns an array mapping [ epoch => latest_commit ]
307 # latest_commit may be undef if nothing was done to that epoch
308 # $replace_map = { $object_id => $strref, ... }
309 sub _replace_oids ($$$) {
310         my ($self, $mime, $replace_map) = @_;
311         $self->done;
312         my $ibx = $self->{ibx};
313         my $pfx = "$ibx->{inboxdir}/git";
314         my $rewrites = []; # epoch => commit
315         my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
316
317         foreach my $i (0..$max) {
318                 my $git_dir = "$pfx/$i.git";
319                 -d $git_dir or next;
320                 my $git = PublicInbox::Git->new($git_dir);
321                 my $im = $self->import_init($git, 0, 1);
322                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
323                 $im->done;
324         }
325         $rewrites;
326 }
327
328 sub content_hashes ($) {
329         my ($mime) = @_;
330         my @chashes = ( content_hash($mime) );
331
332         # We still support Email::MIME, here, and
333         # Email::MIME->as_string doesn't always round-trip, so we may
334         # use a second content_hash
335         my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
336         push @chashes, $rt if $chashes[0] ne $rt;
337         \@chashes;
338 }
339
340 sub content_matches ($$) {
341         my ($chashes, $existing) = @_;
342         my $chash = content_hash($existing);
343         foreach (@$chashes) {
344                 return 1 if $_ eq $chash
345         }
346         0
347 }
348
349 # used for removing or replacing (purging)
350 sub rewrite_internal ($$;$$$) {
351         my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
352         $self->idx_init;
353         my ($im, $need_reindex, $replace_map);
354         if ($sref) {
355                 $replace_map = {}; # oid => sref
356                 $need_reindex = [] if $new_eml;
357         } else {
358                 $im = $self->importer;
359         }
360         my $oidx = $self->{oidx};
361         my $chashes = content_hashes($old_eml);
362         my $removed = [];
363         my $mids = mids($old_eml);
364
365         # We avoid introducing new blobs into git since the raw content
366         # can be slightly different, so we do not need the user-supplied
367         # message now that we have the mids and content_hash
368         $old_eml = undef;
369         my $mark;
370
371         foreach my $mid (@$mids) {
372                 my %gone; # num => [ smsg, $mime, raw ]
373                 my ($id, $prev);
374                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
375                         my $msg = get_blob($self, $smsg);
376                         if (!defined($msg)) {
377                                 warn "broken smsg for $mid\n";
378                                 next; # continue
379                         }
380                         my $orig = $$msg;
381                         my $cur = PublicInbox::Eml->new($msg);
382                         if (content_matches($chashes, $cur)) {
383                                 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
384                         }
385                 }
386                 my $n = scalar keys %gone;
387                 next unless $n;
388                 if ($n > 1) {
389                         warn "BUG: multiple articles linked to <$mid>\n",
390                                 join(',', sort keys %gone), "\n";
391                 }
392                 foreach my $num (keys %gone) {
393                         my ($smsg, $mime, $orig) = @{$gone{$num}};
394                         # $removed should only be set once assuming
395                         # no bugs in our deduplication code:
396                         $removed = [ undef, $mime, $smsg ];
397                         my $oid = $smsg->{blob};
398                         if ($replace_map) {
399                                 $replace_map->{$oid} = $sref;
400                         } else {
401                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
402                                 $removed->[0] = $mark;
403                         }
404                         $orig = undef;
405                         if ($need_reindex) { # ->replace
406                                 push @$need_reindex, $smsg;
407                         } else { # ->purge or ->remove
408                                 $self->{mm}->num_delete($num);
409                         }
410                         unindex_oid_aux($self, $oid, $mid);
411                 }
412         }
413
414         if (defined $mark) {
415                 my $cmt = $im->get_mark($mark);
416                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
417         }
418         if ($replace_map && scalar keys %$replace_map) {
419                 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
420                 return { rewrites => $rewrites, need_reindex => $need_reindex };
421         }
422         defined($mark) ? $removed : undef;
423 }
424
425 # public (see PublicInbox::Import->remove), but note the 3rd element
426 # (retval[2]) is not part of the stable API shared with Import->remove
427 sub remove {
428         my ($self, $eml, $cmt_msg) = @_;
429         my $r = $self->{ibx}->with_umask(\&rewrite_internal,
430                                                 $self, $eml, $cmt_msg);
431         defined($r) && defined($r->[0]) ? @$r: undef;
432 }
433
434 sub _replace ($$;$$) {
435         my ($self, $old_eml, $new_eml, $sref) = @_;
436         my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
437         my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
438                         $self, $old_eml, undef, $new_eml, $sref) or return;
439
440         my $rewrites = $rewritten->{rewrites};
441         # ->done is called if there are rewrites since we gc+prune from git
442         $self->idx_init if @$rewrites;
443
444         for my $i (0..$#$rewrites) {
445                 defined(my $cmt = $rewrites->[$i]) or next;
446                 $self->{last_commit}->[$i] = $cmt;
447         }
448         $rewritten;
449 }
450
451 # public
452 sub purge {
453         my ($self, $mime) = @_;
454         my $rewritten = _replace($self, $mime, undef, \'') or return;
455         $rewritten->{rewrites}
456 }
457
458 # returns the git object_id of $fh, does not write the object to FS
459 sub git_hash_raw ($$) {
460         my ($self, $raw) = @_;
461         # grab the expected OID we have to reindex:
462         pipe(my($in, $w)) or die "pipe: $!";
463         my $git_dir = $self->git->{git_dir};
464         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
465         my $r = popen_rd($cmd, undef, { 0 => $in });
466         print $w $$raw or die "print \$w: $!";
467         close $w or die "close \$w: $!";
468         local $/ = "\n";
469         chomp(my $oid = <$r>);
470         close $r or die "git hash-object failed: $?";
471         $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
472         $oid;
473 }
474
475 sub _check_mids_match ($$$) {
476         my ($old_list, $new_list, $hdrs) = @_;
477         my %old_mids = map { $_ => 1 } @$old_list;
478         my %new_mids = map { $_ => 1 } @$new_list;
479         my @old = keys %old_mids;
480         my @new = keys %new_mids;
481         my $err = "$hdrs may not be changed when replacing\n";
482         die $err if scalar(@old) != scalar(@new);
483         delete @new_mids{@old};
484         delete @old_mids{@new};
485         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
486 }
487
488 # Changing Message-IDs or References with ->replace isn't supported.
489 # The rules for dealing with messages with multiple or conflicting
490 # Message-IDs are pretty complex and rethreading hasn't been fully
491 # implemented, yet.
492 sub check_mids_match ($$) {
493         my ($old, $new) = @_;
494         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
495         _check_mids_match(references($old), references($new),
496                         'References/In-Reply-To');
497 }
498
499 # public
500 sub replace ($$$) {
501         my ($self, $old_mime, $new_mime) = @_;
502
503         check_mids_match($old_mime, $new_mime);
504
505         # mutt will always add Content-Length:, Status:, Lines: when editing
506         PublicInbox::Import::drop_unwanted_headers($new_mime);
507
508         my $raw = $new_mime->as_string;
509         my $expect_oid = git_hash_raw($self, \$raw);
510         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
511         my $need_reindex = $rewritten->{need_reindex};
512
513         # just in case we have bugs in deduplication code:
514         my $n = scalar(@$need_reindex);
515         if ($n > 1) {
516                 my $list = join(', ', map {
517                                         "$_->{num}: <$_->{mid}>"
518                                 } @$need_reindex);
519                 warn <<"";
520 W: rewritten $n messages matching content of original message (expected: 1).
521 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
522 W: $list
523
524         }
525
526         # make sure we really got the OID:
527         my ($blob, $type, $bytes) = $self->git->check($expect_oid);
528         $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
529
530         # don't leak FDs to Xapian:
531         $self->git->cleanup;
532
533         # reindex modified messages:
534         for my $smsg (@$need_reindex) {
535                 my $new_smsg = bless {
536                         blob => $blob,
537                         num => $smsg->{num},
538                         mid => $smsg->{mid},
539                 }, 'PublicInbox::Smsg';
540                 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
541                 $new_smsg->populate($new_mime, $sync);
542                 $new_smsg->set_bytes($raw, $bytes);
543                 do_idx($self, $new_mime, $new_smsg);
544         }
545         $rewritten->{rewrites};
546 }
547
548 sub last_epoch_commit ($$;$) {
549         my ($self, $i, $cmt) = @_;
550         my $v = PublicInbox::Search::SCHEMA_VERSION();
551         $self->{mm}->last_commit_xap($v, $i, $cmt);
552 }
553
554 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
555         my ($self) = @_;
556         defined(my $epoch_max = $self->{epoch_max}) or return;
557         my $last_commit = $self->{last_commit};
558         foreach my $i (0..$epoch_max) {
559                 defined(my $cmt = $last_commit->[$i]) or next;
560                 $last_commit->[$i] = undef;
561                 last_epoch_commit($self, $i, $cmt);
562         }
563 }
564
565 # public
566 sub checkpoint ($;$) {
567         my ($self, $wait) = @_;
568
569         if (my $im = $self->{im}) {
570                 if ($wait) {
571                         $im->barrier;
572                 } else {
573                         $im->checkpoint;
574                 }
575         }
576         my $shards = $self->{idx_shards};
577         if ($shards) {
578                 my $mm = $self->{mm};
579                 my $dbh = $mm->{dbh} if $mm;
580
581                 # SQLite msgmap data is second in importance
582                 $dbh->commit if $dbh;
583
584                 # SQLite overview is third
585                 $self->{oidx}->commit_lazy;
586
587                 # Now deal with Xapian
588
589                 # start commit_txn_lazy asynchronously on all parallel shards
590                 # (non-parallel waits here)
591                 $_->ipc_do('commit_txn_lazy') for @$shards;
592
593                 # transactions started on parallel shards,
594                 # wait for them by issuing an echo command (echo can only
595                 # run after commit_txn_lazy is done)
596                 if ($wait && $self->{parallel}) {
597                         my $i = 0;
598                         for my $shard (@$shards) {
599                                 my $echo = $shard->ipc_do('echo', $i);
600                                 $echo == $i or die <<"";
601 shard[$i] bad echo:$echo != $i waiting for txn commit
602
603                                 ++$i;
604                         }
605                 }
606
607                 my $midx = $self->{midx}; # misc index
608                 $midx->commit_txn if $midx;
609
610                 # last_commit is special, don't commit these until
611                 # Xapian shards are done:
612                 $dbh->begin_work if $dbh;
613                 set_last_commits($self);
614                 if ($dbh) {
615                         $dbh->commit;
616                         $dbh->begin_work;
617                 }
618                 $midx->begin_txn if $midx;
619         }
620         $self->{total_bytes} += $self->{transact_bytes};
621         $self->{transact_bytes} = 0;
622 }
623
624 # issue a write barrier to ensure all data is visible to other processes
625 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
626 # public
627 sub barrier { checkpoint($_[0], 1) };
628
629 # true if locked and active
630 sub active { !!$_[0]->{im} }
631
632 # public
633 sub done {
634         my ($self) = @_;
635         my $err = '';
636         if (my $im = delete $self->{im}) {
637                 eval { $im->done }; # PublicInbox::Import::done
638                 $err .= "import done: $@\n" if $@;
639         }
640         if (!$err) {
641                 eval { checkpoint($self) };
642                 $err .= "checkpoint: $@\n" if $@;
643         }
644         if (my $mm = delete $self->{mm}) {
645                 my $m = $err ? 'rollback' : 'commit';
646                 eval { $mm->{dbh}->$m };
647                 $err .= "msgmap $m: $@\n" if $@;
648         }
649         my $shards = delete $self->{idx_shards};
650         if ($shards) {
651                 for (@$shards) {
652                         eval { $_->shard_close };
653                         $err .= "shard close: $@\n" if $@;
654                 }
655         }
656         eval { $self->{oidx}->dbh_close };
657         $err .= "over close: $@\n" if $@;
658         delete $self->{midx};
659         my $nbytes = $self->{total_bytes};
660         $self->{total_bytes} = 0;
661         $self->lock_release(!!$nbytes) if $shards;
662         $self->git->cleanup;
663         die $err if $err;
664 }
665
666 sub write_alternates ($$$) {
667         my ($info_dir, $mode, $out) = @_;
668         my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
669         my $tmp = $fh->filename;
670         print $fh @$out or die "print $tmp: $!\n";
671         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
672         close $fh or die "close $tmp $!\n";
673         my $alt = "$info_dir/alternates";
674         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
675         $fh->unlink_on_destroy(0);
676 }
677
678 sub fill_alternates ($$) {
679         my ($self, $epoch) = @_;
680
681         my $pfx = "$self->{ibx}->{inboxdir}/git";
682         my $all = "$self->{ibx}->{inboxdir}/all.git";
683         PublicInbox::Import::init_bare($all) unless -d $all;
684         my $info_dir = "$all/objects/info";
685         my $alt = "$info_dir/alternates";
686         my (%alt, $new);
687         my $mode = 0644;
688         if (-e $alt) {
689                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
690                 $mode = (stat($fh))[2] & 07777;
691
692                 # we assign a sort score to every alternate and favor
693                 # the newest (highest numbered) one because loose objects
694                 # require scanning epochs and only the latest epoch is
695                 # expected to see loose objects
696                 my $score;
697                 my $other = 0; # in case admin adds non-epoch repos
698                 %alt = map {;
699                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
700                                 $score = $1 + 0;
701                         } else {
702                                 $score = --$other;
703                         }
704                         $_ => $score;
705                 } split(/\n+/, do { local $/; <$fh> });
706         }
707
708         foreach my $i (0..$epoch) {
709                 my $dir = "../../git/$i.git/objects";
710                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
711                         $alt{$dir} = $i;
712                         $new = 1;
713                 }
714         }
715         return unless $new;
716         write_alternates($info_dir, $mode,
717                 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
718 }
719
720 sub git_init {
721         my ($self, $epoch) = @_;
722         my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
723         PublicInbox::Import::init_bare($git_dir);
724         run_die([qw(git config), "--file=$git_dir/config",
725                 qw(include.path ../../all.git/config)]);
726         fill_alternates($self, $epoch);
727         $git_dir
728 }
729
730 sub importer {
731         my ($self) = @_;
732         my $im = $self->{im};
733         if ($im) {
734                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
735                         return $im;
736                 } else {
737                         $self->{im} = undef;
738                         $im->done;
739                         $im = undef;
740                         $self->checkpoint;
741                         my $git_dir = $self->git_init(++$self->{epoch_max});
742                         my $git = PublicInbox::Git->new($git_dir);
743                         return $self->import_init($git, 0);
744                 }
745         }
746         my $epoch = 0;
747         my $max;
748         my $latest = $self->{ibx}->git_dir_latest(\$max);
749         if (defined $latest) {
750                 my $git = PublicInbox::Git->new($latest);
751                 my $packed_bytes = $git->packed_bytes;
752                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
753
754                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
755                         $epoch = $max + 1;
756                 } else {
757                         $self->{epoch_max} = $max;
758                         return $self->import_init($git, $packed_bytes);
759                 }
760         }
761         $self->{epoch_max} = $epoch;
762         $latest = $self->git_init($epoch);
763         $self->import_init(PublicInbox::Git->new($latest), 0);
764 }
765
766 sub import_init {
767         my ($self, $git, $packed_bytes, $tmp) = @_;
768         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
769         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
770         $im->{lock_path} = undef;
771         $im->{path_type} = 'v2';
772         $self->{im} = $im unless $tmp;
773         $im;
774 }
775
776 # XXX experimental
777 sub diff ($$$) {
778         my ($mid, $cur, $new) = @_;
779
780         my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
781         print $ah $cur->as_string or die "print: $!";
782         $ah->flush or die "flush: $!";
783         PublicInbox::Import::drop_unwanted_headers($new);
784         my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
785         print $bh $new->as_string or die "print: $!";
786         $bh->flush or die "flush: $!";
787         my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
788         print STDERR "# MID conflict <$mid>\n";
789         my $pid = spawn($cmd, undef, { 1 => 2 });
790         waitpid($pid, 0) == $pid or die "diff did not finish";
791 }
792
793 sub get_blob ($$) {
794         my ($self, $smsg) = @_;
795         if (my $im = $self->{im}) {
796                 my $msg = $im->cat_blob($smsg->{blob});
797                 return $msg if $msg;
798         }
799         # older message, should be in alternates
800         $self->{ibx}->msg_by_smsg($smsg);
801 }
802
803 sub content_exists ($$$) {
804         my ($self, $mime, $mid) = @_;
805         my $oidx = $self->{oidx};
806         my $chashes = content_hashes($mime);
807         my ($id, $prev);
808         while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
809                 my $msg = get_blob($self, $smsg);
810                 if (!defined($msg)) {
811                         warn "broken smsg for $mid\n";
812                         next;
813                 }
814                 my $cur = PublicInbox::Eml->new($msg);
815                 return 1 if content_matches($chashes, $cur);
816
817                 # XXX DEBUG_DIFF is experimental and may be removed
818                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
819         }
820         undef;
821 }
822
823 sub atfork_child {
824         my ($self) = @_;
825         if (my $older_siblings = $self->{idx_shards}) {
826                 $_->ipc_sibling_atfork_child for @$older_siblings;
827         }
828         if (my $im = $self->{im}) {
829                 $im->atfork_child;
830         }
831         die "BUG: unexpected mm" if $self->{mm};
832 }
833
834 sub reindex_checkpoint ($$) {
835         my ($self, $sync) = @_;
836
837         $self->git->async_wait_all;
838         $self->update_last_commit($sync);
839         ${$sync->{need_checkpoint}} = 0;
840         my $mm_tmp = $sync->{mm_tmp};
841         $mm_tmp->atfork_prepare if $mm_tmp;
842         die 'BUG: {im} during reindex' if $self->{im};
843         if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
844                 checkpoint($self, 1); # no need to release lock on pure index
845         } else {
846                 $self->done; # release lock
847         }
848
849         if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
850                 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
851         }
852
853         # allow -watch or -mda to write...
854         $self->idx_init($sync->{-opt}); # reacquire lock
855         if (my $intvl = $sync->{check_intvl}) { # eidx
856                 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
857         }
858         $mm_tmp->atfork_parent if $mm_tmp;
859 }
860
861 sub index_finalize ($$) {
862         my ($arg, $index) = @_;
863         ++$arg->{self}->{nidx};
864         if (defined(my $cur = $arg->{cur_cmt})) {
865                 ${$arg->{latest_cmt}} = $cur;
866         } elsif ($index) {
867                 die 'BUG: {cur_cmt} missing';
868         } # else { unindexing @leftovers doesn't set {cur_cmt}
869 }
870
871 sub index_oid { # cat_async callback
872         my ($bref, $oid, $type, $size, $arg) = @_;
873         is_bad_blob($oid, $type, $size, $arg->{oid}) and
874                 return index_finalize($arg, 1); # size == 0 purged returns here
875         my $self = $arg->{self};
876         local $self->{current_info} = "$self->{current_info} $oid";
877         my ($num, $mid0);
878         my $eml = PublicInbox::Eml->new($$bref);
879         my $mids = mids($eml);
880         my $chash = content_hash($eml);
881
882         if (scalar(@$mids) == 0) {
883                 warn "E: $oid has no Message-ID, skipping\n";
884                 return;
885         }
886
887         # {unindexed} is unlikely
888         if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
889                 $num = delete($unindexed->{$mids->[0]});
890                 if (defined $num) {
891                         $mid0 = $mids->[0];
892                         $self->{mm}->mid_set($num, $mid0);
893                         delete($arg->{unindexed}) if !keys(%$unindexed);
894                 }
895         }
896         if (!defined($num)) { # reuse if reindexing (or duplicates)
897                 my $oidx = $self->{oidx};
898                 for my $mid (@$mids) {
899                         ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
900                         last if defined $num;
901                 }
902         }
903         $mid0 //= do { # is this a number we got before?
904                 $num = $arg->{mm_tmp}->num_for($mids->[0]);
905                 defined($num) ? $mids->[0] : undef;
906         };
907         if (!defined($num)) {
908                 for (my $i = $#$mids; $i >= 1; $i--) {
909                         $num = $arg->{mm_tmp}->num_for($mids->[$i]);
910                         if (defined($num)) {
911                                 $mid0 = $mids->[$i];
912                                 last;
913                         }
914                 }
915         }
916         if (defined($num)) {
917                 $arg->{mm_tmp}->num_delete($num);
918         } else { # never seen
919                 $num = $self->{mm}->mid_insert($mids->[0]);
920                 if (defined($num)) {
921                         $mid0 = $mids->[0];
922                 } else { # rare, try the rest of them, backwards
923                         for (my $i = $#$mids; $i >= 1; $i--) {
924                                 $num = $self->{mm}->mid_insert($mids->[$i]);
925                                 if (defined($num)) {
926                                         $mid0 = $mids->[$i];
927                                         last;
928                                 }
929                         }
930                 }
931         }
932         if (!defined($num)) {
933                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
934                 return;
935         }
936         ++${$arg->{nr}};
937         my $smsg = bless {
938                 num => $num,
939                 blob => $oid,
940                 mid => $mid0,
941         }, 'PublicInbox::Smsg';
942         $smsg->populate($eml, $arg);
943         $smsg->set_bytes($$bref, $size);
944         if (do_idx($self, $eml, $smsg)) {
945                 ${$arg->{need_checkpoint}} = 1;
946         }
947         index_finalize($arg, 1);
948 }
949
950 # only update last_commit for $i on reindex iff newer than current
951 sub update_last_commit {
952         my ($self, $sync, $stk) = @_;
953         my $unit = $sync->{unit} // return;
954         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
955         defined($latest_cmt) or return;
956         my $last = last_epoch_commit($self, $unit->{epoch});
957         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
958                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
959                 chomp(my $n = $unit->{git}->qx(@cmd));
960                 return if $n ne '' && $n == 0;
961         }
962         last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
963 }
964
965 sub last_commits {
966         my ($self, $sync) = @_;
967         my $heads = [];
968         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
969                 $heads->[$i] = last_epoch_commit($self, $i);
970         }
971         $heads;
972 }
973
974 # returns a revision range for git-log(1)
975 sub log_range ($$$) {
976         my ($sync, $unit, $tip) = @_;
977         my $opt = $sync->{-opt};
978         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
979         my $i = $unit->{epoch};
980         my $cur = $sync->{ranges}->[$i] or do {
981                 $pr->("$i.git indexing all of $tip\n") if $pr;
982                 return $tip; # all of it
983         };
984
985         # fast equality check to avoid (v)fork+execve overhead
986         if ($cur eq $tip) {
987                 $sync->{ranges}->[$i] = undef;
988                 return;
989         }
990
991         my $range = "$cur..$tip";
992         $pr->("$i.git checking contiguity... ") if $pr;
993         my $git = $unit->{git};
994         if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
995                 $pr->("OK\n") if $pr;
996                 my $n = $git->qx(qw(rev-list --count), $range);
997                 chomp($n);
998                 if ($n == 0) {
999                         $sync->{ranges}->[$i] = undef;
1000                         $pr->("$i.git has nothing new\n") if $pr;
1001                         return; # nothing to do
1002                 }
1003                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1004         } else {
1005                 $pr->("FAIL\n") if $pr;
1006                 warn <<"";
1007 discontiguous range: $range
1008 Rewritten history? (in $git->{git_dir})
1009
1010                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1011                 if ($base) {
1012                         $range = "$base..$tip";
1013                         warn "found merge-base: $base\n"
1014                 } else {
1015                         $range = $tip;
1016                         warn "discarding history at $cur\n";
1017                 }
1018                 warn <<"";
1019 reindexing $git->{git_dir}
1020 starting at $range
1021
1022                 # $cur^0 may no longer exist if pruned by git
1023                 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1024                         $unit->{unindex_range} = "$base..$cur";
1025                 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1026                         $unit->{unindex_range} = "$base..";
1027                 } else {
1028                         warn "W: unable to unindex before $range\n";
1029                 }
1030         }
1031         $range;
1032 }
1033
1034 # overridden by ExtSearchIdx
1035 sub artnum_max { $_[0]->{mm}->num_highwater }
1036
1037 sub sync_prepare ($$) {
1038         my ($self, $sync) = @_;
1039         $sync->{ranges} = sync_ranges($self, $sync);
1040         my $pr = $sync->{-opt}->{-progress};
1041         my $regen_max = 0;
1042         my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1043         my $pfx;
1044         if ($pr) {
1045                 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1046                 $pfx //= $sync->{ibx}->{inboxdir};
1047         }
1048
1049         my $reindex_heads;
1050         if ($self->{ibx_map}) {
1051                 # ExtSearchIdx won't index messages unless they're in
1052                 # over.sqlite3 for a given inbox, so don't read beyond
1053                 # what's in the per-inbox index.
1054                 $reindex_heads = [];
1055                 my $v = PublicInbox::Search::SCHEMA_VERSION;
1056                 my $mm = $sync->{ibx}->mm;
1057                 for my $i (0..$sync->{epoch_max}) {
1058                         $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1059                 }
1060         } elsif ($sync->{reindex}) { # V2 inbox
1061                 # reindex stops at the current heads and we later
1062                 # rerun index_sync without {reindex}
1063                 $reindex_heads = $self->last_commits($sync);
1064         }
1065         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1066                 $sync->{index_oid} = $self->can('index_oid');
1067         }
1068         my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1069         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1070                 my $git_dir = "$git_pfx/$i.git";
1071                 -d $git_dir or next; # missing epochs are fine
1072                 my $git = PublicInbox::Git->new($git_dir);
1073                 my $unit = { git => $git, epoch => $i };
1074                 my $tip;
1075                 if ($reindex_heads) {
1076                         $tip = $head = $reindex_heads->[$i] or next;
1077                 } else {
1078                         $tip = $git->qx(qw(rev-parse -q --verify), $head);
1079                         next if $?; # new repo
1080                         chomp $tip;
1081                 }
1082                 my $range = log_range($sync, $unit, $tip) or next;
1083                 # can't use 'rev-list --count' if we use --diff-filter
1084                 $pr->("$pfx $i.git counting $range ... ") if $pr;
1085                 # Don't bump num_highwater on --reindex by using {D}.
1086                 # We intentionally do NOT use {D} in the non-reindex case
1087                 # because we want NNTP article number gaps from unindexed
1088                 # messages to show up in mirrors, too.
1089                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1090                 my $stk = log2stack($sync, $git, $range);
1091                 return 0 if $sync->{quit};
1092                 my $nr = $stk ? $stk->num_records : 0;
1093                 $pr->("$nr\n") if $pr;
1094                 $unit->{stack} = $stk; # may be undef
1095                 unshift @{$sync->{todo}}, $unit;
1096                 $regen_max += $nr;
1097         }
1098         return 0 if $sync->{quit};
1099
1100         # XXX this should not happen unless somebody bypasses checks in
1101         # our code and blindly injects "d" file history into git repos
1102         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1103                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1104                 local $self->{current_info} = 'leftover ';
1105                 my $unindex_oid = $self->can('unindex_oid');
1106                 for my $oid (@leftovers) {
1107                         last if $sync->{quit};
1108                         $oid = unpack('H*', $oid);
1109                         my $req = { %$sync, oid => $oid };
1110                         $self->git->cat_async($oid, $unindex_oid, $req);
1111                 }
1112                 $self->git->cat_async_wait;
1113         }
1114         return 0 if $sync->{quit};
1115         if (!$regen_max) {
1116                 $sync->{-regen_fmt} = "%u/?\n";
1117                 return 0;
1118         }
1119
1120         # reindex should NOT see new commits anymore, if we do,
1121         # it's a problem and we need to notice it via die()
1122         my $pad = length($regen_max) + 1;
1123         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1124         $sync->{nr} = \(my $nr = 0);
1125         return -1 if $sync->{reindex};
1126         $regen_max + $self->artnum_max || 0;
1127 }
1128
1129 sub unindex_oid_aux ($$$) {
1130         my ($self, $oid, $mid) = @_;
1131         my @removed = $self->{oidx}->remove_oid($oid, $mid);
1132         for my $num (@removed) {
1133                 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1134         }
1135 }
1136
1137 sub unindex_oid ($$;$) { # git->cat_async callback
1138         my ($bref, $oid, $type, $size, $arg) = @_;
1139         is_bad_blob($oid, $type, $size, $arg->{oid}) and
1140                 return index_finalize($arg, 0);
1141         my $self = $arg->{self};
1142         local $self->{current_info} = "$self->{current_info} $oid";
1143         my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1144         my $mm = $self->{mm};
1145         my $mids = mids(PublicInbox::Eml->new($bref));
1146         undef $$bref;
1147         my $oidx = $self->{oidx};
1148         foreach my $mid (@$mids) {
1149                 my %gone;
1150                 my ($id, $prev);
1151                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1152                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1153                 }
1154                 my $n = scalar(keys(%gone)) or next;
1155                 if ($n > 1) {
1156                         warn "BUG: multiple articles linked to $oid\n",
1157                                 join(',',sort keys %gone), "\n";
1158                 }
1159                 foreach my $num (keys %gone) {
1160                         if ($unindexed) {
1161                                 my $mid0 = $mm->mid_for($num);
1162                                 $unindexed->{$mid0} = $num;
1163                         }
1164                         $mm->num_delete($num);
1165                 }
1166                 unindex_oid_aux($self, $oid, $mid);
1167         }
1168         index_finalize($arg, 0);
1169 }
1170
1171 sub git { $_[0]->{ibx}->git }
1172
1173 # this is rare, it only happens when we get discontiguous history in
1174 # a mirror because the source used -purge or -edit
1175 sub unindex_todo ($$$) {
1176         my ($self, $sync, $unit) = @_;
1177         my $unindex_range = delete($unit->{unindex_range}) // return;
1178         my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1179         my $before = scalar keys %$unindexed;
1180         # order does not matter, here:
1181         my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1182                                 --no-abbrev --no-renames), $unindex_range);
1183         local $sync->{in_unindex} = 1;
1184         my $unindex_oid = $self->can('unindex_oid');
1185         while (<$fh>) {
1186                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1187                 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1188         }
1189         close $fh or die "git log failed: \$?=$?";
1190         $self->git->cat_async_wait;
1191
1192         return unless $sync->{-opt}->{prune};
1193         my $after = scalar keys %$unindexed;
1194         return if $before == $after;
1195
1196         # ensure any blob can not longer be accessed via dumb HTTP
1197         run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1198                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1199 }
1200
1201 sub sync_ranges ($$) {
1202         my ($self, $sync) = @_;
1203         my $reindex = $sync->{reindex};
1204         return $self->last_commits($sync) unless $reindex;
1205         return [] if ref($reindex) ne 'HASH';
1206
1207         my $ranges = $reindex->{from}; # arrayref;
1208         if (ref($ranges) ne 'ARRAY') {
1209                 die 'BUG: $reindex->{from} not an ARRAY';
1210         }
1211         $ranges;
1212 }
1213
1214 sub index_xap_only { # git->cat_async callback
1215         my ($bref, $oid, $type, $size, $smsg) = @_;
1216         my $self = $smsg->{self};
1217         my $idx = idx_shard($self, $smsg->{num});
1218         $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1219         $self->{transact_bytes} += $smsg->{bytes};
1220 }
1221
1222 sub index_xap_step ($$$;$) {
1223         my ($self, $sync, $beg, $step) = @_;
1224         my $end = $sync->{art_end};
1225         return if $beg > $end; # nothing to do
1226
1227         $step //= $self->{shards};
1228         my $ibx = $self->{ibx};
1229         if (my $pr = $sync->{-opt}->{-progress}) {
1230                 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1231                         "$beg..$end (% $step)\n");
1232         }
1233         for (my $num = $beg; $num <= $end; $num += $step) {
1234                 last if $sync->{quit};
1235                 my $smsg = $ibx->over->get_art($num) or next;
1236                 $smsg->{self} = $self;
1237                 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1238                 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1239                         ${$sync->{nr}} = $num;
1240                         reindex_checkpoint($self, $sync);
1241                 }
1242         }
1243 }
1244
1245 sub index_todo ($$$) {
1246         my ($self, $sync, $unit) = @_;
1247         return if $sync->{quit};
1248         unindex_todo($self, $sync, $unit);
1249         my $stk = delete($unit->{stack}) or return;
1250         my $all = $self->git;
1251         my $index_oid = $self->can('index_oid');
1252         my $unindex_oid = $self->can('unindex_oid');
1253         my $pfx;
1254         if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1255                 $pfx = "$1 $2"; # v2
1256         } else { # v1
1257                 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1258                 $pfx //= $unit->{git}->{git_dir};
1259         }
1260         local $self->{current_info} = "$pfx ";
1261         local $sync->{latest_cmt} = \(my $latest_cmt);
1262         local $sync->{unit} = $unit;
1263         while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1264                 if ($sync->{quit}) {
1265                         warn "waiting to quit...\n";
1266                         $all->async_wait_all;
1267                         $self->update_last_commit($sync);
1268                         return;
1269                 }
1270                 my $req = {
1271                         %$sync,
1272                         autime => $at,
1273                         cotime => $ct,
1274                         oid => $oid,
1275                         cur_cmt => $cmt
1276                 };
1277                 if ($f eq 'm') {
1278                         if ($sync->{max_size}) {
1279                                 $all->check_async($oid, \&check_size, $req);
1280                         } else {
1281                                 $all->cat_async($oid, $index_oid, $req);
1282                         }
1283                 } elsif ($f eq 'd') {
1284                         $all->cat_async($oid, $unindex_oid, $req);
1285                 }
1286                 if (${$sync->{need_checkpoint}}) {
1287                         reindex_checkpoint($self, $sync);
1288                 }
1289         }
1290         $all->async_wait_all;
1291         $self->update_last_commit($sync, $stk);
1292 }
1293
1294 sub xapian_only {
1295         my ($self, $opt, $sync, $art_beg) = @_;
1296         my $seq = $opt->{sequential_shard};
1297         $art_beg //= 0;
1298         local $self->{parallel} = 0 if $seq;
1299         $self->idx_init($opt); # acquire lock
1300         if (my $art_end = $self->{ibx}->mm->max) {
1301                 $sync //= {
1302                         need_checkpoint => \(my $bool = 0),
1303                         -opt => $opt,
1304                         self => $self,
1305                         nr => \(my $nr = 0),
1306                         -regen_fmt => "%u/?\n",
1307                 };
1308                 $sync->{art_end} = $art_end;
1309                 if ($seq || !$self->{parallel}) {
1310                         my $shard_end = $self->{shards} - 1;
1311                         for my $i (0..$shard_end) {
1312                                 last if $sync->{quit};
1313                                 index_xap_step($self, $sync, $art_beg + $i);
1314                                 if ($i != $shard_end) {
1315                                         reindex_checkpoint($self, $sync);
1316                                 }
1317                         }
1318                 } else { # parallel (maybe)
1319                         index_xap_step($self, $sync, $art_beg, 1);
1320                 }
1321         }
1322         $self->git->cat_async_wait;
1323         $self->done;
1324 }
1325
1326 # public, called by public-inbox-index
1327 sub index_sync {
1328         my ($self, $opt) = @_;
1329         $opt //= {};
1330         return xapian_only($self, $opt) if $opt->{xapian_only};
1331
1332         my $epoch_max;
1333         my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1334         if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1335                 use Time::HiRes qw(stat);
1336                 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1337                         my $c = $mm[10]; # 10 = ctime (nsec NV)
1338                         my @hd = stat("$latest/refs/heads");
1339                         my @pr = stat("$latest/packed-refs");
1340                         return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1341                 }
1342         }
1343
1344         my $pr = $opt->{-progress};
1345         my $seq = $opt->{sequential_shard};
1346         my $art_beg; # the NNTP article number we start xapian_only at
1347         my $idxlevel = $self->{ibx}->{indexlevel};
1348         local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1349
1350         $self->idx_init($opt); # acquire lock
1351         fill_alternates($self, $epoch_max);
1352         $self->{oidx}->rethread_prepare($opt);
1353         my $sync = {
1354                 need_checkpoint => \(my $bool = 0),
1355                 reindex => $opt->{reindex},
1356                 -opt => $opt,
1357                 self => $self,
1358                 ibx => $self->{ibx},
1359                 epoch_max => $epoch_max,
1360         };
1361         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1362         local $SIG{QUIT} = $quit;
1363         local $SIG{INT} = $quit;
1364         local $SIG{TERM} = $quit;
1365
1366         if (sync_prepare($self, $sync)) {
1367                 # tmp_clone seems to fail if inside a transaction, so
1368                 # we rollback here (because we opened {mm} for reading)
1369                 # Note: we do NOT rely on DBI transactions for atomicity;
1370                 # only for batch performance.
1371                 $self->{mm}->{dbh}->rollback;
1372                 $self->{mm}->{dbh}->begin_work;
1373                 $sync->{mm_tmp} =
1374                         $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1375
1376                 # xapian_only works incrementally w/o --reindex
1377                 if ($seq && !$opt->{reindex}) {
1378                         $art_beg = $sync->{mm_tmp}->max || -1;
1379                         $art_beg++;
1380                 }
1381         }
1382         # work forwards through history
1383         index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1384         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1385         $self->done;
1386
1387         if (my $nr = $sync->{nr}) {
1388                 my $pr = $sync->{-opt}->{-progress};
1389                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1390         }
1391
1392         my $quit_warn;
1393         # deal with Xapian shards sequentially
1394         if ($seq && delete($sync->{mm_tmp})) {
1395                 if ($sync->{quit}) {
1396                         $quit_warn = 1;
1397                 } else {
1398                         $self->{ibx}->{indexlevel} = $idxlevel;
1399                         xapian_only($self, $opt, $sync, $art_beg);
1400                         $quit_warn = 1 if $sync->{quit};
1401                 }
1402         }
1403
1404         # --reindex on the command-line
1405         if (!$sync->{quit} && $opt->{reindex} &&
1406                         !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1407                 $self->lock_acquire;
1408                 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1409                 if (my $xdb = $s0->idx_acquire) {
1410                         my $n = $xdb->get_metadata('has_threadid');
1411                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1412                 }
1413                 $s0->idx_release;
1414                 $self->lock_release;
1415         }
1416
1417         # reindex does not pick up new changes, so we rerun w/o it:
1418         if ($opt->{reindex} && !$sync->{quit}) {
1419                 my %again = %$opt;
1420                 $sync = undef;
1421                 delete @again{qw(rethread reindex -skip_lock)};
1422                 index_sync($self, \%again);
1423                 $opt->{quit} = $again{quit}; # propagate to caller
1424         }
1425         warn <<EOF if $quit_warn;
1426 W: interrupted, --xapian-only --reindex required upon restart
1427 EOF
1428 }
1429
1430 1;