]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiXSearch.pm
lei q: fix warning on remote imports
[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 use PublicInbox::ContentHash qw(git_sha);
22
23 sub new {
24         my ($class) = @_;
25         PublicInbox::Search::load_xapian();
26         bless {
27                 qp_flags => $PublicInbox::Search::QP_FLAGS |
28                                 PublicInbox::Search::FLAG_PURE_NOT(),
29         }, $class
30 }
31
32 sub attach_external {
33         my ($self, $ibxish) = @_; # ibxish = ExtSearch or Inbox
34         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
35         my $srch = $ibxish->search or
36                 return warn("$desc not indexed for Xapian\n");
37         my @shards = $srch->xdb_shards_flat or
38                 return warn("$desc has no Xapian shards\n");
39
40         if (delete $self->{xdb}) { # XXX: do we need this?
41                 # clobber existing {xdb} if amending
42                 my $expect = delete $self->{nshard};
43                 my $shards = delete $self->{shards_flat};
44                 scalar(@$shards) == $expect or die
45                         "BUG: {nshard}$expect != shards=".scalar(@$shards);
46
47                 my $prev = {};
48                 for my $old_ibxish (@{$self->{shard2ibx}}) {
49                         next if $prev == $old_ibxish;
50                         $prev = $old_ibxish;
51                         my @shards = $old_ibxish->search->xdb_shards_flat;
52                         push @{$self->{shards_flat}}, @shards;
53                 }
54                 my $nr = scalar(@{$self->{shards_flat}});
55                 $nr == $expect or die
56                         "BUG: reloaded $nr shards, expected $expect"
57         }
58         push @{$self->{shards_flat}}, @shards;
59         push(@{$self->{shard2ibx}}, $ibxish) for (@shards);
60 }
61
62 # returns a list of local inboxes (or count in scalar context)
63 sub locals { @{$_[0]->{locals} // []} }
64
65 sub remotes { @{$_[0]->{remotes} // []} }
66
67 # called by PublicInbox::Search::xdb (usually via ->mset)
68 sub xdb_shards_flat { @{$_[0]->{shards_flat} // []} }
69
70 sub mitem_kw ($$;$) {
71         my ($smsg, $mitem, $flagged) = @_;
72         my $kw = xap_terms('K', $mitem->get_document);
73         $kw->{flagged} = 1 if $flagged;
74         # we keep the empty array here to prevent expensive work in
75         # ->xsmsg_vmd, _unbless_smsg will clobber it iff it's empty
76         $smsg->{kw} = [ sort keys %$kw ];
77 }
78
79 # like over->get_art
80 sub smsg_for {
81         my ($self, $mitem) = @_;
82         # cf. https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
83         my $nshard = $self->{nshard};
84         my $docid = $mitem->get_docid;
85         my $shard = ($docid - 1) % $nshard;
86         my $num = int(($docid - 1) / $nshard) + 1;
87         my $ibx = $self->{shard2ibx}->[$shard];
88         my $smsg = $ibx->over->get_art($num);
89         return if $smsg->{bytes} == 0;
90         mitem_kw($smsg, $mitem) if $ibx->can('msg_keywords');
91         $smsg;
92 }
93
94 sub recent {
95         my ($self, $qstr, $opt) = @_;
96         $opt //= {};
97         $opt->{relevance} //= -2;
98         $self->mset($qstr //= 'z:1..', $opt);
99 }
100
101 sub over {}
102
103 sub _mset_more ($$) {
104         my ($mset, $mo) = @_;
105         my $size = $mset->size;
106         $size >= $mo->{limit} && (($mo->{offset} += $size) < $mo->{limit});
107 }
108
109 # $startq will EOF when do_augment is done augmenting and allow
110 # query_mset and query_thread_mset to proceed.
111 sub wait_startq ($) {
112         my ($lei) = @_;
113         my $startq = delete $lei->{startq} or return;
114         while (1) {
115                 my $n = sysread($startq, my $do_augment_done, 1);
116                 if (defined $n) {
117                         return if $n == 0; # no MUA
118                         if ($do_augment_done eq 'q') {
119                                 $lei->{opt}->{quiet} = 1;
120                                 delete $lei->{opt}->{verbose};
121                                 delete $lei->{-progress};
122                         } else {
123                                 $lei->fail("$$ WTF `$do_augment_done'");
124                         }
125                         return;
126                 }
127                 return $lei->fail("$$ wait_startq: $!") unless $!{EINTR};
128         }
129 }
130
131 sub mset_progress {
132         my $lei = shift;
133         return if $lei->{early_mua} || !$lei->{-progress};
134         if ($lei->{pkt_op_p}) {
135                 pkt_do($lei->{pkt_op_p}, 'mset_progress', @_);
136         } else { # single lei-daemon consumer
137                 my ($desc, $mset_size, $mset_total_est) = @_;
138                 $lei->{-mset_total} += $mset_size;
139                 $lei->qerr("# $desc $mset_size/$mset_total_est");
140         }
141 }
142
143 sub query_thread_mset { # for --threads
144         my ($self, $ibxish) = @_;
145         local $0 = "$0 query_thread_mset";
146         my $lei = $self->{lei};
147         my ($srch, $over) = ($ibxish->search, $ibxish->over);
148         my $desc = $ibxish->{inboxdir} // $ibxish->{topdir};
149         return warn("$desc not indexed by Xapian\n") unless ($srch && $over);
150         my $mo = { %{$lei->{mset_opt}} };
151         my $mset;
152         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $ibxish);
153         my $can_kw = !!$ibxish->can('msg_keywords');
154         my $fl = $lei->{opt}->{threads} > 1 ? 1 : undef;
155         do {
156                 $mset = $srch->mset($mo->{qstr}, $mo);
157                 mset_progress($lei, $desc, $mset->size,
158                                 $mset->get_matches_estimated);
159                 my $ids = $srch->mset_to_artnums($mset, $mo);
160                 my $ctx = { ids => $ids };
161                 my $i = 0;
162                 my %n2item = map { ($ids->[$i++], $_) } $mset->items;
163                 while ($over->expand_thread($ctx)) {
164                         for my $n (@{$ctx->{xids}}) {
165                                 my $smsg = $over->get_art($n) or next;
166                                 my $mitem = delete $n2item{$smsg->{num}};
167                                 next if $smsg->{bytes} == 0;
168                                 wait_startq($lei); # wait for keyword updates
169                                 if ($mitem) {
170                                         if ($can_kw) {
171                                                 mitem_kw($smsg, $mitem, $fl);
172                                         } elsif ($fl) {
173                                                 $smsg->{lei_q_tt_flagged} = 1;
174                                         }
175                                 }
176                                 $each_smsg->($smsg, $mitem);
177                         }
178                         @{$ctx->{xids}} = ();
179                 }
180         } while (_mset_more($mset, $mo));
181         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
182         $lei->{ovv}->ovv_atexit_child($lei);
183 }
184
185 sub query_mset { # non-parallel for non-"--threads" users
186         my ($self) = @_;
187         local $0 = "$0 query_mset";
188         my $lei = $self->{lei};
189         my $mo = { %{$lei->{mset_opt}} };
190         my $mset;
191         for my $loc (locals($self)) {
192                 attach_external($self, $loc);
193         }
194         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei, $self);
195         do {
196                 $mset = $self->mset($mo->{qstr}, $mo);
197                 mset_progress($lei, 'xsearch', $mset->size,
198                                 $mset->size, $mset->get_matches_estimated);
199                 for my $mitem ($mset->items) {
200                         my $smsg = smsg_for($self, $mitem) or next;
201                         wait_startq($lei);
202                         $each_smsg->($smsg, $mitem);
203                 }
204         } while (_mset_more($mset, $mo));
205         undef $each_smsg; # drops @io for l2m->{each_smsg_done}
206         $lei->{ovv}->ovv_atexit_child($lei);
207 }
208
209 sub each_remote_eml { # callback for MboxReader->mboxrd
210         my ($eml, $self, $lei, $each_smsg) = @_;
211         my $xoids = $lei->{ale}->xoids_for($eml, 1);
212         if ($self->{import_sto} && !$xoids) {
213                 $self->{import_sto}->ipc_do('add_eml', $eml);
214         }
215         my $smsg = bless {}, 'PublicInbox::Smsg';
216         $smsg->{blob} = $xoids ? (keys(%$xoids))[0]
217                                 : git_sha(1, $eml)->hexdigest;
218         $smsg->populate($eml);
219         $smsg->parse_references($eml, mids($eml));
220         $smsg->{$_} //= '' for qw(from to cc ds subject references mid);
221         delete @$smsg{qw(From Subject -ds -ts)};
222         wait_startq($lei);
223         if ($lei->{-progress}) {
224                 ++$lei->{-nr_remote_eml};
225                 my $now = now();
226                 my $next = $lei->{-next_progress} //= ($now + 1);
227                 if ($now > $next) {
228                         $lei->{-next_progress} = $now + 1;
229                         my $nr = $lei->{-nr_remote_eml};
230                         $lei->err("# $lei->{-current_url} $nr/?");
231                 }
232         }
233         $each_smsg->($smsg, undef, $eml);
234 }
235
236 sub query_remote_mboxrd {
237         my ($self, $uris) = @_;
238         local $0 = "$0 query_remote_mboxrd";
239         local $SIG{TERM} = sub { exit(0) }; # for DESTROY (File::Temp, $reap)
240         my $lei = $self->{lei};
241         my $opt = $lei->{opt};
242         my @qform = (q => $lei->{mset_opt}->{qstr}, x => 'm');
243         push(@qform, t => 1) if $opt->{threads};
244         my $verbose = $opt->{verbose};
245         my ($reap_tail, $reap_curl);
246         my $cerr = File::Temp->new(TEMPLATE => 'curl.err-XXXX', TMPDIR => 1);
247         fcntl($cerr, F_SETFL, O_APPEND|O_RDWR) or warn "set O_APPEND: $!";
248         my $rdr = { 2 => $cerr, pgid => 0 };
249         my $sigint_reap = $lei->can('sigint_reap');
250         if ($verbose) {
251                 # spawn a process to force line-buffering, otherwise curl
252                 # will write 1 character at-a-time and parallel outputs
253                 # mmmaaayyy llloookkk llliiikkkeee ttthhhiiisss
254                 my $o = { 1 => $lei->{2}, 2 => $lei->{2}, pgid => 0 };
255                 my $pid = spawn(['tail', '-f', $cerr->filename], undef, $o);
256                 $reap_tail = PublicInbox::OnDestroy->new($sigint_reap, $pid);
257         }
258         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
259         push @$curl, '-s', '-d', '';
260         my $each_smsg = $lei->{ovv}->ovv_each_smsg_cb($lei);
261         $self->{import_sto} = $lei->{sto} if $lei->{opt}->{'import-remote'};
262         for my $uri (@$uris) {
263                 $lei->{-current_url} = $uri->as_string;
264                 $lei->{-nr_remote_eml} = 0;
265                 $uri->query_form(@qform);
266                 my $cmd = $curl->for_uri($lei, $uri);
267                 $lei->qerr("# $cmd");
268                 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
269                 $reap_curl = PublicInbox::OnDestroy->new($sigint_reap, $pid);
270                 $fh = IO::Uncompress::Gunzip->new($fh);
271                 PublicInbox::MboxReader->mboxrd($fh, \&each_remote_eml, $self,
272                                                 $lei, $each_smsg);
273                 my $err = waitpid($pid, 0) == $pid ? undef
274                                                 : "BUG: waitpid($cmd): $!";
275                 @$reap_curl = (); # cancel OnDestroy
276                 die $err if $err;
277                 my $nr = $lei->{-nr_remote_eml};
278                 if ($nr && $lei->{sto}) {
279                         my $wait = $lei->{sto}->ipc_do('done');
280                 }
281                 if ($? == 0) {
282                         mset_progress($lei, $lei->{-current_url}, $nr, $nr);
283                         next;
284                 }
285                 $err = '';
286                 if (-s $cerr) {
287                         seek($cerr, 0, SEEK_SET) or
288                                         $lei->err("seek($cmd stderr): $!");
289                         $err = do { local $/; <$cerr> } //
290                                         "read($cmd stderr): $!";
291                         truncate($cerr, 0) or
292                                         $lei->err("truncate($cmd stderr): $!");
293                 }
294                 next if (($? >> 8) == 22 && $err =~ /\b404\b/);
295                 $uri->query_form(q => $lei->{mset_opt}->{qstr});
296                 $lei->child_error($?, "E: <$uri> $err");
297         }
298         undef $each_smsg;
299         $lei->{ovv}->ovv_atexit_child($lei);
300 }
301
302 sub git { $_[0]->{git} // die 'BUG: git uninitialized' }
303
304 sub xsearch_done_wait { # dwaitpid callback
305         my ($arg, $pid) = @_;
306         my ($wq, $lei) = @$arg;
307         $lei->child_error($?, 'non-fatal error from '.ref($wq)) if $?;
308 }
309
310 sub query_done { # EOF callback for main daemon
311         my ($lei) = @_;
312         my $l2m = delete $lei->{l2m};
313         $l2m->wq_wait_old(\&xsearch_done_wait, $lei) if $l2m;
314         if (my $lxs = delete $lei->{lxs}) {
315                 $lxs->wq_wait_old(\&xsearch_done_wait, $lei);
316         }
317         $lei->{ovv}->ovv_end($lei);
318         if ($l2m) { # close() calls LeiToMail reap_compress
319                 if (my $out = delete $lei->{old_1}) {
320                         if (my $mbout = $lei->{1}) {
321                                 close($mbout) or return $lei->fail(<<"");
322 Error closing $lei->{ovv}->{dst}: $!
323
324                         }
325                         $lei->{1} = $out;
326                 }
327                 if ($l2m->lock_free) {
328                         $l2m->poke_dst;
329                         $lei->poke_mua;
330                 } else { # mbox users
331                         delete $l2m->{mbl}; # drop dotlock
332                         $lei->start_mua;
333                 }
334         }
335         $lei->{-progress} and
336                 $lei->err('# ', $lei->{-mset_total} // 0, " matches");
337         $lei->dclose;
338 }
339
340 sub do_post_augment {
341         my ($lei) = @_;
342         my $l2m = $lei->{l2m} or return; # client disconnected
343         my $err;
344         eval { $l2m->post_augment($lei) };
345         $err = $@;
346         if ($err) {
347                 if (my $lxs = delete $lei->{lxs}) {
348                         $lxs->wq_kill;
349                         $lxs->wq_close(0, undef, $lei);
350                 }
351                 $lei->fail("$err");
352         }
353         if (!$err && delete $lei->{early_mua}) { # non-augment case
354                 $lei->start_mua;
355         }
356         close(delete $lei->{au_done}); # triggers wait_startq in lei_xsearch
357 }
358
359 sub incr_post_augment { # called whenever an l2m shard finishes augment
360         my ($lei) = @_;
361         my $l2m = $lei->{l2m} or return; # client disconnected
362         return if ++$lei->{nr_post_augment} != $l2m->{-wq_nr_workers};
363         do_post_augment($lei);
364 }
365
366 my $MAX_PER_HOST = 4;
367
368 sub concurrency {
369         my ($self, $opt) = @_;
370         my $nl = $opt->{threads} ? locals($self) : 1;
371         my $nr = remotes($self);
372         $nr = $MAX_PER_HOST if $nr > $MAX_PER_HOST;
373         $nl + $nr;
374 }
375
376 sub start_query { # always runs in main (lei-daemon) process
377         my ($self) = @_;
378         if ($self->{threads}) {
379                 for my $ibxish (locals($self)) {
380                         $self->wq_io_do('query_thread_mset', [], $ibxish);
381                 }
382         } elsif (locals($self)) {
383                 $self->wq_io_do('query_mset', []);
384         }
385         my $i = 0;
386         my $q = [];
387         for my $uri (remotes($self)) {
388                 push @{$q->[$i++ % $MAX_PER_HOST]}, $uri;
389         }
390         for my $uris (@$q) {
391                 $self->wq_io_do('query_remote_mboxrd', [], $uris);
392         }
393         $self->wq_close(1); # lei_xsearch workers stop when done
394 }
395
396 sub incr_start_query { # called whenever an l2m shard starts do_post_auth
397         my ($self, $l2m) = @_;
398         return if ++$self->{nr_start_query} != $l2m->{-wq_nr_workers};
399         start_query($self);
400 }
401
402 sub ipc_atfork_child {
403         my ($self) = @_;
404         $self->{lei}->lei_atfork_child;
405         $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
406         $self->SUPER::ipc_atfork_child;
407 }
408
409 sub delete_pkt_op { # OnDestroy callback
410         my $unclosed_after_die = delete($_[0])->{pkt_op_p} or return;
411         close $unclosed_after_die;
412 }
413
414 sub do_query {
415         my ($self, $lei) = @_;
416         my $l2m = $lei->{l2m};
417         my $ops = {
418                 '|' => [ $lei->can('sigpipe_handler'), $lei ],
419                 '!' => [ $lei->can('fail_handler'), $lei ],
420                 '.' => [ \&do_post_augment, $lei ],
421                 '+' => [ \&incr_post_augment, $lei ],
422                 '' => [ \&query_done, $lei ],
423                 'mset_progress' => [ \&mset_progress, $lei ],
424                 'x_it' => [ $lei->can('x_it'), $lei ],
425                 'child_error' => [ $lei->can('child_error'), $lei ],
426                 'incr_start_query' => [ \&incr_start_query, $self, $l2m ],
427         };
428         $lei->{auth}->op_merge($ops, $l2m) if $l2m && $lei->{auth};
429         my $od = PublicInbox::OnDestroy->new($$, \&delete_pkt_op, $lei);
430         ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
431         $lei->{1}->autoflush(1);
432         $lei->start_pager if delete $lei->{need_pager};
433         $lei->{ovv}->ovv_begin($lei);
434         if ($l2m) {
435                 $l2m->pre_augment($lei);
436                 if ($lei->{opt}->{augment} && delete $lei->{early_mua}) {
437                         $lei->start_mua;
438                 }
439                 $l2m->wq_workers_start('lei2mail', undef,
440                                         $lei->oldset, { lei => $lei });
441                 pipe($lei->{startq}, $lei->{au_done}) or die "pipe: $!";
442                 # 1031: F_SETPIPE_SZ
443                 fcntl($lei->{startq}, 1031, 4096) if $^O eq 'linux';
444         }
445         $self->wq_workers_start('lei_xsearch', undef,
446                                 $lei->oldset, { lei => $lei });
447         my $op = delete $lei->{pkt_op_c};
448         delete $lei->{pkt_op_p};
449         $self->{threads} = $lei->{opt}->{threads};
450         if ($l2m) {
451                 $l2m->net_merge_complete unless $lei->{auth};
452         } else {
453                 start_query($self);
454         }
455         $lei->event_step_init; # wait for shutdowns
456         if ($lei->{oneshot}) {
457                 while ($op->{sock}) { $op->event_step }
458         }
459 }
460
461 sub add_uri {
462         my ($self, $uri) = @_;
463         if (my $curl = $self->{curl} //= which('curl') // 0) {
464                 require PublicInbox::MboxReader;
465                 require IO::Uncompress::Gunzip;
466                 require PublicInbox::LeiCurl;
467                 push @{$self->{remotes}}, $uri;
468         } else {
469                 warn "curl missing, ignoring $uri\n";
470         }
471 }
472
473 sub prepare_external {
474         my ($self, $loc, $boost) = @_; # n.b. already ordered by boost
475         if (ref $loc) { # already a URI, or PublicInbox::Inbox-like object
476                 return add_uri($self, $loc) if $loc->can('scheme');
477         } elsif ($loc =~ m!\Ahttps?://!) {
478                 require URI;
479                 return add_uri($self, URI->new($loc));
480         } elsif (-f "$loc/ei.lock") {
481                 require PublicInbox::ExtSearch;
482                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
483                 $loc = PublicInbox::ExtSearch->new($loc);
484         } elsif (-f "$loc/inbox.lock" || -d "$loc/public-inbox") {
485                 die "`\\n' not allowed in `$loc'\n" if index($loc, "\n") >= 0;
486                 require PublicInbox::Inbox; # v2, v1
487                 $loc = bless { inboxdir => $loc }, 'PublicInbox::Inbox';
488         } else {
489                 warn "W: ignoring $loc, unable to determine type\n";
490                 return;
491         }
492         push @{$self->{locals}}, $loc;
493 }
494
495
496 1;