Search in sources :

Example 1 with MiniRaftCluster

use of org.apache.ratis.server.impl.MiniRaftCluster in project incubator-ratis by apache.

the class ParameterizedBaseTest method setAndStart.

/**
 * Set {@link #currentCluster} to the given cluster and start it if {@link #currentCluster} is changed.
 */
public static void setAndStart(MiniRaftCluster cluster) throws InterruptedException, IOException {
    final MiniRaftCluster previous = currentCluster.getAndSet(cluster);
    if (previous != cluster) {
        if (previous != null) {
            previous.shutdown();
        }
        cluster.start();
        RaftTestUtil.waitForLeader(cluster);
    }
}
Also used : MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster)

Example 2 with MiniRaftCluster

use of org.apache.ratis.server.impl.MiniRaftCluster in project incubator-ratis by apache.

the class RaftSnapshotBaseTest method getSnapshotFiles.

public static List<File> getSnapshotFiles(MiniRaftCluster cluster, long startIndex, long endIndex) {
    final RaftServer.Division leader = cluster.getLeader();
    final SimpleStateMachineStorage storage = SimpleStateMachine4Testing.get(leader).getStateMachineStorage();
    final long term = leader.getInfo().getCurrentTerm();
    return LongStream.range(startIndex, endIndex).mapToObj(i -> storage.getSnapshotFile(term, i)).collect(Collectors.toList());
}
Also used : RATIS_SERVER_INSTALL_SNAPSHOT_COUNT(org.apache.ratis.server.metrics.RaftServerMetricsImpl.RATIS_SERVER_INSTALL_SNAPSHOT_COUNT) RaftLog(org.apache.ratis.server.raftlog.RaftLog) LogSegmentPath(org.apache.ratis.server.raftlog.segmented.LogSegmentPath) LoggerFactory(org.slf4j.LoggerFactory) RATIS_APPLICATION_NAME_METRICS(org.apache.ratis.metrics.RatisMetrics.RATIS_APPLICATION_NAME_METRICS) Log4jUtils(org.apache.ratis.util.Log4jUtils) RaftServerTestUtil(org.apache.ratis.server.impl.RaftServerTestUtil) Level(org.apache.log4j.Level) After(org.junit.After) Counter(com.codahale.metrics.Counter) RaftServerMetricsImpl(org.apache.ratis.server.metrics.RaftServerMetricsImpl) JavaUtils(org.apache.ratis.util.JavaUtils) Before(org.junit.Before) Logger(org.slf4j.Logger) LongStream(java.util.stream.LongStream) LogEntryProto(org.apache.ratis.proto.RaftProtos.LogEntryProto) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) STATEMACHINE_TAKE_SNAPSHOT_TIMER(org.apache.ratis.server.impl.StateMachineMetrics.STATEMACHINE_TAKE_SNAPSHOT_TIMER) RATIS_STATEMACHINE_METRICS(org.apache.ratis.server.impl.StateMachineMetrics.RATIS_STATEMACHINE_METRICS) Test(org.junit.Test) IOException(java.io.IOException) SimpleStateMachineStorage(org.apache.ratis.statemachine.impl.SimpleStateMachineStorage) BaseTest(org.apache.ratis.BaseTest) RatisMetricRegistry(org.apache.ratis.metrics.RatisMetricRegistry) Collectors(java.util.stream.Collectors) File(java.io.File) RATIS_STATEMACHINE_METRICS_DESC(org.apache.ratis.server.impl.StateMachineMetrics.RATIS_STATEMACHINE_METRICS_DESC) RaftTestUtil(org.apache.ratis.RaftTestUtil) FileUtils(org.apache.ratis.util.FileUtils) MetricRegistries(org.apache.ratis.metrics.MetricRegistries) MetricRegistryInfo(org.apache.ratis.metrics.MetricRegistryInfo) List(java.util.List) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) RaftProperties(org.apache.ratis.conf.RaftProperties) LifeCycle(org.apache.ratis.util.LifeCycle) Optional(java.util.Optional) Timer(com.codahale.metrics.Timer) RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) RaftServer(org.apache.ratis.server.RaftServer) SimpleStateMachineStorage(org.apache.ratis.statemachine.impl.SimpleStateMachineStorage)

