]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei q: support reading queries from stdin
[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(dwaitpid now);
12 use PublicInbox::PktOp qw(pkt_do);
13 use PublicInbox::Import;
14 use File::Temp 0.19 (); # 0.19 for ->newdir
15 use File::Spec ();
16 use PublicInbox::Search qw(xap_terms);
17 use PublicInbox::Spawn qw(popen_rd spawn which);
18 use PublicInbox::MID qw(mids);
19 use PublicInbox::Smsg;
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 query_prepare is done augmenting and allow
103 # query_mset and query_thread_mset to proceed.
104 sub wait_startq ($) {
105         my ($startq) = @_;
106         $_[0] = undef;
107         read($startq, my $query_prepare_done, 1);
108 }
109
110 sub mset_progress {
111         my $lei = shift;
112         return unless $lei->{-progress};
113         if ($lei->{pkt_op}) { # called via pkt_op/pkt_do from workers
114                 pkt_do($lei->{pkt_op}, 'mset_progress', @_);
115         } else { # single lei-daemon consumer
116                 my ($desc, $mset_size, $mset_total_est) = @_;
117                 $lei->{-mset_total} += $mset_size;
118                 $lei->err("# $desc $mset_size/$mset_total_est");
119         }
120 }
121
122 sub query_thread_mset { # for --thread
123         my ($self, $lei, $ibxish) = @_;
124         local $0 = "$0 query_thread_mset";
125         $lei->atfork_child_wq($self);
126         my $startq = delete $lei->{startq};
127
128         my ($srch, $over) = ($ibxish->search, $ibxish->over);
129         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
130         return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
131         my $mo = { %{$lei->{mset_opt}} };
132         my $mset;
133         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
134         do {
135                 $mset = $srch->mset($mo->{qstr}, $mo);
136                 mset_progress($lei, $desc, $mset->size,
137                                 $mset->get_matches_estimated);
138                 my $ids = $srch->mset_to_artnums($mset, $mo);
139                 my $ctx = { ids => $ids };
140                 my $i = 0;
141                 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
142                 while ($over->expand_thread($ctx)) {
143                         for my $n (@{$ctx->{xids}}) {
144                                 my $smsg = $over->get_art($n) or next;
145                                 wait_startq($startq) if $startq;
146                                 my $mitem = delete $n2item{$smsg->{num}};
147                                 $each_smsg->($smsg, $mitem);
148                         }
149                         @{$ctx->{xids}} = ();
150                 }
151         } while (_mset_more($mset, $mo));
152         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
153         $lei->{ovv}->ovv_atexit_child($lei);
154 }
155
156 sub query_mset { # non-parallel for non-"--thread" users
157         my ($self, $lei) = @_;
158         local $0 = "$0 query_mset";
159         $lei->atfork_child_wq($self);
160         my $startq = delete $lei->{startq};
161         my $mo = { %{$lei->{mset_opt}} };
162         my $mset;
163         for my $loc (locals($self)) {
164                 attach_external($self, $loc);
165         }
166         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
167         do {
168                 $mset = $self->mset($mo->{qstr}, $mo);
169                 mset_progress($lei, 'xsearch', $mset->size,
170                                 $mset->size, $mset->get_matches_estimated);
171                 for my $mitem ($mset->items) {
172                         my $smsg = smsg_for($self, $mitem) or next;
173                         wait_startq($startq) if $startq;
174                         $each_smsg->($smsg, $mitem);
175                 }
176         } while (_mset_more($mset, $mo));
177         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
178         $lei->{ovv}->ovv_atexit_child($lei);
179 }
180
181 sub each_eml { # callback for MboxReader->mboxrd
182         my ($eml, $self, $lei, $each_smsg) = @_;
183         my $smsg = bless {}, 'PublicInbox::Smsg';
184         $smsg->populate($eml);
185         $smsg->parse_references($eml, mids($eml));
186         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
187         delete @$smsg{qw(From Subject -ds -ts)};
188         if (my $startq = delete($lei->{startq})) { wait_startq($startq) }
189         if ($lei->{-progress}) {
190                 ++$lei->{-nr_remote_eml};
191                 my $now = now();
192                 my $next = $lei->{-next_progress} //= ($now + 1);
193                 if ($now > $next) {
194                         $lei->{-next_progress} = $now + 1;
195                         my $nr = $lei->{-nr_remote_eml};
196                         $lei->err("# $lei->{-current_url} $nr/?");
197                 }
198         }
199         $each_smsg->($smsg, undef, $eml);
200 }
201
202 # PublicInbox::OnDestroy callback
203 sub kill_reap {
204         my ($pid) = @_;
205         kill('KILL', $pid); # spawn() blocks other signals
206         waitpid($pid, 0);
207 }
208
209 sub query_remote_mboxrd {
210         my ($self, $lei, $uris) = @_;
211         local $0 = "$0 query_remote_mboxrd";
212         $lei->atfork_child_wq($self);
213         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
214         my ($opt, $env) = @$lei{qw(opt env)};
215         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
216         push(@qform, t => 1) if $opt->{thread};
217         my @cmd = ($self->{curl}, qw(-sSf -d), '');
218         my $verbose = $opt->{verbose};
219         my $reap;
220         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
221         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
222         my $rdr = { 2 => $cerr };
223         my $coff = 0;
224         if ($verbose) {
225                 # spawn a process to force line-buffering, otherwise curl
226                 # will write 1 character at-a-time and parallel outputs
227                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
228                 push @cmd, '-v';
229                 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
230                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
231                 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
232         }
233         for my $o ($lei->curl_opt) {
234                 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
235                 if ($o =~ s/=[is]@\z//) {
236                         my $ary = $opt->{$o} or next;
237                         push @cmd, map { ("--$o", $_) } @$ary;
238                 } elsif ($o =~ s/=[is]\z//) {
239                         my $val = $opt->{$o} // next;
240                         push @cmd, "--$o", $val;
241                 } elsif ($opt->{$o}) {
242                         push @cmd, "--$o";
243                 }
244         }
245         $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
246         my $tor = $opt->{torsocks} //= 'auto';
247         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
248         for my $uri (@$uris) {
249                 $lei->{-current_url} = $uri->as_string;
250                 $lei->{-nr_remote_eml} = 0;
251                 $uri->query_form(@qform);
252                 my $cmd = [ @cmd, $uri->as_string ];
253                 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
254                                 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
255                         unshift @$cmd, which('torsocks');
256                 } elsif (PublicInbox::Config::git_bool($tor)) {
257                         unshift @$cmd, which('torsocks');
258                 }
259
260                 # continue anyways if torsocks is missing; a proxy may be
261                 # specified via CLI, curlrc, environment variable, or even
262                 # firewall rule
263                 shift(@$cmd) if !$cmd->[0];
264
265                 $lei->err("# @$cmd") if $verbose;
266                 my ($fh, $pid) = popen_rd($cmd, $env, $rdr);
267                 $fh = IO::Uncompress::Gunzip->new($fh);
268                 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
269                                                 $lei, $each_smsg);
270                 waitpid($pid, 0) == $pid or die "BUG: waitpid (curl): $!";
271                 if ($? == 0) {
272                         my $nr = $lei->{-nr_remote_eml};
273                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
274                         next;
275                 }
276                 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
277                 my $e = do { local $/; <$cerr> } //
278                                 die "read(curl stderr): $!\n";
279                 $coff += length($e);
280                 truncate($cerr, 0);
281                 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
282                 $lei->child_error($?);
283                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
284                 # --verbose already showed the error via tail(1)
285                 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
286         }
287         undef $each_smsg;
288         $lei->{ovv}->ovv_atexit_child($lei);
289 }
290
291 sub git {
292         my ($self) = @_;
293         my (%seen, @dirs);
294         my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
295         for my $ibx (@{$self->{shard2ibx} // []}) {
296                 my $d = File::Spec->canonpath($ibx->git->{git_dir});
297                 $seen{$d} //= push @dirs, "$d/objects\n"
298         }
299         my $git_dir = $tmp->dirname;
300         PublicInbox::Import::init_bare($git_dir);
301         my $f = "$git_dir/objects/info/alternates";
302         open my $alt, '>', $f or die "open($f): $!";
303         print $alt @dirs or die "print $f: $!";
304         close $alt or die "close $f: $!";
305         my $git = PublicInbox::Git->new($git_dir);
306         $git->{-tmp} = $tmp;
307         $git;
308 }
309
310 sub query_done { # EOF callback
311         my ($lei) = @_;
312         my $has_l2m = exists $lei->{l2m};
313         for my $f (qw(lxs l2m)) {
314                 my $wq = delete $lei->{$f} or next;
315                 $wq->wq_wait_old($lei);
316         }
317         $lei->{ovv}->ovv_end($lei);
318         if ($has_l2m) { # close() calls LeiToMail reap_compress
319                 if (my $out = delete $lei->{old_1}) {
320                         if (my $mbout = $lei->{1}) {
321                                 close($mbout) or return $lei->fail(<<"");
322 Error closing $lei->{ovv}->{dst}: $!
323
324                         }
325                         $lei->{1} = $out;
326                 }
327                 $lei->start_mua;
328         }
329         $lei->{-progress} and
330                 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
331         $lei->dclose;
332 }
333
334 sub do_post_augment {
335         my ($lei, $zpipe, $au_done) = @_;
336         my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
337         eval { $l2m->post_augment($lei, $zpipe) };
338         if (my $err = $@) {
339                 if (my $lxs = delete $lei->{lxs}) {
340                         $lxs->wq_kill;
341                         $lxs->wq_close;
342                 }
343                 $lei->fail("$err");
344         }
345         close $au_done; # triggers wait_startq
346 }
347
348 my $MAX_PER_HOST = 4;
349
350 sub concurrency {
351         my ($self, $opt) = @_;
352         my $nl = $opt->{thread} ? locals($self) : 1;
353         my $nr = remotes($self);
354         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
355         $nl + $nr;
356 }
357
358 sub start_query { # always runs in main (lei-daemon) process
359         my ($self, $io, $lei) = @_;
360         if ($lei->{opt}->{thread}) {
361                 for my $ibxish (locals($self)) {
362                         $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
363                 }
364         } elsif (locals($self)) {
365                 $self->wq_do('query_mset', $io, $lei);
366         }
367         my $i = 0;
368         my $q = [];
369         for my $uri (remotes($self)) {
370                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
371         }
372         for my $uris (@$q) {
373                 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
374         }
375         @$io = ();
376 }
377
378 sub query_prepare { # called by wq_do
379         my ($self, $lei) = @_;
380         local $0 = "$0 query_prepare";
381         $lei->atfork_child_wq($self);
382         delete $lei->{l2m}->{-wq_s1};
383         eval { $lei->{l2m}->do_augment($lei) };
384         $lei->fail($@) if $@;
385         pkt_do($lei->{pkt_op}, '.') == 1 or die "do_post_augment trigger: $!"
386 }
387
388 sub fail_handler ($;$$) {
389         my ($lei, $code, $io) = @_;
390         for my $f (qw(lxs l2m)) {
391                 my $wq = delete $lei->{$f} or next;
392                 $wq->wq_wait_old($lei) if $wq->wq_kill_old; # lei-daemon
393         }
394         close($io) if $io; # needed to avoid warnings on SIGPIPE
395         $lei->x_it($code // (1 >> 8));
396 }
397
398 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
399         fail_handler($_[0], 13, delete $_[0]->{1});
400 }
401
402 sub do_query {
403         my ($self, $lei) = @_;
404         $lei->{1}->autoflush(1);
405         $lei->start_pager if -t $lei->{1};
406         $lei->{ovv}->ovv_begin($lei);
407         my ($au_done, $zpipe);
408         my $l2m = $lei->{l2m};
409         if ($l2m) {
410                 pipe($lei->{startq}, $au_done) or die "pipe: $!";
411                 # 1031: F_SETPIPE_SZ
412                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
413                 $zpipe = $l2m->pre_augment($lei);
414         }
415         my $ops = {
416                 '|' => [ \&sigpipe_handler, $lei ],
417                 '!' => [ \&fail_handler, $lei ],
418                 '.' => [ \&do_post_augment, $lei, $zpipe, $au_done ],
419                 '' => [ \&query_done, $lei ],
420                 'mset_progress' => [ \&mset_progress, $lei ],
421                 'x_it' => [ $lei->can('x_it'), $lei ],
422                 'child_error' => [ $lei->can('child_error'), $lei ],
423         };
424         (my $op, $lei->{pkt_op}) = PublicInbox::PktOp->pair($ops);
425         my ($lei_ipc, @io) = $lei->atfork_parent_wq($self);
426         delete($lei->{pkt_op});
427
428         $lei->event_step_init; # wait for shutdowns
429         if ($l2m) {
430                 $self->wq_do('query_prepare', \@io, $lei_ipc);
431                 $io[1] = $zpipe->[1] if $zpipe;
432         }
433         start_query($self, \@io, $lei_ipc);
434         $self->wq_close(1);
435         if ($lei->{oneshot}) {
436                 # for the $lei_ipc->atfork_child_wq PIPE handler:
437                 while ($op->{sock}) { $op->event_step }
438         }
439 }
440
441 sub add_uri {
442         my ($self, $uri) = @_;
443         if (my $curl = $self->{curl} //= which('curl') // 0) {
444                 require PublicInbox::MboxReader;
445                 require IO::Uncompress::Gunzip;
446                 push @{$self->{remotes}}, $uri;
447         } else {
448                 warn "curl missing, ignoring $uri\n";
449         }
450 }
451
452 sub prepare_external {
453         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
454         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
455                 return add_uri($self, $loc) if $loc->can('scheme');
456         } elsif ($loc =~ m!\Ahttps?://!) {
457                 require URI;
458                 return add_uri($self, URI->new($loc));
459         } elsif (-f "$loc/ei.lock") {
460                 require PublicInbox::ExtSearch;
461                 $loc = PublicInbox::ExtSearch->new($loc);
462         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
463                 require PublicInbox::Inbox; # v2, v1
464                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
465         } else {
466                 warn "W: ignoring $loc, unable to determine type\n";
467                 return;
468         }
469         push @{$self->{locals}}, $loc;
470 }
471
472
473 1;