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