Search in sources :

Example 1 with CommitInfoProto

use of org.apache.ratis.proto.RaftProtos.CommitInfoProto in project incubator-ratis by apache.

the class WatchRequestTests method checkAll.

static void checkAll(List<CompletableFuture<WatchReplies>> watches, Logger LOG) throws Exception {
    for (int i = 0; i < watches.size(); i++) {
        final WatchReplies watchReplies = watches.get(i).get(GET_TIMEOUT_SECOND, TimeUnit.SECONDS);
        final long logIndex = watchReplies.logIndex;
        LOG.info("checkAll {}: logIndex={}", i, logIndex);
        final RaftClientReply watchAllReply = watchReplies.getAll();
        Assert.assertTrue(watchAllReply.isSuccess());
        final RaftClientReply watchAllCommittedReply = watchReplies.getAllCommitted();
        Assert.assertTrue(watchAllCommittedReply.isSuccess());
        {
            // check commit infos
            final Collection<CommitInfoProto> commitInfos = watchAllCommittedReply.getCommitInfos();
            final String message = "logIndex=" + logIndex + ", " + ProtoUtils.toString(commitInfos);
            Assert.assertEquals(NUM_SERVERS, commitInfos.size());
            commitInfos.forEach(info -> Assert.assertTrue(message, logIndex <= info.getCommitIndex()));
        }
    }
}
Also used : RaftRetryFailureException(org.apache.ratis.protocol.exceptions.RaftRetryFailureException) NotReplicatedException(org.apache.ratis.protocol.exceptions.NotReplicatedException) CheckedSupplier(org.apache.ratis.util.function.CheckedSupplier) CompletableFuture(java.util.concurrent.CompletableFuture) RetryPolicies(org.apache.ratis.retry.RetryPolicies) ArrayList(java.util.ArrayList) TimeoutIOException(org.apache.ratis.protocol.exceptions.TimeoutIOException) Log4jUtils(org.apache.ratis.util.Log4jUtils) ReplicationLevel(org.apache.ratis.proto.RaftProtos.ReplicationLevel) ProtoUtils(org.apache.ratis.util.ProtoUtils) RaftServerTestUtil(org.apache.ratis.server.impl.RaftServerTestUtil) CheckedConsumer(org.apache.ratis.util.function.CheckedConsumer) Level(org.apache.log4j.Level) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) AlreadyClosedException(org.apache.ratis.protocol.exceptions.AlreadyClosedException) SimpleStateMachine4Testing(org.apache.ratis.statemachine.SimpleStateMachine4Testing) Assert.fail(org.junit.Assert.fail) Before(org.junit.Before) StateMachine(org.apache.ratis.statemachine.StateMachine) Logger(org.slf4j.Logger) RetryPolicy(org.apache.ratis.retry.RetryPolicy) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) Collection(java.util.Collection) Test(org.junit.Test) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) Stream(java.util.stream.Stream) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RaftProperties(org.apache.ratis.conf.RaftProperties) RaftServer(org.apache.ratis.server.RaftServer) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) RaftClientConfigKeys(org.apache.ratis.client.RaftClientConfigKeys) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) TimeDuration(org.apache.ratis.util.TimeDuration) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) Collection(java.util.Collection)

Example 2 with CommitInfoProto

use of org.apache.ratis.proto.RaftProtos.CommitInfoProto in project incubator-ratis by apache.

the class RaftAsyncTests method runTestStaleReadAsync.

