Search in sources :

Example 41 with SimpleMessage

use of org.apache.ratis.RaftTestUtil.SimpleMessage in project incubator-ratis by apache.

the class RaftReconfigurationBaseTest method runTestNoChangeRequest.

void runTestNoChangeRequest(CLUSTER cluster) throws Exception {
    final RaftServer.Division leader = RaftTestUtil.waitForLeader(cluster);
    try (final RaftClient client = cluster.createClient(leader.getId())) {
        client.io().send(new SimpleMessage("m"));
        final RaftLog leaderLog = leader.getRaftLog();
        final long committedIndex = leaderLog.getLastCommittedIndex();
        final RaftConfiguration confBefore = cluster.getLeader().getRaftConf();
        // no real configuration change in the request
        final RaftClientReply reply = client.admin().setConfiguration(cluster.getPeers().toArray(RaftPeer.emptyArray()));
        Assert.assertTrue(reply.isSuccess());
        final long newCommittedIndex = leaderLog.getLastCommittedIndex();
        for (long i = committedIndex + 1; i <= newCommittedIndex; i++) {
            final LogEntryProto e = leaderLog.get(i);
            Assert.assertTrue(e.hasMetadataEntry());
        }
        Assert.assertSame(confBefore, cluster.getLeader().getRaftConf());
    }
}
Also used : LogEntryProto(org.apache.ratis.proto.RaftProtos.LogEntryProto) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RaftConfiguration(org.apache.ratis.server.RaftConfiguration) RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClient(org.apache.ratis.client.RaftClient) RaftLog(org.apache.ratis.server.raftlog.RaftLog)

Example 42 with SimpleMessage

use of org.apache.ratis.RaftTestUtil.SimpleMessage in project incubator-ratis by apache.

the class RaftReconfigurationBaseTest method runTestReconfTwice.

void runTestReconfTwice(CLUSTER cluster) throws Exception {
    final RaftPeerId leaderId = RaftTestUtil.waitForLeader(cluster).getId();
    try (final RaftClient client = cluster.createClient(leaderId)) {
        // submit some msgs before reconf
        for (int i = 0; i < STAGING_CATCHUP_GAP * 2; i++) {
            RaftClientReply reply = client.io().send(new SimpleMessage("m" + i));
            Assert.assertTrue(reply.isSuccess());
        }
        final AtomicBoolean reconf1 = new AtomicBoolean(false);
        final AtomicBoolean reconf2 = new AtomicBoolean(false);
        final AtomicReference<RaftPeer[]> finalPeers = new AtomicReference<>(null);
        final AtomicReference<RaftPeer[]> deadPeers = new AtomicReference<>(null);
        CountDownLatch latch = new CountDownLatch(1);
        Thread clientThread = new Thread(() -> {
            try {
                PeerChanges c1 = cluster.addNewPeers(2, true);
                LOG.info("Start changing the configuration: {}", asList(c1.allPeersInNewConf));
                RaftClientReply reply = client.admin().setConfiguration(c1.allPeersInNewConf);
                reconf1.set(reply.isSuccess());
                PeerChanges c2 = cluster.removePeers(2, true, asList(c1.newPeers));
                finalPeers.set(c2.allPeersInNewConf);
                deadPeers.set(c2.removedPeers);
                LOG.info("Start changing the configuration again: {}", asList(c2.allPeersInNewConf));
                reply = client.admin().setConfiguration(c2.allPeersInNewConf);
                reconf2.set(reply.isSuccess());
                latch.countDown();
            } catch (Exception ignored) {
                LOG.warn("{} is ignored", JavaUtils.getClassSimpleName(ignored.getClass()), ignored);
            }
        });
        clientThread.start();
        latch.await();
        Assert.assertTrue(reconf1.get());
        Assert.assertTrue(reconf2.get());
        waitAndCheckNewConf(cluster, finalPeers.get(), 2, null);
        final RaftPeerId leader2 = RaftTestUtil.waitForLeader(cluster).getId();
        // check configuration manager's internal state
        // each reconf will generate two configurations: (old, new) and (new)
        cluster.getServerAliveStream().forEach(server -> {
            final ConfigurationManager confManager = RaftServerTestUtil.getConfigurationManager(server);
            // each reconf will generate two configurations: (old, new) and (new)
            // each leader change generates one configuration.
            // expectedConf = 1 (init) + 2*2 (two conf changes) + #leader
            final int expectedConf = leader2.equals(leaderId) ? 6 : 7;
            Assert.assertEquals(server.getId() + ": " + confManager, expectedConf, confManager.numOfConf());
        });
    }
}
Also used : SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) LeaderNotReadyException(org.apache.ratis.protocol.exceptions.LeaderNotReadyException) TimeoutException(java.util.concurrent.TimeoutException) ReconfigurationInProgressException(org.apache.ratis.protocol.exceptions.ReconfigurationInProgressException) ReconfigurationTimeoutException(org.apache.ratis.protocol.exceptions.ReconfigurationTimeoutException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) PeerChanges(org.apache.ratis.server.impl.MiniRaftCluster.PeerChanges) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftClient(org.apache.ratis.client.RaftClient)

