]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei q: continue remote search if torsocks(1) is missing
[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);
12 use PublicInbox::OpPipe;
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 Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
20
21 sub new {
22         my ($class) = @_;
23         PublicInbox::Search::load_xapian();
24         bless {
25                 qp_flags => $PublicInbox::Search::QP_FLAGS |
26                                 PublicInbox::Search::FLAG_PURE_NOT(),
27         }, $class
28 }
29
30 sub attach_external {
31         my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
32         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
33         my $srch = $ibxish->search or
34                 return warn("$desc not indexed for Xapian\n");
35         my @shards = $srch->xdb_shards_flat or
36                 return warn("$desc has no Xapian shardsXapian\n");
37
38         if (delete $self->{xdb}) { # XXX: do we need this?
39                 # clobber existing {xdb} if amending
40                 my $expect = delete $self->{nshard};
41                 my $shards = delete $self->{shards_flat};
42                 scalar(@$shards) == $expect or die
43                         "BUG: {nshard}$expect != shards=".scalar(@$shards);
44
45                 my $prev = {};
46                 for my $old_ibxish (@{$self->{shard2ibx}}) {
47                         next if $prev == $old_ibxish;
48                         $prev = $old_ibxish;
49                         my @shards = $old_ibxish->search->xdb_shards_flat;
50                         push @{$self->{shards_flat}}, @shards;
51                 }
52                 my $nr = scalar(@{$self->{shards_flat}});
53                 $nr == $expect or die
54                         "BUG: reloaded $nr shards, expected $expect"
55         }
56         push @{$self->{shards_flat}}, @shards;
57         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
58 }
59
60 # returns a list of local inboxes (or count in scalar context)
61 sub locals { @{$_[0]->{locals} // []} }
62
63 sub remotes { @{$_[0]->{remotes} // []} }
64
65 # called by PublicInbox::Search::xdb
66 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
67
68 # like over->get_art
69 sub smsg_for {
70         my ($self, $mitem) = @_;
71         # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
72         my $nshard = $self->{nshard};
73         my $docid = $mitem->get_docid;
74         my $shard = ($docid - 1) % $nshard;
75         my $num = int(($docid - 1) / $nshard) + 1;
76         my $ibx = $self->{shard2ibx}->[$shard];
77         my $smsg = $ibx->over->get_art($num);
78         if (ref($ibx->can('msg_keywords'))) {
79                 my $kw = xap_terms('K', $mitem->get_document);
80                 $smsg->{kw} = [ sort keys %$kw ];
81         }
82         $smsg->{docid} = $docid;
83         $smsg;
84 }
85
86 sub recent {
87         my ($self, $qstr, $opt) = @_;
88         $opt //= {};
89         $opt->{relevance} //= -2;
90         $self->mset($qstr //= 'bytes:1..', $opt);
91 }
92
93 sub over {}
94
95 sub _mset_more ($$) {
96         my ($mset, $mo) = @_;
97         my $size = $mset->size;
98         $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
99 }
100
101 # $startq will EOF when query_prepare is done augmenting and allow
102 # query_mset and query_thread_mset to proceed.
103 sub wait_startq ($) {
104         my ($startq) = @_;
105         $_[0] = undef;
106         read($startq, my $query_prepare_done, 1);
107 }
108
109 sub query_thread_mset { # for --thread
110         my ($self, $lei, $ibxish) = @_;
111         local $0 = "$0 query_thread_mset";
112         my $startq = delete $self->{5};
113         my %sig = $lei->atfork_child_wq($self);
114         local @SIG{keys %sig} = values %sig;
115
116         my ($srch, $over) = ($ibxish->search, $ibxish->over);
117         unless ($srch && $over) {
118                 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
119                 warn "$desc not indexed by Xapian\n";
120                 return;
121         }
122         my $mo = { %{$lei->{mset_opt}} };
123         my $mset;
124         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
125         do {
126                 $mset = $srch->mset($mo->{qstr}, $mo);
127                 my $ids = $srch->mset_to_artnums($mset, $mo);
128                 my $ctx = { ids => $ids };
129                 my $i = 0;
130                 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
131                 while ($over->expand_thread($ctx)) {
132                         for my $n (@{$ctx->{xids}}) {
133                                 my $smsg = $over->get_art($n) or next;
134                                 wait_startq($startq) if $startq;
135                                 my $mitem = delete $n2item{$smsg->{num}};
136                                 $each_smsg->($smsg, $mitem);
137                         }
138                         @{$ctx->{xids}} = ();
139                 }
140         } while (_mset_more($mset, $mo));
141         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
142         $lei->{ovv}->ovv_atexit_child($lei);
143 }
144
145 sub query_mset { # non-parallel for non-"--thread" users
146         my ($self, $lei) = @_;
147         local $0 = "$0 query_mset";
148         my $startq = delete $self->{5};
149         my %sig = $lei->atfork_child_wq($self);
150         local @SIG{keys %sig} = values %sig;
151         my $mo = { %{$lei->{mset_opt}} };
152         my $mset;
153         for my $loc (locals($self)) {
154                 attach_external($self, $loc);
155         }
156         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
157         do {
158                 $mset = $self->mset($mo->{qstr}, $mo);
159                 for my $mitem ($mset->items) {
160                         my $smsg = smsg_for($self, $mitem) or next;
161                         wait_startq($startq) if $startq;
162                         $each_smsg->($smsg, $mitem);
163                 }
164         } while (_mset_more($mset, $mo));
165         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
166         $lei->{ovv}->ovv_atexit_child($lei);
167 }
168
169 sub each_eml { # callback for MboxReader->mboxrd
170         my ($eml, $self, $lei, $each_smsg) = @_;
171         my $smsg = bless {}, 'PublicInbox::Smsg';
172         $smsg->populate($eml);
173         $smsg->parse_references($eml, mids($eml));
174         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
175         delete @$smsg{qw(From Subject -ds -ts)};
176         if (my $startq = delete($self->{5})) { wait_startq($startq) }
177         $each_smsg->($smsg, undef, $eml);
178 }
179
180 # PublicInbox::OnDestroy callback
181 sub kill_reap {
182         my ($pid) = @_;
183         kill('KILL', $pid); # spawn() blocks other signals
184         waitpid($pid, 0);
185 }
186
187 sub query_remote_mboxrd {
188         my ($self, $lei, $uris) = @_;
189         local $0 = "$0 query_remote_mboxrd";
190         my %sig = $lei->atfork_child_wq($self); # keep $self->{5} startq
191         local @SIG{keys %sig} = values %sig;
192         my ($opt, $env) = @$lei{qw(opt env)};
193         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
194         push(@qform, t => 1) if $opt->{thread};
195         my @cmd = ($self->{curl}, qw(-sSf -d), '');
196         my $verbose = $opt->{verbose};
197         my $reap;
198         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
199         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
200         my $rdr = { 2 => $cerr };
201         my $coff = 0;
202         if ($verbose) {
203                 # spawn a process to force line-buffering, otherwise curl
204                 # will write 1 character at-a-time and parallel outputs
205                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
206                 push @cmd, '-v';
207                 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
208                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
209                 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
210         }
211         for my $o ($lei->curl_opt) {
212                 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
213                 if ($o =~ s/=[is]@\z//) {
214                         my $ary = $opt->{$o} or next;
215                         push @cmd, map { ("--$o", $_) } @$ary;
216                 } elsif ($o =~ s/=[is]\z//) {
217                         my $val = $opt->{$o} // next;
218                         push @cmd, "--$o", $val;
219                 } elsif ($opt->{$o}) {
220                         push @cmd, "--$o";
221                 }
222         }
223         $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
224         my $tor = $opt->{torsocks} //= 'auto';
225         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
226         for my $uri (@$uris) {
227                 $uri->query_form(@qform);
228                 my $cmd = [ @cmd, $uri->as_string ];
229                 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
230                                 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
231                         unshift @$cmd, which('torsocks');
232                 } elsif (PublicInbox::Config::git_bool($tor)) {
233                         unshift @$cmd, which('torsocks');
234                 }
235
236                 # continue anyways if torsocks is missing; a proxy may be
237                 # specified via CLI, curlrc, environment variable, or even
238                 # firewall rule
239                 shift(@$cmd) if !$cmd->[0];
240
241                 $lei->err("# @$cmd") if $verbose;
242                 $? = 0;
243                 my $fh = popen_rd($cmd, $env, $rdr);
244                 $fh = IO::Uncompress::Gunzip->new($fh);
245                 eval {
246                         PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
247                                                         $lei, $each_smsg);
248                 };
249                 return $lei->fail("E: @$cmd: $@") if $@;
250                 next unless $?;
251                 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
252                 my $e = do { local $/; <$cerr> } //
253                                 die "read(curl stderr): $!\n";
254                 $coff += length($e);
255                 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
256                 $lei->child_error($?);
257                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
258                 # --verbose already showed the error via tail(1)
259                 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
260         }
261         undef $each_smsg;
262         $lei->{ovv}->ovv_atexit_child($lei);
263 }
264
265 sub git {
266         my ($self) = @_;
267         my (%seen, @dirs);
268         my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
269         for my $ibx (@{$self->{shard2ibx} // []}) {
270                 my $d = File::Spec->canonpath($ibx->git->{git_dir});
271                 $seen{$d} //= push @dirs, "$d/objects\n"
272         }
273         my $git_dir = $tmp->dirname;
274         PublicInbox::Import::init_bare($git_dir);
275         my $f = "$git_dir/objects/info/alternates";
276         open my $alt, '>', $f or die "open($f): $!";
277         print $alt @dirs or die "print $f: $!";
278         close $alt or die "close $f: $!";
279         my $git = PublicInbox::Git->new($git_dir);
280         $git->{-tmp} = $tmp;
281         $git;
282 }
283
284 sub query_done { # EOF callback
285         my ($lei) = @_;
286         my $has_l2m = exists $lei->{l2m};
287         for my $f (qw(lxs l2m)) {
288                 my $wq = delete $lei->{$f} or next;
289                 $wq->wq_wait_old;
290         }
291         $lei->{ovv}->ovv_end($lei);
292         if ($has_l2m) { # close() calls LeiToMail reap_compress
293                 if (my $out = delete $lei->{old_1}) {
294                         if (my $mbout = $lei->{1}) {
295                                 close($mbout) or return $lei->fail(<<"");
296 Error closing $lei->{ovv}->{dst}: $!
297
298                         }
299                         $lei->{1} = $out;
300                 }
301                 $lei->start_mua;
302         }
303         $lei->dclose;
304 }
305
306 sub do_post_augment {
307         my ($lei, $zpipe, $au_done) = @_;
308         my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
309         eval { $l2m->post_augment($lei, $zpipe) };
310         if (my $err = $@) {
311                 if (my $lxs = delete $lei->{lxs}) {
312                         $lxs->wq_kill;
313                         $lxs->wq_close;
314                 }
315                 $lei->fail("$err");
316         }
317         close $au_done; # triggers wait_startq
318 }
319
320 my $MAX_PER_HOST = 4;
321 sub MAX_PER_HOST { $MAX_PER_HOST }
322
323 sub concurrency {
324         my ($self, $opt) = @_;
325         my $nl = $opt->{thread} ? locals($self) : 1;
326         my $nr = remotes($self);
327         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
328         $nl + $nr;
329 }
330
331 sub start_query { # always runs in main (lei-daemon) process
332         my ($self, $io, $lei) = @_;
333         if ($lei->{opt}->{thread}) {
334                 for my $ibxish (locals($self)) {
335                         $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
336                 }
337         } elsif (locals($self)) {
338                 $self->wq_do('query_mset', $io, $lei);
339         }
340         my $i = 0;
341         my $q = [];
342         for my $uri (remotes($self)) {
343                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
344         }
345         for my $uris (@$q) {
346                 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
347         }
348         @$io = ();
349 }
350
351 sub query_prepare { # called by wq_do
352         my ($self, $lei) = @_;
353         local $0 = "$0 query_prepare";
354         my %sig = $lei->atfork_child_wq($self);
355         -p $lei->{0} or die "BUG: \$done pipe expected";
356         local @SIG{keys %sig} = values %sig;
357         eval { $lei->{l2m}->do_augment($lei) };
358         $lei->fail($@) if $@;
359         syswrite($lei->{0}, '.') == 1 or die "do_post_augment trigger: $!";
360 }
361
362 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
363         my ($lei) = @_;
364         my $lxs = delete $lei->{lxs};
365         if ($lxs && $lxs->wq_kill_old) {
366                 kill 'PIPE', $$;
367                 $lxs->wq_wait_old;
368         }
369         close(delete $lei->{1}) if $lei->{1};
370 }
371
372 sub do_query {
373         my ($self, $lei_orig) = @_;
374         my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
375         $io[0] = undef;
376         pipe(my $done, $io[0]) or die "pipe $!";
377         $lei_orig->{1}->autoflush(1);
378
379         $lei_orig->event_step_init; # wait for shutdowns
380         my $done_op = {
381                 '' => [ \&query_done, $lei_orig ],
382                 '!' => [ \&sigpipe_handler, $lei_orig ]
383         };
384         my $in_loop = exists $lei_orig->{sock};
385         $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
386         my $l2m = $lei->{l2m};
387         if ($l2m) {
388                 # may redirect $lei->{1} for mbox
389                 my $zpipe = $l2m->pre_augment($lei_orig);
390                 $io[1] = $lei_orig->{1};
391                 pipe(my ($startq, $au_done)) or die "pipe: $!";
392                 $done_op->{'.'} = [ \&do_post_augment, $lei_orig,
393                                         $zpipe, $au_done ];
394                 local $io[4] = *STDERR{GLOB}; # don't send l2m->{-wq_s1}
395                 die "BUG: unexpected \$io[5]: $io[5]" if $io[5];
396                 $self->wq_do('query_prepare', \@io, $lei);
397                 fcntl($startq, 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
398                 $io[5] = $startq;
399                 $io[1] = $zpipe->[1] if $zpipe;
400         }
401         start_query($self, \@io, $lei);
402         $self->wq_close(1);
403         unless ($in_loop) {
404                 # for the $lei->atfork_child_wq PIPE handler:
405                 while ($done->{sock}) { $done->event_step }
406         }
407 }
408
409 sub ipc_atfork_prepare {
410         my ($self) = @_;
411         if (exists $self->{remotes}) {
412                 require PublicInbox::MboxReader;
413                 require IO::Uncompress::Gunzip;
414         }
415         # FDS: (0: done_wr, 1: stdout|mbox, 2: stderr,
416         #       3: sock, 4: $l2m->{-wq_s1}, 5: $startq)
417         $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
418 }
419
420 sub add_uri {
421         my ($self, $uri) = @_;
422         if (my $curl = $self->{curl} //= which('curl') // 0) {
423                 push @{$self->{remotes}}, $uri;
424         } else {
425                 warn "curl missing, ignoring $uri\n";
426         }
427 }
428
429 sub prepare_external {
430         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
431         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
432                 return add_uri($self, $loc) if $loc->can('scheme');
433         } elsif ($loc =~ m!\Ahttps?://!) {
434                 require URI;
435                 return add_uri($self, URI->new($loc));
436         } elsif (-f "$loc/ei.lock") {
437                 require PublicInbox::ExtSearch;
438                 $loc = PublicInbox::ExtSearch->new($loc);
439         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
440                 require PublicInbox::Inbox; # v2, v1
441                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
442         } else {
443                 warn "W: ignoring $loc, unable to determine type\n";
444                 return;
445         }
446         push @{$self->{locals}}, $loc;
447 }
448
449
450 1;