]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/ExtSearchIdx.pm
*index: more consistent graceful shutdown checks
[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 PublicInbox::Search;
22 use PublicInbox::SearchIdx qw(crlf_adjust prepare_stack is_ancestor);
23 use PublicInbox::OverIdx;
24 use PublicInbox::MiscIdx;
25 use PublicInbox::MID qw(mids);
26 use PublicInbox::V2Writable;
27 use PublicInbox::InboxWritable;
28 use PublicInbox::ContentHash qw(content_hash);
29 use PublicInbox::Eml;
30 use File::Spec;
31
32 sub new {
33         my (undef, $dir, $opt) = @_;
34         $dir = File::Spec->canonpath($dir);
35         my $l = $opt->{indexlevel} // 'full';
36         $l !~ $PublicInbox::SearchIdx::INDEXLEVELS and
37                 die "invalid indexlevel=$l\n";
38         $l eq 'basic' and die "E: indexlevel=basic not yet supported\n";
39         my $self = bless {
40                 xpfx => "$dir/ei".PublicInbox::Search::SCHEMA_VERSION,
41                 topdir => $dir,
42                 creat => $opt->{creat},
43                 ibx_map => {}, # (newsgroup//inboxdir) => $ibx
44                 ibx_list => [],
45                 indexlevel => $l,
46                 transact_bytes => 0,
47                 total_bytes => 0,
48                 current_info => '',
49                 parallel => 1,
50                 lock_path => "$dir/ei.lock",
51         }, __PACKAGE__;
52         $self->{shards} = $self->count_shards || nproc_shards($opt->{creat});
53         my $oidx = PublicInbox::OverIdx->new("$self->{xpfx}/over.sqlite3");
54         $oidx->{-no_fsync} = 1 if $opt->{-no_fsync};
55         $self->{oidx} = $oidx;
56         $self
57 }
58
59 sub attach_inbox {
60         my ($self, $ibx) = @_;
61         $ibx = PublicInbox::InboxWritable->new($ibx);
62         my $key = $ibx->eidx_key;
63         if (!$ibx->over || !$ibx->mm) {
64                 warn "W: skipping $key (unindexed)\n";
65                 return;
66         }
67         if (!defined($ibx->uidvalidity)) {
68                 warn "W: skipping $key (no UIDVALIDITY)\n";
69                 return;
70         }
71         my $ibxdir = File::Spec->canonpath($ibx->{inboxdir});
72         if ($ibxdir ne $ibx->{inboxdir}) {
73                 warn "W: `$ibx->{inboxdir}' canonicalized to `$ibxdir'\n";
74                 $ibx->{inboxdir} = $ibxdir;
75         }
76         $ibx = PublicInbox::InboxWritable->new($ibx);
77         $self->{ibx_map}->{$key} //= 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         $cfg->each_inbox(\&_ibx_attach, $self);
91 }
92
93 sub git_blob_digest ($) {
94         my ($bref) = @_;
95         my $dig = Digest::SHA->new(1); # XXX SHA256 later
96         $dig->add('blob '.length($$bref)."\0");
97         $dig->add($$bref);
98         $dig;
99 }
100
101 sub is_bad_blob ($$$$) {
102         my ($oid, $type, $size, $expect_oid) = @_;
103         if ($type ne 'blob') {
104                 carp "W: $expect_oid is not a blob (type=$type)";
105                 return 1;
106         }
107         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
108         $size == 0 ? 1 : 0; # size == 0 means purged
109 }
110
111 sub check_batch_limit ($) {
112         my ($req) = @_;
113         my $self = $req->{self};
114         my $new_smsg = $req->{new_smsg};
115
116         # {raw_bytes} may be unset, so just use {bytes}
117         my $n = $self->{transact_bytes} += $new_smsg->{bytes};
118
119         # set flag for PublicInbox::V2Writable::index_todo:
120         ${$req->{need_checkpoint}} = 1 if $n >= $self->{batch_bytes};
121 }
122
123 sub do_xpost ($$) {
124         my ($req, $smsg) = @_;
125         my $self = $req->{self};
126         my $docid = $smsg->{num};
127         my $idx = $self->idx_shard($docid);
128         my $oid = $req->{oid};
129         my $xibx = $req->{ibx};
130         my $eml = $req->{eml};
131         if (my $new_smsg = $req->{new_smsg}) { # 'm' on cross-posted message
132                 my $xnum = $req->{xnum};
133                 $self->{oidx}->add_xref3($docid, $xnum, $oid, $xibx->eidx_key);
134                 $idx->shard_add_eidx_info($docid, $oid, $xibx, $eml);
135                 check_batch_limit($req);
136         } else { # 'd'
137                 $self->{oidx}->remove_xref3($docid, $oid, $xibx->eidx_key);
138                 $idx->shard_remove_eidx_info($docid, $oid, $xibx, $eml);
139         }
140 }
141
142 # called by V2Writable::sync_prepare
143 sub artnum_max { $_[0]->{oidx}->eidx_max }
144
145 sub index_unseen ($) {
146         my ($req) = @_;
147         my $new_smsg = $req->{new_smsg} or die 'BUG: {new_smsg} unset';
148         my $eml = delete $req->{eml};
149         $new_smsg->populate($eml, $req);
150         my $self = $req->{self};
151         my $docid = $self->{oidx}->adj_counter('eidx_docid', '+');
152         $new_smsg->{num} = $docid;
153         my $idx = $self->idx_shard($docid);
154         $self->{oidx}->add_overview($eml, $new_smsg);
155         my $oid = $new_smsg->{blob};
156         my $ibx = delete $req->{ibx} or die 'BUG: {ibx} unset';
157         $self->{oidx}->add_xref3($docid, $req->{xnum}, $oid, $ibx->eidx_key);
158         $idx->index_raw(undef, $eml, $new_smsg, $ibx);
159         check_batch_limit($req);
160 }
161
162 sub do_finalize ($) {
163         my ($req) = @_;
164         if (my $indexed = $req->{indexed}) {
165                 do_xpost($req, $_) for @$indexed;
166         } elsif (exists $req->{new_smsg}) { # totally unseen messsage
167                 index_unseen($req);
168         } else {
169                 # `d' message was already unindexed in the v1/v2 inboxes,
170                 # so it's too noisy to warn, here.
171         }
172         # cur_cmt may be undef for unindex_oid, set by V2Writable::index_todo
173         if (defined(my $cur_cmt = $req->{cur_cmt})) {
174                 ${$req->{latest_cmt}} = $cur_cmt;
175         }
176 }
177
178 sub do_step ($) { # main iterator for adding messages to the index
179         my ($req) = @_;
180         my $self = $req->{self};
181         while (1) {
182                 if (my $next_arg = $req->{next_arg}) {
183                         if (my $smsg = $self->{oidx}->next_by_mid(@$next_arg)) {
184                                 $req->{cur_smsg} = $smsg;
185                                 $self->git->cat_async($smsg->{blob},
186                                                         \&ck_existing, $req);
187                                 return; # ck_existing calls do_step
188                         }
189                         delete $req->{cur_smsg};
190                         delete $req->{next_arg};
191                 }
192                 my $mid = shift(@{$req->{mids}});
193                 last unless defined $mid;
194                 my ($id, $prev);
195                 $req->{next_arg} = [ $mid, \$id, \$prev ];
196                 # loop again
197         }
198         do_finalize($req);
199 }
200
201 sub _blob_missing ($) { # called when req->{cur_smsg}->{blob} is bad
202         my ($req) = @_;
203         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
204         my $self = $req->{self};
205         my $xref3 = $self->{oidx}->get_xref3($smsg->{num});
206         my @keep = grep(!/:$smsg->{blob}\z/, @$xref3);
207         if (@keep) {
208                 $keep[0] =~ /:([a-f0-9]{40,}+)\z/ or
209                         die "BUG: xref $keep[0] has no OID";
210                 my $oidhex = $1;
211                 $self->{oidx}->remove_xref3($smsg->{num}, $smsg->{blob});
212                 my $upd = $self->{oidx}->update_blob($smsg, $oidhex);
213                 my $saved = $self->{oidx}->get_art($smsg->{num});
214         } else {
215                 $self->{oidx}->delete_by_num($smsg->{num});
216         }
217 }
218
219 sub ck_existing { # git->cat_async callback
220         my ($bref, $oid, $type, $size, $req) = @_;
221         my $smsg = $req->{cur_smsg} or die 'BUG: {cur_smsg} missing';
222         if ($type eq 'missing') {
223                 _blob_missing($req);
224         } elsif (!is_bad_blob($oid, $type, $size, $smsg->{blob})) {
225                 my $cur = PublicInbox::Eml->new($bref);
226                 if (content_hash($cur) eq $req->{chash}) {
227                         push @{$req->{indexed}}, $smsg; # for do_xpost
228                 } # else { index_unseen later }
229         }
230         do_step($req);
231 }
232
233 # is the messages visible in the inbox currently being indexed?
234 # return the number if so
235 sub cur_ibx_xnum ($$) {
236         my ($req, $bref) = @_;
237         my $ibx = $req->{ibx} or die 'BUG: current {ibx} missing';
238
239         # XXX overkill?
240         git_blob_digest($bref)->hexdigest eq $req->{oid} or die
241                 "BUG: blob mismatch $req->{oid}";
242
243         $req->{eml} = PublicInbox::Eml->new($bref);
244         $req->{chash} = content_hash($req->{eml});
245         $req->{mids} = mids($req->{eml});
246         my @q = @{$req->{mids}}; # copy
247         while (defined(my $mid = shift @q)) {
248                 my ($id, $prev);
249                 while (my $x = $ibx->over->next_by_mid($mid, \$id, \$prev)) {
250                         return $x->{num} if $x->{blob} eq $req->{oid};
251                 }
252         }
253         undef;
254 }
255
256 sub index_oid { # git->cat_async callback for 'm'
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         my $new_smsg = $req->{new_smsg} = bless {
262                 blob => $oid,
263         }, 'PublicInbox::Smsg';
264         $new_smsg->{bytes} = $size + crlf_adjust($$bref);
265         defined($req->{xnum} = cur_ibx_xnum($req, $bref)) or return;
266         ++${$req->{nr}};
267         do_step($req);
268 }
269
270 sub unindex_oid { # git->cat_async callback for 'd'
271         my ($bref, $oid, $type, $size, $req) = @_;
272         my $self = $req->{self};
273         local $self->{current_info} = "$self->{current_info} $oid";
274         return if is_bad_blob($oid, $type, $size, $req->{oid});
275         return if defined(cur_ibx_xnum($req, $bref)); # was re-added
276         do_step($req);
277 }
278
279 # overrides V2Writable::last_commits, called by sync_ranges via sync_prepare
280 sub last_commits {
281         my ($self, $sync) = @_;
282         my $heads = [];
283         my $ekey = $sync->{ibx}->eidx_key;
284         my $uv = $sync->{ibx}->uidvalidity;
285         for my $i (0..$sync->{epoch_max}) {
286                 $heads->[$i] = $self->{oidx}->eidx_meta("lc-v2:$ekey//$uv;$i");
287         }
288         $heads;
289 }
290
291 sub _sync_inbox ($$$) {
292         my ($self, $sync, $ibx) = @_;
293         $sync->{ibx} = $ibx;
294         $sync->{nr} = \(my $nr = 0);
295         my $v = $ibx->version;
296         my $ekey = $ibx->eidx_key;
297         if ($v == 2) {
298                 my $epoch_max;
299                 defined($ibx->git_dir_latest(\$epoch_max)) or return;
300                 $sync->{epoch_max} = $epoch_max;
301                 sync_prepare($self, $sync); # or return # TODO: once MiscIdx is stable
302         } elsif ($v == 1) {
303                 my $uv = $ibx->uidvalidity;
304                 my $lc = $self->{oidx}->eidx_meta("lc-v1:$ekey//$uv");
305                 my $stk = prepare_stack($sync, $lc ? "$lc..HEAD" : 'HEAD');
306                 my $unit = { stack => $stk, git => $ibx->git };
307                 push @{$sync->{todo}}, $unit;
308         } else {
309                 warn "E: $ekey unsupported inbox version (v$v)\n";
310                 return;
311         }
312         for my $unit (@{delete($sync->{todo}) // []}) {
313                 last if $sync->{quit};
314                 index_todo($self, $sync, $unit);
315         }
316         $self->{midx}->index_ibx($ibx) unless $sync->{quit};
317         $ibx->git->cleanup; # done with this inbox, now
318 }
319
320 sub eidx_sync { # main entry point
321         my ($self, $opt) = @_;
322         $self->idx_init($opt); # acquire lock via V2Writable::_idx_init
323         $self->{oidx}->rethread_prepare($opt);
324
325         my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
326         local $self->{current_info} = '';
327         local $SIG{__WARN__} = sub {
328                 $warn_cb->($self->{current_info}, ': ', @_);
329         };
330         my $sync = {
331                 need_checkpoint => \(my $need_checkpoint = 0),
332                 reindex => $opt->{reindex},
333                 -opt => $opt,
334                 self => $self,
335                 -regen_fmt => "%u/?\n",
336         };
337         local $SIG{USR1} = sub { $need_checkpoint = 1 };
338         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
339         local $SIG{QUIT} = $quit;
340         local $SIG{INT} = $quit;
341         local $SIG{TERM} = $quit;
342
343         # don't use $_ here, it'll get clobbered by reindex_checkpoint
344         for my $ibx (@{$self->{ibx_list}}) {
345                 last if $sync->{quit};
346                 _sync_inbox($self, $sync, $ibx);
347         }
348         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
349
350         PublicInbox::V2Writable::done($self);
351 }
352
353 sub update_last_commit { # overrides V2Writable
354         my ($self, $sync, $stk) = @_;
355         my $unit = $sync->{unit} // return;
356         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
357         defined($latest_cmt) or return;
358         my $ibx = $sync->{ibx} or die 'BUG: {ibx} missing';
359         my $ekey = $ibx->eidx_key;
360         my $uv = $ibx->uidvalidity;
361         my $epoch = $unit->{epoch};
362         my $meta_key;
363         my $v = $ibx->version;
364         if ($v == 2) {
365                 die 'No {epoch} for v2 unit' unless defined $epoch;
366                 $meta_key = "lc-v2:$ekey//$uv;$epoch";
367         } elsif ($v == 1) {
368                 die 'Unexpected {epoch} for v1 unit' if defined $epoch;
369                 $meta_key = "lc-v1:$ekey//$uv";
370         } else {
371                 die "Unsupported inbox version: $v";
372         }
373         my $last = $self->{oidx}->eidx_meta($meta_key);
374         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
375                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
376                 chomp(my $n = $unit->{git}->qx(@cmd));
377                 return if $n ne '' && $n == 0;
378         }
379         $self->{oidx}->eidx_meta($meta_key, $latest_cmt);
380 }
381
382 sub _idx_init { # with_umask callback
383         my ($self, $opt) = @_;
384         PublicInbox::V2Writable::_idx_init($self, $opt);
385         $self->{midx} = PublicInbox::MiscIdx->new($self);
386 }
387
388 sub idx_init { # similar to V2Writable
389         my ($self, $opt) = @_;
390         return if $self->{idx_shards};
391
392         $self->git->cleanup;
393
394         my $ALL = $self->git->{git_dir}; # ALL.git
395         PublicInbox::Import::init_bare($ALL) unless -d $ALL;
396         my $info_dir = "$ALL/objects/info";
397         my $alt = "$info_dir/alternates";
398         my $mode = 0644;
399         my (@old, @new, %seen); # seen: st_dev + st_ino
400         if (-e $alt) {
401                 open(my $fh, '<', $alt) or die "open $alt: $!";
402                 $mode = (stat($fh))[2] & 07777;
403                 while (my $line = <$fh>) {
404                         chomp(my $d = $line);
405                         if (my @st = stat($d)) {
406                                 next if $seen{"$st[0]\0$st[1]"}++;
407                         } else {
408                                 warn "W: stat($d) failed (from $alt): $!\n";
409                         }
410                         push @old, $line;
411                 }
412         }
413         for my $ibx (@{$self->{ibx_list}}) {
414                 my $line = $ibx->git->{git_dir} . "/objects\n";
415                 chomp(my $d = $line);
416                 if (my @st = stat($d)) {
417                         next if $seen{"$st[0]\0$st[1]"}++;
418                 } else {
419                         warn "W: stat($d) failed (from $ibx->{inboxdir}): $!\n";
420                 }
421                 push @new, $line;
422         }
423         if (scalar @new) {
424                 push @old, @new;
425                 my $o = \@old;
426                 PublicInbox::V2Writable::write_alternates($info_dir, $mode, $o);
427         }
428         $self->parallel_init($self->{indexlevel});
429         $self->umask_prepare;
430         $self->with_umask(\&_idx_init, $self, $opt);
431         $self->{oidx}->begin_lazy;
432         $self->{oidx}->eidx_prep;
433         $self->{midx}->begin_txn;
434 }
435
436 no warnings 'once';
437 *done = \&PublicInbox::V2Writable::done;
438 *umask_prepare = \&PublicInbox::InboxWritable::umask_prepare;
439 *with_umask = \&PublicInbox::InboxWritable::with_umask;
440 *parallel_init = \&PublicInbox::V2Writable::parallel_init;
441 *nproc_shards = \&PublicInbox::V2Writable::nproc_shards;
442 *sync_prepare = \&PublicInbox::V2Writable::sync_prepare;
443 *index_todo = \&PublicInbox::V2Writable::index_todo;
444 *count_shards = \&PublicInbox::V2Writable::count_shards;
445 *atfork_child = \&PublicInbox::V2Writable::atfork_child;
446 *idx_shard = \&PublicInbox::V2Writable::idx_shard;
447
448 1;