1 # Copyright (C) 2018-2019 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);
12 my ($class, $v2writable, $shard) = @_;
13 my $self = $class->SUPER::new($v2writable->{-inbox}, 1, $shard);
14 # create the DB before forking:
17 $self->spawn_worker($v2writable, $shard) if $v2writable->{parallel};
22 my ($self, $v2w, $shard) = @_;
24 pipe($r, $w) or die "pipe failed: $!\n";
28 defined $pid or die "fork failed: $!\n";
30 my $bnote = $v2w->atfork_child;
31 close $w or die "failed to close: $!";
33 # F_SETPIPE_SZ = 1031 on Linux; increasing the pipe size here
34 # speeds V2Writable batch imports across 8 cores by nearly 20%
35 fcntl($r, 1031, 1048576) if $^O eq 'linux';
37 eval { shard_worker_loop($self, $v2w, $r, $shard, $bnote) };
38 die "worker $shard died: $@\n" if $@;
39 die "unexpected MM $self->{mm}" if $self->{mm};
44 close $r or die "failed to close: $!";
47 sub shard_worker_loop ($$$$$) {
48 my ($self, $v2w, $r, $shard, $bnote) = @_;
49 $0 = "pi-v2-shard[$shard]";
50 $self->begin_txn_lazy;
51 while (my $line = $r->getline) {
52 $v2w->{current_info} = "[$shard] $line";
53 if ($line eq "commit\n") {
54 $self->commit_txn_lazy;
55 } elsif ($line eq "close\n") {
57 } elsif ($line eq "barrier\n") {
58 $self->commit_txn_lazy;
59 # no need to lock < 512 bytes is atomic under POSIX
60 print $bnote "barrier $shard\n" or
61 die "write failed for barrier $!\n";
62 } elsif ($line =~ /\AD ([a-f0-9]{40,}) (.+)\n\z/s) {
63 my ($oid, $mid) = ($1, $2);
64 $self->begin_txn_lazy;
65 $self->remove_by_oid($oid, $mid);
68 my ($len, $artnum, $oid, $mid0) = split(/ /, $line);
69 $self->begin_txn_lazy;
70 my $n = read($r, my $msg, $len) or die "read: $!\n";
71 $n == $len or die "short read: $n != $len\n";
72 my $mime = PublicInbox::MIME->new(\$msg);
73 $artnum = int($artnum);
74 $self->add_message($mime, $n, $artnum, $oid, $mid0);
80 # called by V2Writable
82 my ($self, $bytes, $msgref, $artnum, $oid, $mid0, $mime) = @_;
83 if (my $w = $self->{w}) {
84 print $w "$bytes $artnum $oid $mid0\n", $$msgref or die
85 "failed to write shard $!\n";
86 $w->flush or die "failed to flush: $!\n";
89 $self->begin_txn_lazy;
90 $self->add_message($mime, $bytes, $artnum, $oid, $mid0);
95 close $_[0]->{w} or die "failed to close write pipe: $!\n";
98 # called by V2Writable:
101 if (my $w = $self->{w}) {
102 print $w "barrier\n" or die "failed to print: $!";
103 $w->flush or die "failed to flush: $!";
105 $self->commit_txn_lazy;