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::MultiGit;
25 use PublicInbox::Search;
26 use PublicInbox::SearchIdx qw(prepare_stack is_ancestor is_bad_blob);
27 use PublicInbox::OverIdx;
28 use PublicInbox::MiscIdx;
29 use PublicInbox::MID qw(mids);
30 use PublicInbox::V2Writable;
31 use PublicInbox::InboxWritable;
32 use PublicInbox::ContentHash qw(content_hash);
34 use PublicInbox::DS qw(now add_timer);
35 use DBI qw(:sql_types); # SQL_BLOB
38 my (undef, $dir, $opt) = @_;
39 my $l = $opt->{indexlevel} // 'full';
40 $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
41 die "invalid indexlevel=$l\n";
42 $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
44 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
46 creat => $opt->{creat},
47 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
48 ibx_active => [], # by config section order
49 ibx_known => [], # by config section order
55 lock_path => "$dir/ei.lock",
57 $self->{shards} = $self->count_shards ||
58 nproc_shards({ nproc => $opt->{jobs} });
59 my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
60 $self->{-no_fsync} = $oidx->{-no_fsync} = 1 if !$opt->{fsync};
61 $self->{oidx} = $oidx;
66 my ($self, $ibx, $types) = @_;
67 $self->{ibx_map}->{$ibx->eidx_key} //= do {
68 delete $self->{-ibx_ary_known}; # invalidate cache
69 delete $self->{-ibx_ary_active}; # invalidate cache
70 $types //= [ qw(active known) ];
72 push @{$self->{"ibx_$t"}}, $ibx;
78 sub _ibx_attach { # each_inbox callback
79 my ($ibx, $self, $types) = @_;
80 attach_inbox($self, $ibx, $types);
84 my ($self, $cfg, $ibxs) = @_;
88 for my $ibx (@$ibxs) {
89 $self->{ibx_map}->{$ibx->eidx_key} //= do {
90 push @{$self->{ibx_active}}, $ibx;
91 push @{$self->{ibx_known}}, $ibx;
95 delete $self->{-ibx_ary_known};
96 delete $self->{-ibx_ary_active};
99 $types //= [ qw(known active) ];
100 $cfg->each_inbox(\&_ibx_attach, $self, $types);
103 sub check_batch_limit ($) {
105 my $self = $req->{self};
106 my $new_smsg = $req->{new_smsg};
107 my $n = $self->{transact_bytes} += $new_smsg->{bytes};
109 # set flag for PublicInbox::V2Writable::index_todo:
110 ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
113 sub apply_boost ($$) {
114 my ($req, $smsg) = @_;
115 my $id2pos = $req->{id2pos}; # index in ibx_sorted
116 my $xr3 = $req->{self}->{oidx}->get_xref3($smsg->{num}, 1);
118 $id2pos->{$a->[0]} <=> $id2pos->{$b->[0]}
120 $a->[1] <=> $b->[1] # break ties with {xnum}
122 my $top_blob = unpack('H*', $xr3->[0]->[2]);
123 my $new_smsg = $req->{new_smsg};
124 return if $top_blob ne $new_smsg->{blob}; # loser
126 # replace the old smsg with the more boosted one
127 $new_smsg->{num} = $smsg->{num};
128 $new_smsg->populate($req->{eml}, $req);
129 $req->{self}->{oidx}->add_overview($req->{eml}, $new_smsg);
133 my ($req, $smsg) = @_;
134 my $self = $req->{self};
135 my $docid = $smsg->{num};
136 my $idx = $self->idx_shard($docid);
137 my $oid = $req->{oid};
138 my $xibx = $req->{ibx};
139 my $eml = $req->{eml};
140 my $eidx_key = $xibx->eidx_key;
141 if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
142 my $xnum = $req->{xnum};
143 $self->{oidx}->add_xref3($docid, $xnum, $oid, $eidx_key);
144 $idx->ipc_do('add_eidx_info', $docid, $eidx_key, $eml);
145 apply_boost($req, $smsg) if $req->{boost_in_use};
148 my $nr = $self->{oidx}->remove_xref3($docid, $oid, $eidx_key,
151 $self->{oidx}->eidxq_del($docid);
152 $idx->ipc_do('xdb_remove', $docid);
153 } elsif ($rm_eidx_info) {
154 $idx->ipc_do('remove_eidx_info',
155 $docid, $eidx_key, $eml);
156 $self->{oidx}->eidxq_add($docid); # yes, add
161 # called by V2Writable::sync_prepare
162 sub artnum_max { $_[0]->{oidx}->eidx_max }
164 sub index_unseen ($) {
166 my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
167 my $eml = delete $req->{eml};
168 $new_smsg->populate($eml, $req);
169 my $self = $req->{self};
170 my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
171 $new_smsg->{num} = $docid;
172 my $idx = $self->idx_shard($docid);
173 $self->{oidx}->add_overview($eml, $new_smsg);
174 my $oid = $new_smsg->{blob};
175 my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
176 $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
177 $idx->index_eml($eml, $new_smsg, $ibx->eidx_key);
178 check_batch_limit($req);
181 sub do_finalize ($) {
183 if (my $indexed = $req->{indexed}) { # duplicated messages
184 do_xpost($req, $_) for @$indexed;
185 } elsif (exists $req->{new_smsg}) { # totally unseen messsage
188 # `d' message was already unindexed in the v1/v2 inboxes,
189 # so it's too noisy to warn, here.
191 # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
192 if (defined(my $cur_cmt = $req->{cur_cmt})) {
193 ${$req->{latest_cmt}} = $cur_cmt;
197 sub do_step ($) { # main iterator for adding messages to the index
199 my $self = $req->{self} // die 'BUG: {self} missing';
201 if (my $next_arg = $req->{next_arg}) {
202 if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
203 $req->{cur_smsg} = $smsg;
204 $self->git->cat_async($smsg->{blob},
205 \&ck_existing, $req);
206 return; # ck_existing calls do_step
208 delete $req->{next_arg};
210 die "BUG: {cur_smsg} still set" if $req->{cur_smsg};
211 my $mid = shift(@{$req->{mids}}) // last;
213 $req->{next_arg} = [ $mid, \$id, \$prev ];
219 sub _blob_missing ($$) { # called when $smsg->{blob} is bad
220 my ($req, $smsg) = @_;
221 my $self = $req->{self};
222 my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
223 my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
225 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
226 die "BUG: xref $keep[0] has no OID";
228 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
229 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
230 my $saved = $self->{oidx}->get_art($smsg->{num});
232 $self->{oidx}->delete_by_num($smsg->{num});
236 sub ck_existing { # git->cat_async callback
237 my ($bref, $oid, $type, $size, $req) = @_;
238 my $smsg = delete $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
239 if ($type eq 'missing') {
240 _blob_missing($req, $smsg);
241 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
242 my $self = $req->{self} // die 'BUG: {self} missing';
243 local $self->{current_info} = "$self->{current_info} $oid";
244 my $cur = PublicInbox::Eml->new($bref);
245 if (content_hash($cur) eq $req->{chash}) {
246 push @{$req->{indexed}}, $smsg; # for do_xpost
247 } # else { index_unseen later }
252 # is the messages visible in the inbox currently being indexed?
253 # return the number if so
254 sub cur_ibx_xnum ($$) {
255 my ($req, $bref) = @_;
256 my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
258 $req->{eml} = PublicInbox::Eml->new($bref);
259 $req->{chash} = content_hash($req->{eml});
260 $req->{mids} = mids($req->{eml});
261 for my $mid (@{$req->{mids}}) {
263 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
264 return $x->{num} if $x->{blob} eq $req->{oid};
270 sub index_oid { # git->cat_async callback for 'm'
271 my ($bref, $oid, $type, $size, $req) = @_;
272 my $self = $req->{self};
273 local $self->{current_info} = "$self->{current_info} $oid";
274 return if is_bad_blob($oid, $type, $size, $req->{oid});
275 my $new_smsg = $req->{new_smsg} = bless {
277 }, 'PublicInbox::Smsg';
278 $new_smsg->set_bytes($$bref, $size);
279 defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
284 sub unindex_oid { # git->cat_async callback for 'd'
285 my ($bref, $oid, $type, $size, $req) = @_;
286 my $self = $req->{self};
287 local $self->{current_info} = "$self->{current_info} $oid";
288 return if is_bad_blob($oid, $type, $size, $req->{oid});
289 return if defined(cur_ibx_xnum($req, $bref)); # was re-added
293 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
295 my ($self, $sync) = @_;
297 my $ekey = $sync->{ibx}->eidx_key;
298 my $uv = $sync->{ibx}->uidvalidity;
299 for my $i (0..$sync->{epoch_max}) {
300 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
305 sub _ibx_index_reject ($) {
307 $ibx->mm // return 'unindexed, no msgmap.sqlite3';
308 $ibx->uidvalidity // return 'no UIDVALIDITY';
309 $ibx->over // return 'unindexed, no over.sqlite3';
313 sub _sync_inbox ($$$) {
314 my ($self, $sync, $ibx) = @_;
315 my $ekey = $ibx->eidx_key;
316 if (defined(my $err = _ibx_index_reject($ibx))) {
317 return "W: skipping $ekey ($err)";
320 $sync->{nr} = \(my $nr = 0);
321 my $v = $ibx->version;
323 $sync->{epoch_max} = $ibx->max_git_epoch // return;
324 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
326 my $uv = $ibx->uidvalidity;
327 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
328 my $head = $ibx->mm->last_commit //
329 return "E: $ibx->{inboxdir} is not indexed";
330 my $stk = prepare_stack($sync, $lc ? "$lc..$head" : $head);
331 my $unit = { stack => $stk, git => $ibx->git };
332 push @{$sync->{todo}}, $unit;
334 return "E: $ekey unsupported inbox version (v$v)";
336 for my $unit (@{delete($sync->{todo}) // []}) {
337 last if $sync->{quit};
338 index_todo($self, $sync, $unit);
340 $self->{midx}->index_ibx($ibx) unless $sync->{quit};
341 $ibx->git->cleanup; # done with this inbox, now
345 sub gc_unref_doc ($$$$) {
346 my ($self, $ibx_id, $eidx_key, $docid) = @_;
348 # for debug/info purposes, oids may no longer be accessible
349 my $dbh = $self->{oidx}->dbh;
350 my $sth = $dbh->prepare_cached(<<'', undef, 1);
351 SELECT oidbin FROM xref3 WHERE docid = ? AND ibx_id = ?
353 $sth->execute($docid, $ibx_id);
354 my @oid = map { unpack('H*', $_->[0]) } @{$sth->fetchall_arrayref};
356 $remain += $self->{oidx}->remove_xref3($docid, $oid, $eidx_key);
359 $self->{oidx}->eidxq_add($docid); # enqueue for reindex
361 warn "I: unref #$docid $eidx_key $oid\n";
364 warn "I: remove #$docid $eidx_key @oid\n";
365 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
370 my ($self, $opt) = @_;
371 $self->{cfg} or die "E: GC requires ->attach_config\n";
373 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
375 my $dbh = $self->{oidx}->dbh;
376 $dbh->do('PRAGMA case_sensitive_like = ON'); # only place we use LIKE
377 my $x3_doc = $dbh->prepare('SELECT docid FROM xref3 WHERE ibx_id = ?');
378 my $ibx_ck = $dbh->prepare('SELECT ibx_id,eidx_key FROM inboxes');
379 my $lc_i = $dbh->prepare(<<'');
380 SELECT key FROM eidx_meta WHERE key LIKE ? ESCAPE ?
383 while (my ($ibx_id, $eidx_key) = $ibx_ck->fetchrow_array) {
384 next if $self->{ibx_map}->{$eidx_key};
385 $self->{midx}->remove_eidx_key($eidx_key);
386 warn "I: deleting messages for $eidx_key...\n";
387 $x3_doc->execute($ibx_id);
388 while (defined(my $docid = $x3_doc->fetchrow_array)) {
389 gc_unref_doc($self, $ibx_id, $eidx_key, $docid);
391 $dbh->prepare_cached(<<'')->execute($ibx_id);
392 DELETE FROM inboxes WHERE ibx_id = ?
394 # drop last_commit info
396 $pat =~ s/([_%\\])/\\$1/g;
397 $lc_i->execute("lc-%:$pat//%", '\\');
398 while (my ($key) = $lc_i->fetchrow_array) {
399 next if $key !~ m!\Alc-v[1-9]+:\Q$eidx_key\E//!;
400 warn "I: removing $key\n";
401 $dbh->prepare_cached(<<'')->execute($key);
402 DELETE FROM eidx_meta WHERE key = ?
406 warn "I: $eidx_key removed\n";
409 # it's not real unless it's in `over', we use parallelism here,
410 # shards will be reading directly from over, so commit
411 $self->{oidx}->commit_lazy;
412 $self->{oidx}->begin_lazy;
414 for my $idx (@{$self->{idx_shards}}) {
415 warn "I: cleaning up shard #$idx->{shard}\n";
416 $idx->shard_over_check($self->{oidx});
418 my $nr = $dbh->do(<<'');
419 DELETE FROM xref3 WHERE docid NOT IN (SELECT num FROM over)
421 warn "I: eliminated $nr stale xref3 entries\n" if $nr != 0;
423 # fixup from old bugs:
424 $nr = $dbh->do(<<'');
425 DELETE FROM over WHERE num NOT IN (SELECT docid FROM xref3)
427 warn "I: eliminated $nr stale over entries\n" if $nr != 0;
432 my ($self, $sync, $smsg) = @_;
433 my $ibx_id = delete($smsg->{ibx_id}) // die '{ibx_id} unset';
434 my $pos = $sync->{id2pos}->{$ibx_id} // die "$ibx_id no pos";
435 $self->{-ibx_ary_known}->[$pos] //
436 die "BUG: ibx for $smsg->{blob} not mapped"
439 sub _fd_constrained ($) {
441 $self->{-fd_constrained} //= do {
443 if (eval { require BSD::Resource; 1 }) {
444 my $NOFILE = BSD::Resource::RLIMIT_NOFILE();
445 ($soft, undef) = BSD::Resource::getrlimit($NOFILE);
447 chomp($soft = `sh -c 'ulimit -n'`);
449 if (defined($soft)) {
450 # $want is an estimate
451 my $want = scalar(@{$self->{ibx_active}}) + 64;
452 my $ret = $want > $soft;
455 RLIMIT_NOFILE=$soft insufficient (want: $want), will close DB handles early
460 warn "Unable to determine RLIMIT_NOFILE: $@\n";
466 sub _reindex_finalize ($$$) {
467 my ($req, $smsg, $eml) = @_;
468 my $sync = $req->{sync};
469 my $self = $sync->{self};
470 my $by_chash = delete $req->{by_chash} or die 'BUG: no {by_chash}';
471 my $nr = scalar(keys(%$by_chash)) or die 'BUG: no content hashes';
472 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
473 my $docid = $smsg->{num} = $orig_smsg->{num};
474 $self->{oidx}->add_overview($eml, $smsg); # may rethread
475 check_batch_limit({ %$sync, new_smsg => $smsg });
476 my $chash0 = $smsg->{chash} // die "BUG: $smsg->{blob} no {chash}";
477 my $stable = delete($by_chash->{$chash0}) //
478 die "BUG: $smsg->{blob} chash missing";
479 my $idx = $self->idx_shard($docid);
480 my $top_smsg = pop @$stable;
481 $top_smsg == $smsg or die 'BUG: top_smsg != smsg';
482 my $ibx = _ibx_for($self, $sync, $smsg);
483 $idx->index_eml($eml, $smsg, $ibx->eidx_key);
484 for my $x (reverse @$stable) {
485 $ibx = _ibx_for($self, $sync, $x);
486 my $hdr = delete $x->{hdr} // die 'BUG: no {hdr}';
487 $idx->ipc_do('add_eidx_info', $docid, $ibx->eidx_key, $hdr);
489 return if $nr == 1; # likely, all good
491 warn "W: #$docid split into $nr due to deduplication change\n";
493 for my $ary (values %$by_chash) {
494 for my $x (reverse @$ary) {
495 warn "removing #$docid xref3 $x->{blob}\n";
496 my $n = $self->{oidx}->remove_xref3($docid, $x->{blob});
497 die "BUG: $x->{blob} invalidated #$docid" if $n == 0;
499 my $x = pop(@$ary) // die "BUG: #$docid {by_chash} empty";
500 $x->{num} = delete($x->{xnum}) // die '{xnum} unset';
501 $ibx = _ibx_for($self, $sync, $x);
502 if (my $over = $ibx->over) {
503 my $e = $over->get_art($x->{num});
504 $e->{blob} eq $x->{blob} or die <<EOF;
505 $x->{blob} != $e->{blob} (${\$ibx->eidx_key}:$e->{num});
507 push @todo, $ibx, $e;
508 $over->dbh_close if _fd_constrained($self);
510 die "$ibx->{inboxdir}: over.sqlite3 unusable: $!\n";
514 while (my ($ibx, $e) = splice(@todo, 0, 2)) {
515 reindex_unseen($self, $sync, $ibx, $e);
519 sub _reindex_oid { # git->cat_async callback
520 my ($bref, $oid, $type, $size, $req) = @_;
521 my $sync = $req->{sync};
522 my $self = $sync->{self};
523 my $orig_smsg = $req->{orig_smsg} // die 'BUG: no {orig_smsg}';
524 my $expect_oid = $req->{xr3r}->[$req->{ix}]->[2];
525 my $docid = $orig_smsg->{num};
526 if (is_bad_blob($oid, $type, $size, $expect_oid)) {
527 my $remain = $self->{oidx}->remove_xref3($docid, $expect_oid);
529 warn "W: #$docid gone or corrupted\n";
530 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
531 } elsif (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
532 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
534 warn "BUG: #$docid gone (UNEXPECTED)\n";
535 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
539 my $ci = $self->{current_info};
540 local $self->{current_info} = "$ci #$docid $oid";
541 my $re_smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
542 $re_smsg->set_bytes($$bref, $size);
543 my $eml = PublicInbox::Eml->new($bref);
544 $re_smsg->populate($eml, { autime => $orig_smsg->{ds},
545 cotime => $orig_smsg->{ts} });
546 my $chash = content_hash($eml);
547 $re_smsg->{chash} = $chash;
548 $re_smsg->{xnum} = $req->{xr3r}->[$req->{ix}]->[1];
549 $re_smsg->{ibx_id} = $req->{xr3r}->[$req->{ix}]->[0];
550 $re_smsg->{hdr} = $eml->header_obj;
551 push @{$req->{by_chash}->{$chash}}, $re_smsg;
552 if (my $next_oid = $req->{xr3r}->[++$req->{ix}]->[2]) {
553 $self->git->cat_async($next_oid, \&_reindex_oid, $req);
554 } else { # last $re_smsg is the highest priority xref3
555 local $self->{current_info} = "$ci #$docid";
556 _reindex_finalize($req, $re_smsg, $eml);
560 sub _reindex_smsg ($$$) {
561 my ($self, $sync, $smsg) = @_;
562 my $docid = $smsg->{num};
563 my $xr3 = $self->{oidx}->get_xref3($docid, 1);
564 if (scalar(@$xr3) == 0) { # _reindex_check_stale should've covered this
566 BUG? #$docid $smsg->{blob} is not referenced by inboxes during reindex
568 $self->{oidx}->delete_by_num($docid);
569 $self->idx_shard($docid)->ipc_do('xdb_remove', $docid);
573 # we sort {xr3r} in the reverse order of ibx_sorted so we can
574 # hit the common case in _reindex_finalize without rereading
575 # from git (or holding multiple messages in memory).
576 my $id2pos = $sync->{id2pos}; # index in ibx_sorted
578 $id2pos->{$b->[0]} <=> $id2pos->{$a->[0]}
580 $b->[1] <=> $a->[1] # break ties with {xnum}
582 @$xr3 = map { [ $_->[0], $_->[1], unpack('H*', $_->[2]) ] } @$xr3;
583 my $req = { orig_smsg => $smsg, sync => $sync, xr3r => $xr3, ix => 0 };
584 $self->git->cat_async($xr3->[$req->{ix}]->[2], \&_reindex_oid, $req);
587 sub checkpoint_due ($) {
589 ${$sync->{need_checkpoint}} || (now() > $sync->{next_check});
593 # I've copied FS images and only changed the hostname before,
594 # so prepend hostname. Use `state' since these a BOFH can change
595 # these while this process is running and we always want to be
596 # able to release locks taken by this process.
597 state $retval = hostname . '-' . do {
598 my $m; # machine-id(5) is systemd
599 if (open(my $fh, '<', '/etc/machine-id')) { $m = <$fh> }
600 # (g)hostid(1) is in GNU coreutils, kern.hostid is most BSDs
601 chomp($m ||= `{ sysctl -n kern.hostid ||
602 hostid || ghostid; } 2>/dev/null`
603 || "no-machine-id-or-hostid-on-$^O");
610 my $expect = delete($self->{-eidxq_locked}) or return;
611 my ($owner_pid, undef) = split(/-/, $expect);
612 return if $owner_pid != $$; # shards may fork
613 my $oidx = $self->{oidx};
615 my $cur = $oidx->eidx_meta('eidxq_lock') // '';
616 if ($cur eq $expect) {
617 $oidx->eidx_meta('eidxq_lock', '');
619 } elsif ($cur ne '') {
620 warn "E: eidxq_lock($expect) stolen by $cur\n";
622 warn "E: eidxq_lock($expect) released by another process\n";
629 eidxq_release($self) and $self->{oidx}->commit_lazy;
632 sub _eidxq_take ($) {
634 my $val = "$$-${\time}-$>-".host_ident;
635 $self->{oidx}->eidx_meta('eidxq_lock', $val);
636 $self->{-eidxq_locked} = $val;
639 sub eidxq_lock_acquire ($) {
641 my $oidx = $self->{oidx};
643 my $cur = $oidx->eidx_meta('eidxq_lock') || return _eidxq_take($self);
644 if (my $locked = $self->{-eidxq_locked}) { # be lazy
645 return $locked if $locked eq $cur;
647 my ($pid, $time, $euid, $ident) = split(/-/, $cur, 4);
648 my $t = strftime('%Y-%m-%d %k:%M:%S', gmtime($time));
649 if ($euid == $> && $ident eq host_ident) {
652 I: PID:$pid (re)indexing Xapian since $t, it will continue our work
656 warn "I: eidxq_lock is stale ($cur), clobbering\n";
657 return _eidxq_take($self);
659 warn "E: kill(0, $pid) failed: $!\n"; # fall-through:
661 my $fn = $oidx->dbh->sqlite_db_filename;
663 W: PID:$pid, UID:$euid on $ident is indexing Xapian since $t
664 W: If this is unexpected, delete `eidxq_lock' from the `eidx_meta' table:
665 W: sqlite3 $fn 'DELETE FROM eidx_meta WHERE key = "eidxq_lock"'
670 sub ibx_sorted ($$) {
671 my ($self, $type) = @_;
672 $self->{"-ibx_ary_$type"} //= do {
673 # highest boost first, stable for config-ordering tiebreaker
676 ($b->{boost} // 0) <=> ($a->{boost} // 0)
677 } @{$self->{'ibx_'.$type} // die "BUG: $type unknown"} ];
681 sub prep_id2pos ($) {
685 $id2pos{$_->{-ibx_id}} = $pos++ for (@{ibx_sorted($self, 'known')});
689 sub eidxq_process ($$) { # for reindexing
690 my ($self, $sync) = @_;
691 return unless $self->{cfg};
693 return unless eidxq_lock_acquire($self);
694 my $dbh = $self->{oidx}->dbh;
695 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
697 local $sync->{-regen_fmt} = "%u/$tot\n";
698 my $pr = $sync->{-opt}->{-progress};
700 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
701 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
702 $pr->("Xapian indexing $min..$max (total=$tot)\n");
704 $sync->{id2pos} //= prep_id2pos($self);
707 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
708 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
710 while (defined(my $docid = $iter->fetchrow_array)) {
711 last if $sync->{quit};
712 if (my $smsg = $self->{oidx}->get_art($docid)) {
713 _reindex_smsg($self, $sync, $smsg);
715 warn "E: #$docid does not exist in over\n";
717 $del->execute($docid);
720 if (checkpoint_due($sync)) {
721 $dbh = $del = $iter = undef;
722 reindex_checkpoint($self, $sync); # release lock
723 $dbh = $self->{oidx}->dbh;
727 $self->git->async_wait_all;
728 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
731 sub _reindex_unseen { # git->cat_async callback
732 my ($bref, $oid, $type, $size, $req) = @_;
733 return if is_bad_blob($oid, $type, $size, $req->{oid});
734 my $self = $req->{self} // die 'BUG: {self} unset';
735 local $self->{current_info} = "$self->{current_info} $oid";
736 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
737 $new_smsg->set_bytes($$bref, $size);
738 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
739 $req->{new_smsg} = $new_smsg;
740 $req->{chash} = content_hash($eml);
741 $req->{mids} = mids($eml); # do_step iterates through this
742 do_step($req); # enter the normal indexing flow
745 # --reindex may catch totally unseen messages, this handles them
746 sub reindex_unseen ($$$$) {
747 my ($self, $sync, $ibx, $xsmsg) = @_;
750 autime => $xsmsg->{ds},
751 cotime => $xsmsg->{ts},
752 oid => $xsmsg->{blob},
754 xnum => $xsmsg->{num},
755 # {mids} and {chash} will be filled in at _reindex_unseen
757 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
758 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
761 sub _reindex_check_unseen ($$$) {
762 my ($self, $sync, $ibx) = @_;
763 my $ibx_id = $ibx->{-ibx_id};
765 my ($beg, $end) = (1, $slice);
767 # first, check if we missed any messages in target $ibx
769 my $pr = $sync->{-opt}->{-progress};
770 my $ekey = $ibx->eidx_key;
771 local $sync->{-regen_fmt} =
772 "$ekey checking unseen %u/".$ibx->over->max."\n";
775 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
776 ${$sync->{nr}} = $beg;
777 $beg = $msgs->[-1]->{num} + 1;
778 $end = $beg + $slice;
779 if (checkpoint_due($sync)) {
780 reindex_checkpoint($self, $sync); # release lock
783 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
784 SELECT DISTINCT(docid) FROM xref3 WHERE
785 ibx_id = ? AND xnum = ? AND oidbin = ?
787 for my $xsmsg (@$msgs) {
788 my $oidbin = pack('H*', $xsmsg->{blob});
789 $inx3->bind_param(1, $ibx_id);
790 $inx3->bind_param(2, $xsmsg->{num});
791 $inx3->bind_param(3, $oidbin, SQL_BLOB);
793 my $docids = $inx3->fetchall_arrayref;
794 # index messages which were totally missed
795 # the first time around ASAP:
796 if (scalar(@$docids) == 0) {
797 reindex_unseen($self, $sync, $ibx, $xsmsg);
798 } else { # already seen, reindex later
799 for my $r (@$docids) {
800 $self->{oidx}->eidxq_add($r->[0]);
803 last if $sync->{quit};
805 last if $sync->{quit};
809 sub _reindex_check_stale ($$$) {
810 my ($self, $sync, $ibx) = @_;
812 my $pr = $sync->{-opt}->{-progress};
814 my $ekey = $ibx->eidx_key;
815 local $sync->{-regen_fmt} =
816 "$ekey check stale/missing %u/".$ibx->over->max."\n";
819 if (checkpoint_due($sync)) {
820 reindex_checkpoint($self, $sync); # release lock
822 # now, check if there's stale xrefs
823 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
824 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
825 ORDER BY docid,xnum ASC LIMIT 10000
827 $iter->execute($ibx->{-ibx_id}, $min);
830 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
831 return if $sync->{quit};
832 ${$sync->{nr}} = $xnum;
834 $fetching = $min = $docid;
835 my $smsg = $ibx->over->get_art($xnum);
839 } elsif (pack('H*', $smsg->{blob}) ne $oidbin) {
840 $err = "mismatch (!= $smsg->{blob})";
842 next; # likely, all good
844 # current_info already has eidx_key
845 my $oidhex = unpack('H*', $oidbin);
846 warn "$xnum:$oidhex (#$docid): $err\n";
847 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
848 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
850 $del->bind_param(1, $ibx->{-ibx_id});
851 $del->bind_param(2, $xnum);
852 $del->bind_param(3, $oidbin, SQL_BLOB);
855 # get_xref3 over-fetches, but this is a rare path:
856 my $xr3 = $self->{oidx}->get_xref3($docid);
857 my $idx = $self->idx_shard($docid);
858 if (scalar(@$xr3) == 0) { # all gone
859 $self->{oidx}->delete_by_num($docid);
860 $self->{oidx}->eidxq_del($docid);
861 $idx->ipc_do('xdb_remove', $docid);
862 } else { # enqueue for reindex of remaining messages
863 $idx->ipc_do('remove_eidx_info',
864 $docid, $ibx->eidx_key);
865 $self->{oidx}->eidxq_add($docid); # yes, add
868 } while (defined $fetching);
871 sub _reindex_inbox ($$$) {
872 my ($self, $sync, $ibx) = @_;
873 my $ekey = $ibx->eidx_key;
874 local $self->{current_info} = $ekey;
875 if (defined(my $err = _ibx_index_reject($ibx))) {
876 warn "W: cannot reindex $ekey ($err)\n";
878 _reindex_check_unseen($self, $sync, $ibx);
879 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
881 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
885 my ($self, $sync) = @_;
886 return unless $self->{cfg};
888 # acquire eidxq_lock early because full reindex takes forever
889 # and incremental -extindex processes can run during our checkpoints
890 if (!eidxq_lock_acquire($self)) {
891 warn "E: aborting --reindex\n";
894 for my $ibx (@{ibx_sorted($self, 'active')}) {
895 _reindex_inbox($self, $sync, $ibx);
896 last if $sync->{quit};
898 $self->git->async_wait_all; # ensure eidxq gets filled completely
899 eidxq_process($self, $sync) unless $sync->{quit};
903 my ($self, $sync, $ibx) = @_;
904 my $err = _sync_inbox($self, $sync, $ibx);
905 delete @$ibx{qw(mm over)};
906 warn $err, "\n" if defined($err);
909 sub dd_smsg { # git->cat_async callback
910 my ($bref, $oid, $type, $size, $dd) = @_;
911 my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
912 my $self = $dd->{self} // die 'BUG: {self} missing';
913 my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
914 if ($type eq 'missing') {
915 _blob_missing($dd, $smsg);
916 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
917 local $self->{current_info} = "$self->{current_info} $oid";
918 my $chash = content_hash(PublicInbox::Eml->new($bref));
919 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
921 return if $per_mid->{last_smsg} != $smsg;
922 while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
923 my $keep = shift @$ary;
924 next if !scalar(@$ary);
925 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
927 "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
928 join(', ', map { "#$_->{num}" } @$ary),"\n";
929 next if $per_mid->{sync}->{-opt}->{'dry-run'};
930 my $oidx = $self->{oidx};
931 for my $smsg (@$ary) {
932 my $gone = $smsg->{num};
933 $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
934 $self->idx_shard($gone)->ipc_do('xdb_remove', $gone);
935 $oidx->delete_by_num($gone);
940 sub eidx_dedupe ($$$) {
941 my ($self, $sync, $msgids) = @_;
942 $sync->{dedupe_cull} = 0;
945 return unless eidxq_lock_acquire($self);
946 my ($iter, $cur_mid);
949 my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
950 SELECT MAX(id) FROM msgid
952 local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
954 # note: we could write this query more intelligently,
955 # but that causes lock contention with read-only processes
957 $cur_mid = $msgids->[$idx];
958 if ($cur_mid eq '') { # all Message-IDs
959 $iter = $self->{oidx}->dbh->prepare(<<EOS);
960 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
962 $iter->execute($min_id);
964 $iter = $self->{oidx}->dbh->prepare(<<EOS);
965 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
967 $iter->execute($cur_mid, $min_id);
969 while (my ($mid, $id) = $iter->fetchrow_array) {
970 last if $sync->{quit};
971 $self->{current_info} = "dedupe $mid";
972 ${$sync->{nr}} = $min_id = $id;
974 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
977 next if scalar(@smsg) < 2;
979 dd_chash => {}, # chash => [ary of smsgs]
980 last_smsg => $smsg[-1],
984 $candidates += scalar(@smsg) - 1;
985 for my $smsg (@smsg) {
991 $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
993 # need to wait on every single one @smsg contents can get
994 # invalidated inside dd_smsg for messages with multiple
996 $self->git->async_wait_all;
998 if (checkpoint_due($sync)) {
1000 reindex_checkpoint($self, $sync);
1001 goto dedupe_restart;
1004 goto dedupe_restart if defined($msgids->[++$idx]);
1006 my $n = delete $sync->{dedupe_cull};
1007 if (my $pr = $sync->{-opt}->{-progress}) {
1008 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1013 sub eidx_sync { # main entry point
1014 my ($self, $opt) = @_;
1016 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1017 local $self->{current_info} = '';
1018 local $SIG{__WARN__} = sub {
1019 return if PublicInbox::Eml::warn_ignore(@_);
1020 $warn_cb->($self->{current_info}, ': ', @_);
1022 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1023 $self->{oidx}->rethread_prepare($opt);
1025 need_checkpoint => \(my $need_checkpoint = 0),
1027 next_check => now() + 10,
1029 # DO NOT SET {reindex} here, it's incompatible with reused
1030 # V2Writable code, reindex is totally different here
1031 # compared to v1/v2 inboxes because we have multiple histories
1033 -regen_fmt => "%u/?\n",
1035 local $SIG{USR1} = sub { $need_checkpoint = 1 };
1036 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1037 local $SIG{QUIT} = $quit;
1038 local $SIG{INT} = $quit;
1039 local $SIG{TERM} = $quit;
1040 for my $ibx (@{ibx_sorted($self, 'known')}) {
1041 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1044 if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1045 $sync->{id2pos} //= prep_id2pos($self);
1046 $sync->{boost_in_use} = 1;
1049 if (my $msgids = delete($opt->{dedupe})) {
1050 local $sync->{checkpoint_unlocks} = 1;
1051 eidx_dedupe($self, $sync, $msgids);
1053 if (delete($opt->{reindex})) {
1054 local $sync->{checkpoint_unlocks} = 1;
1055 eidx_reindex($self, $sync);
1058 # don't use $_ here, it'll get clobbered by reindex_checkpoint
1059 if ($opt->{scan} // 1) {
1060 for my $ibx (@{ibx_sorted($self, 'active')}) {
1061 last if $sync->{quit};
1062 sync_inbox($self, $sync, $ibx);
1065 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1066 eidxq_process($self, $sync) unless $sync->{quit};
1068 eidxq_release($self);
1070 $sync; # for eidx_watch
1073 sub update_last_commit { # overrides V2Writable
1074 my ($self, $sync, $stk) = @_;
1075 my $unit = $sync->{unit} // return;
1076 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1077 defined($latest_cmt) or return;
1078 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1079 my $ekey = $ibx->eidx_key;
1080 my $uv = $ibx->uidvalidity;
1081 my $epoch = $unit->{epoch};
1083 my $v = $ibx->version;
1085 die 'No {epoch} for v2 unit' unless defined $epoch;
1086 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1088 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1089 $meta_key = "lc-v1:$ekey//$uv";
1091 die "Unsupported inbox version: $v";
1093 my $last = $self->{oidx}->eidx_meta($meta_key);
1094 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1095 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1096 chomp(my $n = $unit->{git}->qx(@cmd));
1097 return if $n ne '' && $n == 0;
1099 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1102 sub _idx_init { # with_umask callback
1103 my ($self, $opt) = @_;
1104 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1105 $self->{midx} = PublicInbox::MiscIdx->new($self);
1108 sub symlink_packs ($$) {
1109 my ($ibx, $pd) = @_;
1111 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1112 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1113 my $src = substr($idx, 0, -length('.idx'));
1114 my $dst = $pd . substr($src, rindex($src, '/'));
1115 if (-f "$src.pack" and
1116 symlink("$src.pack", "$dst.pack") and
1117 symlink($idx, "$dst.idx") and
1120 # .promisor, .bitmap, .rev and .keep are optional
1121 # XXX should we symlink .keep here?
1122 for my $s (qw(promisor bitmap rev)) {
1123 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1125 } elsif (!$!{EEXIST}) {
1126 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1127 unlink "$dst.pack", "$dst.idx";
1133 sub idx_init { # similar to V2Writable
1134 my ($self, $opt) = @_;
1135 return if $self->{idx_shards};
1137 $self->git->cleanup;
1139 my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1140 my ($has_new, $alt, $seen);
1141 if ($opt->{-private}) { # LeiStore
1142 my $local = "$self->{topdir}/local"; # lei/store
1143 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1144 'ALL.git', 'local');
1147 umask 077; # don't bother restoring for lei
1148 PublicInbox::Import::init_bare($ALL);
1149 $self->git->qx(qw(config core.sharedRepository 0600));
1151 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1152 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1153 } else { # extindex has no epochs
1154 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1156 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1158 PublicInbox::Import::init_bare($ALL);
1161 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1163 my $pd = "$ALL/objects/pack";
1164 if (opendir(my $dh, $pd)) { # drop stale symlinks
1165 while (defined(my $dn = readdir($dh))) {
1166 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1168 unlink($f) if -l $f && !-e $f;
1171 } elsif ($!{ENOENT}) {
1172 mkdir($pd) or die "mkdir($pd): $!";
1174 die "opendir($pd): $!";
1177 for my $ibx (@{ibx_sorted($self, 'active')}) {
1178 # create symlinks for multi-pack-index
1179 $git_midx += symlink_packs($ibx, $pd);
1180 # add new lines to our alternates file
1181 my $d = $ibx->git->{git_dir} . '/objects';
1182 next if exists $alt->{$d};
1183 if (my @st = stat($d)) {
1184 next if $seen->{"$st[0]\0$st[1]"}++;
1186 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1187 next if $opt->{-idx_gc};
1191 ($has_new || $new ne '') and
1192 $self->{mg}->write_alternates($mode, $alt, $new);
1193 $git_midx and $self->with_umask(sub {
1194 my @cmd = ('multi-pack-index');
1195 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1196 my $lk = $self->lock_for_scope;
1197 system('git', "--git-dir=$ALL", @cmd, 'write');
1198 # ignore errors, fairly new command, may not exist
1200 $self->parallel_init($self->{indexlevel});
1201 $self->with_umask(\&_idx_init, $self, $opt);
1202 $self->{oidx}->begin_lazy;
1203 $self->{oidx}->eidx_prep;
1204 $self->{midx}->create_xdb if $new ne '';
1207 sub _watch_commit { # PublicInbox::DS::add_timer callback
1209 delete $self->{-commit_timer};
1210 eidxq_process($self, $self->{-watch_sync});
1211 eidxq_release($self);
1212 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1213 reindex_checkpoint($self, $self->{-watch_sync});
1214 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1216 # call event_step => done unless commit_timer is armed
1217 PublicInbox::DS::requeue($self);
1220 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1221 my ($self, $ibx) = @_;
1222 my $opt = $self->{-watch_sync}->{-opt};
1223 my $pr = $opt->{-progress};
1224 my $ekey = $ibx->eidx_key;
1225 local $0 = "sync $ekey";
1226 $pr->("indexing $ekey\n") if $pr;
1227 $self->idx_init($opt);
1228 sync_inbox($self, $self->{-watch_sync}, $ibx);
1229 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1230 \&_watch_commit, $self);
1233 sub eidx_reload { # -extindex --watch SIGHUP handler
1234 my ($self, $idler) = @_;
1236 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1237 $pr->('reloading ...') if $pr;
1238 delete $self->{-resync_queue};
1239 delete $self->{-ibx_ary_known};
1240 delete $self->{-ibx_ary_active};
1241 $self->{ibx_known} = [];
1242 $self->{ibx_active} = [];
1243 %{$self->{ibx_map}} = ();
1244 delete $self->{-watch_sync}->{id2pos};
1245 my $cfg = PublicInbox::Config->new;
1246 attach_config($self, $cfg);
1247 $idler->refresh($cfg);
1248 $pr->(" done\n") if $pr;
1250 warn "reload not supported without --all\n";
1254 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1256 $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1257 PublicInbox::DS::requeue($self); # trigger our ->event_step
1260 sub event_step { # PublicInbox::DS::requeue callback
1262 if (my $resync_queue = $self->{-resync_queue}) {
1263 if (my $ibx = shift(@$resync_queue)) {
1264 on_inbox_unlock($self, $ibx);
1265 PublicInbox::DS::requeue($self);
1267 delete $self->{-resync_queue};
1268 _watch_commit($self);
1271 done($self) unless $self->{-commit_timer};
1275 sub eidx_watch { # public-inbox-extindex --watch main loop
1276 my ($self, $opt) = @_;
1277 local @SIG{keys %SIG} = values %SIG;
1278 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1279 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1281 require PublicInbox::InboxIdle;
1282 require PublicInbox::DS;
1283 require PublicInbox::Syscall;
1284 require PublicInbox::Sigfd;
1285 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1286 if (!$self->{cfg}) {
1287 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1289 for my $ibx (@{ibx_sorted($self, 'active')}) {
1290 $ibx->subscribe_unlock(__PACKAGE__, $self)
1292 my $pr = $opt->{-progress};
1293 $pr->("performing initial scan ...\n") if $pr;
1294 my $sync = eidx_sync($self, $opt); # initial sync
1295 return if $sync->{quit};
1296 my $oldset = PublicInbox::DS::block_signals();
1297 local $self->{current_info} = '';
1298 my $cb = $SIG{__WARN__} || \&CORE::warn;
1299 local $SIG{__WARN__} = sub {
1300 return if PublicInbox::Eml::warn_ignore(@_);
1301 $cb->($self->{current_info}, ': ', @_);
1304 HUP => sub { eidx_reload($self, $idler) },
1305 USR1 => sub { eidx_resync_start($self) },
1306 TSTP => sub { kill('STOP', $$) },
1308 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1309 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1310 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1311 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1312 $pr->("initial scan complete, entering event loop\n") if $pr;
1313 # calls InboxIdle->event_step:
1314 PublicInbox::DS::event_loop($sig, $oldset);
1319 *done = \&PublicInbox::V2Writable::done;
1320 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1321 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1322 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1323 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1324 *index_todo = \&PublicInbox::V2Writable::index_todo;
1325 *count_shards = \&PublicInbox::V2Writable::count_shards;
1326 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1327 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1328 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1329 *checkpoint = \&PublicInbox::V2Writable::checkpoint;