Example 43 with SimpleMessage

use of org.apache.ratis.RaftTestUtil.SimpleMessage in project incubator-ratis by apache.

the class RaftAsyncTests method runTestCheckLeadershipFailure.

void runTestCheckLeadershipFailure(CLUSTER cluster) throws Exception {
    LOG.info("Running testCheckLeadershipFailure");
    waitForLeader(cluster);
    final RaftServer.Division prevLeader = cluster.getLeader();
    final long termOfPrevLeader = prevLeader.getInfo().getCurrentTerm();
    LOG.info("Previous Leader is elected on term {}", termOfPrevLeader);
    try (final RaftClient client = cluster.createClient()) {
        // block append entries request
        cluster.getServerAliveStream().filter(impl -> !impl.getInfo().isLeader()).map(SimpleStateMachine4Testing::get).forEach(peer -> logSyncDelay.setDelayMs(peer.getId().toString(), 1000));
        // trigger append entries request
        client.async().send(new SimpleMessage("abc"));
        // default max election timeout is 300ms, 1s is long enough to
        // trigger failure of LeaderState::checkLeadership()
        Thread.sleep(1000);
        // previous leader should not there.
        cluster.getServerAliveStream().map(RaftServer.Division::getInfo).forEach(info -> Assert.assertTrue(!info.isLeader() || info.getCurrentTerm() > termOfPrevLeader));
    } finally {
        // unblock append entries request
        logSyncDelay.clear();
    }
    waitForLeader(cluster);
    final RaftServer.Division currLeader = cluster.getLeader();
    final long termOfCurrLeader = currLeader.getInfo().getCurrentTerm();
    LOG.info("Current Leader is elected on term {}", termOfCurrLeader);
    // leader on termOfPrevLeader should step-down.
    Assert.assertTrue(termOfPrevLeader < termOfCurrLeader);
}
Also used : RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClient(org.apache.ratis.client.RaftClient)

Example 44 with SimpleMessage

use of org.apache.ratis.RaftTestUtil.SimpleMessage in project incubator-ratis by apache.

the class RaftAsyncTests method runTestRequestAsyncWithRetryFailure.

void runTestRequestAsyncWithRetryFailure(boolean initialMessages, CLUSTER cluster) throws Exception {
    final TimeDuration sleepTime = HUNDRED_MILLIS;
    final RetryLimited retryPolicy = RetryPolicies.retryUpToMaximumCountWithFixedSleep(10, sleepTime);
    try (final RaftClient client = cluster.createClient(null, retryPolicy)) {
        RaftPeerId leader = null;
        if (initialMessages) {
            // cluster is already started, send a few success messages
            leader = RaftTestUtil.waitForLeader(cluster).getId();
            final SimpleMessage[] messages = SimpleMessage.create(10, "initial-");
            final List<CompletableFuture<RaftClientReply>> replies = new ArrayList<>();
            for (int i = 0; i < messages.length; i++) {
                replies.add(client.async().send(messages[i]));
            }
            for (int i = 0; i < messages.length; i++) {
                RaftTestUtil.assertSuccessReply(replies.get(i));
            }
            // kill the only server
            cluster.killServer(leader);
        }
        // now, either the cluster is not yet started or the server is killed.
        final List<CompletableFuture<RaftClientReply>> replies = new ArrayList<>();
        {
            final SimpleMessage[] messages = SimpleMessage.create(10);
            int i = 0;
            // send half of the calls without starting the cluster
            for (; i < messages.length / 2; i++) {
                replies.add(client.async().send(messages[i]));
            }
            // sleep most of the retry time
            sleepTime.apply(t -> t * (retryPolicy.getMaxAttempts() - 1)).sleep();
            // send another half of the calls without starting the cluster
            for (; i < messages.length; i++) {
                replies.add(client.async().send(messages[i]));
            }
            Assert.assertEquals(messages.length, replies.size());
        }
        // sleep again so that the first half calls will fail retries.
        // the second half still have retry time remaining.
        sleepTime.apply(t -> t * 2).sleep();
        if (leader != null) {
            cluster.restartServer(leader, false);
        } else {
            cluster.start();
        }
        // all the calls should fail for ordering guarantee
        for (int i = 0; i < replies.size(); i++) {
            final CheckedRunnable<Exception> getReply = replies.get(i)::get;
            final String name = "retry-failure-" + i;
            if (i == 0) {
                final Throwable t = testFailureCase(name, getReply, ExecutionException.class, RaftRetryFailureException.class);
                assertRaftRetryFailureException((RaftRetryFailureException) t.getCause(), retryPolicy, name);
            } else {
                testFailureCase(name, getReply, ExecutionException.class, AlreadyClosedException.class, RaftRetryFailureException.class);
            }
        }
        testFailureCaseAsync("last-request", () -> client.async().send(new SimpleMessage("last")), AlreadyClosedException.class, RaftRetryFailureException.class);
    }
}
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) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) ArrayList(java.util.ArrayList) ByteString(org.apache.ratis.thirdparty.com.google.protobuf.ByteString) RaftRetryFailureException(org.apache.ratis.protocol.exceptions.RaftRetryFailureException) TimeoutException(java.util.concurrent.TimeoutException) InvalidProtocolBufferException(org.apache.ratis.thirdparty.com.google.protobuf.InvalidProtocolBufferException) AlreadyClosedException(org.apache.ratis.protocol.exceptions.AlreadyClosedException) StateMachineException(org.apache.ratis.protocol.exceptions.StateMachineException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) ExecutionException(java.util.concurrent.ExecutionException) CompletableFuture(java.util.concurrent.CompletableFuture) TimeDuration(org.apache.ratis.util.TimeDuration) RetryLimited(org.apache.ratis.retry.RetryPolicies.RetryLimited) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftClient(org.apache.ratis.client.RaftClient)

