]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei_xsearch: ensure curl.err and tail(1) cleanup happens
[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 query_thread_mset { # for --thread
111         my ($self, $lei, $ibxish) = @_;
112         local $0 = "$0 query_thread_mset";
113         $lei->atfork_child_wq($self);
114         my $startq = delete $lei->{startq};
115
116         my ($srch, $over) = ($ibxish->search, $ibxish->over);
117         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
118         return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
119         my $mo = { %{$lei->{mset_opt}} };
120         my $mset;
121         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
122         do {
123                 $mset = $srch->mset($mo->{qstr}, $mo);
124                 pkt_do($lei->{pkt_op}, 'mset_progress', $desc, $mset->size,
125                                 $mset->get_matches_estimated);
126                 my $ids = $srch->mset_to_artnums($mset, $mo);
127                 my $ctx = { ids => $ids };
128                 my $i = 0;
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);
136                         }
137                         @{$ctx->{xids}} = ();
138                 }
139         } while (_mset_more($mset, $mo));
140         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
141         $lei->{ovv}->ovv_atexit_child($lei);
142 }
143
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}} };
150         my $mset;
151         for my $loc (locals($self)) {
152                 attach_external($self, $loc);
153         }
154         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
155         do {
156                 $mset = $self->mset($mo->{qstr}, $mo);
157                 pkt_do($lei->{pkt_op}, 'mset_progress', 'xsearch',
158                                 $mset->size, $mset->get_matches_estimated);
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($lei->{startq})) { wait_startq($startq) }
177         ++$lei->{-nr_remote_eml};
178         if (!$lei->{opt}->{quiet}) {
179                 my $now = now();
180                 my $next = $lei->{-next_progress} //= ($now + 1);
181                 if ($now > $next) {
182                         $lei->{-next_progress} = $now + 1;
183                         my $nr = $lei->{-nr_remote_eml};
184                         $lei->err("# $lei->{-current_url} $nr/?");
185                 }
186         }
187         $each_smsg->($smsg, undef, $eml);
188 }
189
190 # PublicInbox::OnDestroy callback
191 sub kill_reap {
192         my ($pid) = @_;
193         kill('KILL', $pid); # spawn() blocks other signals
194         waitpid($pid, 0);
195 }
196
197 sub query_remote_mboxrd {
198         my ($self, $lei, $uris) = @_;
199         local $0 = "$0 query_remote_mboxrd";
200         $lei->atfork_child_wq($self);
201         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
202         my ($opt, $env) = @$lei{qw(opt env)};
203         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
204         push(@qform, t => 1) if $opt->{thread};
205         my @cmd = ($self->{curl}, qw(-sSf -d), '');
206         my $verbose = $opt->{verbose};
207         my $reap;
208         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
209         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
210         my $rdr = { 2 => $cerr };
211         my $coff = 0;
212         if ($verbose) {
213                 # spawn a process to force line-buffering, otherwise curl
214                 # will write 1 character at-a-time and parallel outputs
215                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
216                 push @cmd, '-v';
217                 my $o = { 1 => $lei->{2}, 2 => $lei->{2} };
218                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
219                 $reap = PublicInbox::OnDestroy->new(\&kill_reap, $pid);
220         }
221         for my $o ($lei->curl_opt) {
222                 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
223                 if ($o =~ s/=[is]@\z//) {
224                         my $ary = $opt->{$o} or next;
225                         push @cmd, map { ("--$o", $_) } @$ary;
226                 } elsif ($o =~ s/=[is]\z//) {
227                         my $val = $opt->{$o} // next;
228                         push @cmd, "--$o", $val;
229                 } elsif ($opt->{$o}) {
230                         push @cmd, "--$o";
231                 }
232         }
233         $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
234         my $tor = $opt->{torsocks} //= 'auto';
235         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
236         for my $uri (@$uris) {
237                 $lei->{-current_url} = $uri->as_string;
238                 $lei->{-nr_remote_eml} = 0;
239                 $uri->query_form(@qform);
240                 my $cmd = [ @cmd, $uri->as_string ];
241                 if ($tor eq 'auto' && substr($uri->host, -6) eq '.onion' &&
242                                 (($env->{LD_PRELOAD}//'') !~ /torsocks/)) {
243                         unshift @$cmd, which('torsocks');
244                 } elsif (PublicInbox::Config::git_bool($tor)) {
245                         unshift @$cmd, which('torsocks');
246                 }
247
248                 # continue anyways if torsocks is missing; a proxy may be
249                 # specified via CLI, curlrc, environment variable, or even
250                 # firewall rule
251                 shift(@$cmd) if !$cmd->[0];
252
253                 $lei->err("# @$cmd") if $verbose;
254                 $? = 0;
255                 my $fh = popen_rd($cmd, $env, $rdr);
256                 $fh = IO::Uncompress::Gunzip->new($fh);
257                 eval {
258                         PublicInbox::MboxReader->mboxrd($fh, \&each_eml, $self,
259                                                         $lei, $each_smsg);
260                 };
261                 return $lei->fail("E: @$cmd: $@") if $@;
262                 if ($? == 0) {
263                         my $nr = $lei->{-nr_remote_eml};
264                         pkt_do($lei->{pkt_op}, 'mset_progress',
265                                 $lei->{-current_url}, $nr, $nr);
266                         next;
267                 }
268                 seek($cerr, $coff, SEEK_SET) or warn "seek(curl stderr): $!\n";
269                 my $e = do { local $/; <$cerr> } //
270                                 die "read(curl stderr): $!\n";
271                 $coff += length($e);
272                 truncate($cerr, 0);
273                 next if (($? >> 8) == 22 && $e =~ /\b404\b/);
274                 $lei->child_error($?);
275                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
276                 # --verbose already showed the error via tail(1)
277                 $lei->err("E: $uri \$?=$?\n", $verbose ? () : $e);
278         }
279         undef $each_smsg;
280         $lei->{ovv}->ovv_atexit_child($lei);
281 }
282
283 sub git {
284         my ($self) = @_;
285         my (%seen, @dirs);
286         my $tmp = File::Temp->newdir('lei_xsrch_git-XXXXXXXX', TMPDIR => 1);
287         for my $ibx (@{$self->{shard2ibx} // []}) {
288                 my $d = File::Spec->canonpath($ibx->git->{git_dir});
289                 $seen{$d} //= push @dirs, "$d/objects\n"
290         }
291         my $git_dir = $tmp->dirname;
292         PublicInbox::Import::init_bare($git_dir);
293         my $f = "$git_dir/objects/info/alternates";
294         open my $alt, '>', $f or die "open($f): $!";
295         print $alt @dirs or die "print $f: $!";
296         close $alt or die "close $f: $!";
297         my $git = PublicInbox::Git->new($git_dir);
298         $git->{-tmp} = $tmp;
299         $git;
300 }
301
302 sub query_done { # EOF callback
303         my ($lei) = @_;
304         my $has_l2m = exists $lei->{l2m};
305         for my $f (qw(lxs l2m)) {
306                 my $wq = delete $lei->{$f} or next;
307                 $wq->wq_wait_old($lei);
308         }
309         $lei->{ovv}->ovv_end($lei);
310         if ($has_l2m) { # close() calls LeiToMail reap_compress
311                 if (my $out = delete $lei->{old_1}) {
312                         if (my $mbout = $lei->{1}) {
313                                 close($mbout) or return $lei->fail(<<"");
314 Error closing $lei->{ovv}->{dst}: $!
315
316                         }
317                         $lei->{1} = $out;
318                 }
319                 $lei->start_mua;
320         }
321         $lei->{opt}->{quiet} or
322                 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
323         $lei->dclose;
324 }
325
326 sub mset_progress { # called via pkt_op/pkt_do from workers
327         my ($lei, $pargs) = @_;
328         my ($desc, $mset_size, $mset_total_est) = @$pargs;
329         return if $lei->{opt}->{quiet};
330         $lei->{-mset_total} += $mset_size;
331         $lei->err("# $desc $mset_size/$mset_total_est");
332 }
333
334 sub do_post_augment {
335         my ($lei, $zpipe, $au_done) = @_;
336         my $l2m = $lei->{l2m} or die 'BUG: no {l2m}';
337         eval { $l2m->post_augment($lei, $zpipe) };
338         if (my $err = $@) {
339                 if (my $lxs = delete $lei->{lxs}) {
340                         $lxs->wq_kill;
341                         $lxs->wq_close;
342                 }
343                 $lei->fail("$err");
344         }
345         close $au_done; # triggers wait_startq
346 }
347
348 my $MAX_PER_HOST = 4;
349 sub MAX_PER_HOST { $MAX_PER_HOST }
350
351 sub concurrency {
352         my ($self, $opt) = @_;
353         my $nl = $opt->{thread} ? locals($self) : 1;
354         my $nr = remotes($self);
355         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
356         $nl + $nr;
357 }
358
359 sub start_query { # always runs in main (lei-daemon) process
360         my ($self, $io, $lei) = @_;
361         if ($lei->{opt}->{thread}) {
362                 for my $ibxish (locals($self)) {
363                         $self->wq_do('query_thread_mset', $io, $lei, $ibxish);
364                 }
365         } elsif (locals($self)) {
366                 $self->wq_do('query_mset', $io, $lei);
367         }
368         my $i = 0;
369         my $q = [];
370         for my $uri (remotes($self)) {
371                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
372         }
373         for my $uris (@$q) {
374                 $self->wq_do('query_remote_mboxrd', $io, $lei, $uris);
375         }
376         @$io = ();
377 }
378
379 sub query_prepare { # called by wq_do
380         my ($self, $lei) = @_;
381         local $0 = "$0 query_prepare";
382         $lei->atfork_child_wq($self);
383         delete $lei->{l2m}->{-wq_s1};
384         eval { $lei->{l2m}->do_augment($lei) };
385         $lei->fail($@) if $@;
386         pkt_do($lei->{pkt_op}, '.') == 1 or die "do_post_augment trigger: $!"
387 }
388
389 sub fail_handler ($;$$) {
390         my ($lei, $code, $io) = @_;
391         for my $f (qw(lxs l2m)) {
392                 my $wq = delete $lei->{$f} or next;
393                 $wq->wq_wait_old($lei) if $wq->wq_kill_old; # lei-daemon
394         }
395         close($io) if $io; # needed to avoid warnings on SIGPIPE
396         $lei->x_it($code // (1 >> 8));
397 }
398
399 sub sigpipe_handler { # handles SIGPIPE from l2m/lxs workers
400         fail_handler($_[0], 13, delete $_[0]->{1});
401 }
402
403 sub do_query {
404         my ($self, $lei) = @_;
405         $lei->{1}->autoflush(1);
406         my ($au_done, $zpipe);
407         my $l2m = $lei->{l2m};
408         if ($l2m) {
409                 pipe($lei->{startq}, $au_done) or die "pipe: $!";
410                 # 1031: F_SETPIPE_SZ
411                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
412                 $zpipe = $l2m->pre_augment($lei);
413         }
414         my $ops = {
415                 '|' => [ \&sigpipe_handler, $lei ],
416                 '!' => [ \&fail_handler, $lei ],
417                 '.' => [ \&do_post_augment, $lei, $zpipe, $au_done ],
418                 '' => [ \&query_done, $lei ],
419                 'mset_progress' => [ \&mset_progress, $lei ],
420         };
421         (my $op, $lei->{pkt_op}) = PublicInbox::PktOp->pair($ops, !$lei->{oneshot});
422         my ($lei_ipc, @io) = $lei->atfork_parent_wq($self);
423         delete($lei->{pkt_op});
424
425         $lei->event_step_init; # wait for shutdowns
426         if ($l2m) {
427                 $self->wq_do('query_prepare', \@io, $lei_ipc);
428                 $io[1] = $zpipe->[1] if $zpipe;
429         }
430         start_query($self, \@io, $lei_ipc);
431         $self->wq_close(1);
432         if ($lei->{oneshot}) {
433                 # for the $lei_ipc->atfork_child_wq PIPE handler:
434                 while ($op->{sock}) { $op->event_step }
435         }
436 }
437
438 sub add_uri {
439         my ($self, $uri) = @_;
440         if (my $curl = $self->{curl} //= which('curl') // 0) {
441                 require PublicInbox::MboxReader;
442                 require IO::Uncompress::Gunzip;
443                 push @{$self->{remotes}}, $uri;
444         } else {
445                 warn "curl missing, ignoring $uri\n";
446         }
447 }
448
449 sub prepare_external {
450         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
451         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
452                 return add_uri($self, $loc) if $loc->can('scheme');
453         } elsif ($loc =~ m!\Ahttps?://!) {
454                 require URI;
455                 return add_uri($self, URI->new($loc));
456         } elsif (-f "$loc/ei.lock") {
457                 require PublicInbox::ExtSearch;
458                 $loc = PublicInbox::ExtSearch->new($loc);
459         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
460                 require PublicInbox::Inbox; # v2, v1
461                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
462         } else {
463                 warn "W: ignoring $loc, unable to determine type\n";
464                 return;
465         }
466         push @{$self->{locals}}, $loc;
467 }
468
469
470 1;