1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Detached/external index cross inbox search indexing support
5 # read-write counterpart to PublicInbox::ExtSearch
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.
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)
16 package PublicInbox::ExtSearchIdx;
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 File::Glob qw(bsd_glob GLOB_NOSORT);
24 use PublicInbox::Search;
25 use PublicInbox::SearchIdx qw(prepare_stack is_ancestor 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);
33 use PublicInbox::DS qw(now add_timer);
34 use DBI qw(:sql_types); # SQL_BLOB
37 my (undef, $dir, $opt) = @_;
38 my $l = $opt->{indexlevel} // 'full';
39 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
40 die "invalid indexlevel=$l\n";
41 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
43 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
45 creat => $opt->{creat},
46 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
53 lock_path => "$dir/ei.lock",
55 $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
56 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
57 $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{fsync};
58 $self->{oidx} = $oidx;
63 my ($self, $ibx) = @_;
64 $self->{ibx_map}->{$ibx->eidx_key} //= do {
65 push @{$self->{ibx_list}}, $ibx;
70 sub _ibx_attach { # each_inbox callback
71 my ($ibx, $self) = @_;
72 attach_inbox($self, $ibx);
76 my ($self, $cfg) = @_;
78 $cfg->each_inbox(\&_ibx_attach, $self);
81 sub check_batch_limit ($) {
83 my $self = $req->{self};
84 my $new_smsg = $req->{new_smsg};
85 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
87 # set flag for PublicInbox::V2Writable::index_todo:
88 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
92 my ($req, $smsg) = @_;
93 my $self = $req->{self};
94 my $docid = $smsg->{num};
95 my $idx = $self->idx_shard($docid);
96 my $oid = $req->{oid};
97 my $xibx = $req->{ibx};
98 my $eml = $req->{eml};
99 my $eidx_key = $xibx->eidx_key;
100 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
101 my $xnum = $req->{xnum};
102 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
103 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
104 check_batch_limit($req);
107 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
110 $self->{oidx}->eidxq_del($docid);
111 $idx->ipc_do('xdb_remove', $docid);
112 } elsif ($rm_eidx_info) {
113 $idx->ipc_do('remove_eidx_info',
114 $docid, $eidx_key, $eml);
115 $self->{oidx}->eidxq_add($docid); # yes, add
120 # called by V2Writable::sync_prepare
121 sub artnum_max { $_[0]->{oidx}->eidx_max }
123 sub index_unseen ($) {
125 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
126 my $eml = delete $req->{eml};
127 $new_smsg->populate($eml, $req);
128 my $self = $req->{self};
129 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
130 $new_smsg->{num} = $docid;
131 my $idx = $self->idx_shard($docid);
132 $self->{oidx}->add_overview($eml, $new_smsg);
133 my $oid = $new_smsg->{blob};
134 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
135 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
136 $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
137 check_batch_limit($req);
140 sub do_finalize ($) {
142 if (my $indexed = $req->{indexed}) { # duplicated messages
143 do_xpost($req, $_) for @$indexed;
144 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
147 # `d' message was already unindexed in the v1/v2 inboxes,
148 # so it's too noisy to warn, here.
150 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
151 if (defined(my $cur_cmt = $req->{cur_cmt})) {
152 ${$req->{latest_cmt}} = $cur_cmt;
156 sub do_step ($) { # main iterator for adding messages to the index
158 my $self = $req->{self} // die 'BUG: {self} missing';
160 if (my $next_arg = $req->{next_arg}) {
161 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
162 $req->{cur_smsg} = $smsg;
163 $self->git->cat_async($smsg->{blob},
164 \&ck_existing, $req);
165 return; # ck_existing calls do_step
167 delete $req->{next_arg};
169 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
170 my $mid = shift(@{$req->{mids}}) // last;
172 $req->{next_arg} = [ $mid, \$id, \$prev ];
178 sub _blob_missing ($$) { # called when $smsg->{blob} is bad
179 my ($req, $smsg) = @_;
180 my $self = $req->{self};
181 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
182 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
184 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
185 die "BUG: xref $keep[0] has no OID";
187 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
188 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
189 my $saved = $self->{oidx}->get_art($smsg->{num});
191 $self->{oidx}->delete_by_num($smsg->{num});
195 sub ck_existing { # git->cat_async callback
196 my ($bref, $oid, $type, $size, $req) = @_;
197 my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
198 if ($type eq 'missing') {
199 _blob_missing($req, $smsg);
200 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
201 my $self = $req->{self} // die 'BUG: {self} missing';
202 local $self->{current_info} = "$self->{current_info} $oid";
203 my $cur = PublicInbox::Eml->new($bref);
204 if (content_hash($cur) eq $req->{chash}) {
205 push @{$req->{indexed}}, $smsg; # for do_xpost
206 } # else { index_unseen later }
211 # is the messages visible in the inbox currently being indexed?
212 # return the number if so
213 sub cur_ibx_xnum ($$) {
214 my ($req, $bref) = @_;
215 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
217 $req->{eml} = PublicInbox::Eml->new($bref);
218 $req->{chash} = content_hash($req->{eml});
219 $req->{mids} = mids($req->{eml});
220 for my $mid (@{$req->{mids}}) {
222 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
223 return $x->{num} if $x->{blob} eq $req->{oid};
229 sub index_oid { # git->cat_async callback for 'm'
230 my ($bref, $oid, $type, $size, $req) = @_;
231 my $self = $req->{self};
232 local $self->{current_info} = "$self->{current_info} $oid";
233 return if is_bad_blob($oid, $type, $size, $req->{oid});
234 my $new_smsg = $req->{new_smsg} = bless {
236 }, 'PublicInbox::Smsg';
237 $new_smsg->set_bytes($$bref, $size);
238 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
243 sub unindex_oid { # git->cat_async callback for 'd'
244 my ($bref, $oid, $type, $size, $req) = @_;
245 my $self = $req->{self};
246 local $self->{current_info} = "$self->{current_info} $oid";
247 return if is_bad_blob($oid, $type, $size, $req->{oid});
248 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
252 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
254 my ($self, $sync) = @_;
256 my $ekey = $sync->{ibx}->eidx_key;
257 my $uv = $sync->{ibx}->uidvalidity;
258 for my $i (0..$sync->{epoch_max}) {
259 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
264 sub _ibx_index_reject ($) {
266 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
267 $ibx->uidvalidity // return 'no UIDVALIDITY';
268 $ibx->over // return 'unindexed, no over.sqlite3';
272 sub _sync_inbox ($$$) {
273 my ($self, $sync, $ibx) = @_;
274 my $ekey = $ibx->eidx_key;
275 if (defined(my $err = _ibx_index_reject($ibx))) {
276 return "W: skipping $ekey ($err)";
279 $sync->{nr} = \(my $nr = 0);
280 my $v = $ibx->version;
282 $sync->{epoch_max} = $ibx->max_git_epoch // return;
283 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
285 my $uv = $ibx->uidvalidity;
286 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
287 my $head = $ibx->mm->last_commit //
288 return "E: $ibx->{inboxdir} is not indexed";
289 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
290 my $unit = { stack => $stk, git => $ibx->git };
291 push @{$sync->{todo}}, $unit;
293 return "E: $ekey unsupported inbox version (v$v)";
295 for my $unit (@{delete($sync->{todo}) // []}) {
296 last if $sync->{quit};
297 index_todo($self, $sync, $unit);
299 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
300 $ibx->git->cleanup; # done with this inbox, now
304 sub gc_unref_doc ($$$$) {
305 my ($self, $ibx_id, $eidx_key, $docid) = @_;
306 my $dbh = $self->{oidx}->dbh;
308 # for debug/info purposes, oids may no longer be accessible
309 my $sth = $dbh->prepare_cached(<<'', undef, 1);
310 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
312 $sth->execute($docid, $ibx_id);
313 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
315 $dbh->prepare_cached(<<'')->execute($docid, $ibx_id);
316 DELETE FROM xref3 WHERE docid = ? AND ibx_id = ?
318 my $remain = $self->{oidx}->get_xref3($docid);
319 if (scalar(@$remain)) {
320 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
322 warn "I: unref #$docid $eidx_key $oid\n";
325 warn "I: remove #$docid $eidx_key @oid\n";
326 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
331 my ($self, $opt) = @_;
332 $self->{cfg} or die "E: GC requires ->attach_config\n";
334 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
336 my $dbh = $self->{oidx}->dbh;
337 $dbh->do('PRAGMA case_sensitive_like = ON'); # only place we use LIKE
338 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
339 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
340 my $lc_i = $dbh->prepare(<<'');
341 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
344 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
345 next if $self->{ibx_map}->{$eidx_key};
346 $self->{midx}->remove_eidx_key($eidx_key);
347 warn "I: deleting messages for $eidx_key...\n";
348 $x3_doc->execute($ibx_id);
349 while (defined(my $docid = $x3_doc->fetchrow_array)) {
350 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
352 $dbh->prepare_cached(<<'')->execute($ibx_id);
353 DELETE FROM inboxes WHERE ibx_id = ?
355 # drop last_commit info
357 $pat =~ s/([_%\\])/\\$1/g;
358 $lc_i->execute("lc-%:$pat//%", '\\');
359 while (my ($key) = $lc_i->fetchrow_array) {
360 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
361 warn "I: removing $key\n";
362 $dbh->prepare_cached(<<'')->execute($key);
363 DELETE FROM eidx_meta WHERE key = ?
367 warn "I: $eidx_key removed\n";
370 # it's not real unless it's in `over', we use parallelism here,
371 # shards will be reading directly from over, so commit
372 $self->{oidx}->commit_lazy;
373 $self->{oidx}->begin_lazy;
375 for my $idx (@{$self->{idx_shards}}) {
376 warn "I: cleaning up shard #$idx->{shard}\n";
377 $idx->shard_over_check($self->{oidx});
379 my $nr = $dbh->do(<<'');
380 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
382 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
388 my ($self, $sync, $smsg) = @_;
389 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
390 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
391 $self->{ibx_list}->[$pos] // die "BUG: ibx for $smsg->{blob} not mapped"
394 sub _fd_constrained ($) {
396 $self->{-fd_constrained} //= do {
398 if (eval { require BSD::Resource; 1 }) {
399 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
400 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
402 chomp($soft = `sh -c 'ulimit -n'`);
404 if (defined($soft)) {
405 my $want = scalar(@{$self->{ibx_list}}) + 64; # estimate
406 my $ret = $want > $soft;
409 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
414 warn "Unable to determine RLIMIT_NOFILE: $@\n";
420 sub _reindex_finalize ($$$) {
421 my ($req, $smsg, $eml) = @_;
422 my $sync = $req->{sync};
423 my $self = $sync->{self};
424 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
425 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
426 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
427 my $docid = $smsg->{num} = $orig_smsg->{num};
428 $self->{oidx}->add_overview($eml, $smsg); # may rethread
429 check_batch_limit({ %$sync, new_smsg => $smsg });
430 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
431 my $stable = delete($by_chash->{$chash0}) //
432 die "BUG: $smsg->{blob} chash missing";
433 my $idx = $self->idx_shard($docid);
434 my $top_smsg = pop @$stable;
435 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
436 my $ibx = _ibx_for($self, $sync, $smsg);
437 $idx->index_eml($eml, $smsg, $ibx->eidx_key);
438 for my $x (reverse @$stable) {
439 $ibx = _ibx_for($self, $sync, $x);
440 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
441 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
443 return if $nr == 1; # likely, all good
445 warn "W: #$docid split into $nr due to deduplication change\n";
447 for my $ary (values %$by_chash) {
448 for my $x (reverse @$ary) {
449 warn "removing #$docid xref3 $x->{blob}\n";
450 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
451 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
453 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
454 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
455 $ibx = _ibx_for($self, $sync, $x);
456 if (my $over = $ibx->over) {
457 my $e = $over->get_art($x->{num});
458 $e->{blob} eq $x->{blob} or die <<EOF;
459 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
461 push @todo, $ibx, $e;
462 $over->dbh_close if _fd_constrained($self);
464 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
468 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
469 reindex_unseen($self, $sync, $ibx, $e);
473 sub _reindex_oid { # git->cat_async callback
474 my ($bref, $oid, $type, $size, $req) = @_;
475 my $sync = $req->{sync};
476 my $self = $sync->{self};
477 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
478 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
479 my $docid = $orig_smsg->{num};
480 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
481 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
483 warn "W: #$docid gone or corrupted\n";
484 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
485 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
486 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
488 warn "BUG: #$docid gone (UNEXPECTED)\n";
489 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
493 my $ci = $self->{current_info};
494 local $self->{current_info} = "$ci #$docid $oid";
495 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
496 $re_smsg->set_bytes($$bref, $size);
497 my $eml = PublicInbox::Eml->new($bref);
498 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
499 cotime => $orig_smsg->{ts} });
500 my $chash = content_hash($eml);
501 $re_smsg->{chash} = $chash;
502 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
503 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
504 $re_smsg->{hdr} = $eml->header_obj;
505 push @{$req->{by_chash}->{$chash}}, $re_smsg;
506 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
507 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
508 } else { # last $re_smsg is the highest priority xref3
509 local $self->{current_info} = "$ci #$docid";
510 _reindex_finalize($req, $re_smsg, $eml);
514 sub _reindex_smsg ($$$) {
515 my ($self, $sync, $smsg) = @_;
516 my $docid = $smsg->{num};
517 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
518 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
520 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
522 $self->{oidx}->delete_by_num($docid);
523 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
527 # we sort {xr3r} in the reverse order of {ibx_list} so we can
528 # hit the common case in _reindex_finalize without rereading
529 # from git (or holding multiple messages in memory).
530 my $id2pos = $sync->{id2pos}; # index in {ibx_list}
532 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
534 $b->[1] <=> $a->[1] # break ties with {xnum}
536 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
537 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
538 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
541 sub checkpoint_due ($) {
543 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
547 # I've copied FS images and only changed the hostname before,
548 # so prepend hostname. Use `state' since these a BOFH can change
549 # these while this process is running and we always want to be
550 # able to release locks taken by this process.
551 state $retval = hostname . '-' . do {
552 my $m; # machine-id(5) is systemd
553 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
554 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
555 chomp($m ||= `{ sysctl -n kern.hostid ||
556 hostid || ghostid; } 2>/dev/null`
557 || "no-machine-id-or-hostid-on-$^O");
564 my $expect = delete($self->{-eidxq_locked}) or return;
565 my ($owner_pid, undef) = split(/-/, $expect);
566 return if $owner_pid != $$; # shards may fork
567 my $oidx = $self->{oidx};
569 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
570 if ($cur eq $expect) {
571 $oidx->eidx_meta('eidxq_lock', '');
573 } elsif ($cur ne '') {
574 warn "E: eidxq_lock($expect) stolen by $cur\n";
576 warn "E: eidxq_lock($expect) released by another process\n";
583 eidxq_release($self) and $self->{oidx}->commit_lazy;
586 sub _eidxq_take ($) {
588 my $val = "$$-${\time}-$>-".host_ident;
589 $self->{oidx}->eidx_meta('eidxq_lock', $val);
590 $self->{-eidxq_locked} = $val;
593 sub eidxq_lock_acquire ($) {
595 my $oidx = $self->{oidx};
597 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
598 if (my $locked = $self->{-eidxq_locked}) { # be lazy
599 return $locked if $locked eq $cur;
601 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
602 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
603 if ($euid == $> && $ident eq host_ident) {
606 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
610 warn "I: eidxq_lock is stale ($cur), clobbering\n";
611 return _eidxq_take($self);
613 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
615 my $fn = $oidx->dbh->sqlite_db_filename;
617 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
618 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
619 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
624 sub eidxq_process ($$) { # for reindexing
625 my ($self, $sync) = @_;
627 return unless eidxq_lock_acquire($self);
628 my $dbh = $self->{oidx}->dbh;
629 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
631 local $sync->{-regen_fmt} = "%u/$tot\n";
632 my $pr = $sync->{-opt}->{-progress};
634 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
635 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
636 $pr->("Xapian indexing $min..$max (total=$tot)\n");
638 $sync->{id2pos} //= do {
641 $id2pos{$_->{-ibx_id}} = $pos++ for @{$self->{ibx_list}};
646 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
647 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
649 while (defined(my $docid = $iter->fetchrow_array)) {
650 last if $sync->{quit};
651 if (my $smsg = $self->{oidx}->get_art($docid)) {
652 _reindex_smsg($self, $sync, $smsg);
654 warn "E: #$docid does not exist in over\n";
656 $del->execute($docid);
659 if (checkpoint_due($sync)) {
660 $dbh = $del = $iter = undef;
661 reindex_checkpoint($self, $sync); # release lock
662 $dbh = $self->{oidx}->dbh;
666 $self->git->async_wait_all;
667 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
670 sub _reindex_unseen { # git->cat_async callback
671 my ($bref, $oid, $type, $size, $req) = @_;
672 return if is_bad_blob($oid, $type, $size, $req->{oid});
673 my $self = $req->{self} // die 'BUG: {self} unset';
674 local $self->{current_info} = "$self->{current_info} $oid";
675 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
676 $new_smsg->set_bytes($$bref, $size);
677 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
678 $req->{new_smsg} = $new_smsg;
679 $req->{chash} = content_hash($eml);
680 $req->{mids} = mids($eml); # do_step iterates through this
681 do_step($req); # enter the normal indexing flow
684 # --reindex may catch totally unseen messages, this handles them
685 sub reindex_unseen ($$$$) {
686 my ($self, $sync, $ibx, $xsmsg) = @_;
689 autime => $xsmsg->{ds},
690 cotime => $xsmsg->{ts},
691 oid => $xsmsg->{blob},
693 xnum => $xsmsg->{num},
694 # {mids} and {chash} will be filled in at _reindex_unseen
696 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
697 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
700 sub _reindex_check_unseen ($$$) {
701 my ($self, $sync, $ibx) = @_;
702 my $ibx_id = $ibx->{-ibx_id};
704 my ($beg, $end) = (1, $slice);
706 # first, check if we missed any messages in target $ibx
708 my $pr = $sync->{-opt}->{-progress};
709 my $ekey = $ibx->eidx_key;
710 local $sync->{-regen_fmt} =
711 "$ekey checking unseen %u/".$ibx->over->max."\n";
714 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
715 ${$sync->{nr}} = $beg;
716 $beg = $msgs->[-1]->{num} + 1;
717 $end = $beg + $slice;
718 if (checkpoint_due($sync)) {
719 reindex_checkpoint($self, $sync); # release lock
722 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
723 SELECT DISTINCT(docid) FROM xref3 WHERE
724 ibx_id = ? AND xnum = ? AND oidbin = ?
726 for my $xsmsg (@$msgs) {
727 my $oidbin = pack('H*', $xsmsg->{blob});
728 $inx3->bind_param(1, $ibx_id);
729 $inx3->bind_param(2, $xsmsg->{num});
730 $inx3->bind_param(3, $oidbin, SQL_BLOB);
732 my $docids = $inx3->fetchall_arrayref;
733 # index messages which were totally missed
734 # the first time around ASAP:
735 if (scalar(@$docids) == 0) {
736 reindex_unseen($self, $sync, $ibx, $xsmsg);
737 } else { # already seen, reindex later
738 for my $r (@$docids) {
739 $self->{oidx}->eidxq_add($r->[0]);
742 last if $sync->{quit};
744 last if $sync->{quit};
748 sub _reindex_check_stale ($$$) {
749 my ($self, $sync, $ibx) = @_;
751 my $pr = $sync->{-opt}->{-progress};
753 my $ekey = $ibx->eidx_key;
754 local $sync->{-regen_fmt} =
755 "$ekey check stale/missing %u/".$ibx->over->max."\n";
758 if (checkpoint_due($sync)) {
759 reindex_checkpoint($self, $sync); # release lock
761 # now, check if there's stale xrefs
762 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
763 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
764 ORDER BY docid,xnum ASC LIMIT 10000
766 $iter->execute($ibx->{-ibx_id}, $min);
769 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
770 return if $sync->{quit};
771 ${$sync->{nr}} = $xnum;
773 $fetching = $min = $docid;
774 my $smsg = $ibx->over->get_art($xnum);
775 my $oidhex = unpack('H*', $oidbin);
779 } elsif ($smsg->{blob} ne $oidhex) {
780 $err = "mismatch (!= $smsg->{blob})";
782 next; # likely, all good
784 # current_info already has eidx_key
785 warn "$xnum:$oidhex (#$docid): $err\n";
786 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
787 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
789 $del->bind_param(1, $ibx->{-ibx_id});
790 $del->bind_param(2, $xnum);
791 $del->bind_param(3, $oidbin, SQL_BLOB);
794 # get_xref3 over-fetches, but this is a rare path:
795 my $xr3 = $self->{oidx}->get_xref3($docid);
796 my $idx = $self->idx_shard($docid);
797 if (scalar(@$xr3) == 0) { # all gone
798 $self->{oidx}->delete_by_num($docid);
799 $self->{oidx}->eidxq_del($docid);
800 $idx->ipc_do('xdb_remove', $docid);
801 } else { # enqueue for reindex of remaining messages
802 $idx->ipc_do('remove_eidx_info',
803 $docid, $ibx->eidx_key);
804 $self->{oidx}->eidxq_add($docid); # yes, add
807 } while (defined $fetching);
810 sub _reindex_inbox ($$$) {
811 my ($self, $sync, $ibx) = @_;
812 my $ekey = $ibx->eidx_key;
813 local $self->{current_info} = $ekey;
814 if (defined(my $err = _ibx_index_reject($ibx))) {
815 warn "W: cannot reindex $ekey ($err)\n";
817 _reindex_check_unseen($self, $sync, $ibx);
818 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
820 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
824 my ($self, $sync) = @_;
826 # acquire eidxq_lock early because full reindex takes forever
827 # and incremental -extindex processes can run during our checkpoints
828 if (!eidxq_lock_acquire($self)) {
829 warn "E: aborting --reindex\n";
832 for my $ibx (@{$self->{ibx_list}}) {
833 _reindex_inbox($self, $sync, $ibx);
834 last if $sync->{quit};
836 $self->git->async_wait_all; # ensure eidxq gets filled completely
837 eidxq_process($self, $sync) unless $sync->{quit};
841 my ($self, $sync, $ibx) = @_;
842 my $err = _sync_inbox($self, $sync, $ibx);
843 delete @$ibx{qw(mm over)};
844 warn $err, "\n" if defined($err);
847 sub eidx_sync { # main entry point
848 my ($self, $opt) = @_;
850 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
851 local $self->{current_info} = '';
852 local $SIG{__WARN__} = sub {
853 $warn_cb->($self->{current_info}, ': ', @_);
855 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
856 $self->{oidx}->rethread_prepare($opt);
858 need_checkpoint => \(my $need_checkpoint = 0),
860 next_check => now() + 10,
862 # DO NOT SET {reindex} here, it's incompatible with reused
863 # V2Writable code, reindex is totally different here
864 # compared to v1/v2 inboxes because we have multiple histories
866 -regen_fmt => "%u/?\n",
868 local $SIG{USR1} = sub { $need_checkpoint = 1 };
869 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
870 local $SIG{QUIT} = $quit;
871 local $SIG{INT} = $quit;
872 local $SIG{TERM} = $quit;
873 for my $ibx (@{$self->{ibx_list}}) {
874 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
876 if (delete($opt->{reindex})) {
877 local $sync->{checkpoint_unlocks} = 1;
878 eidx_reindex($self, $sync);
881 # don't use $_ here, it'll get clobbered by reindex_checkpoint
882 if ($opt->{scan} // 1) {
883 for my $ibx (@{$self->{ibx_list}}) {
884 last if $sync->{quit};
885 sync_inbox($self, $sync, $ibx);
888 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
889 eidxq_process($self, $sync) unless $sync->{quit};
891 eidxq_release($self);
893 $sync; # for eidx_watch
896 sub update_last_commit { # overrides V2Writable
897 my ($self, $sync, $stk) = @_;
898 my $unit = $sync->{unit} // return;
899 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
900 defined($latest_cmt) or return;
901 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
902 my $ekey = $ibx->eidx_key;
903 my $uv = $ibx->uidvalidity;
904 my $epoch = $unit->{epoch};
906 my $v = $ibx->version;
908 die 'No {epoch} for v2 unit' unless defined $epoch;
909 $meta_key = "lc-v2:$ekey//$uv;$epoch";
911 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
912 $meta_key = "lc-v1:$ekey//$uv";
914 die "Unsupported inbox version: $v";
916 my $last = $self->{oidx}->eidx_meta($meta_key);
917 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
918 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
919 chomp(my $n = $unit->{git}->qx(@cmd));
920 return if $n ne '' && $n == 0;
922 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
925 sub _idx_init { # with_umask callback
926 my ($self, $opt) = @_;
927 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
928 $self->{midx} = PublicInbox::MiscIdx->new($self);
931 sub symlink_packs ($$) {
934 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
935 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
936 my $src = substr($idx, 0, -length('.idx'));
937 my $dst = $pd . substr($src, rindex($src, '/'));
938 if (-f "$src.pack" and
939 symlink("$src.pack", "$dst.pack") and
940 symlink($idx, "$dst.idx") and
943 # .promisor, .bitmap, .rev and .keep are optional
944 # XXX should we symlink .keep here?
945 for my $s (qw(promisor bitmap rev)) {
946 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
948 } elsif (!$!{EEXIST}) {
949 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
950 unlink "$dst.pack", "$dst.idx";
956 sub idx_init { # similar to V2Writable
957 my ($self, $opt) = @_;
958 return if $self->{idx_shards};
962 my $ALL = $self->git->{git_dir}; # ALL.git
964 if ($opt->{-private}) { # LeiStore
967 umask 077; # don't bother restoring
968 PublicInbox::Import::init_bare($ALL);
969 $self->git->qx(qw(config core.sharedRepository 0600));
972 PublicInbox::Import::init_bare($ALL) unless $old;
974 my $info_dir = "$ALL/objects/info";
975 my $alt = "$info_dir/alternates";
976 my (@old, @new, %seen); # seen: st_dev + st_ino
978 open(my $fh, '<', $alt) or die "open $alt: $!";
979 $mode = (stat($fh))[2] & 07777;
980 while (my $line = <$fh>) {
981 chomp(my $d = $line);
983 # expand relative path (/local/ stuff)
984 substr($d, 0, 3) eq '../' and
985 $d = "$ALL/objects/$d";
986 if (my @st = stat($d)) {
987 next if $seen{"$st[0]\0$st[1]"}++;
989 warn "W: stat($d) failed (from $alt): $!\n";
990 next if $opt->{-idx_gc};
996 # for LeiStore, and possibly some mirror-only state
997 if (opendir(my $dh, my $local = "$self->{topdir}/local")) {
998 # highest numbered epoch first
999 for my $n (sort { $b <=> $a } map { substr($_, 0, -4) + 0 }
1000 grep(/\A[0-9]+\.git\z/, readdir($dh))) {
1001 my $d = "$local/$n.git/objects"; # absolute path
1002 if (my @st = stat($d)) {
1003 next if $seen{"$st[0]\0$st[1]"}++;
1004 # favor relative paths for rename-friendliness
1005 push @new, "../../local/$n.git/objects\n";
1007 warn "W: stat($d) failed: $!\n";
1011 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1014 my $pd = "$ALL/objects/pack";
1015 if (!mkdir($pd) && $!{EEXIST} && opendir($dh, $pd)) {
1016 # drop stale symlinks
1017 while (defined(my $dn = readdir($dh))) {
1018 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1020 unlink($f) if -l $f && !-e $f;
1025 for my $ibx (@{$self->{ibx_list}}) {
1026 # create symlinks for multi-pack-index
1027 $git_midx += symlink_packs($ibx, $pd);
1028 # add new lines to our alternates file
1029 my $line = $ibx->git->{git_dir} . "/objects\n";
1030 chomp(my $d = $line);
1031 if (my @st = stat($d)) {
1032 next if $seen{"$st[0]\0$st[1]"}++;
1034 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1035 next if $opt->{-idx_gc};
1042 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
1044 $git_midx and $self->with_umask(sub {
1045 my @cmd = ('multi-pack-index');
1046 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1047 my $lk = $self->lock_for_scope;
1048 system('git', "--git-dir=$ALL", @cmd, 'write');
1049 # ignore errors, fairly new command, may not exist
1051 $self->parallel_init($self->{indexlevel});
1052 $self->with_umask(\&_idx_init, $self, $opt);
1053 $self->{oidx}->begin_lazy;
1054 $self->{oidx}->eidx_prep;
1055 $self->{midx}->create_xdb if @new;
1058 sub _watch_commit { # PublicInbox::DS::add_timer callback
1060 delete $self->{-commit_timer};
1061 eidxq_process($self, $self->{-watch_sync});
1062 eidxq_release($self);
1063 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1064 reindex_checkpoint($self, $self->{-watch_sync});
1065 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1067 # call event_step => done unless commit_timer is armed
1068 PublicInbox::DS::requeue($self);
1071 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1072 my ($self, $ibx) = @_;
1073 my $opt = $self->{-watch_sync}->{-opt};
1074 my $pr = $opt->{-progress};
1075 my $ekey = $ibx->eidx_key;
1076 local $0 = "sync $ekey";
1077 $pr->("indexing $ekey\n") if $pr;
1078 $self->idx_init($opt);
1079 sync_inbox($self, $self->{-watch_sync}, $ibx);
1080 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1081 \&_watch_commit, $self);
1084 sub eidx_reload { # -extindex --watch SIGHUP handler
1085 my ($self, $idler) = @_;
1087 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1088 $pr->('reloading ...') if $pr;
1089 delete $self->{-resync_queue};
1090 @{$self->{ibx_list}} = ();
1091 %{$self->{ibx_map}} = ();
1092 delete $self->{-watch_sync}->{id2pos};
1093 my $cfg = PublicInbox::Config->new;
1094 attach_config($self, $cfg);
1095 $idler->refresh($cfg);
1096 $pr->(" done\n") if $pr;
1098 warn "reload not supported without --all\n";
1102 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1104 $self->{-resync_queue} //= [ @{$self->{ibx_list}} ];
1105 PublicInbox::DS::requeue($self); # trigger our ->event_step
1108 sub event_step { # PublicInbox::DS::requeue callback
1110 if (my $resync_queue = $self->{-resync_queue}) {
1111 if (my $ibx = shift(@$resync_queue)) {
1112 on_inbox_unlock($self, $ibx);
1113 PublicInbox::DS::requeue($self);
1115 delete $self->{-resync_queue};
1116 _watch_commit($self);
1119 done($self) unless $self->{-commit_timer};
1123 sub eidx_watch { # public-inbox-extindex --watch main loop
1124 my ($self, $opt) = @_;
1126 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1127 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1129 require PublicInbox::InboxIdle;
1130 require PublicInbox::DS;
1131 require PublicInbox::Syscall;
1132 require PublicInbox::Sigfd;
1133 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1134 if (!$self->{cfg}) {
1135 $idler->watch_inbox($_) for @{$self->{ibx_list}};
1137 $_->subscribe_unlock(__PACKAGE__, $self) for @{$self->{ibx_list}};
1138 my $pr = $opt->{-progress};
1139 $pr->("performing initial scan ...\n") if $pr;
1140 my $sync = eidx_sync($self, $opt); # initial sync
1141 return if $sync->{quit};
1142 my $oldset = PublicInbox::DS::block_signals();
1143 local $self->{current_info} = '';
1144 my $cb = $SIG{__WARN__} || \&CORE::warn;
1145 local $SIG{__WARN__} = sub { $cb->($self->{current_info}, ': ', @_) };
1147 HUP => sub { eidx_reload($self, $idler) },
1148 USR1 => sub { eidx_resync_start($self) },
1149 TSTP => sub { kill('STOP', $$) },
1151 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1152 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1153 my $sigfd = PublicInbox::Sigfd->new($sig,
1154 $PublicInbox::Syscall::SFD_NONBLOCK);
1155 %SIG = (%SIG, %$sig) if !$sigfd;
1156 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1158 # wake up every second to accept signals if we don't
1159 # have signalfd or IO::KQueue:
1160 PublicInbox::DS::sig_setmask($oldset);
1161 PublicInbox::DS->SetLoopTimeout(1000);
1163 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1164 $pr->("initial scan complete, entering event loop\n") if $pr;
1165 PublicInbox::DS->EventLoop; # calls InboxIdle->event_step
1170 *done = \&PublicInbox::V2Writable::done;
1171 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1172 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1173 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1174 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1175 *index_todo = \&PublicInbox::V2Writable::index_todo;
1176 *count_shards = \&PublicInbox::V2Writable::count_shards;
1177 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1178 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1179 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1180 *checkpoint = \&PublicInbox::V2Writable::checkpoint;