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