void runTestStaleReadAsync(CLUSTER cluster) throws Exception {
    final int numMesssages = 10;
    try (RaftClient client = cluster.createClient()) {
        RaftTestUtil.waitForLeader(cluster);
        // submit some messages
        final List<CompletableFuture<RaftClientReply>> futures = new ArrayList<>();
        for (int i = 0; i < numMesssages; i++) {
            final String s = "" + i;
            LOG.info("sendAsync " + s);
            futures.add(client.async().send(new SimpleMessage(s)));
        }
        Assert.assertEquals(numMesssages, futures.size());
        final List<RaftClientReply> replies = new ArrayList<>();
        for (CompletableFuture<RaftClientReply> f : futures) {
            final RaftClientReply r = f.join();
            Assert.assertTrue(r.isSuccess());
            replies.add(r);
        }
        futures.clear();
        // Use a follower with the max commit index
        final RaftClientReply lastWriteReply = replies.get(replies.size() - 1);
        final RaftPeerId leader = lastWriteReply.getServerId();
        LOG.info("leader = " + leader);
        final Collection<CommitInfoProto> commitInfos = lastWriteReply.getCommitInfos();
        LOG.info("commitInfos = " + commitInfos);
        final CommitInfoProto followerCommitInfo = commitInfos.stream().filter(info -> !RaftPeerId.valueOf(info.getServer().getId()).equals(leader)).max(Comparator.comparing(CommitInfoProto::getCommitIndex)).get();
        final RaftPeerId follower = RaftPeerId.valueOf(followerCommitInfo.getServer().getId());
        final long followerCommitIndex = followerCommitInfo.getCommitIndex();
        LOG.info("max follower = {}, commitIndex = {}", follower, followerCommitIndex);
        // test a failure case
        testFailureCaseAsync("sendStaleReadAsync(..) with a larger commit index", () -> client.async().sendStaleRead(new SimpleMessage("" + Long.MAX_VALUE), followerCommitInfo.getCommitIndex(), follower), StateMachineException.class, IndexOutOfBoundsException.class);
        // test sendStaleReadAsync
        for (int i = 0; i < numMesssages; i++) {
            final RaftClientReply reply = replies.get(i);
            final String query = "" + i;
            LOG.info("query=" + query + ", reply=" + reply);
            final Message message = new SimpleMessage(query);
            final CompletableFuture<RaftClientReply> readFuture = client.async().sendReadOnly(message);
            futures.add(readFuture.thenCompose(r -> {
                if (reply.getLogIndex() <= followerCommitIndex) {
                    LOG.info("sendStaleReadAsync, query=" + query);
                    return client.async().sendStaleRead(message, followerCommitIndex, follower);
                } else {
                    return CompletableFuture.completedFuture(null);
                }
            }).thenApply(staleReadReply -> {
                if (staleReadReply == null) {
                    return null;
                }
                final ByteString expected = readFuture.join().getMessage().getContent();
                final ByteString computed = staleReadReply.getMessage().getContent();
                try {
                    LOG.info("query " + query + " returns " + LogEntryProto.parseFrom(expected).getStateMachineLogEntry().getLogData().toStringUtf8());
                } catch (InvalidProtocolBufferException e) {
                    throw new CompletionException(e);
                }
                Assert.assertEquals("log entry mismatch for query=" + query, expected, computed);
                return null;
            }));
        }
        JavaUtils.allOf(futures).join();
    }
}
Also used : RaftGroup(org.apache.ratis.protocol.RaftGroup) RaftRetryFailureException(org.apache.ratis.protocol.exceptions.RaftRetryFailureException) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) RetryPolicies(org.apache.ratis.retry.RetryPolicies) InvalidProtocolBufferException(org.apache.ratis.thirdparty.com.google.protobuf.InvalidProtocolBufferException) ArrayList(java.util.ArrayList) Log4jUtils(org.apache.ratis.util.Log4jUtils) Message(org.apache.ratis.protocol.Message) RaftServerTestUtil(org.apache.ratis.server.impl.RaftServerTestUtil) CheckedRunnable(org.apache.ratis.util.function.CheckedRunnable) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteString(org.apache.ratis.thirdparty.com.google.protobuf.ByteString) Level(org.apache.log4j.Level) AlreadyClosedException(org.apache.ratis.protocol.exceptions.AlreadyClosedException) SimpleStateMachine4Testing(org.apache.ratis.statemachine.SimpleStateMachine4Testing) StreamSupport(java.util.stream.StreamSupport) JavaUtils(org.apache.ratis.util.JavaUtils) StateMachineException(org.apache.ratis.protocol.exceptions.StateMachineException) RaftTestUtil.waitForLeader(org.apache.ratis.RaftTestUtil.waitForLeader) StateMachine(org.apache.ratis.statemachine.StateMachine) LogEntryProto(org.apache.ratis.proto.RaftProtos.LogEntryProto) RetryPolicy(org.apache.ratis.retry.RetryPolicy) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) Collection(java.util.Collection) RaftClientTestUtil(org.apache.ratis.client.impl.RaftClientTestUtil) Test(org.junit.Test) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RaftProperties(org.apache.ratis.conf.RaftProperties) RetryLimited(org.apache.ratis.retry.RetryPolicies.RetryLimited) RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) Comparator(java.util.Comparator) RaftClientConfigKeys(org.apache.ratis.client.RaftClientConfigKeys) DelayLocalExecutionInjection(org.apache.ratis.server.impl.DelayLocalExecutionInjection) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) TimeDuration(org.apache.ratis.util.TimeDuration) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) Message(org.apache.ratis.protocol.Message) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) ByteString(org.apache.ratis.thirdparty.com.google.protobuf.ByteString) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) ArrayList(java.util.ArrayList) InvalidProtocolBufferException(org.apache.ratis.thirdparty.com.google.protobuf.InvalidProtocolBufferException) ByteString(org.apache.ratis.thirdparty.com.google.protobuf.ByteString) CompletableFuture(java.util.concurrent.CompletableFuture) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) CompletionException(java.util.concurrent.CompletionException) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftClient(org.apache.ratis.client.RaftClient)

