]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei q: demangle and quiet curl output
[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::OpPipe;
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);
18 use PublicInbox::MID qw(mids);
19 use Fcntl qw(SEEK_SET F_SETFL O_APPEND O_RDWR);
20
21 sub new {
22         my ($class) = @_;
23         PublicInbox::Search::load_xapian();
24         bless {
25                 qp_flags => $PublicInbox::Search::QP_FLAGS |
26                                 PublicInbox::Search::FLAG_PURE_NOT(),
27         }, $class
28 }
29
30 sub attach_external {
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");
37
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);
44
45                 my $prev = {};
46                 for my $old_ibxish (@{$self->{shard2ibx}}) {
47                         next if $prev == $old_ibxish;
48                         $prev = $old_ibxish;
49                         my @shards = $old_ibxish->search->xdb_shards_flat;
50                         push @{$self->{shards_flat}}, @shards;
51                 }
52                 my $nr = scalar(@{$self->{shards_flat}});
53                 $nr == $expect or die
54                         "BUG: reloaded $nr shards, expected $expect"
55         }
56         push @{$self->{shards_flat}}, @shards;
57         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
58 }
59
60 # returns a list of local inboxes (or count in scalar context)
61 sub locals { @{$_[0]->{locals} // []} }
62
63 sub remotes { @{$_[0]->{remotes} // []} }
64
65 # called by PublicInbox::Search::xdb
66 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
67
68 # like over->get_art
69 sub smsg_for {
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 ];
81         }
82         $smsg->{docid} = $docid;
83         $smsg;
84 }
85
86 sub recent {
87         my ($self, $qstr, $opt) = @_;
88         $opt //= {};
89         $opt->{relevance} //= -2;
90         $self->mset($qstr //= 'bytes:1..', $opt);
91 }
92
93 sub over {}
94
95 sub _mset_more ($$) {
96         my ($mset, $mo) = @_;
97         my $size = $mset->size;
98         $size && (($mo->{offset} += $size) < ($mo->{limit} // 10000));
99 }
100
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 ($) {
104         my ($startq) = @_;
105         $_[0] = undef;
106         read($startq, my $query_prepare_done, 1);
107 }
108
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;
115
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";
120                 return;
121         }
122         my $mo = { %{$lei->{mset_opt}} };
123         my $mset;
124         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
125         do {
126                 $mset = $srch->mset($mo->{qstr}, $mo);
127                 my $ids = $srch->mset_to_artnums($mset, $mo);
128                 my $ctx = { ids => $ids };
129                 my $i = 0;
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);
137                         }
138                         @{$ctx->{xids}} = ();
139                 }
140         } while (_mset_more($mset, $mo));
141         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
142         $lei->{ovv}->ovv_atexit_child($lei);
143 }
144
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}} };
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($self->{5})) { 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         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 = (qw(curl -sSf -d), '');
196         my $verbose = $opt->{verbose};
197         my $reap;
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 };
201         my $coff = 0;
202         if ($verbose) {
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
206                 push @cmd, '-v';
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);
210         }
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}) {
220                         push @cmd, "--$o";
221                 }
222         }
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, 'torsocks';
232                 } elsif (PublicInbox::Config::git_bool($tor)) {
233                         unshift @$cmd, 'torsocks';
234                 }
235                 $lei->err("# @$cmd") if $verbose;
236                 $? = 0;
237                 my $fh = popen_rd($cmd, $env, $rdr);
238                 $fh = IO::Uncompress::Gunzip->new($fh);
239                 eval {
240                         PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
241                                                         $lei, $each_smsg);
242                 };
243                 return $lei->fail("E: @$cmd: $@") if $@;
244                 next unless $?;
245                 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
246                 my $e = do { local $/; <$cerr> } //
247                                 die "read(curl stderr): $!\n";
248                 $coff += length($e);
249                 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
250                 $lei->child_error($?);
251                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
252                 # --verbose already showed the error via tail(1)
253                 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
254         }
255         undef $each_smsg;
256         $lei->{ovv}->ovv_atexit_child($lei);
257 }
258
259 sub git {
260         my ($self) = @_;
261         my (%seen, @dirs);
262         my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
263         for my $ibx (@{$self->{shard2ibx} // []}) {
264                 my $d = File::Spec->canonpath($ibx->git->{git_dir});
265                 $seen{$d} //= push @dirs, "$d/objects\n"
266         }
267         my $git_dir = $tmp->dirname;
268         PublicInbox::Import::init_bare($git_dir);
269         my $f = "$git_dir/objects/info/alternates";
270         open my $alt, '>', $f or die "open($f): $!";
271         print $alt @dirs or die "print $f: $!";
272         close $alt or die "close $f: $!";
273         my $git = PublicInbox::Git->new($git_dir);
274         $git->{-tmp} = $tmp;
275         $git;
276 }
277
278 sub query_done { # EOF callback
279         my ($lei) = @_;
280         my $has_l2m = exists $lei->{l2m};
281         for my $f (qw(lxs l2m)) {
282                 my $wq = delete $lei->{$f} or next;
283                 $wq->wq_wait_old;
284         }
285         $lei->{ovv}->ovv_end($lei);
286         if ($has_l2m) { # close() calls LeiToMail reap_compress
287                 if (my $out = delete $lei->{old_1}) {
288                         if (my $mbout = $lei->{1}) {
289                                 close($mbout) or return $lei->fail(<<"");
290 Error closing $lei->{ovv}->{dst}: $!
291
292                         }
293                         $lei->{1} = $out;
294                 }
295                 $lei->start_mua;
296         }
297         $lei->dclose;
298 }
299
300 sub do_post_augment {
301         my ($lei, $zpipe, $au_done) = @_;
302         my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
303         eval { $l2m->post_augment($lei, $zpipe) };
304         if (my $err = $@) {
305                 if (my $lxs = delete $lei->{lxs}) {
306                         $lxs->wq_kill;
307                         $lxs->wq_close;
308                 }
309                 $lei->fail("$err");
310         }
311         close $au_done; # triggers wait_startq
312 }
313
314 my $MAX_PER_HOST = 4;
315 sub MAX_PER_HOST { $MAX_PER_HOST }
316
317 sub concurrency {
318         my ($self, $opt) = @_;
319         my $nl = $opt->{thread} ? locals($self) : 1;
320         my $nr = remotes($self);
321         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
322         $nl + $nr;
323 }
324
325 sub start_query { # always runs in main (lei-daemon) process
326         my ($self, $io, $lei) = @_;
327         if ($lei->{opt}->{thread}) {
328                 for my $ibxish (locals($self)) {
329                         $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
330                 }
331         } elsif (locals($self)) {
332                 $self->wq_do('query_mset', $io, $lei);
333         }
334         my $i = 0;
335         my $q = [];
336         for my $uri (remotes($self)) {
337                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
338         }
339         for my $uris (@$q) {
340                 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
341         }
342         @$io = ();
343 }
344
345 sub query_prepare { # called by wq_do
346         my ($self, $lei) = @_;
347         local $0 = "$0 query_prepare";
348         my %sig = $lei->atfork_child_wq($self);
349         -p $lei->{0} or die "BUG: \$done pipe expected";
350         local @SIG{keys %sig} = values %sig;
351         eval { $lei->{l2m}->do_augment($lei) };
352         $lei->fail($@) if $@;
353         syswrite($lei->{0}, '.') == 1 or die "do_post_augment trigger: $!";
354 }
355
356 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
357         my ($lei) = @_;
358         my $lxs = delete $lei->{lxs};
359         if ($lxs && $lxs->wq_kill_old) {
360                 kill 'PIPE', $$;
361                 $lxs->wq_wait_old;
362         }
363         close(delete $lei->{1}) if $lei->{1};
364 }
365
366 sub do_query {
367         my ($self, $lei_orig) = @_;
368         my ($lei, @io) = $lei_orig->atfork_parent_wq($self);
369         $io[0] = undef;
370         pipe(my $done, $io[0]) or die "pipe $!";
371         $lei_orig->{1}->autoflush(1);
372
373         $lei_orig->event_step_init; # wait for shutdowns
374         my $done_op = {
375                 '' => [ \&query_done, $lei_orig ],
376                 '!' => [ \&sigpipe_handler, $lei_orig ]
377         };
378         my $in_loop = exists $lei_orig->{sock};
379         $done = PublicInbox::OpPipe->new($done, $done_op, $in_loop);
380         my $l2m = $lei->{l2m};
381         if ($l2m) {
382                 # may redirect $lei->{1} for mbox
383                 my $zpipe = $l2m->pre_augment($lei_orig);
384                 $io[1] = $lei_orig->{1};
385                 pipe(my ($startq, $au_done)) or die "pipe: $!";
386                 $done_op->{'.'} = [ \&do_post_augment, $lei_orig,
387                                         $zpipe, $au_done ];
388                 local $io[4] = *STDERR{GLOB}; # don't send l2m->{-wq_s1}
389                 die "BUG: unexpected \$io[5]: $io[5]" if $io[5];
390                 $self->wq_do('query_prepare', \@io, $lei);
391                 fcntl($startq, 1031, 4096) if $^O eq 'linux'; # F_SETPIPE_SZ
392                 $io[5] = $startq;
393                 $io[1] = $zpipe->[1] if $zpipe;
394         }
395         start_query($self, \@io, $lei);
396         $self->wq_close(1);
397         unless ($in_loop) {
398                 # for the $lei->atfork_child_wq PIPE handler:
399                 while ($done->{sock}) { $done->event_step }
400         }
401 }
402
403 sub ipc_atfork_prepare {
404         my ($self) = @_;
405         if (exists $self->{remotes}) {
406                 require PublicInbox::MboxReader;
407                 require IO::Uncompress::Gunzip;
408         }
409         # FDS: (0: done_wr, 1: stdout|mbox, 2: stderr,
410         #       3: sock, 4: $l2m->{-wq_s1}, 5: $startq)
411         $self->SUPER::ipc_atfork_prepare; # PublicInbox::IPC
412 }
413
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 push(@{$self->{remotes}}, $loc) if $loc->can('scheme');
418         } elsif ($loc =~ m!\Ahttps?://!) {
419                 require URI;
420                 return push(@{$self->{remotes}}, 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';
427         } else {
428                 warn "W: ignoring $loc, unable to determine type\n";
429                 return;
430         }
431         push @{$self->{locals}}, $loc;
432 }
433
434
435 1;