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