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 shards\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 $lei->atfork_child_wq($self);
113 my $startq = delete $lei->{startq};
115 my ($srch, $over) = ($ibxish->search, $ibxish->over);
116 unless ($srch && $over) {
117 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
118 warn "$desc not indexed by Xapian\n";
121 my $mo = { %{$lei->{mset_opt}} };
123 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
125 $mset = $srch->mset($mo->{qstr}, $mo);
126 my $ids = $srch->mset_to_artnums($mset, $mo);
127 my $ctx = { ids => $ids };
129 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
130 while ($over->expand_thread($ctx)) {
131 for my $n (@{$ctx->{xids}}) {
132 my $smsg = $over->get_art($n) or next;
133 wait_startq($startq) if $startq;
134 my $mitem = delete $n2item{$smsg->{num}};
135 $each_smsg->($smsg, $mitem);
137 @{$ctx->{xids}} = ();
139 } while (_mset_more($mset, $mo));
140 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
141 $lei->{ovv}->ovv_atexit_child($lei);
144 sub query_mset { # non-parallel for non-"--thread" users
145 my ($self, $lei) = @_;
146 local $0 = "$0 query_mset";
147 $lei->atfork_child_wq($self);
148 my $startq = delete $lei->{startq};
149 my $mo = { %{$lei->{mset_opt}} };
151 for my $loc (locals($self)) {
152 attach_external($self, $loc);
154 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
156 $mset = $self->mset($mo->{qstr}, $mo);
157 for my $mitem ($mset->items) {
158 my $smsg = smsg_for($self, $mitem) or next;
159 wait_startq($startq) if $startq;
160 $each_smsg->($smsg, $mitem);
162 } while (_mset_more($mset, $mo));
163 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
164 $lei->{ovv}->ovv_atexit_child($lei);
167 sub each_eml { # callback for MboxReader->mboxrd
168 my ($eml, $self, $lei, $each_smsg) = @_;
169 my $smsg = bless {}, 'PublicInbox::Smsg';
170 $smsg->populate($eml);
171 $smsg->parse_references($eml, mids($eml));
172 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
173 delete @$smsg{qw(From Subject -ds -ts)};
174 if (my $startq = delete($lei->{startq})) { wait_startq($startq) }
175 $each_smsg->($smsg, undef, $eml);
178 # PublicInbox::OnDestroy callback
181 kill('KILL', $pid); # spawn() blocks other signals
185 sub query_remote_mboxrd {
186 my ($self, $lei, $uris) = @_;
187 local $0 = "$0 query_remote_mboxrd";
188 $lei->atfork_child_wq($self);
189 my ($opt, $env) = @$lei{qw(opt env)};
190 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
191 push(@qform, t => 1) if $opt->{thread};
192 my @cmd = ($self->{curl}, qw(-sSf -d), '');
193 my $verbose = $opt->{verbose};
195 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
196 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
197 my $rdr = { 2 => $cerr };
200 # spawn a process to force line-buffering, otherwise curl
201 # will write 1 character at-a-time and parallel outputs
202 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
204 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
205 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
206 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
208 for my $o ($lei->curl_opt) {
209 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
210 if ($o =~ s/=[is]@\z//) {
211 my $ary = $opt->{$o} or next;
212 push @cmd, map { ("--$o", $_) } @$ary;
213 } elsif ($o =~ s/=[is]\z//) {
214 my $val = $opt->{$o} // next;
215 push @cmd, "--$o", $val;
216 } elsif ($opt->{$o}) {
220 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
221 my $tor = $opt->{torsocks} //= 'auto';
222 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
223 for my $uri (@$uris) {
224 $uri->query_form(@qform);
225 my $cmd = [ @cmd, $uri->as_string ];
226 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
227 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
228 unshift @$cmd, which('torsocks');
229 } elsif (PublicInbox::Config::git_bool($tor)) {
230 unshift @$cmd, which('torsocks');
233 # continue anyways if torsocks is missing; a proxy may be
234 # specified via CLI, curlrc, environment variable, or even
236 shift(@$cmd) if !$cmd->[0];
238 $lei->err("# @$cmd") if $verbose;
240 my $fh = popen_rd($cmd, $env, $rdr);
241 $fh = IO::Uncompress::Gunzip->new($fh);
243 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
246 return $lei->fail("E: @$cmd: $@") if $@;
248 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
249 my $e = do { local $/; <$cerr> } //
250 die "read(curl stderr): $!\n";
252 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
253 $lei->child_error($?);
254 $uri->query_form(q => $lei->{mset_opt}->{qstr});
255 # --verbose already showed the error via tail(1)
256 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
259 $lei->{ovv}->ovv_atexit_child($lei);
265 my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
266 for my $ibx (@{$self->{shard2ibx} // []}) {
267 my $d = File::Spec->canonpath($ibx->git->{git_dir});
268 $seen{$d} //= push @dirs, "$d/objects\n"
270 my $git_dir = $tmp->dirname;
271 PublicInbox::Import::init_bare($git_dir);
272 my $f = "$git_dir/objects/info/alternates";
273 open my $alt, '>', $f or die "open($f): $!";
274 print $alt @dirs or die "print $f: $!";
275 close $alt or die "close $f: $!";
276 my $git = PublicInbox::Git->new($git_dir);
281 sub query_done { # EOF callback
283 my $has_l2m = exists $lei->{l2m};
284 for my $f (qw(lxs l2m)) {
285 my $wq = delete $lei->{$f} or next;
286 $wq->wq_wait_old($lei);
288 $lei->{ovv}->ovv_end($lei);
289 if ($has_l2m) { # close() calls LeiToMail reap_compress
290 if (my $out = delete $lei->{old_1}) {
291 if (my $mbout = $lei->{1}) {
292 close($mbout) or return $lei->fail(<<"");
293 Error closing $lei->{ovv}->{dst}: $!
303 sub do_post_augment {
304 my ($lei, $zpipe, $au_done) = @_;
305 my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
306 eval { $l2m->post_augment($lei, $zpipe) };
308 if (my $lxs = delete $lei->{lxs}) {
314 close $au_done; # triggers wait_startq
317 my $MAX_PER_HOST = 4;
318 sub MAX_PER_HOST { $MAX_PER_HOST }
321 my ($self, $opt) = @_;
322 my $nl = $opt->{thread} ? locals($self) : 1;
323 my $nr = remotes($self);
324 $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
328 sub start_query { # always runs in main (lei-daemon) process
329 my ($self, $io, $lei) = @_;
330 if ($lei->{opt}->{thread}) {
331 for my $ibxish (locals($self)) {
332 $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
334 } elsif (locals($self)) {
335 $self->wq_do('query_mset', $io, $lei);
339 for my $uri (remotes($self)) {
340 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
343 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
348 sub query_prepare { # called by wq_do
349 my ($self, $lei) = @_;
350 local $0 = "$0 query_prepare";
351 $lei->atfork_child_wq($self);
352 delete $lei->{l2m}->{-wq_s1};
353 eval { $lei->{l2m}->do_augment($lei) };
354 $lei->fail($@) if $@;
355 syswrite($lei->{op_pipe}, '.') == 1 or die "do_post_augment trigger: $!"
358 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
360 my $lxs = delete $lei->{lxs};
361 if ($lxs && $lxs->wq_kill_old) { # is this the daemon?
362 $lxs->wq_wait_old($lei);
364 close(delete $lei->{1}) if $lei->{1};
369 my ($self, $lei) = @_;
370 $lei->{1}->autoflush(1);
371 my ($au_done, $zpipe);
372 my $l2m = $lei->{l2m};
374 pipe($lei->{startq}, $au_done) or die "pipe: $!";
376 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
377 $zpipe = $l2m->pre_augment($lei);
379 pipe(my $done, $lei->{op_pipe}) or die "pipe $!";
380 my ($lei_ipc, @io) = $lei->atfork_parent_wq($self);
381 delete($lei->{op_pipe});
383 $lei->event_step_init; # wait for shutdowns
385 '' => [ \&query_done, $lei ],
386 '!' => [ \&sigpipe_handler, $lei ]
388 my $in_loop = exists $lei->{sock};
389 $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
391 $done_op->{'.'} = [ \&do_post_augment, $lei, $zpipe, $au_done ];
392 $self->wq_do('query_prepare', \@io, $lei_ipc);
393 $io[1] = $zpipe->[1] if $zpipe;
395 start_query($self, \@io, $lei_ipc);
398 # for the $lei_ipc->atfork_child_wq PIPE handler:
399 while ($done->{sock}) { $done->event_step }
404 my ($self, $uri) = @_;
405 if (my $curl = $self->{curl} //= which('curl') // 0) {
406 require PublicInbox::MboxReader;
407 require IO::Uncompress::Gunzip;
408 push @{$self->{remotes}}, $uri;
410 warn "curl missing, ignoring $uri\n";
414 sub prepare_external {
415 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
416 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
417 return add_uri($self, $loc) if $loc->can('scheme');
418 } elsif ($loc =~ m!\Ahttps?://!) {
420 return add_uri($self, URI->new($loc));
421 } elsif (-f "$loc/ei.lock") {
422 require PublicInbox::ExtSearch;
423 $loc = PublicInbox::ExtSearch->new($loc);
424 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
425 require PublicInbox::Inbox; # v2, v1
426 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
428 warn "W: ignoring $loc, unable to determine type\n";
431 push @{$self->{locals}}, $loc;