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