Example 3 with CommitInfoProto

use of org.apache.ratis.proto.RaftProtos.CommitInfoProto in project incubator-ratis by apache.

the class StateMachineUpdater method takeSnapshot.

private void takeSnapshot() {
    final long i;
    try {
        Timer.Context takeSnapshotTimerContext = stateMachineMetrics.getTakeSnapshotTimer().time();
        i = stateMachine.takeSnapshot();
        takeSnapshotTimerContext.stop();
        server.getSnapshotRequestHandler().completeTakingSnapshot(i);
        final long lastAppliedIndex = getLastAppliedIndex();
        if (i > lastAppliedIndex) {
            throw new StateMachineException("Bug in StateMachine: snapshot index = " + i + " > appliedIndex = " + lastAppliedIndex + "; StateMachine class=" + stateMachine.getClass().getName() + ", stateMachine=" + stateMachine);
        }
        stateMachine.getStateMachineStorage().cleanupOldSnapshots(snapshotRetentionPolicy);
    } catch (IOException e) {
        LOG.error(name + ": Failed to take snapshot", e);
        return;
    }
    if (i >= 0) {
        LOG.info("{}: Took a snapshot at index {}", name, i);
        snapshotIndex.updateIncreasingly(i, infoIndexChange);
        final long purgeIndex;
        if (purgeUptoSnapshotIndex) {
            // We can purge up to snapshot index even if all the peers do not have
            // commitIndex up to this snapshot index.
            purgeIndex = i;
        } else {
            final LongStream commitIndexStream = server.getCommitInfos().stream().mapToLong(CommitInfoProto::getCommitIndex);
            purgeIndex = LongStream.concat(LongStream.of(i), commitIndexStream).min().orElse(i);
        }
        raftLog.purge(purgeIndex);
    }
}
Also used : StateMachineException(org.apache.ratis.protocol.exceptions.StateMachineException) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) Timer(com.codahale.metrics.Timer) RaftLogIOException(org.apache.ratis.server.raftlog.RaftLogIOException) IOException(java.io.IOException) LongStream(java.util.stream.LongStream)

Example 4 with CommitInfoProto

use of org.apache.ratis.proto.RaftProtos.CommitInfoProto in project incubator-ratis by apache.

the class LeaderStateImpl method stop.

void stop() {
    this.running = false;
    // do not interrupt event processor since it may be in the middle of logSync
    senders.forEach(LogAppender::stop);
    final NotLeaderException nle = server.generateNotLeaderException();
    final Collection<CommitInfoProto> commitInfos = server.getCommitInfos();
    try {
        final Collection<TransactionContext> transactions = pendingRequests.sendNotLeaderResponses(nle, commitInfos);
        server.getStateMachine().leaderEvent().notifyNotLeader(transactions);
        watchRequests.failWatches(nle);
    } catch (IOException e) {
        LOG.warn("{}: Caught exception in sendNotLeaderResponses", this, e);
    }
    messageStreamRequests.clear();
    server.getServerRpc().notifyNotLeader(server.getMemberId().getGroupId());
    logAppenderMetrics.unregister();
    raftServerMetrics.unregister();
    pendingRequests.close();
}
Also used : NotLeaderException(org.apache.ratis.protocol.exceptions.NotLeaderException) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) LogAppender(org.apache.ratis.server.leader.LogAppender) TransactionContext(org.apache.ratis.statemachine.TransactionContext) IOException(java.io.IOException)

Example 5 with CommitInfoProto

use of org.apache.ratis.proto.RaftProtos.CommitInfoProto in project incubator-ratis by apache.

the class WatchRequestTests method checkMajority.

