1 # Copyright (C) 2018 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, $v2writable, $shard) = @_;
24 pipe($r, $w) or die "pipe failed: $!\n";
28 defined $pid or die "fork failed: $!\n";
30 my $bnote = $v2writable->atfork_child;
32 close $w or die "failed to close: $!";
34 # F_SETPIPE_SZ = 1031 on Linux; increasing the pipe size here
35 # speeds V2Writable batch imports across 8 cores by nearly 20%
36 fcntl($r, 1031, 1048576) if $^O eq 'linux';
38 eval { shard_worker_loop($self, $r, $shard, $bnote) };
39 die "worker $shard died: $@\n" if $@;
40 die "unexpected MM $self->{mm}" if $self->{mm};
45 close $r or die "failed to close: $!";
48 sub shard_worker_loop ($$$$) {
49 my ($self, $r, $shard, $bnote) = @_;
50 $0 = "pi-v2-shard[$shard]";
51 my $current_info = '';
52 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
53 local $SIG{__WARN__} = sub {
55 $warn_cb->("[$shard] $current_info: ", @_);
57 $self->begin_txn_lazy;
58 while (my $line = $r->getline) {
59 $current_info = $line;
60 if ($line eq "commit\n") {
61 $self->commit_txn_lazy;
62 } elsif ($line eq "close\n") {
64 } elsif ($line eq "barrier\n") {
65 $self->commit_txn_lazy;
66 # no need to lock < 512 bytes is atomic under POSIX
67 print $bnote "barrier $shard\n" or
68 die "write failed for barrier $!\n";
69 } elsif ($line =~ /\AD ([a-f0-9]{40,}) (.+)\n\z/s) {
70 my ($oid, $mid) = ($1, $2);
71 $self->begin_txn_lazy;
72 $self->remove_by_oid($oid, $mid);
75 my ($len, $artnum, $oid, $mid0) = split(/ /, $line);
76 $self->begin_txn_lazy;
77 my $n = read($r, my $msg, $len) or die "read: $!\n";
78 $n == $len or die "short read: $n != $len\n";
79 my $mime = PublicInbox::MIME->new(\$msg);
80 $artnum = int($artnum);
81 $self->add_message($mime, $n, $artnum, $oid, $mid0);
87 # called by V2Writable
89 my ($self, $bytes, $msgref, $artnum, $oid, $mid0, $mime) = @_;
90 if (my $w = $self->{w}) {
91 print $w "$bytes $artnum $oid $mid0\n", $$msgref or die
92 "failed to write shard $!\n";
93 $w->flush or die "failed to flush: $!\n";
96 $self->begin_txn_lazy;
97 $self->add_message($mime, $bytes, $artnum, $oid, $mid0);
102 close $_[0]->{w} or die "failed to close write pipe: $!\n";
105 # called by V2Writable:
108 if (my $w = $self->{w}) {
109 print $w "barrier\n" or die "failed to print: $!";
110 $w->flush or die "failed to flush: $!";
112 $self->commit_txn_lazy;