Example 45 with SimpleMessage

use of org.apache.ratis.RaftTestUtil.SimpleMessage in project incubator-ratis by apache.

the class RaftAsyncTests method runTestNoRetryWaitOnNotLeaderException.

private void runTestNoRetryWaitOnNotLeaderException(MiniRaftCluster cluster) throws Exception {
    final RaftServer.Division leader = waitForLeader(cluster);
    final List<RaftServer.Division> followers = cluster.getFollowers();
    Assert.assertNotNull(followers);
    Assert.assertEquals(2, followers.size());
    Assert.assertNotSame(leader, followers.get(0));
    Assert.assertNotSame(leader, followers.get(1));
    // send a message to make sure that the leader is ready
    try (final RaftClient client = cluster.createClient(leader.getId())) {
        final CompletableFuture<RaftClientReply> f = client.async().send(new SimpleMessage("first"));
        FIVE_SECONDS.apply(f::get);
    }
    // if sleep interval defined by retry policy is used the test will timeout
    final RetryPolicy r = event -> () -> TimeDuration.valueOf(60, TimeUnit.SECONDS);
    try (final RaftClient client = cluster.createClient(followers.get(0).getId(), cluster.getGroup(), r)) {
        final CompletableFuture<RaftClientReply> f = client.async().send(new SimpleMessage("abc"));
        FIVE_SECONDS.apply(f::get);
    } catch (TimeoutException e) {
        throw new AssertionError("Failed to get async result", e);
    }
}
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) RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RetryPolicy(org.apache.ratis.retry.RetryPolicy) RaftClient(org.apache.ratis.client.RaftClient) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

SimpleMessage (org.apache.ratis.RaftTestUtil.SimpleMessage)52 RaftClient (org.apache.ratis.client.RaftClient)46 RaftClientReply (org.apache.ratis.protocol.RaftClientReply)27 RaftPeerId (org.apache.ratis.protocol.RaftPeerId)20 Test (org.junit.Test)20 RaftServer (org.apache.ratis.server.RaftServer)19 IOException (java.io.IOException)15 RaftClientRpc (org.apache.ratis.client.RaftClientRpc)12 CompletableFuture (java.util.concurrent.CompletableFuture)11 RaftLog (org.apache.ratis.server.raftlog.RaftLog)10 LogEntryProto (org.apache.ratis.proto.RaftProtos.LogEntryProto)9 SimpleStateMachine4Testing (org.apache.ratis.statemachine.SimpleStateMachine4Testing)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 ArrayList (java.util.ArrayList)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 BaseTest (org.apache.ratis.BaseTest)7 MiniRaftCluster (org.apache.ratis.server.impl.MiniRaftCluster)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 RaftClientRequest (org.apache.ratis.protocol.RaftClientRequest)6 File (java.io.File)5