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>
4 # Combine any combination of PublicInbox::Search,
5 # PublicInbox::ExtSearch, and PublicInbox::LeiSearch objects
7 package PublicInbox::LeiXSearch;
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
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);
23 PublicInbox::Search::load_xapian();
25 qp_flags => $PublicInbox::Search::QP_FLAGS |
26 PublicInbox::Search::FLAG_PURE_NOT(),
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");
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);
46 for my $old_ibxish (@{$self->{shard2ibx}}) {
47 next if $prev == $old_ibxish;
49 my @shards = $old_ibxish->search->xdb_shards_flat;
50 push @{$self->{shards_flat}}, @shards;
52 my $nr = scalar(@{$self->{shards_flat}});
54 "BUG: reloaded $nr shards, expected $expect"
56 push @{$self->{shards_flat}}, @shards;
57 push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
60 # returns a list of local inboxes (or count in scalar context)
61 sub locals { @{$_[0]->{locals} // []} }
63 sub remotes { @{$_[0]->{remotes} // []} }
65 # called by PublicInbox::Search::xdb
66 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
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 ];
82 $smsg->{docid} = $docid;
87 my ($self, $qstr, $opt) = @_;
89 $opt->{relevance} //= -2;
90 $self->mset($qstr //= 'bytes:1..', $opt);
97 my $size = $mset->size;
98 $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
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 ($) {
106 read($startq, my $query_prepare_done, 1);
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;
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";
122 my $mo = { %{$lei->{mset_opt}} };
124 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
126 $mset = $srch->mset($mo->{qstr}, $mo);
127 my $ids = $srch->mset_to_artnums($mset, $mo);
128 my $ctx = { ids => $ids };
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);
138 @{$ctx->{xids}} = ();
140 } while (_mset_more($mset, $mo));
141 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
142 $lei->{ovv}->ovv_atexit_child($lei);
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}} };
153 for my $loc (locals($self)) {
154 attach_external($self, $loc);
156 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
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);
164 } while (_mset_more($mset, $mo));
165 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
166 $lei->{ovv}->ovv_atexit_child($lei);
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);
180 # PublicInbox::OnDestroy callback
183 kill('KILL', $pid); # spawn() blocks other signals
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};
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 };
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
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);
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}) {
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');
236 # continue anyways if torsocks is missing; a proxy may be
237 # specified via CLI, curlrc, environment variable, or even
239 shift(@$cmd) if !$cmd->[0];
241 $lei->err("# @$cmd") if $verbose;
243 my $fh = popen_rd($cmd, $env, $rdr);
244 $fh = IO::Uncompress::Gunzip->new($fh);
246 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
249 return $lei->fail("E: @$cmd: $@") if $@;
251 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
252 my $e = do { local $/; <$cerr> } //
253 die "read(curl stderr): $!\n";
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);
262 $lei->{ovv}->ovv_atexit_child($lei);
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"
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);
284 sub query_done { # EOF callback
286 my $has_l2m = exists $lei->{l2m};
287 for my $f (qw(lxs l2m)) {
288 my $wq = delete $lei->{$f} or next;
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}: $!
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) };
311 if (my $lxs = delete $lei->{lxs}) {
317 close $au_done; # triggers wait_startq
320 my $MAX_PER_HOST = 4;
321 sub MAX_PER_HOST { $MAX_PER_HOST }
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;
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);
337 } elsif (locals($self)) {
338 $self->wq_do('query_mset', $io, $lei);
342 for my $uri (remotes($self)) {
343 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
346 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
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: $!";
362 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
364 my $lxs = delete $lei->{lxs};
365 if ($lxs && $lxs->wq_kill_old) {
369 close(delete $lei->{1}) if $lei->{1};
373 my ($self, $lei_orig) = @_;
374 my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
376 pipe(my $done, $io[0]) or die "pipe $!";
377 $lei_orig->{1}->autoflush(1);
379 $lei_orig->event_step_init; # wait for shutdowns
381 '' => [ \&query_done, $lei_orig ],
382 '!' => [ \&sigpipe_handler, $lei_orig ]
384 my $in_loop = exists $lei_orig->{sock};
385 $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
386 my $l2m = $lei->{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,
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
399 $io[1] = $zpipe->[1] if $zpipe;
401 start_query($self, \@io, $lei);
404 # for the $lei->atfork_child_wq PIPE handler:
405 while ($done->{sock}) { $done->event_step }
409 sub ipc_atfork_prepare {
411 if (exists $self->{remotes}) {
412 require PublicInbox::MboxReader;
413 require IO::Uncompress::Gunzip;
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
421 my ($self, $uri) = @_;
422 if (my $curl = $self->{curl} //= which('curl') // 0) {
423 push @{$self->{remotes}}, $uri;
425 warn "curl missing, ignoring $uri\n";
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?://!) {
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';
443 warn "W: ignoring $loc, unable to determine type\n";
446 push @{$self->{locals}}, $loc;