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