Example 3 with MiniRaftCluster

use of org.apache.ratis.server.impl.MiniRaftCluster in project incubator-ratis by apache.

the class TestGrpcMessageMetrics method testGrpcMessageMetrics.

@Test
public void testGrpcMessageMetrics() throws Exception {
    try (final MiniRaftCluster cluster = newCluster(NUM_SERVERS)) {
        cluster.start();
        sendMessages(cluster);
    }
}
Also used : MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) Test(org.junit.Test) BaseTest(org.apache.ratis.BaseTest)

Example 4 with MiniRaftCluster

use of org.apache.ratis.server.impl.MiniRaftCluster in project incubator-ratis by apache.

the class LogAppenderTests method testFollowerHeartbeatMetric.

@Test
public void testFollowerHeartbeatMetric() throws IOException, InterruptedException {
    // Start a 3 node Ratis ring.
    final MiniRaftCluster cluster = newCluster(3);
    cluster.start();
    final RaftServer.Division leaderServer = waitForLeader(cluster);
    // Write 10 messages to leader.
    try (RaftClient client = cluster.createClient(leaderServer.getId())) {
        for (int i = 1; i <= 10; i++) {
            client.io().send(new RaftTestUtil.SimpleMessage("Msg to make leader ready " + i));
        }
    } catch (IOException e) {
        throw e;
    }
    final RatisMetricRegistry ratisMetricRegistry = ((RaftServerMetricsImpl) leaderServer.getRaftServerMetrics()).getRegistry();
    // Get all last_heartbeat_elapsed_time metric gauges. Should be equal to number of followers.
    SortedMap<String, Gauge> heartbeatElapsedTimeGauges = ratisMetricRegistry.getGauges((s, metric) -> s.contains("lastHeartbeatElapsedTime"));
    assertTrue(heartbeatElapsedTimeGauges.size() == 2);
    for (RaftServer.Division followerServer : cluster.getFollowers()) {
        String followerId = followerServer.getId().toString();
        Gauge metric = heartbeatElapsedTimeGauges.entrySet().parallelStream().filter(e -> e.getKey().contains(followerId)).iterator().next().getValue();
        // Metric for this follower exists.
        assertTrue(metric != null);
        // Metric in nanos > 0.
        assertTrue((long) metric.getValue() > 0);
        // Try to get Heartbeat metrics for follower.
        final RaftServerMetricsImpl followerMetrics = (RaftServerMetricsImpl) followerServer.getRaftServerMetrics();
        // Metric should not exist. It only exists in leader.
        assertTrue(followerMetrics.getRegistry().getGauges((s, m) -> s.contains("lastHeartbeatElapsedTime")).isEmpty());
        for (boolean heartbeat : new boolean[] { true, false }) {
            assertTrue(followerMetrics.getFollowerAppendEntryTimer(heartbeat).getMeanRate() > 0.0d);
            assertTrue(followerMetrics.getFollowerAppendEntryTimer(heartbeat).getCount() > 0L);
        }
    }
}
Also used : LogProtoUtils(org.apache.ratis.server.raftlog.LogProtoUtils) Arrays(java.util.Arrays) RaftLog(org.apache.ratis.server.raftlog.RaftLog) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Log4jUtils(org.apache.ratis.util.Log4jUtils) Level(org.apache.log4j.Level) SimpleStateMachine4Testing(org.apache.ratis.statemachine.SimpleStateMachine4Testing) RaftServerMetricsImpl(org.apache.ratis.server.metrics.RaftServerMetricsImpl) JavaUtils(org.apache.ratis.util.JavaUtils) SizeInBytes(org.apache.ratis.util.SizeInBytes) RaftTestUtil.waitForLeader(org.apache.ratis.RaftTestUtil.waitForLeader) StateMachine(org.apache.ratis.statemachine.StateMachine) EnumMap(java.util.EnumMap) LogEntryProto(org.apache.ratis.proto.RaftProtos.LogEntryProto) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) RatisMetricRegistry(org.apache.ratis.metrics.RatisMetricRegistry) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) LogEntryBodyCase(org.apache.ratis.proto.RaftProtos.LogEntryProto.LogEntryBodyCase) LogAppender(org.apache.ratis.server.leader.LogAppender) RaftProperties(org.apache.ratis.conf.RaftProperties) RaftServer(org.apache.ratis.server.RaftServer) Gauge(com.codahale.metrics.Gauge) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) SortedMap(java.util.SortedMap) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) IOException(java.io.IOException) RaftServerMetricsImpl(org.apache.ratis.server.metrics.RaftServerMetricsImpl) Gauge(com.codahale.metrics.Gauge) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) RatisMetricRegistry(org.apache.ratis.metrics.RatisMetricRegistry) RaftClient(org.apache.ratis.client.RaftClient) Test(org.junit.Test)