static void checkMajority(List<CompletableFuture<RaftClientReply>> replies, List<CompletableFuture<WatchReplies>> watches, Logger LOG) throws Exception {
    for (int i = 0; i < replies.size(); i++) {
        final RaftClientReply reply = replies.get(i).get(GET_TIMEOUT_SECOND, TimeUnit.SECONDS);
        LOG.info("checkMajority {}: receive {}", i, reply);
        final long logIndex = reply.getLogIndex();
        Assert.assertTrue(reply.isSuccess());
        final WatchReplies watchReplies = watches.get(i).get(GET_TIMEOUT_SECOND, TimeUnit.SECONDS);
        Assert.assertEquals(logIndex, watchReplies.logIndex);
        final RaftClientReply watchMajorityReply = watchReplies.getMajority();
        Assert.assertTrue(watchMajorityReply.isSuccess());
        final RaftClientReply watchMajorityCommittedReply = watchReplies.getMajorityCommitted();
        Assert.assertTrue(watchMajorityCommittedReply.isSuccess());
        {
            // check commit infos
            final Collection<CommitInfoProto> commitInfos = watchMajorityCommittedReply.getCommitInfos();
            final String message = "logIndex=" + logIndex + ", " + ProtoUtils.toString(commitInfos);
            Assert.assertEquals(NUM_SERVERS, commitInfos.size());
            // One follower has not committed, so min must be less than logIndex
            final long min = commitInfos.stream().map(CommitInfoProto::getCommitIndex).min(Long::compare).get();
            Assert.assertTrue(message, logIndex > min);
            // All other followers have committed
            commitInfos.stream().map(CommitInfoProto::getCommitIndex).sorted(Long::compare).skip(1).forEach(ci -> Assert.assertTrue(message, logIndex <= ci));
        }
    }
}
Also used : RaftRetryFailureException(org.apache.ratis.protocol.exceptions.RaftRetryFailureException) NotReplicatedException(org.apache.ratis.protocol.exceptions.NotReplicatedException) CheckedSupplier(org.apache.ratis.util.function.CheckedSupplier) CompletableFuture(java.util.concurrent.CompletableFuture) RetryPolicies(org.apache.ratis.retry.RetryPolicies) ArrayList(java.util.ArrayList) TimeoutIOException(org.apache.ratis.protocol.exceptions.TimeoutIOException) Log4jUtils(org.apache.ratis.util.Log4jUtils) ReplicationLevel(org.apache.ratis.proto.RaftProtos.ReplicationLevel) ProtoUtils(org.apache.ratis.util.ProtoUtils) RaftServerTestUtil(org.apache.ratis.server.impl.RaftServerTestUtil) CheckedConsumer(org.apache.ratis.util.function.CheckedConsumer) Level(org.apache.log4j.Level) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) AlreadyClosedException(org.apache.ratis.protocol.exceptions.AlreadyClosedException) SimpleStateMachine4Testing(org.apache.ratis.statemachine.SimpleStateMachine4Testing) Assert.fail(org.junit.Assert.fail) Before(org.junit.Before) StateMachine(org.apache.ratis.statemachine.StateMachine) Logger(org.slf4j.Logger) RetryPolicy(org.apache.ratis.retry.RetryPolicy) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) Collection(java.util.Collection) Test(org.junit.Test) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) Stream(java.util.stream.Stream) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RaftProperties(org.apache.ratis.conf.RaftProperties) RaftServer(org.apache.ratis.server.RaftServer) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) RaftClientConfigKeys(org.apache.ratis.client.RaftClientConfigKeys) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) TimeDuration(org.apache.ratis.util.TimeDuration) CommitInfoProto(org.apache.ratis.proto.RaftProtos.CommitInfoProto) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) Collection(java.util.Collection)

Aggregations

CommitInfoProto (org.apache.ratis.proto.RaftProtos.CommitInfoProto)6 Collection (java.util.Collection)4 List (java.util.List)4 Level (org.apache.log4j.Level)4 RaftClient (org.apache.ratis.client.RaftClient)4 RaftServer (org.apache.ratis.server.RaftServer)4 Log4jUtils (org.apache.ratis.util.Log4jUtils)4 Assert (org.junit.Assert)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 ExecutionException (java.util.concurrent.ExecutionException)3 TimeUnit (java.util.concurrent.TimeUnit)3 RaftClientConfigKeys (org.apache.ratis.client.RaftClientConfigKeys)3 RaftProperties (org.apache.ratis.conf.RaftProperties)3 RaftClientReply (org.apache.ratis.protocol.RaftClientReply)3 AlreadyClosedException (org.apache.ratis.protocol.exceptions.AlreadyClosedException)3 RaftRetryFailureException (org.apache.ratis.protocol.exceptions.RaftRetryFailureException)3 RetryPolicies (org.apache.ratis.retry.RetryPolicies)3