]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
c46aba3b122b5e9bf46f5fd705cdbeab09376f62
[public-inbox.git] / lib / PublicInbox / LeiXSearch.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Combine any combination of PublicInbox::Search,
5 # PublicInbox::ExtSearch, and PublicInbox::LeiSearch objects
6 # into one Xapian DB
7 package PublicInbox::LeiXSearch;
8 use strict;
9 use v5.10.1;
10 use parent qw(PublicInbox::LeiSearch PublicInbox::IPC);
11 use PublicInbox::DS qw(now);
12 use PublicInbox::PktOp qw(pkt_do);
13 use File::Temp 0.19 (); # 0.19 for ->newdir
14 use File::Spec ();
15 use PublicInbox::Search qw(xap_terms);
16 use PublicInbox::Spawn qw(popen_rd spawn which);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::Smsg;
19 use PublicInbox::Eml;
20 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
21
22 sub new {
23         my ($class) = @_;
24         PublicInbox::Search::load_xapian();
25         bless {
26                 qp_flags => $PublicInbox::Search::QP_FLAGS |
27                                 PublicInbox::Search::FLAG_PURE_NOT(),
28         }, $class
29 }
30
31 sub attach_external {
32         my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
33         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
34         my $srch = $ibxish->search or
35                 return warn("$desc not indexed for Xapian\n");
36         my @shards = $srch->xdb_shards_flat or
37                 return warn("$desc has no Xapian shards\n");
38
39         if (delete $self->{xdb}) { # XXX: do we need this?
40                 # clobber existing {xdb} if amending
41                 my $expect = delete $self->{nshard};
42                 my $shards = delete $self->{shards_flat};
43                 scalar(@$shards) == $expect or die
44                         "BUG: {nshard}$expect != shards=".scalar(@$shards);
45
46                 my $prev = {};
47                 for my $old_ibxish (@{$self->{shard2ibx}}) {
48                         next if $prev == $old_ibxish;
49                         $prev = $old_ibxish;
50                         my @shards = $old_ibxish->search->xdb_shards_flat;
51                         push @{$self->{shards_flat}}, @shards;
52                 }
53                 my $nr = scalar(@{$self->{shards_flat}});
54                 $nr == $expect or die
55                         "BUG: reloaded $nr shards, expected $expect"
56         }
57         push @{$self->{shards_flat}}, @shards;
58         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
59 }
60
61 # returns a list of local inboxes (or count in scalar context)
62 sub locals { @{$_[0]->{locals} // []} }
63
64 sub remotes { @{$_[0]->{remotes} // []} }
65
66 # called by PublicInbox::Search::xdb
67 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
68
69 # like over->get_art
70 sub smsg_for {
71         my ($self, $mitem) = @_;
72         # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
73         my $nshard = $self->{nshard};
74         my $docid = $mitem->get_docid;
75         my $shard = ($docid - 1) % $nshard;
76         my $num = int(($docid - 1) / $nshard) + 1;
77         my $ibx = $self->{shard2ibx}->[$shard];
78         my $smsg = $ibx->over->get_art($num);
79         if (ref($ibx->can('msg_keywords'))) {
80                 my $kw = xap_terms('K', $mitem->get_document);
81                 $smsg->{kw} = [ sort keys %$kw ];
82         }
83         $smsg->{docid} = $docid;
84         $smsg;
85 }
86
87 sub recent {
88         my ($self, $qstr, $opt) = @_;
89         $opt //= {};
90         $opt->{relevance} //= -2;
91         $self->mset($qstr //= 'bytes:1..', $opt);
92 }
93
94 sub over {}
95
96 sub _mset_more ($$) {
97         my ($mset, $mo) = @_;
98         my $size = $mset->size;
99         $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
100 }
101
102 # $startq will EOF when do_augment is done augmenting and allow
103 # query_mset and query_thread_mset to proceed.
104 sub wait_startq ($) {
105         my ($lei) = @_;
106         my $startq = delete $lei->{startq} or return;
107         while (1) {
108                 my $n = sysread($startq, my $do_augment_done, 1);
109                 if (defined $n) {
110                         return if $n == 0; # no MUA
111                         if ($do_augment_done eq 'q') {
112                                 $lei->{opt}->{quiet} = 1;
113                                 delete $lei->{opt}->{verbose};
114                                 delete $lei->{-progress};
115                         } else {
116                                 $lei->fail("$$ WTF `$do_augment_done'");
117                         }
118                         return;
119                 }
120                 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
121         }
122 }
123
124 sub mset_progress {
125         my $lei = shift;
126         return if $lei->{early_mua} || !$lei->{-progress};
127         if ($lei->{pkt_op_p}) {
128                 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
129         } else { # single lei-daemon consumer
130                 my ($desc, $mset_size, $mset_total_est) = @_;
131                 $lei->{-mset_total} += $mset_size;
132                 $lei->qerr("# $desc $mset_size/$mset_total_est");
133         }
134 }
135
136 sub query_thread_mset { # for --threads
137         my ($self, $ibxish) = @_;
138         local $0 = "$0 query_thread_mset";
139         my $lei = $self->{lei};
140         my ($srch, $over) = ($ibxish->search, $ibxish->over);
141         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
142         return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
143         my $mo = { %{$lei->{mset_opt}} };
144         my $mset;
145         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
146         do {
147                 $mset = $srch->mset($mo->{qstr}, $mo);
148                 mset_progress($lei, $desc, $mset->size,
149                                 $mset->get_matches_estimated);
150                 my $ids = $srch->mset_to_artnums($mset, $mo);
151                 my $ctx = { ids => $ids };
152                 my $i = 0;
153                 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
154                 while ($over->expand_thread($ctx)) {
155                         for my $n (@{$ctx->{xids}}) {
156                                 my $smsg = $over->get_art($n) or next;
157                                 wait_startq($lei);
158                                 my $mitem = delete $n2item{$smsg->{num}};
159                                 $each_smsg->($smsg, $mitem);
160                         }
161                         @{$ctx->{xids}} = ();
162                 }
163         } while (_mset_more($mset, $mo));
164         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
165         $lei->{ovv}->ovv_atexit_child($lei);
166 }
167
168 sub query_mset { # non-parallel for non-"--threads" users
169         my ($self) = @_;
170         local $0 = "$0 query_mset";
171         my $lei = $self->{lei};
172         my $mo = { %{$lei->{mset_opt}} };
173         my $mset;
174         for my $loc (locals($self)) {
175                 attach_external($self, $loc);
176         }
177         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
178         do {
179                 $mset = $self->mset($mo->{qstr}, $mo);
180                 mset_progress($lei, 'xsearch', $mset->size,
181                                 $mset->size, $mset->get_matches_estimated);
182                 for my $mitem ($mset->items) {
183                         my $smsg = smsg_for($self, $mitem) or next;
184                         wait_startq($lei);
185                         $each_smsg->($smsg, $mitem);
186                 }
187         } while (_mset_more($mset, $mo));
188         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
189         $lei->{ovv}->ovv_atexit_child($lei);
190 }
191
192 sub each_eml { # callback for MboxReader->mboxrd
193         my ($eml, $self, $lei, $each_smsg) = @_;
194         my $smsg = bless {}, 'PublicInbox::Smsg';
195         $smsg->populate($eml);
196         $smsg->parse_references($eml, mids($eml));
197         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
198         delete @$smsg{qw(From Subject -ds -ts)};
199         wait_startq($lei);
200         if ($lei->{-progress}) {
201                 ++$lei->{-nr_remote_eml};
202                 my $now = now();
203                 my $next = $lei->{-next_progress} //= ($now + 1);
204                 if ($now > $next) {
205                         $lei->{-next_progress} = $now + 1;
206                         my $nr = $lei->{-nr_remote_eml};
207                         $lei->err("# $lei->{-current_url} $nr/?");
208                 }
209         }
210         $each_smsg->($smsg, undef, $eml);
211 }
212
213 sub query_remote_mboxrd {
214         my ($self, $uris) = @_;
215         local $0 = "$0 query_remote_mboxrd";
216         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
217         my $lei = $self->{lei};
218         my $opt = $lei->{opt};
219         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
220         push(@qform, t => 1) if $opt->{threads};
221         my $verbose = $opt->{verbose};
222         my ($reap_tail, $reap_curl);
223         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
224         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
225         my $rdr = { 2 => $cerr, pgid => 0 };
226         my $sigint_reap = $lei->can('sigint_reap');
227         if ($verbose) {
228                 # spawn a process to force line-buffering, otherwise curl
229                 # will write 1 character at-a-time and parallel outputs
230                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
231                 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
232                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
233                 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
234         }
235         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
236         push @$curl, '-s', '-d', '';
237         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
238         for my $uri (@$uris) {
239                 $lei->{-current_url} = $uri->as_string;
240                 $lei->{-nr_remote_eml} = 0;
241                 $uri->query_form(@qform);
242                 my $cmd = $curl->for_uri($lei, $uri);
243                 $lei->qerr("# $cmd");
244                 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
245                 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
246                 $fh = IO::Uncompress::Gunzip->new($fh);
247                 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
248                                                 $lei, $each_smsg);
249                 my $err = waitpid($pid, 0) == $pid ? undef
250                                                 : "BUG: waitpid($cmd): $!";
251                 @$reap_curl = (); # cancel OnDestroy
252                 die $err if $err;
253                 if ($? == 0) {
254                         my $nr = $lei->{-nr_remote_eml};
255                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
256                         next;
257                 }
258                 $err = '';
259                 if (-s $cerr) {
260                         seek($cerr, 0, SEEK_SET) or
261                                         $lei->err("seek($cmd stderr): $!");
262                         $err = do { local $/; <$cerr> } //
263                                         "read($cmd stderr): $!";
264                         truncate($cerr, 0) or
265                                         $lei->err("truncate($cmd stderr): $!");
266                 }
267                 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
268                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
269                 $lei->child_error($?, "E: <$uri> $err");
270         }
271         undef $each_smsg;
272         $lei->{ovv}->ovv_atexit_child($lei);
273 }
274
275 # called by LeiOverview::each_smsg_cb
276 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
277
278 sub git_tmp ($) {
279         my ($self) = @_;
280         my (%seen, @dirs);
281         my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
282         for my $ibxish (locals($self)) {
283                 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
284                 $seen{$d} //= push @dirs, "$d/objects\n"
285         }
286         my $git_dir = $tmp->dirname;
287         PublicInbox::Import::init_bare($git_dir);
288         my $f = "$git_dir/objects/info/alternates";
289         open my $alt, '>', $f or die "open($f): $!";
290         print $alt @dirs or die "print $f: $!";
291         close $alt or die "close $f: $!";
292         my $git = PublicInbox::Git->new($git_dir);
293         $git->{-tmp} = $tmp;
294         $git;
295 }
296
297 sub xsearch_done_wait { # dwaitpid callback
298         my ($arg, $pid) = @_;
299         my ($wq, $lei) = @$arg;
300         $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
301 }
302
303 sub query_done { # EOF callback for main daemon
304         my ($lei) = @_;
305         my $l2m = delete $lei->{l2m};
306         $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
307         if (my $lxs = delete $lei->{lxs}) {
308                 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
309         }
310         $lei->{ovv}->ovv_end($lei);
311         if ($l2m) { # close() calls LeiToMail reap_compress
312                 if (my $out = delete $lei->{old_1}) {
313                         if (my $mbout = $lei->{1}) {
314                                 close($mbout) or return $lei->fail(<<"");
315 Error closing $lei->{ovv}->{dst}: $!
316
317                         }
318                         $lei->{1} = $out;
319                 }
320                 if ($l2m->lock_free) {
321                         $l2m->poke_dst;
322                         $lei->poke_mua;
323                 } else { # mbox users
324                         $lei->start_mua;
325                 }
326         }
327         $lei->{-progress} and
328                 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
329         $lei->dclose;
330 }
331
332 sub do_post_augment {
333         my ($lei) = @_;
334         my $l2m = $lei->{l2m} or die 'BUG: unexpected do_post_augment';
335         my $err;
336         eval { $l2m->post_augment($lei) };
337         $err = $@;
338         if ($err) {
339                 if (my $lxs = delete $lei->{lxs}) {
340                         $lxs->wq_kill;
341                         $lxs->wq_close(0, undef, $lei);
342                 }
343                 $lei->fail("$err");
344         }
345         if (!$err && delete $lei->{early_mua}) { # non-augment case
346                 $lei->start_mua;
347         }
348         close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
349 }
350
351 sub incr_post_augment { # called whenever an l2m shard finishes augment
352         my ($lei) = @_;
353         my $l2m = $lei->{l2m} or die 'BUG: unexpected incr_post_augment';
354         return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
355         do_post_augment($lei);
356 }
357
358 my $MAX_PER_HOST = 4;
359
360 sub concurrency {
361         my ($self, $opt) = @_;
362         my $nl = $opt->{threads} ? locals($self) : 1;
363         my $nr = remotes($self);
364         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
365         $nl + $nr;
366 }
367
368 sub start_query { # always runs in main (lei-daemon) process
369         my ($self) = @_;
370         if ($self->{threads}) {
371                 for my $ibxish (locals($self)) {
372                         $self->wq_io_do('query_thread_mset', [], $ibxish);
373                 }
374         } elsif (locals($self)) {
375                 $self->wq_io_do('query_mset', []);
376         }
377         my $i = 0;
378         my $q = [];
379         for my $uri (remotes($self)) {
380                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
381         }
382         for my $uris (@$q) {
383                 $self->wq_io_do('query_remote_mboxrd', [], $uris);
384         }
385         $self->wq_close(1); # lei_xsearch workers stop when done
386 }
387
388 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
389         my ($self, $l2m) = @_;
390         return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
391         start_query($self);
392 }
393
394 sub ipc_atfork_child {
395         my ($self) = @_;
396         $self->{lei}->lei_atfork_child;
397         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
398         $self->SUPER::ipc_atfork_child;
399 }
400
401 sub do_query {
402         my ($self, $lei) = @_;
403         my $l2m = $lei->{l2m};
404         my $ops = {
405                 '|' => [ $lei->can('sigpipe_handler'), $lei ],
406                 '!' => [ $lei->can('fail_handler'), $lei ],
407                 '.' => [ \&do_post_augment, $lei ],
408                 '+' => [ \&incr_post_augment, $lei ],
409                 '' => [ \&query_done, $lei ],
410                 'mset_progress' => [ \&mset_progress, $lei ],
411                 'x_it' => [ $lei->can('x_it'), $lei ],
412                 'child_error' => [ $lei->can('child_error'), $lei ],
413                 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
414         };
415         $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
416         ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
417         $lei->{1}->autoflush(1);
418         $lei->start_pager if delete $lei->{need_pager};
419         $lei->{ovv}->ovv_begin($lei);
420         if ($l2m) {
421                 $l2m->pre_augment($lei);
422                 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
423                         $lei->start_mua;
424                 }
425                 $l2m->wq_workers_start('lei2mail', undef,
426                                         $lei->oldset, { lei => $lei });
427                 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
428                 # 1031: F_SETPIPE_SZ
429                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
430         }
431         if (!$lei->{opt}->{threads} && locals($self)) { # for query_mset
432                 # lei->{git_tmp} is set for wq_wait_old so we don't
433                 # delete until all lei2mail + lei_xsearch workers are reaped
434                 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
435         }
436         $self->wq_workers_start('lei_xsearch', undef,
437                                 $lei->oldset, { lei => $lei });
438         my $op = delete $lei->{pkt_op_c};
439         delete $lei->{pkt_op_p};
440         $self->{threads} = $lei->{opt}->{threads};
441         if ($l2m) {
442                 $l2m->net_merge_complete unless $lei->{auth};
443         } else {
444                 start_query($self);
445         }
446         $lei->event_step_init; # wait for shutdowns
447         if ($lei->{oneshot}) {
448                 while ($op->{sock}) { $op->event_step }
449         }
450 }
451
452 sub add_uri {
453         my ($self, $uri) = @_;
454         if (my $curl = $self->{curl} //= which('curl') // 0) {
455                 require PublicInbox::MboxReader;
456                 require IO::Uncompress::Gunzip;
457                 require PublicInbox::LeiCurl;
458                 push @{$self->{remotes}}, $uri;
459         } else {
460                 warn "curl missing, ignoring $uri\n";
461         }
462 }
463
464 sub prepare_external {
465         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
466         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
467                 return add_uri($self, $loc) if $loc->can('scheme');
468         } elsif ($loc =~ m!\Ahttps?://!) {
469                 require URI;
470                 return add_uri($self, URI->new($loc));
471         } elsif (-f "$loc/ei.lock") {
472                 require PublicInbox::ExtSearch;
473                 $loc = PublicInbox::ExtSearch->new($loc);
474         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
475                 require PublicInbox::Inbox; # v2, v1
476                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
477         } else {
478                 warn "W: ignoring $loc, unable to determine type\n";
479                 return;
480         }
481         push @{$self->{locals}}, $loc;
482 }
483
484
485 1;