Example 5 with MiniRaftCluster

use of org.apache.ratis.server.impl.MiniRaftCluster in project incubator-ratis by apache.

the class RaftBasicTests method testWithLoad.

static void testWithLoad(final int numClients, final int numMessages, boolean useAsync, MiniRaftCluster cluster, Logger LOG) throws Exception {
    LOG.info("Running testWithLoad: numClients=" + numClients + ", numMessages=" + numMessages + ", async=" + useAsync);
    waitForLeader(cluster);
    final List<Client4TestWithLoad> clients = Stream.iterate(0, i -> i + 1).limit(numClients).map(i -> new Client4TestWithLoad(i, numMessages, useAsync, cluster, LOG)).collect(Collectors.toList());
    final AtomicInteger lastStep = new AtomicInteger();
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        private int previousLastStep = lastStep.get();

        @Override
        public void run() {
            LOG.info(cluster.printServers());
            LOG.info(BlockRequestHandlingInjection.getInstance().toString());
            LOG.info(cluster.toString());
            clients.forEach(c -> LOG.info("  " + c));
            JavaUtils.dumpAllThreads(s -> LOG.info(s));
            final int last = lastStep.get();
            if (last != previousLastStep) {
                previousLastStep = last;
            } else {
                final RaftServer.Division leader = cluster.getLeader();
                LOG.info("NO PROGRESS at " + last + ", try to restart leader=" + leader);
                if (leader != null) {
                    try {
                        cluster.restartServer(leader.getId(), false);
                        LOG.info("Restarted leader=" + leader);
                    } catch (IOException e) {
                        LOG.error("Failed to restart leader=" + leader);
                    }
                }
            }
        }
    }, 5_000L, 10_000L);
    clients.forEach(Thread::start);
    int count = 0;
    for (; ; ) {
        if (clients.stream().noneMatch(Client4TestWithLoad::isRunning)) {
            break;
        }
        final int n = clients.stream().mapToInt(c -> c.step.get()).sum();
        Assert.assertTrue(n >= lastStep.get());
        if (n - lastStep.get() < 50 * numClients) {
            // Change leader at least 50 steps.
            Thread.sleep(10);
            continue;
        }
        lastStep.set(n);
        count++;
        try {
            RaftServer.Division leader = cluster.getLeader();
            if (leader != null) {
                RaftTestUtil.changeLeader(cluster, leader.getId());
            }
        } catch (IllegalStateException e) {
            LOG.error("Failed to change leader ", e);
        }
    }
    LOG.info("Leader change count=" + count);
    timer.cancel();
    for (Client4TestWithLoad c : clients) {
        if (c.exceptionInClientThread.get() != null) {
            throw new AssertionError(c.exceptionInClientThread.get());
        }
        RaftTestUtil.assertLogEntries(cluster, c.messages);
    }
}
Also used : RetryCacheTestUtil(org.apache.ratis.server.impl.RetryCacheTestUtil) Timer(java.util.Timer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Level(org.apache.log4j.Level) JavaUtils(org.apache.ratis.util.JavaUtils) TimerTask(java.util.TimerTask) BlockRequestHandlingInjection(org.apache.ratis.server.impl.BlockRequestHandlingInjection) RaftTestUtil.waitForLeader(org.apache.ratis.RaftTestUtil.waitForLeader) STATEMACHINE_APPLIED_INDEX_GAUGE(org.apache.ratis.server.impl.StateMachineMetrics.STATEMACHINE_APPLIED_INDEX_GAUGE) Timestamp(org.apache.ratis.util.Timestamp) LogEntryProto(org.apache.ratis.proto.RaftProtos.LogEntryProto) Predicate(java.util.function.Predicate) Set(java.util.Set) RATIS_STATEMACHINE_METRICS(org.apache.ratis.server.impl.StateMachineMetrics.RATIS_STATEMACHINE_METRICS) Collectors(java.util.stream.Collectors) RATIS_STATEMACHINE_METRICS_DESC(org.apache.ratis.server.impl.StateMachineMetrics.RATIS_STATEMACHINE_METRICS_DESC) MetricRegistries(org.apache.ratis.metrics.MetricRegistries) MetricRegistryInfo(org.apache.ratis.metrics.MetricRegistryInfo) List(java.util.List) Stream(java.util.stream.Stream) RaftClientReply(org.apache.ratis.protocol.RaftClientReply) Optional(java.util.Optional) ClientInvocationId(org.apache.ratis.protocol.ClientInvocationId) Gauge(com.codahale.metrics.Gauge) SortedMap(java.util.SortedMap) MiniRaftCluster(org.apache.ratis.server.impl.MiniRaftCluster) TimeDuration(org.apache.ratis.util.TimeDuration) RaftGroupMemberId(org.apache.ratis.protocol.RaftGroupMemberId) RaftLog(org.apache.ratis.server.raftlog.RaftLog) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) RATIS_APPLICATION_NAME_METRICS(org.apache.ratis.metrics.RatisMetrics.RATIS_APPLICATION_NAME_METRICS) Log4jUtils(org.apache.ratis.util.Log4jUtils) RaftServerTestUtil(org.apache.ratis.server.impl.RaftServerTestUtil) RaftServerMetricsImpl(org.apache.ratis.server.metrics.RaftServerMetricsImpl) Logger(org.slf4j.Logger) RaftPeerId(org.apache.ratis.protocol.RaftPeerId) RaftServerConfigKeys(org.apache.ratis.server.RaftServerConfigKeys) RaftClientTestUtil(org.apache.ratis.client.impl.RaftClientTestUtil) STATEMACHINE_APPLY_COMPLETED_GAUGE(org.apache.ratis.server.impl.StateMachineMetrics.STATEMACHINE_APPLY_COMPLETED_GAUGE) Test(org.junit.Test) IOException(java.io.IOException) RatisMetricRegistry(org.apache.ratis.metrics.RatisMetricRegistry) TimeUnit(java.util.concurrent.TimeUnit) ExitUtils(org.apache.ratis.util.ExitUtils) RaftServer(org.apache.ratis.server.RaftServer) SimpleMessage(org.apache.ratis.RaftTestUtil.SimpleMessage) RaftClient(org.apache.ratis.client.RaftClient) Assert(org.junit.Assert) RaftServer(org.apache.ratis.server.RaftServer) IOException(java.io.IOException) Timer(java.util.Timer) TimerTask(java.util.TimerTask) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Aggregations

MiniRaftCluster (org.apache.ratis.server.impl.MiniRaftCluster)11 RaftServer (org.apache.ratis.server.RaftServer)8 Test (org.junit.Test)8 List (java.util.List)7 RaftClient (org.apache.ratis.client.RaftClient)7 RaftServerConfigKeys (org.apache.ratis.server.RaftServerConfigKeys)7 Assert (org.junit.Assert)7 ArrayList (java.util.ArrayList)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 Level (org.apache.log4j.Level)6 RaftProperties (org.apache.ratis.conf.RaftProperties)6 RaftClientReply (org.apache.ratis.protocol.RaftClientReply)6 Log4jUtils (org.apache.ratis.util.Log4jUtils)6 TimeDuration (org.apache.ratis.util.TimeDuration)6 Logger (org.slf4j.Logger)6 IOException (java.io.IOException)5 LogEntryProto (org.apache.ratis.proto.RaftProtos.LogEntryProto)5 RaftPeerId (org.apache.ratis.protocol.RaftPeerId)5 RaftServerTestUtil (org.apache.ratis.server.impl.RaftServerTestUtil)5 TimeUnit (java.util.concurrent.TimeUnit)4