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