]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
extsearchidx: lock eidxq on full --reindex
[public-inbox.git] / lib / PublicInbox / ExtSearchIdx.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
6 #
7 # It's based on the same ideas as public-inbox-v2-format(5) using
8 # over.sqlite3 for dedupe and sharded Xapian.  msgmap.sqlite3 is
9 # missing, so there is no Message-ID conflict resolution, meaning
10 # no NNTP support for now.
11 #
12 # v2 has a 1:1 mapping of index:inbox or msgmap for NNTP support.
13 # This is intended to be an M:N index:inbox mapping, but it'll likely
14 # be 1:N in common practice (M==1)
15
16 package PublicInbox::ExtSearchIdx;
17 use strict;
18 use v5.10.1;
19 use parent qw(PublicInbox::ExtSearch PublicInbox::Lock);
20 use Carp qw(croak carp);
21 use Sys::Hostname qw(hostname);
22 use POSIX qw(strftime);
23 use PublicInbox::Search;
24 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor
25         is_bad_blob);
26 use PublicInbox::OverIdx;
27 use PublicInbox::MiscIdx;
28 use PublicInbox::MID qw(mids);
29 use PublicInbox::V2Writable;
30 use PublicInbox::InboxWritable;
31 use PublicInbox::ContentHash qw(content_hash);
32 use PublicInbox::Eml;
33 use File::Spec;
34 use PublicInbox::DS qw(now);
35 use DBI qw(:sql_types); # SQL_BLOB
36
37 sub new {
38         my (undef, $dir, $opt) = @_;
39         $dir = File::Spec->canonpath($dir);
40         my $l = $opt->{indexlevel} // 'full';
41         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
42                 die "invalid indexlevel=$l\n";
43         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
44         my $self = bless {
45                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
46                 topdir => $dir,
47                 creat => $opt->{creat},
48                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
49                 ibx_list => [],
50                 indexlevel => $l,
51                 transact_bytes => 0,
52                 total_bytes => 0,
53                 current_info => '',
54                 parallel => 1,
55                 lock_path => "$dir/ei.lock",
56         }, __PACKAGE__;
57         $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
58         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
59         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
60         $self->{oidx} = $oidx;
61         $self
62 }
63
64 sub attach_inbox {
65         my ($self, $ibx) = @_;
66         $ibx = PublicInbox::InboxWritable->new($ibx);
67         my $key = $ibx->eidx_key;
68         if (!$ibx->over || !$ibx->mm) {
69                 warn "W: skipping $key (unindexed)\n";
70                 return;
71         }
72         if (!defined($ibx->uidvalidity)) {
73                 warn "W: skipping $key (no UIDVALIDITY)\n";
74                 return;
75         }
76         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
77         if ($ibxdir ne $ibx->{inboxdir}) {
78                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
79                 $ibx->{inboxdir} = $ibxdir;
80         }
81         $ibx = PublicInbox::InboxWritable->new($ibx);
82         $self->{ibx_map}->{$key} //= do {
83                 push @{$self->{ibx_list}}, $ibx;
84                 $ibx;
85         }
86 }
87
88 sub _ibx_attach { # each_inbox callback
89         my ($ibx, $self) = @_;
90         attach_inbox($self, $ibx);
91 }
92
93 sub attach_config {
94         my ($self, $cfg) = @_;
95         $self->{cfg} = $cfg;
96         $cfg->each_inbox(\&_ibx_attach, $self);
97 }
98
99 sub check_batch_limit ($) {
100         my ($req) = @_;
101         my $self = $req->{self};
102         my $new_smsg = $req->{new_smsg};
103
104         # {raw_bytes} may be unset, so just use {bytes}
105         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
106
107         # set flag for PublicInbox::V2Writable::index_todo:
108         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
109 }
110
111 sub do_xpost ($$) {
112         my ($req, $smsg) = @_;
113         my $self = $req->{self};
114         my $docid = $smsg->{num};
115         my $idx = $self->idx_shard($docid);
116         my $oid = $req->{oid};
117         my $xibx = $req->{ibx};
118         my $eml = $req->{eml};
119         my $eidx_key = $xibx->eidx_key;
120         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
121                 my $xnum = $req->{xnum};
122                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
123                 $idx->shard_add_eidx_info($docid, $eidx_key, $eml);
124                 check_batch_limit($req);
125         } else { # 'd'
126                 my $rm_eidx_info;
127                 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
128                                                         \$rm_eidx_info);
129                 if ($nr == 0) {
130                         $self->{oidx}->eidxq_del($docid);
131                         $idx->shard_remove($docid);
132                 } elsif ($rm_eidx_info) {
133                         $idx->shard_remove_eidx_info($docid, $eidx_key, $eml);
134                         $self->{oidx}->eidxq_add($docid); # yes, add
135                 }
136         }
137 }
138
139 # called by V2Writable::sync_prepare
140 sub artnum_max { $_[0]->{oidx}->eidx_max }
141
142 sub index_unseen ($) {
143         my ($req) = @_;
144         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
145         my $eml = delete $req->{eml};
146         $new_smsg->populate($eml, $req);
147         my $self = $req->{self};
148         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
149         $new_smsg->{num} = $docid;
150         my $idx = $self->idx_shard($docid);
151         $self->{oidx}->add_overview($eml, $new_smsg);
152         my $oid = $new_smsg->{blob};
153         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
154         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
155         $idx->index_raw(undef, $eml, $new_smsg, $ibx->eidx_key);
156         check_batch_limit($req);
157 }
158
159 sub do_finalize ($) {
160         my ($req) = @_;
161         if (my $indexed = $req->{indexed}) {
162                 do_xpost($req, $_) for @$indexed;
163         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
164                 index_unseen($req);
165         } else {
166                 # `d' message was already unindexed in the v1/v2 inboxes,
167                 # so it's too noisy to warn, here.
168         }
169         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
170         if (defined(my $cur_cmt = $req->{cur_cmt})) {
171                 ${$req->{latest_cmt}} = $cur_cmt;
172         }
173 }
174
175 sub do_step ($) { # main iterator for adding messages to the index
176         my ($req) = @_;
177         my $self = $req->{self} // die 'BUG: {self} missing';
178         while (1) {
179                 if (my $next_arg = $req->{next_arg}) {
180                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
181                                 $req->{cur_smsg} = $smsg;
182                                 $self->git->cat_async($smsg->{blob},
183                                                         \&ck_existing, $req);
184                                 return; # ck_existing calls do_step
185                         }
186                         delete $req->{cur_smsg};
187                         delete $req->{next_arg};
188                 }
189                 my $mid = shift(@{$req->{mids}});
190                 last unless defined $mid;
191                 my ($id, $prev);
192                 $req->{next_arg} = [ $mid, \$id, \$prev ];
193                 # loop again
194         }
195         do_finalize($req);
196 }
197
198 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
199         my ($req) = @_;
200         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
201         my $self = $req->{self};
202         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
203         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
204         if (@keep) {
205                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
206                         die "BUG: xref $keep[0] has no OID";
207                 my $oidhex = $1;
208                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
209                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
210                 my $saved = $self->{oidx}->get_art($smsg->{num});
211         } else {
212                 $self->{oidx}->delete_by_num($smsg->{num});
213         }
214 }
215
216 sub ck_existing { # git->cat_async callback
217         my ($bref, $oid, $type, $size, $req) = @_;
218         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
219         if ($type eq 'missing') {
220                 _blob_missing($req);
221         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
222                 my $self = $req->{self} // die 'BUG: {self} missing';
223                 local $self->{current_info} = "$self->{current_info} $oid";
224                 my $cur = PublicInbox::Eml->new($bref);
225                 if (content_hash($cur) eq $req->{chash}) {
226                         push @{$req->{indexed}}, $smsg; # for do_xpost
227                 } # else { index_unseen later }
228         }
229         do_step($req);
230 }
231
232 # is the messages visible in the inbox currently being indexed?
233 # return the number if so
234 sub cur_ibx_xnum ($$) {
235         my ($req, $bref) = @_;
236         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
237
238         $req->{eml} = PublicInbox::Eml->new($bref);
239         $req->{chash} = content_hash($req->{eml});
240         $req->{mids} = mids($req->{eml});
241         my @q = @{$req->{mids}}; # copy
242         while (defined(my $mid = shift @q)) {
243                 my ($id, $prev);
244                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
245                         return $x->{num} if $x->{blob} eq $req->{oid};
246                 }
247         }
248         undef;
249 }
250
251 sub index_oid { # git->cat_async callback for 'm'
252         my ($bref, $oid, $type, $size, $req) = @_;
253         my $self = $req->{self};
254         local $self->{current_info} = "$self->{current_info} $oid";
255         return if is_bad_blob($oid, $type, $size, $req->{oid});
256         my $new_smsg = $req->{new_smsg} = bless {
257                 blob => $oid,
258         }, 'PublicInbox::Smsg';
259         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
260         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
261         ++${$req->{nr}};
262         do_step($req);
263 }
264
265 sub unindex_oid { # git->cat_async callback for 'd'
266         my ($bref, $oid, $type, $size, $req) = @_;
267         my $self = $req->{self};
268         local $self->{current_info} = "$self->{current_info} $oid";
269         return if is_bad_blob($oid, $type, $size, $req->{oid});
270         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
271         do_step($req);
272 }
273
274 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
275 sub last_commits {
276         my ($self, $sync) = @_;
277         my $heads = [];
278         my $ekey = $sync->{ibx}->eidx_key;
279         my $uv = $sync->{ibx}->uidvalidity;
280         for my $i (0..$sync->{epoch_max}) {
281                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
282         }
283         $heads;
284 }
285
286 sub _sync_inbox ($$$) {
287         my ($self, $sync, $ibx) = @_;
288         $sync->{ibx} = $ibx;
289         $sync->{nr} = \(my $nr = 0);
290         my $v = $ibx->version;
291         my $ekey = $ibx->eidx_key;
292         if ($v == 2) {
293                 my $epoch_max;
294                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
295                 $sync->{epoch_max} = $epoch_max;
296                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
297         } elsif ($v == 1) {
298                 my $uv = $ibx->uidvalidity;
299                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
300                 my $head = $ibx->mm->last_commit;
301                 unless (defined $head) {
302                         warn "E: $ibx->{inboxdir} is not indexed\n";
303                         return;
304                 }
305                 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
306                 my $unit = { stack => $stk, git => $ibx->git };
307                 push @{$sync->{todo}}, $unit;
308         } else {
309                 warn "E: $ekey unsupported inbox version (v$v)\n";
310                 return;
311         }
312         for my $unit (@{delete($sync->{todo}) // []}) {
313                 last if $sync->{quit};
314                 index_todo($self, $sync, $unit);
315         }
316         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
317         $ibx->git->cleanup; # done with this inbox, now
318 }
319
320 sub gc_unref_doc ($$$$) {
321         my ($self, $ibx_id, $eidx_key, $docid) = @_;
322         my $dbh = $self->{oidx}->dbh;
323
324         # for debug/info purposes, oids may no longer be accessible
325         my $sth = $dbh->prepare_cached(<<'', undef, 1);
326 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
327
328         $sth->execute($docid, $ibx_id);
329         my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
330
331         $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
332 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
333
334         my $remain = $self->{oidx}->get_xref3($docid);
335         if (scalar(@$remain)) {
336                 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
337                 for my $oid (@oid) {
338                         warn "I: unref #$docid $eidx_key $oid\n";
339                 }
340         } else {
341                 warn "I: remove #$docid $eidx_key @oid\n";
342                 $self->idx_shard($docid)->shard_remove($docid);
343         }
344 }
345
346 sub eidx_gc {
347         my ($self, $opt) = @_;
348         $self->{cfg} or die "E: GC requires ->attach_config\n";
349         $opt->{-idx_gc} = 1;
350         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
351
352         my $dbh = $self->{oidx}->dbh;
353         my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
354         my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
355         my $lc_i = $dbh->prepare('SELECT key FROM eidx_meta WHERE key LIKE ?');
356
357         $ibx_ck->execute;
358         while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
359                 next if $self->{ibx_map}->{$eidx_key};
360                 $self->{midx}->remove_eidx_key($eidx_key);
361                 warn "I: deleting messages for $eidx_key...\n";
362                 $x3_doc->execute($ibx_id);
363                 while (defined(my $docid = $x3_doc->fetchrow_array)) {
364                         gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
365                 }
366                 $dbh->prepare_cached(<<'')->execute($ibx_id);
367 DELETE FROM inboxes WHERE ibx_id = ?
368
369                 # drop last_commit info
370                 my $pat = $eidx_key;
371                 $pat =~ s/([_%])/\\$1/g;
372                 $lc_i->execute("lc-%:$pat//%");
373                 while (my ($key) = $lc_i->fetchrow_array) {
374                         next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
375                         warn "I: removing $key\n";
376                         $dbh->prepare_cached(<<'')->execute($key);
377 DELETE FROM eidx_meta WHERE key = ?
378
379                 }
380
381                 warn "I: $eidx_key removed\n";
382         }
383
384         # it's not real unless it's in `over', we use parallelism here,
385         # shards will be reading directly from over, so commit
386         $self->{oidx}->commit_lazy;
387         $self->{oidx}->begin_lazy;
388
389         for my $idx (@{$self->{idx_shards}}) {
390                 warn "I: cleaning up shard #$idx->{shard}\n";
391                 $idx->shard_over_check($self->{oidx});
392         }
393         my $nr = $dbh->do(<<'');
394 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
395
396         warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
397
398         done($self);
399 }
400
401 sub _ibx_for ($$$) {
402         my ($self, $sync, $smsg) = @_;
403         my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
404         my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
405         $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
406 }
407
408 sub _reindex_finalize ($$$) {
409         my ($req, $smsg, $eml) = @_;
410         my $sync = $req->{sync};
411         my $self = $sync->{self};
412         my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
413         my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
414         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
415         my $docid = $smsg->{num} = $orig_smsg->{num};
416         $self->{oidx}->add_overview($eml, $smsg); # may rethread
417         check_batch_limit({ %$sync, new_smsg => $smsg });
418         my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
419         my $stable = delete($by_chash->{$chash0}) //
420                                 die "BUG: $smsg->{blob} chash missing";
421         my $idx = $self->idx_shard($docid);
422         my $top_smsg = pop @$stable;
423         $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
424         my $ibx = _ibx_for($self, $sync, $smsg);
425         $idx->index_raw(undef, $eml, $smsg, $ibx->eidx_key);
426         for my $x (reverse @$stable) {
427                 $ibx = _ibx_for($self, $sync, $x);
428                 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
429                 $idx->shard_add_eidx_info($docid, $ibx->eidx_key, $hdr);
430         }
431         return if $nr == 1; # likely, all good
432
433         warn "W: #$docid split into $nr due to deduplication change\n";
434         my @todo;
435         for my $ary (values %$by_chash) {
436                 for my $x (reverse @$ary) {
437                         warn "removing #$docid xref3 $x->{blob}\n";
438                         my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
439                         die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
440                 }
441                 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
442                 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
443                 $ibx = _ibx_for($self, $sync, $x);
444                 my $e = $ibx->over->get_art($x->{num});
445                 $e->{blob} eq $x->{blob} or die <<EOF;
446 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
447 EOF
448                 push @todo, $ibx, $e;
449         }
450         undef $by_chash;
451         while (my ($ibx, $e) = splice(@todo, 0, 2)) {
452                 reindex_unseen($self, $sync, $ibx, $e);
453         }
454 }
455
456 sub _reindex_oid { # git->cat_async callback
457         my ($bref, $oid, $type, $size, $req) = @_;
458         my $sync = $req->{sync};
459         my $self = $sync->{self};
460         my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
461         my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
462         my $docid = $orig_smsg->{num};
463         if (is_bad_blob($oid, $type, $size, $expect_oid)) {
464                 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
465                 if ($remain == 0) {
466                         warn "W: #$docid gone or corrupted\n";
467                         $self->idx_shard($docid)->shard_remove($docid);
468                 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
469                         $self->git->cat_async($next_oid, \&_reindex_oid, $req);
470                 } else {
471                         warn "BUG: #$docid gone (UNEXPECTED)\n";
472                         $self->idx_shard($docid)->shard_remove($docid);
473                 }
474                 return;
475         }
476         my $ci = $self->{current_info};
477         local $self->{current_info} = "$ci #$docid $oid";
478         my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
479         $re_smsg->{bytes} = $size + crlf_adjust($$bref);
480         my $eml = PublicInbox::Eml->new($bref);
481         $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
482                                 cotime => $orig_smsg->{ts} });
483         my $chash = content_hash($eml);
484         $re_smsg->{chash} = $chash;
485         $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
486         $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
487         $re_smsg->{hdr} = $eml->header_obj;
488         push @{$req->{by_chash}->{$chash}}, $re_smsg;
489         if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
490                 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
491         } else { # last $re_smsg is the highest priority xref3
492                 local $self->{current_info} = "$ci #$docid";
493                 _reindex_finalize($req, $re_smsg, $eml);
494         }
495 }
496
497 sub _reindex_smsg ($$$) {
498         my ($self, $sync, $smsg) = @_;
499         my $docid = $smsg->{num};
500         my $xr3 = $self->{oidx}->get_xref3($docid, 1);
501         if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
502                 warn <<"";
503 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
504
505                 $self->{oidx}->delete_by_num($docid);
506                 $self->idx_shard($docid)->shard_remove($docid);
507                 return;
508         }
509
510         # we sort {xr3r} in the reverse order of {ibx_list} so we can
511         # hit the common case in _reindex_finalize without rereading
512         # from git (or holding multiple messages in memory).
513         my $id2pos = $sync->{id2pos}; # index in {ibx_list}
514         @$xr3 = sort {
515                 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
516                                 ||
517                 $b->[1] <=> $a->[1] # break ties with {xnum}
518         } @$xr3;
519         @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
520         my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
521         $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
522 }
523
524 sub checkpoint_due ($) {
525         my ($sync) = @_;
526         ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
527 }
528
529 sub host_ident () {
530         # I've copied FS images and only changed the hostname before,
531         # so prepend hostname.  Use `state' since these a BOFH can change
532         # these while this process is running and we always want to be
533         # able to release locks taken by this process.
534         state $retval = hostname . '-' . do {
535                 my $m; # machine-id(5) is systemd
536                 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
537                 # hostid(1) is in GNU coreutils, kern.hostid is FreeBSD
538                 chomp($m ||= `hostid` || `sysctl -n kern.hostid`);
539                 $m;
540         };
541 }
542
543 sub eidxq_release {
544         my ($self) = @_;
545         my $expect = delete($self->{-eidxq_locked}) or return;
546         my ($owner_pid, undef) = split(/-/, $expect);
547         return if $owner_pid != $$; # shards may fork
548         my $oidx = $self->{oidx};
549         $oidx->begin_lazy;
550         my $cur = $oidx->eidx_meta('eidxq_lock') // '';
551         if ($cur eq $expect) {
552                 $oidx->eidx_meta('eidxq_lock', '');
553                 return 1;
554         } elsif ($cur ne '') {
555                 warn "E: eidxq_lock($expect) stolen by $cur\n";
556         } else {
557                 warn "E: eidxq_lock($expect) released by another process\n";
558         }
559         undef;
560 }
561
562 sub DESTROY {
563         my ($self) = @_;
564         eidxq_release($self) and $self->{oidx}->commit_lazy;
565 }
566
567 sub _eidxq_take ($) {
568         my ($self) = @_;
569         my $val = "$$-${\time}-$>-".host_ident;
570         $self->{oidx}->eidx_meta('eidxq_lock', $val);
571         $self->{-eidxq_locked} = $val;
572 }
573
574 sub eidxq_lock_acquire ($) {
575         my ($self) = @_;
576         my $oidx = $self->{oidx};
577         $oidx->begin_lazy;
578         my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
579         if (my $locked = $self->{-eidxq_locked}) { # be lazy
580                 return $locked if $locked eq $cur;
581         }
582         my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
583         my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
584         if ($euid == $> && $ident eq host_ident) {
585                 if (kill(0, $pid)) {
586                         warn <<EOM; return;
587 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
588 EOM
589                 }
590                 if ($!{ESRCH}) {
591                         warn "I: eidxq_lock is stale ($cur), clobbering\n";
592                         return _eidxq_take($self);
593                 }
594                 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
595         }
596         my $fn = $oidx->dbh->sqlite_db_filename;
597         warn <<EOF;
598 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
599 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
600 W:      sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
601 EOF
602         undef;
603 }
604
605 sub eidxq_process ($$) { # for reindexing
606         my ($self, $sync) = @_;
607
608         return unless eidxq_lock_acquire($self);
609         my $dbh = $self->{oidx}->dbh;
610         my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
611         ${$sync->{nr}} = 0;
612         $sync->{-regen_fmt} = "%u/$tot\n";
613         my $pr = $sync->{-opt}->{-progress};
614         if ($pr) {
615                 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
616                 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
617                 $pr->("Xapian indexing $min..$max (total=$tot)\n");
618         }
619         $sync->{id2pos} //= do {
620                 my %id2pos;
621                 my $pos = 0;
622                 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
623                 \%id2pos;
624         };
625         my ($del, $iter);
626 restart:
627         $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
628         $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
629         $iter->execute;
630         while (defined(my $docid = $iter->fetchrow_array)) {
631                 last if $sync->{quit};
632                 if (my $smsg = $self->{oidx}->get_art($docid)) {
633                         _reindex_smsg($self, $sync, $smsg);
634                 } else {
635                         warn "E: #$docid does not exist in over\n";
636                 }
637                 $del->execute($docid);
638                 ++${$sync->{nr}};
639
640                 if (checkpoint_due($sync)) {
641                         $dbh = $del = $iter = undef;
642                         reindex_checkpoint($self, $sync); # release lock
643                         $dbh = $self->{oidx}->dbh;
644                         goto restart;
645                 }
646         }
647         $self->git->async_wait_all;
648         $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
649 }
650
651 sub _reindex_unseen { # git->cat_async callback
652         my ($bref, $oid, $type, $size, $req) = @_;
653         return if is_bad_blob($oid, $type, $size, $req->{oid});
654         my $self = $req->{self} // die 'BUG: {self} unset';
655         local $self->{current_info} = "$self->{current_info} $oid";
656         my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
657         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
658         my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
659         $req->{new_smsg} = $new_smsg;
660         $req->{chash} = content_hash($eml);
661         $req->{mids} = mids($eml); # do_step iterates through this
662         do_step($req); # enter the normal indexing flow
663 }
664
665 # --reindex may catch totally unseen messages, this handles them
666 sub reindex_unseen ($$$$) {
667         my ($self, $sync, $ibx, $xsmsg) = @_;
668         my $req = {
669                 %$sync, # has {self}
670                 autime => $xsmsg->{ds},
671                 cotime => $xsmsg->{ts},
672                 oid => $xsmsg->{blob},
673                 ibx => $ibx,
674                 xnum => $xsmsg->{num},
675                 # {mids} and {chash} will be filled in at _reindex_unseen
676         };
677         warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
678         $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
679 }
680
681 sub _reindex_check_unseen ($$$) {
682         my ($self, $sync, $ibx) = @_;
683         my $ibx_id = $ibx->{-ibx_id};
684         my $slice = 1000;
685         my ($beg, $end) = (1, $slice);
686
687         # first, check if we missed any messages in target $ibx
688         my $msgs;
689         my $pr = $sync->{-opt}->{-progress};
690         my $ekey = $ibx->eidx_key;
691         $sync->{-regen_fmt} = "$ekey checking unseen %u/".$ibx->over->max."\n";
692         ${$sync->{nr}} = 0;
693
694         while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
695                 ${$sync->{nr}} = $beg;
696                 $beg = $msgs->[-1]->{num} + 1;
697                 $end = $beg + $slice;
698                 if (checkpoint_due($sync)) {
699                         reindex_checkpoint($self, $sync); # release lock
700                 }
701
702                 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
703 SELECT DISTINCT(docid) FROM xref3 WHERE
704 ibx_id = ? AND xnum = ? AND oidbin = ?
705
706                 for my $xsmsg (@$msgs) {
707                         my $oidbin = pack('H*', $xsmsg->{blob});
708                         $inx3->bind_param(1, $ibx_id);
709                         $inx3->bind_param(2, $xsmsg->{num});
710                         $inx3->bind_param(3, $oidbin, SQL_BLOB);
711                         $inx3->execute;
712                         my $docids = $inx3->fetchall_arrayref;
713                         # index messages which were totally missed
714                         # the first time around ASAP:
715                         if (scalar(@$docids) == 0) {
716                                 reindex_unseen($self, $sync, $ibx, $xsmsg);
717                         } else { # already seen, reindex later
718                                 for my $r (@$docids) {
719                                         $self->{oidx}->eidxq_add($r->[0]);
720                                 }
721                         }
722                         last if $sync->{quit};
723                 }
724                 last if $sync->{quit};
725         }
726 }
727
728 sub _reindex_check_stale ($$$) {
729         my ($self, $sync, $ibx) = @_;
730         my $min = 0;
731         my $pr = $sync->{-opt}->{-progress};
732         my $fetching;
733         my $ekey = $ibx->eidx_key;
734         $sync->{-regen_fmt} =
735                         "$ekey check stale/missing %u/".$ibx->over->max."\n";
736         ${$sync->{nr}} = 0;
737         do {
738                 if (checkpoint_due($sync)) {
739                         reindex_checkpoint($self, $sync); # release lock
740                 }
741                 # now, check if there's stale xrefs
742                 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
743 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
744 ORDER BY docid,xnum ASC LIMIT 10000
745
746                 $iter->execute($ibx->{-ibx_id}, $min);
747                 $fetching = undef;
748
749                 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
750                         return if $sync->{quit};
751                         ${$sync->{nr}} = $xnum;
752
753                         $fetching = $min = $docid;
754                         my $smsg = $ibx->over->get_art($xnum);
755                         my $oidhex = unpack('H*', $oidbin);
756                         my $err;
757                         if (!$smsg) {
758                                 $err = 'stale';
759                         } elsif ($smsg->{blob} ne $oidhex) {
760                                 $err = "mismatch (!= $smsg->{blob})";
761                         } else {
762                                 next; # likely, all good
763                         }
764                         # current_info already has eidx_key
765                         warn "$xnum:$oidhex (#$docid): $err\n";
766                         my $del = $self->{oidx}->dbh->prepare_cached(<<'');
767 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
768
769                         $del->bind_param(1, $ibx->{-ibx_id});
770                         $del->bind_param(2, $xnum);
771                         $del->bind_param(3, $oidbin, SQL_BLOB);
772                         $del->execute;
773
774                         # get_xref3 over-fetches, but this is a rare path:
775                         my $xr3 = $self->{oidx}->get_xref3($docid);
776                         my $idx = $self->idx_shard($docid);
777                         if (scalar(@$xr3) == 0) { # all gone
778                                 $self->{oidx}->delete_by_num($docid);
779                                 $self->{oidx}->eidxq_del($docid);
780                                 $idx->shard_remove($docid);
781                         } else { # enqueue for reindex of remaining messages
782                                 $idx->shard_remove_eidx_info($docid,
783                                                         $ibx->eidx_key);
784                                 $self->{oidx}->eidxq_add($docid); # yes, add
785                         }
786                 }
787         } while (defined $fetching);
788 }
789
790 sub _reindex_inbox ($$$) {
791         my ($self, $sync, $ibx) = @_;
792         local $self->{current_info} = $ibx->eidx_key;
793         _reindex_check_unseen($self, $sync, $ibx);
794         _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
795         delete @$ibx{qw(over mm search git)}; # won't need these for a bit
796 }
797
798 sub eidx_reindex {
799         my ($self, $sync) = @_;
800
801         # acquire eidxq_lock early because full reindex takes forever
802         # and incremental -extindex processes can run during our checkpoints
803         if (!eidxq_lock_acquire($self)) {
804                 warn "E: aborting --reindex\n";
805                 return;
806         }
807         for my $ibx (@{$self->{ibx_list}}) {
808                 _reindex_inbox($self, $sync, $ibx);
809                 last if $sync->{quit};
810         }
811         $self->git->async_wait_all; # ensure eidxq gets filled completely
812         eidxq_process($self, $sync) unless $sync->{quit};
813 }
814
815 sub eidx_sync { # main entry point
816         my ($self, $opt) = @_;
817
818         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
819         local $self->{current_info} = '';
820         local $SIG{__WARN__} = sub {
821                 $warn_cb->($self->{current_info}, ': ', @_);
822         };
823         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
824         $self->{oidx}->rethread_prepare($opt);
825         my $sync = {
826                 need_checkpoint => \(my $need_checkpoint = 0),
827                 check_intvl => 10,
828                 next_check => now() + 10,
829                 -opt => $opt,
830                 # DO NOT SET {reindex} here, it's incompatible with reused
831                 # V2Writable code, reindex is totally different here
832                 # compared to v1/v2 inboxes because we have multiple histories
833                 self => $self,
834                 -regen_fmt => "%u/?\n",
835         };
836         local $SIG{USR1} = sub { $need_checkpoint = 1 };
837         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
838         local $SIG{QUIT} = $quit;
839         local $SIG{INT} = $quit;
840         local $SIG{TERM} = $quit;
841         for my $ibx (@{$self->{ibx_list}}) {
842                 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
843         }
844         if (delete($opt->{reindex})) {
845                 $sync->{checkpoint_unlocks} = 1;
846                 eidx_reindex($self, $sync);
847         }
848
849         # don't use $_ here, it'll get clobbered by reindex_checkpoint
850         for my $ibx (@{$self->{ibx_list}}) {
851                 last if $sync->{quit};
852                 _sync_inbox($self, $sync, $ibx);
853         }
854         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
855         eidxq_process($self, $sync) unless $sync->{quit};
856
857         eidxq_release($self);
858         PublicInbox::V2Writable::done($self);
859 }
860
861 sub update_last_commit { # overrides V2Writable
862         my ($self, $sync, $stk) = @_;
863         my $unit = $sync->{unit} // return;
864         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
865         defined($latest_cmt) or return;
866         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
867         my $ekey = $ibx->eidx_key;
868         my $uv = $ibx->uidvalidity;
869         my $epoch = $unit->{epoch};
870         my $meta_key;
871         my $v = $ibx->version;
872         if ($v == 2) {
873                 die 'No {epoch} for v2 unit' unless defined $epoch;
874                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
875         } elsif ($v == 1) {
876                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
877                 $meta_key = "lc-v1:$ekey//$uv";
878         } else {
879                 die "Unsupported inbox version: $v";
880         }
881         my $last = $self->{oidx}->eidx_meta($meta_key);
882         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
883                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
884                 chomp(my $n = $unit->{git}->qx(@cmd));
885                 return if $n ne '' && $n == 0;
886         }
887         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
888 }
889
890 sub _idx_init { # with_umask callback
891         my ($self, $opt) = @_;
892         PublicInbox::V2Writable::_idx_init($self, $opt);
893         $self->{midx} = PublicInbox::MiscIdx->new($self);
894 }
895
896 sub idx_init { # similar to V2Writable
897         my ($self, $opt) = @_;
898         return if $self->{idx_shards};
899
900         $self->git->cleanup;
901
902         my $ALL = $self->git->{git_dir}; # ALL.git
903         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
904         my $info_dir = "$ALL/objects/info";
905         my $alt = "$info_dir/alternates";
906         my $mode = 0644;
907         my (@old, @new, %seen); # seen: st_dev + st_ino
908         if (-e $alt) {
909                 open(my $fh, '<', $alt) or die "open $alt: $!";
910                 $mode = (stat($fh))[2] & 07777;
911                 while (my $line = <$fh>) {
912                         chomp(my $d = $line);
913                         if (my @st = stat($d)) {
914                                 next if $seen{"$st[0]\0$st[1]"}++;
915                         } else {
916                                 warn "W: stat($d) failed (from $alt): $!\n";
917                                 next if $opt->{-idx_gc};
918                         }
919                         push @old, $line;
920                 }
921         }
922         for my $ibx (@{$self->{ibx_list}}) {
923                 my $line = $ibx->git->{git_dir} . "/objects\n";
924                 chomp(my $d = $line);
925                 if (my @st = stat($d)) {
926                         next if $seen{"$st[0]\0$st[1]"}++;
927                 } else {
928                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
929                         next if $opt->{-idx_gc};
930                 }
931                 push @new, $line;
932         }
933         if (scalar @new) {
934                 push @old, @new;
935                 my $o = \@old;
936                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
937         }
938         $self->parallel_init($self->{indexlevel});
939         $self->umask_prepare;
940         $self->with_umask(\&_idx_init, $self, $opt);
941         $self->{oidx}->begin_lazy;
942         $self->{oidx}->eidx_prep;
943         $self->{midx}->begin_txn;
944 }
945
946 no warnings 'once';
947 *done = \&PublicInbox::V2Writable::done;
948 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
949 *with_umask = \&PublicInbox::InboxWritable::with_umask;
950 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
951 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
952 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
953 *index_todo = \&PublicInbox::V2Writable::index_todo;
954 *count_shards = \&PublicInbox::V2Writable::count_shards;
955 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
956 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
957 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
958
959 1;