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) = @_;
692 return unless eidxq_lock_acquire($self);
693 my $dbh = $self->{oidx}->dbh;
694 my $tot = $dbh->selectrow_array('SELECT COUNT(*) FROM eidxq') or return;
696 local $sync->{-regen_fmt} = "%u/$tot\n";
697 my $pr = $sync->{-opt}->{-progress};
699 my $min = $dbh->selectrow_array('SELECT MIN(docid) FROM eidxq');
700 my $max = $dbh->selectrow_array('SELECT MAX(docid) FROM eidxq');
701 $pr->("Xapian indexing $min..$max (total=$tot)\n");
703 $sync->{id2pos} //= prep_id2pos($self);
706 $del = $dbh->prepare('DELETE FROM eidxq WHERE docid = ?');
707 $iter = $dbh->prepare('SELECT docid FROM eidxq ORDER BY docid ASC');
709 while (defined(my $docid = $iter->fetchrow_array)) {
710 last if $sync->{quit};
711 if (my $smsg = $self->{oidx}->get_art($docid)) {
712 _reindex_smsg($self, $sync, $smsg);
714 warn "E: #$docid does not exist in over\n";
716 $del->execute($docid);
719 if (checkpoint_due($sync)) {
720 $dbh = $del = $iter = undef;
721 reindex_checkpoint($self, $sync); # release lock
722 $dbh = $self->{oidx}->dbh;
726 $self->git->async_wait_all;
727 $pr->("reindexed ${$sync->{nr}}/$tot\n") if $pr;
730 sub _reindex_unseen { # git->cat_async callback
731 my ($bref, $oid, $type, $size, $req) = @_;
732 return if is_bad_blob($oid, $type, $size, $req->{oid});
733 my $self = $req->{self} // die 'BUG: {self} unset';
734 local $self->{current_info} = "$self->{current_info} $oid";
735 my $new_smsg = bless { blob => $oid, }, 'PublicInbox::Smsg';
736 $new_smsg->set_bytes($$bref, $size);
737 my $eml = $req->{eml} = PublicInbox::Eml->new($bref);
738 $req->{new_smsg} = $new_smsg;
739 $req->{chash} = content_hash($eml);
740 $req->{mids} = mids($eml); # do_step iterates through this
741 do_step($req); # enter the normal indexing flow
744 # --reindex may catch totally unseen messages, this handles them
745 sub reindex_unseen ($$$$) {
746 my ($self, $sync, $ibx, $xsmsg) = @_;
749 autime => $xsmsg->{ds},
750 cotime => $xsmsg->{ts},
751 oid => $xsmsg->{blob},
753 xnum => $xsmsg->{num},
754 # {mids} and {chash} will be filled in at _reindex_unseen
756 warn "I: reindex_unseen ${\$ibx->eidx_key}:$req->{xnum}:$req->{oid}\n";
757 $self->git->cat_async($xsmsg->{blob}, \&_reindex_unseen, $req);
760 sub _reindex_check_unseen ($$$) {
761 my ($self, $sync, $ibx) = @_;
762 my $ibx_id = $ibx->{-ibx_id};
764 my ($beg, $end) = (1, $slice);
766 # first, check if we missed any messages in target $ibx
768 my $pr = $sync->{-opt}->{-progress};
769 my $ekey = $ibx->eidx_key;
770 local $sync->{-regen_fmt} =
771 "$ekey checking unseen %u/".$ibx->over->max."\n";
774 while (scalar(@{$msgs = $ibx->over->query_xover($beg, $end)})) {
775 ${$sync->{nr}} = $beg;
776 $beg = $msgs->[-1]->{num} + 1;
777 $end = $beg + $slice;
778 if (checkpoint_due($sync)) {
779 reindex_checkpoint($self, $sync); # release lock
782 my $inx3 = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
783 SELECT DISTINCT(docid) FROM xref3 WHERE
784 ibx_id = ? AND xnum = ? AND oidbin = ?
786 for my $xsmsg (@$msgs) {
787 my $oidbin = pack('H*', $xsmsg->{blob});
788 $inx3->bind_param(1, $ibx_id);
789 $inx3->bind_param(2, $xsmsg->{num});
790 $inx3->bind_param(3, $oidbin, SQL_BLOB);
792 my $docids = $inx3->fetchall_arrayref;
793 # index messages which were totally missed
794 # the first time around ASAP:
795 if (scalar(@$docids) == 0) {
796 reindex_unseen($self, $sync, $ibx, $xsmsg);
797 } else { # already seen, reindex later
798 for my $r (@$docids) {
799 $self->{oidx}->eidxq_add($r->[0]);
802 last if $sync->{quit};
804 last if $sync->{quit};
808 sub _reindex_check_stale ($$$) {
809 my ($self, $sync, $ibx) = @_;
811 my $pr = $sync->{-opt}->{-progress};
813 my $ekey = $ibx->eidx_key;
814 local $sync->{-regen_fmt} =
815 "$ekey check stale/missing %u/".$ibx->over->max."\n";
818 if (checkpoint_due($sync)) {
819 reindex_checkpoint($self, $sync); # release lock
821 # now, check if there's stale xrefs
822 my $iter = $self->{oidx}->dbh->prepare_cached(<<'', undef, 1);
823 SELECT docid,xnum,oidbin FROM xref3 WHERE ibx_id = ? AND docid > ?
824 ORDER BY docid,xnum ASC LIMIT 10000
826 $iter->execute($ibx->{-ibx_id}, $min);
829 while (my ($docid, $xnum, $oidbin) = $iter->fetchrow_array) {
830 return if $sync->{quit};
831 ${$sync->{nr}} = $xnum;
833 $fetching = $min = $docid;
834 my $smsg = $ibx->over->get_art($xnum);
838 } elsif (pack('H*', $smsg->{blob}) ne $oidbin) {
839 $err = "mismatch (!= $smsg->{blob})";
841 next; # likely, all good
843 # current_info already has eidx_key
844 my $oidhex = unpack('H*', $oidbin);
845 warn "$xnum:$oidhex (#$docid): $err\n";
846 my $del = $self->{oidx}->dbh->prepare_cached(<<'');
847 DELETE FROM xref3 WHERE ibx_id = ? AND xnum = ? AND oidbin = ?
849 $del->bind_param(1, $ibx->{-ibx_id});
850 $del->bind_param(2, $xnum);
851 $del->bind_param(3, $oidbin, SQL_BLOB);
854 # get_xref3 over-fetches, but this is a rare path:
855 my $xr3 = $self->{oidx}->get_xref3($docid);
856 my $idx = $self->idx_shard($docid);
857 if (scalar(@$xr3) == 0) { # all gone
858 $self->{oidx}->delete_by_num($docid);
859 $self->{oidx}->eidxq_del($docid);
860 $idx->ipc_do('xdb_remove', $docid);
861 } else { # enqueue for reindex of remaining messages
862 $idx->ipc_do('remove_eidx_info',
863 $docid, $ibx->eidx_key);
864 $self->{oidx}->eidxq_add($docid); # yes, add
867 } while (defined $fetching);
870 sub _reindex_inbox ($$$) {
871 my ($self, $sync, $ibx) = @_;
872 my $ekey = $ibx->eidx_key;
873 local $self->{current_info} = $ekey;
874 if (defined(my $err = _ibx_index_reject($ibx))) {
875 warn "W: cannot reindex $ekey ($err)\n";
877 _reindex_check_unseen($self, $sync, $ibx);
878 _reindex_check_stale($self, $sync, $ibx) unless $sync->{quit};
880 delete @$ibx{qw(over mm search git)}; # won't need these for a bit
884 my ($self, $sync) = @_;
886 # acquire eidxq_lock early because full reindex takes forever
887 # and incremental -extindex processes can run during our checkpoints
888 if (!eidxq_lock_acquire($self)) {
889 warn "E: aborting --reindex\n";
892 for my $ibx (@{ibx_sorted($self, 'active')}) {
893 _reindex_inbox($self, $sync, $ibx);
894 last if $sync->{quit};
896 $self->git->async_wait_all; # ensure eidxq gets filled completely
897 eidxq_process($self, $sync) unless $sync->{quit};
901 my ($self, $sync, $ibx) = @_;
902 my $err = _sync_inbox($self, $sync, $ibx);
903 delete @$ibx{qw(mm over)};
904 warn $err, "\n" if defined($err);
907 sub dd_smsg { # git->cat_async callback
908 my ($bref, $oid, $type, $size, $dd) = @_;
909 my $smsg = $dd->{smsg} // die 'BUG: dd->{smsg} missing';
910 my $self = $dd->{self} // die 'BUG: {self} missing';
911 my $per_mid = $dd->{per_mid} // die 'BUG: {per_mid} missing';
912 if ($type eq 'missing') {
913 _blob_missing($dd, $smsg);
914 } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
915 local $self->{current_info} = "$self->{current_info} $oid";
916 my $chash = content_hash(PublicInbox::Eml->new($bref));
917 push(@{$per_mid->{dd_chash}->{$chash}}, $smsg);
919 return if $per_mid->{last_smsg} != $smsg;
920 while (my ($chash, $ary) = each %{$per_mid->{dd_chash}}) {
921 my $keep = shift @$ary;
922 next if !scalar(@$ary);
923 $per_mid->{sync}->{dedupe_cull} += scalar(@$ary);
925 "# <$keep->{mid}> keeping #$keep->{num}, dropping ",
926 join(', ', map { "#$_->{num}" } @$ary),"\n";
927 next if $per_mid->{sync}->{-opt}->{'dry-run'};
928 my $oidx = $self->{oidx};
929 for my $smsg (@$ary) {
930 my $gone = $smsg->{num};
931 $oidx->merge_xref3($keep->{num}, $gone, $smsg->{blob});
932 $self->idx_shard($gone)->ipc_do('xdb_remove', $gone);
933 $oidx->delete_by_num($gone);
938 sub eidx_dedupe ($$$) {
939 my ($self, $sync, $msgids) = @_;
940 $sync->{dedupe_cull} = 0;
943 return unless eidxq_lock_acquire($self);
944 my ($iter, $cur_mid);
947 my ($max_id) = $self->{oidx}->dbh->selectrow_array(<<EOS);
948 SELECT MAX(id) FROM msgid
950 local $sync->{-regen_fmt} = "dedupe %u/$max_id\n";
952 # note: we could write this query more intelligently,
953 # but that causes lock contention with read-only processes
955 $cur_mid = $msgids->[$idx];
956 if ($cur_mid eq '') { # all Message-IDs
957 $iter = $self->{oidx}->dbh->prepare(<<EOS);
958 SELECT mid,id FROM msgid WHERE id > ? ORDER BY id ASC
960 $iter->execute($min_id);
962 $iter = $self->{oidx}->dbh->prepare(<<EOS);
963 SELECT mid,id FROM msgid WHERE mid = ? AND id > ? ORDER BY id ASC
965 $iter->execute($cur_mid, $min_id);
967 while (my ($mid, $id) = $iter->fetchrow_array) {
968 last if $sync->{quit};
969 $self->{current_info} = "dedupe $mid";
970 ${$sync->{nr}} = $min_id = $id;
972 while (my $x = $self->{oidx}->next_by_mid($mid, \$id, \$prv)) {
975 next if scalar(@smsg) < 2;
977 dd_chash => {}, # chash => [ary of smsgs]
978 last_smsg => $smsg[-1],
982 $candidates += scalar(@smsg) - 1;
983 for my $smsg (@smsg) {
989 $self->git->cat_async($smsg->{blob}, \&dd_smsg, $dd);
991 # need to wait on every single one @smsg contents can get
992 # invalidated inside dd_smsg for messages with multiple
994 $self->git->async_wait_all;
996 if (checkpoint_due($sync)) {
998 reindex_checkpoint($self, $sync);
1002 goto dedupe_restart if defined($msgids->[++$idx]);
1004 my $n = delete $sync->{dedupe_cull};
1005 if (my $pr = $sync->{-opt}->{-progress}) {
1006 $pr->("culled $n/$candidates candidates ($nr_mid msgids)\n");
1011 sub eidx_sync { # main entry point
1012 my ($self, $opt) = @_;
1014 my $warn_cb = $SIG{__WARN__} || \&CORE::warn;
1015 local $self->{current_info} = '';
1016 local $SIG{__WARN__} = sub {
1017 return if PublicInbox::Eml::warn_ignore(@_);
1018 $warn_cb->($self->{current_info}, ': ', @_);
1020 $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
1021 $self->{oidx}->rethread_prepare($opt);
1023 need_checkpoint => \(my $need_checkpoint = 0),
1025 next_check => now() + 10,
1027 # DO NOT SET {reindex} here, it's incompatible with reused
1028 # V2Writable code, reindex is totally different here
1029 # compared to v1/v2 inboxes because we have multiple histories
1031 -regen_fmt => "%u/?\n",
1033 local $SIG{USR1} = sub { $need_checkpoint = 1 };
1034 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1035 local $SIG{QUIT} = $quit;
1036 local $SIG{INT} = $quit;
1037 local $SIG{TERM} = $quit;
1038 for my $ibx (@{ibx_sorted($self, 'known')}) {
1039 $ibx->{-ibx_id} //= $self->{oidx}->ibx_id($ibx->eidx_key);
1042 if (scalar(grep { defined($_->{boost}) } @{$self->{ibx_known}})) {
1043 $sync->{id2pos} //= prep_id2pos($self);
1044 $sync->{boost_in_use} = 1;
1047 if (my $msgids = delete($opt->{dedupe})) {
1048 local $sync->{checkpoint_unlocks} = 1;
1049 eidx_dedupe($self, $sync, $msgids);
1051 if (delete($opt->{reindex})) {
1052 local $sync->{checkpoint_unlocks} = 1;
1053 eidx_reindex($self, $sync);
1056 # don't use $_ here, it'll get clobbered by reindex_checkpoint
1057 if ($opt->{scan} // 1) {
1058 for my $ibx (@{ibx_sorted($self, 'active')}) {
1059 last if $sync->{quit};
1060 sync_inbox($self, $sync, $ibx);
1063 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1064 eidxq_process($self, $sync) unless $sync->{quit};
1066 eidxq_release($self);
1068 $sync; # for eidx_watch
1071 sub update_last_commit { # overrides V2Writable
1072 my ($self, $sync, $stk) = @_;
1073 my $unit = $sync->{unit} // return;
1074 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
1075 defined($latest_cmt) or return;
1076 my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
1077 my $ekey = $ibx->eidx_key;
1078 my $uv = $ibx->uidvalidity;
1079 my $epoch = $unit->{epoch};
1081 my $v = $ibx->version;
1083 die 'No {epoch} for v2 unit' unless defined $epoch;
1084 $meta_key = "lc-v2:$ekey//$uv;$epoch";
1086 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
1087 $meta_key = "lc-v1:$ekey//$uv";
1089 die "Unsupported inbox version: $v";
1091 my $last = $self->{oidx}->eidx_meta($meta_key);
1092 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
1093 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
1094 chomp(my $n = $unit->{git}->qx(@cmd));
1095 return if $n ne '' && $n == 0;
1097 $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
1100 sub _idx_init { # with_umask callback
1101 my ($self, $opt) = @_;
1102 PublicInbox::V2Writable::_idx_init($self, $opt); # acquires ei.lock
1103 $self->{midx} = PublicInbox::MiscIdx->new($self);
1106 sub symlink_packs ($$) {
1107 my ($ibx, $pd) = @_;
1109 my $glob = "$ibx->{inboxdir}/git/*.git/objects/pack/*.idx";
1110 for my $idx (bsd_glob($glob, GLOB_NOSORT)) {
1111 my $src = substr($idx, 0, -length('.idx'));
1112 my $dst = $pd . substr($src, rindex($src, '/'));
1113 if (-f "$src.pack" and
1114 symlink("$src.pack", "$dst.pack") and
1115 symlink($idx, "$dst.idx") and
1118 # .promisor, .bitmap, .rev and .keep are optional
1119 # XXX should we symlink .keep here?
1120 for my $s (qw(promisor bitmap rev)) {
1121 symlink("$src.$s", "$dst.$s") if -f "$src.$s";
1123 } elsif (!$!{EEXIST}) {
1124 warn "W: ln -s $src.{pack,idx} => $dst.*: $!\n";
1125 unlink "$dst.pack", "$dst.idx";
1131 sub idx_init { # similar to V2Writable
1132 my ($self, $opt) = @_;
1133 return if $self->{idx_shards};
1135 $self->git->cleanup;
1137 my $ALL = $self->git->{git_dir}; # topdir/ALL.git
1138 my ($has_new, $alt, $seen);
1139 if ($opt->{-private}) { # LeiStore
1140 my $local = "$self->{topdir}/local"; # lei/store
1141 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1142 'ALL.git', 'local');
1145 umask 077; # don't bother restoring for lei
1146 PublicInbox::Import::init_bare($ALL);
1147 $self->git->qx(qw(config core.sharedRepository 0600));
1149 ($alt, $seen) = $self->{mg}->read_alternates(\$mode);
1150 $has_new = $self->{mg}->merge_epochs($alt, $seen);
1151 } else { # extindex has no epochs
1152 $self->{mg} //= PublicInbox::MultiGit->new($self->{topdir},
1154 ($alt, $seen) = $self->{mg}->read_alternates(\$mode,
1156 PublicInbox::Import::init_bare($ALL);
1159 # git-multi-pack-index(1) can speed up "git cat-file" startup slightly
1161 my $pd = "$ALL/objects/pack";
1162 if (opendir(my $dh, $pd)) { # drop stale symlinks
1163 while (defined(my $dn = readdir($dh))) {
1164 if ($dn =~ /\.(?:idx|pack|promisor|bitmap|rev)\z/) {
1166 unlink($f) if -l $f && !-e $f;
1169 } elsif ($!{ENOENT}) {
1170 mkdir($pd) or die "mkdir($pd): $!";
1172 die "opendir($pd): $!";
1175 for my $ibx (@{ibx_sorted($self, 'active')}) {
1176 # create symlinks for multi-pack-index
1177 $git_midx += symlink_packs($ibx, $pd);
1178 # add new lines to our alternates file
1179 my $d = $ibx->git->{git_dir} . '/objects';
1180 next if exists $alt->{$d};
1181 if (my @st = stat($d)) {
1182 next if $seen->{"$st[0]\0$st[1]"}++;
1184 warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
1185 next if $opt->{-idx_gc};
1189 ($has_new || $new ne '') and
1190 $self->{mg}->write_alternates($mode, $alt, $new);
1191 $git_midx and $self->with_umask(sub {
1192 my @cmd = ('multi-pack-index');
1193 push @cmd, '--no-progress' if ($opt->{quiet}//0) > 1;
1194 my $lk = $self->lock_for_scope;
1195 system('git', "--git-dir=$ALL", @cmd, 'write');
1196 # ignore errors, fairly new command, may not exist
1198 $self->parallel_init($self->{indexlevel});
1199 $self->with_umask(\&_idx_init, $self, $opt);
1200 $self->{oidx}->begin_lazy;
1201 $self->{oidx}->eidx_prep;
1202 $self->{midx}->create_xdb if $new ne '';
1205 sub _watch_commit { # PublicInbox::DS::add_timer callback
1207 delete $self->{-commit_timer};
1208 eidxq_process($self, $self->{-watch_sync});
1209 eidxq_release($self);
1210 my $fmt = delete $self->{-watch_sync}->{-regen_fmt};
1211 reindex_checkpoint($self, $self->{-watch_sync});
1212 $self->{-watch_sync}->{-regen_fmt} = $fmt;
1214 # call event_step => done unless commit_timer is armed
1215 PublicInbox::DS::requeue($self);
1218 sub on_inbox_unlock { # called by PublicInbox::InboxIdle
1219 my ($self, $ibx) = @_;
1220 my $opt = $self->{-watch_sync}->{-opt};
1221 my $pr = $opt->{-progress};
1222 my $ekey = $ibx->eidx_key;
1223 local $0 = "sync $ekey";
1224 $pr->("indexing $ekey\n") if $pr;
1225 $self->idx_init($opt);
1226 sync_inbox($self, $self->{-watch_sync}, $ibx);
1227 $self->{-commit_timer} //= add_timer($opt->{'commit-interval'} // 10,
1228 \&_watch_commit, $self);
1231 sub eidx_reload { # -extindex --watch SIGHUP handler
1232 my ($self, $idler) = @_;
1234 my $pr = $self->{-watch_sync}->{-opt}->{-progress};
1235 $pr->('reloading ...') if $pr;
1236 delete $self->{-resync_queue};
1237 delete $self->{-ibx_ary_known};
1238 delete $self->{-ibx_ary_active};
1239 $self->{ibx_known} = [];
1240 $self->{ibx_active} = [];
1241 %{$self->{ibx_map}} = ();
1242 delete $self->{-watch_sync}->{id2pos};
1243 my $cfg = PublicInbox::Config->new;
1244 attach_config($self, $cfg);
1245 $idler->refresh($cfg);
1246 $pr->(" done\n") if $pr;
1248 warn "reload not supported without --all\n";
1252 sub eidx_resync_start ($) { # -extindex --watch SIGUSR1 handler
1254 $self->{-resync_queue} //= [ @{ibx_sorted($self, 'active')} ];
1255 PublicInbox::DS::requeue($self); # trigger our ->event_step
1258 sub event_step { # PublicInbox::DS::requeue callback
1260 if (my $resync_queue = $self->{-resync_queue}) {
1261 if (my $ibx = shift(@$resync_queue)) {
1262 on_inbox_unlock($self, $ibx);
1263 PublicInbox::DS::requeue($self);
1265 delete $self->{-resync_queue};
1266 _watch_commit($self);
1269 done($self) unless $self->{-commit_timer};
1273 sub eidx_watch { # public-inbox-extindex --watch main loop
1274 my ($self, $opt) = @_;
1275 local @SIG{keys %SIG} = values %SIG;
1276 for my $sig (qw(HUP USR1 TSTP QUIT INT TERM)) {
1277 $SIG{$sig} = sub { warn "SIG$sig ignored while scanning\n" };
1279 require PublicInbox::InboxIdle;
1280 require PublicInbox::DS;
1281 require PublicInbox::Syscall;
1282 require PublicInbox::Sigfd;
1283 my $idler = PublicInbox::InboxIdle->new($self->{cfg});
1284 if (!$self->{cfg}) {
1285 $idler->watch_inbox($_) for (@{ibx_sorted($self, 'active')});
1287 for my $ibx (@{ibx_sorted($self, 'active')}) {
1288 $ibx->subscribe_unlock(__PACKAGE__, $self)
1290 my $pr = $opt->{-progress};
1291 $pr->("performing initial scan ...\n") if $pr;
1292 my $sync = eidx_sync($self, $opt); # initial sync
1293 return if $sync->{quit};
1294 my $oldset = PublicInbox::DS::block_signals();
1295 local $self->{current_info} = '';
1296 my $cb = $SIG{__WARN__} || \&CORE::warn;
1297 local $SIG{__WARN__} = sub {
1298 return if PublicInbox::Eml::warn_ignore(@_);
1299 $cb->($self->{current_info}, ': ', @_);
1302 HUP => sub { eidx_reload($self, $idler) },
1303 USR1 => sub { eidx_resync_start($self) },
1304 TSTP => sub { kill('STOP', $$) },
1306 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1307 $sig->{QUIT} = $sig->{INT} = $sig->{TERM} = $quit;
1308 my $sigfd = PublicInbox::Sigfd->new($sig,
1309 $PublicInbox::Syscall::SFD_NONBLOCK);
1310 @SIG{keys %$sig} = values(%$sig) if !$sigfd;
1311 local $self->{-watch_sync} = $sync; # for ->on_inbox_unlock
1313 # wake up every second to accept signals if we don't
1314 # have signalfd or IO::KQueue:
1315 PublicInbox::DS::sig_setmask($oldset);
1316 PublicInbox::DS->SetLoopTimeout(1000);
1318 PublicInbox::DS->SetPostLoopCallback(sub { !$sync->{quit} });
1319 $pr->("initial scan complete, entering event loop\n") if $pr;
1320 PublicInbox::DS->EventLoop; # calls InboxIdle->event_step
1325 *done = \&PublicInbox::V2Writable::done;
1326 *with_umask = \&PublicInbox::InboxWritable::with_umask;
1327 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
1328 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
1329 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
1330 *index_todo = \&PublicInbox::V2Writable::index_todo;
1331 *count_shards = \&PublicInbox::V2Writable::count_shards;
1332 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
1333 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
1334 *reindex_checkpoint = \&PublicInbox::V2Writable::reindex_checkpoint;
1335 *checkpoint = \&PublicInbox::V2Writable::checkpoint;