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