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(now);
12 use PublicInbox::PktOp qw(pkt_do);
13 use File::Temp 0.19 (); # 0.19 for ->newdir
15 use PublicInbox::Search qw(xap_terms);
16 use PublicInbox::Spawn qw(popen_rd spawn which);
17 use PublicInbox::MID qw(mids);
18 use PublicInbox::Smsg;
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->{limit} && (($mo->{offset} += $size) < $mo->{limit});
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);
111 return unless $lei->{-progress};
112 if ($lei->{pkt_op_p}) {
113 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
114 } else { # single lei-daemon consumer
115 my ($desc, $mset_size, $mset_total_est) = @_;
116 $lei->{-mset_total} += $mset_size;
117 $lei->err("# $desc $mset_size/$mset_total_est");
121 sub query_thread_mset { # for --thread
122 my ($self, $ibxish) = @_;
123 local $0 = "$0 query_thread_mset";
124 my $lei = $self->{lei};
125 my $startq = delete $lei->{startq};
126 my ($srch, $over) = ($ibxish->search, $ibxish->over);
127 my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
128 return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
129 my $mo = { %{$lei->{mset_opt}} };
131 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
133 $mset = $srch->mset($mo->{qstr}, $mo);
134 mset_progress($lei, $desc, $mset->size,
135 $mset->get_matches_estimated);
136 my $ids = $srch->mset_to_artnums($mset, $mo);
137 my $ctx = { ids => $ids };
139 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
140 while ($over->expand_thread($ctx)) {
141 for my $n (@{$ctx->{xids}}) {
142 my $smsg = $over->get_art($n) or next;
143 wait_startq($startq) if $startq;
144 my $mitem = delete $n2item{$smsg->{num}};
145 $each_smsg->($smsg, $mitem);
147 @{$ctx->{xids}} = ();
149 } while (_mset_more($mset, $mo));
150 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
151 $lei->{ovv}->ovv_atexit_child($lei);
154 sub query_mset { # non-parallel for non-"--thread" users
156 local $0 = "$0 query_mset";
157 my $lei = $self->{lei};
158 my $startq = delete $lei->{startq};
159 my $mo = { %{$lei->{mset_opt}} };
161 for my $loc (locals($self)) {
162 attach_external($self, $loc);
164 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
166 $mset = $self->mset($mo->{qstr}, $mo);
167 mset_progress($lei, 'xsearch', $mset->size,
168 $mset->size, $mset->get_matches_estimated);
169 for my $mitem ($mset->items) {
170 my $smsg = smsg_for($self, $mitem) or next;
171 wait_startq($startq) if $startq;
172 $each_smsg->($smsg, $mitem);
174 } while (_mset_more($mset, $mo));
175 undef $each_smsg; # drops @io for l2m->{each_smsg_done}
176 $lei->{ovv}->ovv_atexit_child($lei);
179 sub each_eml { # callback for MboxReader->mboxrd
180 my ($eml, $self, $lei, $each_smsg) = @_;
181 my $smsg = bless {}, 'PublicInbox::Smsg';
182 $smsg->populate($eml);
183 $smsg->parse_references($eml, mids($eml));
184 $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
185 delete @$smsg{qw(From Subject -ds -ts)};
186 if (my $startq = delete($lei->{startq})) { wait_startq($startq) }
187 if ($lei->{-progress}) {
188 ++$lei->{-nr_remote_eml};
190 my $next = $lei->{-next_progress} //= ($now + 1);
192 $lei->{-next_progress} = $now + 1;
193 my $nr = $lei->{-nr_remote_eml};
194 $lei->err("# $lei->{-current_url} $nr/?");
197 $each_smsg->($smsg, undef, $eml);
200 # PublicInbox::OnDestroy callback
203 kill('KILL', $pid); # spawn() blocks other signals
207 sub query_remote_mboxrd {
208 my ($self, $uris) = @_;
209 local $0 = "$0 query_remote_mboxrd";
210 local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
211 my $lei = $self->{lei};
212 my ($opt, $env) = @$lei{qw(opt env)};
213 my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
214 push(@qform, t => 1) if $opt->{thread};
215 my @cmd = ($self->{curl}, qw(-sSf -d), '');
216 my $verbose = $opt->{verbose};
218 my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
219 fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
220 my $rdr = { 2 => $cerr };
223 # spawn a process to force line-buffering, otherwise curl
224 # will write 1 character at-a-time and parallel outputs
225 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
227 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
228 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
229 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
231 for my $o ($lei->curl_opt) {
232 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
233 if ($o =~ s/=[is]@\z//) {
234 my $ary = $opt->{$o} or next;
235 push @cmd, map { ("--$o", $_) } @$ary;
236 } elsif ($o =~ s/=[is]\z//) {
237 my $val = $opt->{$o} // next;
238 push @cmd, "--$o", $val;
239 } elsif ($opt->{$o}) {
243 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
244 my $tor = $opt->{torsocks} //= 'auto';
245 my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
246 for my $uri (@$uris) {
247 $lei->{-current_url} = $uri->as_string;
248 $lei->{-nr_remote_eml} = 0;
249 $uri->query_form(@qform);
250 my $cmd = [ @cmd, $uri->as_string ];
251 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
252 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
253 unshift @$cmd, which('torsocks');
254 } elsif (PublicInbox::Config::git_bool($tor)) {
255 unshift @$cmd, which('torsocks');
258 # continue anyways if torsocks is missing; a proxy may be
259 # specified via CLI, curlrc, environment variable, or even
261 shift(@$cmd) if !$cmd->[0];
263 $lei->err("# @$cmd") if $verbose;
264 my ($fh, $pid) = popen_rd($cmd, $env, $rdr);
265 $fh = IO::Uncompress::Gunzip->new($fh);
266 PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
268 waitpid($pid, 0) == $pid or die "BUG: waitpid (curl): $!";
270 my $nr = $lei->{-nr_remote_eml};
271 mset_progress($lei, $lei->{-current_url}, $nr, $nr);
274 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
275 my $e = do { local $/; <$cerr> } //
276 die "read(curl stderr): $!\n";
279 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
280 $lei->child_error($?);
281 $uri->query_form(q => $lei->{mset_opt}->{qstr});
282 # --verbose already showed the error via tail(1)
283 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
286 $lei->{ovv}->ovv_atexit_child($lei);
289 # called by LeiOverview::each_smsg_cb
290 sub git { $_[0]->{git_tmp} // die 'BUG: caller did not set {git_tmp}' }
295 my $tmp = File::Temp->newdir("lei_xsearch_git.$$-XXXX", TMPDIR => 1);
296 for my $ibxish (locals($self)) {
297 my $d = File::Spec->canonpath($ibxish->git->{git_dir});
298 $seen{$d} //= push @dirs, "$d/objects\n"
300 my $git_dir = $tmp->dirname;
301 PublicInbox::Import::init_bare($git_dir);
302 my $f = "$git_dir/objects/info/alternates";
303 open my $alt, '>', $f or die "open($f): $!";
304 print $alt @dirs or die "print $f: $!";
305 close $alt or die "close $f: $!";
306 my $git = PublicInbox::Git->new($git_dir);
311 sub query_done { # EOF callback for main daemon
313 my $l2m = delete $lei->{l2m};
314 $l2m->wq_wait_old($lei) if $l2m;
315 if (my $lxs = delete $lei->{lxs}) {
316 $lxs->wq_wait_old($lei);
318 $lei->{ovv}->ovv_end($lei);
319 if ($l2m) { # close() calls LeiToMail reap_compress
320 if (my $out = delete $lei->{old_1}) {
321 if (my $mbout = $lei->{1}) {
322 close($mbout) or return $lei->fail(<<"");
323 Error closing $lei->{ovv}->{dst}: $!
328 $l2m->lock_free ? $l2m->poke_dst : $lei->start_mua;
330 $lei->{-progress} and
331 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
335 sub do_post_augment {
337 eval { $lei->{l2m}->post_augment($lei) };
339 if (my $lxs = delete $lei->{lxs}) {
345 close(delete $lei->{au_done}); # triggers wait_startq
348 my $MAX_PER_HOST = 4;
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;
358 sub start_query { # always runs in main (lei-daemon) process
359 my ($self, $lei) = @_;
360 if (my $l2m = $lei->{l2m}) {
361 $lei->start_mua if $l2m->lock_free;
363 if ($lei->{opt}->{thread}) {
364 for my $ibxish (locals($self)) {
365 $self->wq_do('query_thread_mset', [], $ibxish);
367 } elsif (locals($self)) {
368 $self->wq_do('query_mset', []);
372 for my $uri (remotes($self)) {
373 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
376 $self->wq_do('query_remote_mboxrd', [], $uris);
380 sub ipc_atfork_child {
382 $self->{lei}->lei_atfork_child;
383 $self->SUPER::ipc_atfork_child;
386 sub query_prepare { # called by wq_do
388 local $0 = "$0 query_prepare";
389 my $lei = $self->{lei};
390 eval { $lei->{l2m}->do_augment($lei) };
391 $lei->fail($@) if $@;
392 pkt_do($lei->{pkt_op_p}, '.') == 1 or die "do_post_augment trigger: $!"
395 sub fail_handler ($;$$) {
396 my ($lei, $code, $io) = @_;
397 for my $f (qw(lxs l2m)) {
398 my $wq = delete $lei->{$f} or next;
399 $wq->wq_wait_old($lei) if $wq->wq_kill_old; # lei-daemon
401 close($io) if $io; # needed to avoid warnings on SIGPIPE
402 $lei->x_it($code // (1 >> 8));
405 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
406 fail_handler($_[0], 13, delete $_[0]->{1});
410 my ($self, $lei) = @_;
412 '|' => [ \&sigpipe_handler, $lei ],
413 '!' => [ \&fail_handler, $lei ],
414 '.' => [ \&do_post_augment, $lei ],
415 '' => [ \&query_done, $lei ],
416 'mset_progress' => [ \&mset_progress, $lei ],
417 'x_it' => [ $lei->can('x_it'), $lei ],
418 'child_error' => [ $lei->can('child_error'), $lei ],
420 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
421 $lei->{1}->autoflush(1);
422 $lei->start_pager if delete $lei->{need_pager};
423 $lei->{ovv}->ovv_begin($lei);
424 my $l2m = $lei->{l2m};
426 $l2m->pre_augment($lei);
427 $l2m->wq_workers_start('lei2mail', $l2m->{jobs},
428 $lei->oldset, { lei => $lei });
429 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
431 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
433 if (!$lei->{opt}->{thread} && locals($self)) { # for query_mset
434 # lei->{git_tmp} is set for wq_wait_old so we don't
435 # delete until all lei2mail + lei_xsearch workers are reaped
436 $lei->{git_tmp} = $self->{git_tmp} = git_tmp($self);
438 $self->wq_workers_start('lei_xsearch', $self->{jobs},
439 $lei->oldset, { lei => $lei });
440 my $op = delete $lei->{pkt_op_c};
441 delete $lei->{pkt_op_p};
442 $l2m->wq_close(1) if $l2m;
443 $lei->event_step_init; # wait for shutdowns
444 $self->wq_do('query_prepare', []) if $l2m;
445 start_query($self, $lei);
446 $self->wq_close(1); # lei_xsearch workers stop when done
447 if ($lei->{oneshot}) {
448 while ($op->{sock}) { $op->event_step }
453 my ($self, $uri) = @_;
454 if (my $curl = $self->{curl} //= which('curl') // 0) {
455 require PublicInbox::MboxReader;
456 require IO::Uncompress::Gunzip;
457 push @{$self->{remotes}}, $uri;
459 warn "curl missing, ignoring $uri\n";
463 sub prepare_external {
464 my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
465 if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
466 return add_uri($self, $loc) if $loc->can('scheme');
467 } elsif ($loc =~ m!\Ahttps?://!) {
469 return add_uri($self, URI->new($loc));
470 } elsif (-f "$loc/ei.lock") {
471 require PublicInbox::ExtSearch;
472 $loc = PublicInbox::ExtSearch->new($loc);
473 } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
474 require PublicInbox::Inbox; # v2, v1
475 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
477 warn "W: ignoring $loc, unable to determine type\n";
480 push @{$self->{locals}}, $loc;