1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # used to interface with a single Xapian shard in V2 repos.
5 # See L<public-inbox-v2-format(5)> for more info on how we shard Xapian
6 package PublicInbox::SearchIdxShard;
9 use base qw(PublicInbox::SearchIdx);
10 use IO::Handle (); # autoflush
13 my ($class, $v2writable, $shard) = @_;
14 my $ibx = $v2writable->{-inbox};
15 my $self = $class->SUPER::new($ibx, 1, $shard);
16 # create the DB before forking:
18 $self->set_indexlevel;
20 $self->spawn_worker($v2writable, $shard) if $v2writable->{parallel};
25 my ($self, $v2w, $shard) = @_;
27 pipe($r, $w) or die "pipe failed: $!\n";
32 defined $pid or die "fork failed: $!\n";
34 my $bnote = $v2w->atfork_child;
35 close $w or die "failed to close: $!";
37 # F_SETPIPE_SZ = 1031 on Linux; increasing the pipe size here
38 # speeds V2Writable batch imports across 8 cores by nearly 20%
39 fcntl($r, 1031, 1048576) if $^O eq 'linux';
41 eval { shard_worker_loop($self, $v2w, $r, $shard, $bnote) };
42 die "worker $shard died: $@\n" if $@;
43 die "unexpected MM $self->{mm}" if $self->{mm};
48 close $r or die "failed to close: $!";
51 sub shard_worker_loop ($$$$$) {
52 my ($self, $v2w, $r, $shard, $bnote) = @_;
53 $0 = "pi-v2-shard[$shard]";
54 $self->begin_txn_lazy;
55 while (my $line = $r->getline) {
56 $v2w->{current_info} = "[$shard] $line";
57 if ($line eq "commit\n") {
58 $self->commit_txn_lazy;
59 } elsif ($line eq "close\n") {
61 } elsif ($line eq "barrier\n") {
62 $self->commit_txn_lazy;
63 # no need to lock < 512 bytes is atomic under POSIX
64 print $bnote "barrier $shard\n" or
65 die "write failed for barrier $!\n";
66 } elsif ($line =~ /\AD ([a-f0-9]{40,}) (.+)\n\z/s) {
67 my ($oid, $mid) = ($1, $2);
68 $self->begin_txn_lazy;
69 $self->remove_by_oid($oid, $mid);
72 # n.b. $mid may contain spaces(!)
73 my ($bytes, $num, $blob, $ds, $ts, $mid) =
75 $self->begin_txn_lazy;
76 my $n = read($r, my $msg, $bytes) or die "read: $!\n";
77 $n == $bytes or die "short read: $n != $bytes\n";
78 my $mime = PublicInbox::MIME->new(\$msg);
86 }, 'PublicInbox::Smsg';
87 $self->add_message($mime, $smsg);
93 # called by V2Writable
95 my ($self, $msgref, $mime, $smsg) = @_;
96 if (my $w = $self->{w}) {
97 # mid must be last, it can contain spaces (but not LF)
98 print $w join(' ', @$smsg{qw(bytes num blob ds ts mid)}),
99 "\n", $$msgref or die "failed to write shard $!\n";
102 $self->begin_txn_lazy;
103 $self->add_message($mime, $smsg);
108 close $_[0]->{w} or die "failed to close write pipe: $!\n";
111 # called by V2Writable:
114 if (my $w = $self->{w}) {
115 print $w "barrier\n" or die "failed to print: $!";
117 $self->commit_txn_lazy;