Search in sources :

Example 31 with NodeOptions

use of com.alipay.sofa.jraft.option.NodeOptions in project sofa-jraft by sofastack.

the class NodeTest method testRollbackStateMachineWithReadIndex_Issue317.

/**
 * Test rollback stateMachine with readIndex for issue 317:
 * https://github.com/sofastack/sofa-jraft/issues/317
 */
@Test
public void testRollbackStateMachineWithReadIndex_Issue317() throws Exception {
    final Endpoint addr = new Endpoint(TestUtils.getMyIp(), TestUtils.INIT_PORT);
    final PeerId peer = new PeerId(addr, 0);
    NodeManager.getInstance().addAddress(addr);
    final NodeOptions nodeOptions = createNodeOptionsWithSharedTimer();
    final CountDownLatch applyCompleteLatch = new CountDownLatch(1);
    final CountDownLatch applyLatch = new CountDownLatch(1);
    final CountDownLatch readIndexLatch = new CountDownLatch(1);
    final AtomicInteger currentValue = new AtomicInteger(-1);
    final String errorMsg = this.testName.getMethodName();
    final StateMachine fsm = new StateMachineAdapter() {

        @Override
        public void onApply(final Iterator iter) {
            // Notify that the #onApply is preparing to go.
            readIndexLatch.countDown();
            // Wait for submitting a read-index request
            try {
                applyLatch.await();
            } catch (InterruptedException e) {
                fail();
            }
            int i = 0;
            while (iter.hasNext()) {
                byte[] data = iter.next().array();
                int v = Bits.getInt(data, 0);
                assertEquals(i++, v);
                currentValue.set(v);
            }
            if (i > 0) {
                // rollback
                currentValue.set(i - 1);
                iter.setErrorAndRollback(1, new Status(-1, errorMsg));
                applyCompleteLatch.countDown();
            }
        }
    };
    nodeOptions.setFsm(fsm);
    nodeOptions.setLogUri(this.dataPath + File.separator + "log");
    nodeOptions.setRaftMetaUri(this.dataPath + File.separator + "meta");
    nodeOptions.setSnapshotUri(this.dataPath + File.separator + "snapshot");
    nodeOptions.setInitialConf(new Configuration(Collections.singletonList(peer)));
    final Node node = new NodeImpl("unittest", peer);
    assertTrue(node.init(nodeOptions));
    assertEquals(1, node.listPeers().size());
    assertTrue(node.listPeers().contains(peer));
    while (!node.isLeader()) {
        ;
    }
    int n = 5;
    {
        // apply tasks
        for (int i = 0; i < n; i++) {
            byte[] b = new byte[4];
            Bits.putInt(b, 0, i);
            node.apply(new Task(ByteBuffer.wrap(b), null));
        }
    }
    final AtomicInteger readIndexSuccesses = new AtomicInteger(0);
    {
        // Submit a read-index, wait for #onApply
        readIndexLatch.await();
        final CountDownLatch latch = new CountDownLatch(1);
        node.readIndex(null, new ReadIndexClosure() {

            @Override
            public void run(final Status status, final long index, final byte[] reqCtx) {
                try {
                    if (status.isOk()) {
                        readIndexSuccesses.incrementAndGet();
                    } else {
                        assertTrue("Unexpected status: " + status, status.getErrorMsg().contains(errorMsg) || status.getRaftError() == RaftError.ETIMEDOUT || status.getErrorMsg().contains("Invalid state for readIndex: STATE_ERROR"));
                    }
                } finally {
                    latch.countDown();
                }
            }
        });
        // We have already submit a read-index request,
        // notify #onApply can go right now
        applyLatch.countDown();
        // The state machine is in error state, the node should step down.
        while (node.isLeader()) {
            Thread.sleep(10);
        }
        latch.await();
        applyCompleteLatch.await();
    }
    // No read-index request succeed.
    assertEquals(0, readIndexSuccesses.get());
    assertTrue(n - 1 >= currentValue.get());
    node.shutdown();
    node.join();
}
Also used : Status(com.alipay.sofa.jraft.Status) Task(com.alipay.sofa.jraft.entity.Task) Configuration(com.alipay.sofa.jraft.conf.Configuration) StateMachine(com.alipay.sofa.jraft.StateMachine) Node(com.alipay.sofa.jraft.Node) NodeOptions(com.alipay.sofa.jraft.option.NodeOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Endpoint(com.alipay.sofa.jraft.util.Endpoint) Endpoint(com.alipay.sofa.jraft.util.Endpoint) ReadIndexClosure(com.alipay.sofa.jraft.closure.ReadIndexClosure) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Iterator(com.alipay.sofa.jraft.Iterator) PeerId(com.alipay.sofa.jraft.entity.PeerId) Test(org.junit.Test)

Example 32 with NodeOptions

use of com.alipay.sofa.jraft.option.NodeOptions in project sofa-jraft by sofastack.

the class NodeTest method createNodeOptionsWithSharedTimer.

private NodeOptions createNodeOptionsWithSharedTimer() {
    final NodeOptions options = new NodeOptions();
    options.setSharedElectionTimer(true);
    options.setSharedVoteTimer(true);
    return options;
}
Also used : NodeOptions(com.alipay.sofa.jraft.option.NodeOptions)

Example 33 with NodeOptions

use of com.alipay.sofa.jraft.option.NodeOptions in project sofa-jraft by sofastack.

the class BaseCliRequestProcessorTest method testManyNodes.

@Test
public void testManyNodes() {
    Node node1 = Mockito.mock(Node.class);
    Mockito.when(node1.getGroupId()).thenReturn("test");
    Mockito.when(node1.getNodeId()).thenReturn(new NodeId("test", new PeerId("localhost", 8081)));
    NodeOptions opts = new NodeOptions();
    Mockito.when(node1.getOptions()).thenReturn(opts);
    NodeManager.getInstance().addAddress(new Endpoint("localhost", 8081));
    NodeManager.getInstance().add(node1);
    Node node2 = Mockito.mock(Node.class);
    Mockito.when(node2.getGroupId()).thenReturn("test");
    Mockito.when(node2.getNodeId()).thenReturn(new NodeId("test", new PeerId("localhost", 8082)));
    Mockito.when(node2.getOptions()).thenReturn(opts);
    NodeManager.getInstance().addAddress(new Endpoint("localhost", 8082));
    NodeManager.getInstance().add(node2);
    this.processor = new MockCliRequestProcessor(null, "test");
    this.processor.handleRequest(asyncContext, TestUtils.createPingRequest());
    ErrorResponse resp = (ErrorResponse) asyncContext.getResponseObject();
    assertNotNull(resp);
    assertEquals(RaftError.EINVAL.getNumber(), resp.getErrorCode());
    assertEquals("Peer must be specified since there're 2 nodes in group test", resp.getErrorMsg());
}
Also used : Endpoint(com.alipay.sofa.jraft.util.Endpoint) Node(com.alipay.sofa.jraft.Node) NodeId(com.alipay.sofa.jraft.entity.NodeId) NodeOptions(com.alipay.sofa.jraft.option.NodeOptions) PeerId(com.alipay.sofa.jraft.entity.PeerId) ErrorResponse(com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse) Test(org.junit.Test)

Example 34 with NodeOptions

use of com.alipay.sofa.jraft.option.NodeOptions in project sofa-jraft by sofastack.

the class RemoteFileCopierTest method testInitFail.

@Test
public void testInitFail() {
    Mockito.when(rpcService.connect(new Endpoint("localhost", 8081))).thenReturn(false);
    assertFalse(copier.init("remote://localhost:8081/999", null, new SnapshotCopierOptions(rpcService, timerManager, new RaftOptions(), new NodeOptions())));
}
Also used : RaftOptions(com.alipay.sofa.jraft.option.RaftOptions) SnapshotCopierOptions(com.alipay.sofa.jraft.option.SnapshotCopierOptions) Endpoint(com.alipay.sofa.jraft.util.Endpoint) NodeOptions(com.alipay.sofa.jraft.option.NodeOptions) Test(org.junit.Test)

Example 35 with NodeOptions

use of com.alipay.sofa.jraft.option.NodeOptions in project sofa-jraft by sofastack.

the class CounterServer method main.

public static void main(final String[] args) throws IOException {
    if (args.length != 4) {
        System.out.println("Usage : java com.alipay.sofa.jraft.example.counter.CounterServer {dataPath} {groupId} {serverId} {initConf}");
        System.out.println("Example: java com.alipay.sofa.jraft.example.counter.CounterServer /tmp/server1 counter 127.0.0.1:8081 127.0.0.1:8081,127.0.0.1:8082,127.0.0.1:8083");
        System.exit(1);
    }
    final String dataPath = args[0];
    final String groupId = args[1];
    final String serverIdStr = args[2];
    final String initConfStr = args[3];
    final NodeOptions nodeOptions = new NodeOptions();
    // for test, modify some params
    // set election timeout to 1s
    nodeOptions.setElectionTimeoutMs(1000);
    // disable CLI service。
    nodeOptions.setDisableCli(false);
    // do snapshot every 30s
    nodeOptions.setSnapshotIntervalSecs(30);
    // parse server address
    final PeerId serverId = new PeerId();
    if (!serverId.parse(serverIdStr)) {
        throw new IllegalArgumentException("Fail to parse serverId:" + serverIdStr);
    }
    final Configuration initConf = new Configuration();
    if (!initConf.parse(initConfStr)) {
        throw new IllegalArgumentException("Fail to parse initConf:" + initConfStr);
    }
    // set cluster configuration
    nodeOptions.setInitialConf(initConf);
    // start raft server
    final CounterServer counterServer = new CounterServer(dataPath, groupId, serverId, nodeOptions);
    System.out.println("Started counter server at port:" + counterServer.getNode().getNodeId().getPeerId().getPort());
    // GrpcServer need block to prevent process exit
    CounterGrpcHelper.blockUntilShutdown();
}
Also used : Configuration(com.alipay.sofa.jraft.conf.Configuration) NodeOptions(com.alipay.sofa.jraft.option.NodeOptions) PeerId(com.alipay.sofa.jraft.entity.PeerId)

Aggregations

NodeOptions (com.alipay.sofa.jraft.option.NodeOptions)39 PeerId (com.alipay.sofa.jraft.entity.PeerId)24 Endpoint (com.alipay.sofa.jraft.util.Endpoint)22 Configuration (com.alipay.sofa.jraft.conf.Configuration)18 Test (org.junit.Test)16 Node (com.alipay.sofa.jraft.Node)13 RaftGroupService (com.alipay.sofa.jraft.RaftGroupService)9 RaftOptions (com.alipay.sofa.jraft.option.RaftOptions)9 File (java.io.File)8 RpcServer (com.alipay.sofa.jraft.rpc.RpcServer)7 Before (org.junit.Before)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 SynchronizedClosure (com.alipay.sofa.jraft.closure.SynchronizedClosure)3 NodeId (com.alipay.sofa.jraft.entity.NodeId)3 BootstrapOptions (com.alipay.sofa.jraft.option.BootstrapOptions)3 SnapshotCopierOptions (com.alipay.sofa.jraft.option.SnapshotCopierOptions)3 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 Iterator (com.alipay.sofa.jraft.Iterator)2 StateMachine (com.alipay.sofa.jraft.StateMachine)2