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