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