Java Code Examples for com.alipay.sofa.jraft.Status

The following examples show how to use com.alipay.sofa.jraft.Status. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: sofa-jraft   Author: sofastack   File: AbstractPlacementDriverClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean transferLeader(final long regionId, final Peer peer, final boolean refreshConf) {
    Requires.requireNonNull(peer, "peer");
    Requires.requireNonNull(peer.getEndpoint(), "peer.endpoint");
    final String raftGroupId = JRaftHelper.getJRaftGroupId(this.clusterName, regionId);
    final Configuration conf = RouteTable.getInstance().getConfiguration(raftGroupId);
    final Status status = this.cliService.transferLeader(raftGroupId, conf, JRaftHelper.toJRaftPeerId(peer));
    if (status.isOk()) {
        if (refreshConf) {
            refreshRouteConfiguration(regionId);
        }
        return true;
    }
    LOG.error("Fail to [transferLeader], [regionId: {}, peer: {}], status: {}.", regionId, peer, status);
    return false;
}
 
Example #2
Source Project: sofa-jraft   Author: sofastack   File: CliServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Status resetPeer(final String groupId, final PeerId peerId, final Configuration newPeers) {
    Requires.requireTrue(!StringUtils.isBlank(groupId), "Blank group id");
    Requires.requireNonNull(peerId, "Null peerId");
    Requires.requireNonNull(newPeers, "Null new peers");

    if (!this.cliClientService.connect(peerId.getEndpoint())) {
        return new Status(-1, "Fail to init channel to %s", peerId);
    }

    final ResetPeerRequest.Builder rb = ResetPeerRequest.newBuilder() //
        .setGroupId(groupId) //
        .setPeerId(peerId.toString());
    for (final PeerId peer : newPeers) {
        rb.addNewPeers(peer.toString());
    }

    try {
        final Message result = this.cliClientService.resetPeer(peerId.getEndpoint(), rb.build(), null).get();
        return statusFromResponse(result);
    } catch (final Exception e) {
        return new Status(-1, e.getMessage());
    }
}
 
Example #3
Source Project: sofa-jraft   Author: sofastack   File: NodeImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void checkDeadNodes(final Configuration conf, final long monotonicNowMs) {
    // Check learner replicators at first.
    for (PeerId peer : conf.getLearners()) {
        checkReplicator(peer);
    }
    // Ensure quorum nodes alive.
    final List<PeerId> peers = conf.listPeers();
    final Configuration deadNodes = new Configuration();
    if (checkDeadNodes0(peers, monotonicNowMs, true, deadNodes)) {
        return;
    }
    LOG.warn("Node {} steps down when alive nodes don't satisfy quorum, term={}, deadNodes={}, conf={}.",
        getNodeId(), this.currTerm, deadNodes, conf);
    final Status status = new Status();
    status.setError(RaftError.ERAFTTIMEDOUT, "Majority of the group dies: %d/%d", deadNodes.size(), peers.size());
    stepDown(this.currTerm, false, status);
}
 
Example #4
Source Project: sofa-jraft   Author: sofastack   File: CliServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Status snapshot(final String groupId, final PeerId peer) {
    Requires.requireTrue(!StringUtils.isBlank(groupId), "Blank group id");
    Requires.requireNonNull(peer, "Null peer");

    if (!this.cliClientService.connect(peer.getEndpoint())) {
        return new Status(-1, "Fail to init channel to %s", peer);
    }

    final SnapshotRequest.Builder rb = SnapshotRequest.newBuilder() //
        .setGroupId(groupId) //
        .setPeerId(peer.toString());

    try {
        final Message result = this.cliClientService.snapshot(peer.getEndpoint(), rb.build(), null).get();
        return statusFromResponse(result);
    } catch (final Exception e) {
        return new Status(-1, e.getMessage());
    }
}
 
Example #5
Source Project: sofa-jraft   Author: sofastack   File: FSMCallerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOnSnapshotSaveEmptyConf() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    this.fsmCaller.onSnapshotSave(new SaveSnapshotClosure() {

        @Override
        public void run(final Status status) {
            assertFalse(status.isOk());
            assertEquals("Empty conf entry for lastAppliedIndex=10", status.getErrorMsg());
            latch.countDown();
        }

        @Override
        public SnapshotWriter start(final SnapshotMeta meta) {
            // TODO Auto-generated method stub
            return null;
        }
    });
    latch.await();
}
 
Example #6
Source Project: sofa-jraft   Author: sofastack   File: ReplicatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOnRpcReturnedTermMismatch() {
    final Replicator r = getReplicator();
    final RpcRequests.AppendEntriesRequest request = createEmptyEntriesRequest();
    final RpcRequests.AppendEntriesResponse response = RpcRequests.AppendEntriesResponse.newBuilder() //
        .setSuccess(false) //
        .setLastLogIndex(12) //
        .setTerm(2) //
        .build();
    this.id.unlock();

    Replicator.onRpcReturned(this.id, Replicator.RequestType.AppendEntries, Status.OK(), request, response, 0, 0,
        Utils.monotonicMs());
    Mockito.verify(this.node).increaseTermTo(
        2,
        new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term heartbeat_response from peer:%s",
            this.peerId));
    assertNull(r.id);
}
 
Example #7
Source Project: sofa-jraft   Author: sofastack   File: SnapshotExecutorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDoSnapshotWithIntervalDist() throws Exception {
    final NodeOptions nodeOptions = new NodeOptions();
    nodeOptions.setSnapshotLogIndexMargin(5);
    Mockito.when(this.node.getOptions()).thenReturn(nodeOptions);
    Mockito.when(this.fSMCaller.getLastAppliedIndex()).thenReturn(6L);

    final ArgumentCaptor<SaveSnapshotClosure> saveSnapshotClosureArg = ArgumentCaptor
        .forClass(SaveSnapshotClosure.class);
    Mockito.when(this.fSMCaller.onSnapshotSave(saveSnapshotClosureArg.capture())).thenReturn(true);
    final SynchronizedClosure done = new SynchronizedClosure();
    this.executor.doSnapshot(done);
    final SaveSnapshotClosure closure = saveSnapshotClosureArg.getValue();
    assertNotNull(closure);
    closure.start(RaftOutter.SnapshotMeta.newBuilder().setLastIncludedIndex(6).setLastIncludedTerm(1).build());
    closure.run(Status.OK());
    done.await();
    this.executor.join();

    assertEquals(1, this.executor.getLastSnapshotTerm());
    assertEquals(6, this.executor.getLastSnapshotIndex());

}
 
Example #8
Source Project: sofa-jraft   Author: sofastack   File: NodeImpl.java    License: Apache License 2.0 6 votes vote down vote up
void onCaughtUp(final long version, final PeerId peer, final boolean success) {
    if (version != this.version) {
        LOG.warn("Ignore onCaughtUp message, mismatch configuration context version, expect {}, but is {}.",
            this.version, version);
        return;
    }
    Requires.requireTrue(this.stage == Stage.STAGE_CATCHING_UP, "Stage is not in STAGE_CATCHING_UP");
    if (success) {
        this.addingPeers.remove(peer);
        if (this.addingPeers.isEmpty()) {
            nextStage();
            return;
        }
        return;
    }
    LOG.warn("Node {} fail to catch up peer {} when trying to change peers from {} to {}.",
        this.node.getNodeId(), peer, this.oldPeers, this.newPeers);
    reset(new Status(RaftError.ECATCHUP, "Peer %s failed to catch up.", peer));
}
 
Example #9
Source Project: sofa-jraft   Author: sofastack   File: Replicator.java    License: Apache License 2.0 6 votes vote down vote up
public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime,
                                   final CatchUpClosure done) {
    final Replicator r = (Replicator) id.lock();

    if (r == null) {
        RpcUtils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator"));
        return;
    }
    try {
        if (r.catchUpClosure != null) {
            LOG.error("Previous wait_for_caught_up is not over");
            Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call"));
            return;
        }
        done.setMaxMargin(maxMargin);
        if (dueTime > 0) {
            done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(),
                TimeUnit.MILLISECONDS));
        }
        r.catchUpClosure = done;
    } finally {
        id.unlock();
    }
}
 
Example #10
Source Project: sofa-jraft   Author: sofastack   File: ReadOnlyServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOnApplied() throws Exception {
    final ArrayList<ReadIndexState> states = new ArrayList<>();
    final byte[] reqContext = TestUtils.getRandomBytes();
    final CountDownLatch latch = new CountDownLatch(1);
    final ReadIndexState state = new ReadIndexState(new Bytes(reqContext), new ReadIndexClosure() {

        @Override
        public void run(final Status status, final long index, final byte[] reqCtx) {
            assertTrue(status.isOk());
            assertEquals(index, 1);
            assertArrayEquals(reqCtx, reqContext);
            latch.countDown();
        }
    }, Utils.monotonicMs());
    state.setIndex(1);
    states.add(state);
    final ReadIndexStatus readIndexStatus = new ReadIndexStatus(states, null, 1);
    this.readOnlyServiceImpl.getPendingNotifyStatus().put(1L, Arrays.asList(readIndexStatus));

    this.readOnlyServiceImpl.onApplied(2);
    latch.await();
    assertTrue(this.readOnlyServiceImpl.getPendingNotifyStatus().isEmpty());
}
 
Example #11
Source Project: sofa-jraft   Author: sofastack   File: RaftRawKVStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void containsKey(final byte[] key, final KVStoreClosure closure) {
    this.node.readIndex(BytesUtil.EMPTY_BYTES, new ReadIndexClosure() {

        @Override
        public void run(final Status status, final long index, final byte[] reqCtx) {
            if (status.isOk()) {
                RaftRawKVStore.this.kvStore.containsKey(key, closure);
                return;
            }
            RaftRawKVStore.this.readIndexExecutor.execute(() -> {
                if (isLeader()) {
                    LOG.warn("Fail to [containsKey] with 'ReadIndex': {}, try to applying to the state machine.", status);
                    // If 'read index' read fails, try to applying to the state machine at the leader node
                    applyOperation(KVOperation.createContainsKey(key), closure);
                } else {
                    LOG.warn("Fail to [containsKey] with 'ReadIndex': {}.", status);
                    // Client will retry to leader node
                    new KVClosureAdapter(closure, null).run(status);
                }
            });
        }
    });
}
 
Example #12
Source Project: sofa-jraft   Author: sofastack   File: BaseRawKVStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final NodeExecutor nodeExecutor, final boolean isLeader, final KVStoreClosure closure) {
    final Timer.Context timeCtx = getTimeContext("EXECUTE");
    try {
        if (nodeExecutor != null) {
            nodeExecutor.execute(Status.OK(), isLeader);
        }
        setSuccess(closure, Boolean.TRUE);
    } catch (final Exception e) {
        final Logger LOG = LoggerFactory.getLogger(getClass());
        LOG.error("Fail to [EXECUTE], {}.", StackTraceUtil.stackTrace(e));
        if (nodeExecutor != null) {
            nodeExecutor.execute(new Status(RaftError.EIO, "Fail to [EXECUTE]"), isLeader);
        }
        setCriticalError(closure, "Fail to [EXECUTE]", e);
    } finally {
        timeCtx.stop();
    }
}
 
Example #13
Source Project: sofa-jraft   Author: sofastack   File: AbstractKVStoreSnapshotFile.java    License: Apache License 2.0 6 votes vote down vote up
protected void compressSnapshot(final SnapshotWriter writer, final LocalFileMeta.Builder metaBuilder,
                                final Closure done) {
    final String writerPath = writer.getPath();
    final String outputFile = Paths.get(writerPath, SNAPSHOT_ARCHIVE).toString();
    try {
        final Checksum checksum = new CRC64();
        ZipUtil.compress(writerPath, SNAPSHOT_DIR, outputFile, checksum);
        metaBuilder.setChecksum(Long.toHexString(checksum.getValue()));
        if (writer.addFile(SNAPSHOT_ARCHIVE, metaBuilder.build())) {
            done.run(Status.OK());
        } else {
            done.run(new Status(RaftError.EIO, "Fail to add snapshot file: %s", writerPath));
        }
    } catch (final Throwable t) {
        LOG.error("Fail to compress snapshot, path={}, file list={}, {}.", writerPath, writer.listFiles(),
            StackTraceUtil.stackTrace(t));
        done.run(new Status(RaftError.EIO, "Fail to compress snapshot at %s, error is %s", writerPath, t
            .getMessage()));
    }
}
 
Example #14
Source Project: sofa-jraft   Author: sofastack   File: KVStoreStateMachine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onLeaderStop(final Status status) {
    super.onLeaderStop(status);
    final long oldTerm = this.leaderTerm.get();
    this.leaderTerm.set(-1L);
    // Because of the raft state machine must be a sequential commit, in order to prevent the user
    // doing something (needs to go through the raft state machine) in the listeners, we asynchronously
    // triggers the listeners.
    final List<StateListener> listeners = this.storeEngine.getStateListenerContainer() //
        .getStateListenerGroup(getRegionId());
    if (listeners.isEmpty()) {
        return;
    }
    this.storeEngine.getRaftStateTrigger().execute(() -> {
        for (final StateListener listener : listeners) { // iterator the snapshot
            listener.onLeaderStop(oldTerm);
        }
    });
}
 
Example #15
Source Project: sofa-jraft   Author: sofastack   File: MemoryKVStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test method: {@link MemoryRawKVStore#getAndPut(byte[], byte[], KVStoreClosure)}
 */
@Test
public void getAndPutTest() {
    final byte[] key = makeKey("put_test");
    TestClosure closure = new TestClosure();
    this.kvStore.get(key, closure);
    byte[] value = (byte[]) closure.getData();
    assertNull(value);

    value = makeValue("put_test_value");
    KVStoreClosure kvStoreClosure = new BaseKVStoreClosure() {
        @Override
        public void run(Status status) {
            assertEquals(status, Status.OK());
        }
    };
    this.kvStore.getAndPut(key, value, kvStoreClosure);
    assertNull(kvStoreClosure.getData());

    byte[] newVal = makeValue("put_test_value_new");
    this.kvStore.getAndPut(key, newVal, kvStoreClosure);
    assertArrayEquals(value, (byte[]) kvStoreClosure.getData());
}
 
Example #16
Source Project: sofa-jraft   Author: sofastack   File: MockStateMachine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onApply(final Iterator iter) {
    while (iter.hasNext()) {
        this.lock.lock();
        try {
            if (iter.getIndex() <= this.lastAppliedIndex.get()) {
                //prevent duplication
                continue;
            }
            this.lastAppliedIndex.set(iter.getIndex());
            this.logs.add(iter.getData().slice());
            if (iter.done() != null) {
                iter.done().run(Status.OK());
            }
        } finally {
            this.lock.unlock();
        }
        this.appliedIndex = iter.getIndex();
        iter.next();
    }
}
 
Example #17
Source Project: sofa-jraft   Author: sofastack   File: ReplicatorTest.java    License: Apache License 2.0 6 votes vote down vote up
private Replicator testRpcReturnedError() {
    final Replicator r = getReplicator();
    assertNull(r.getBlockTimer());
    final RpcRequests.AppendEntriesRequest request = createEmptyEntriesRequest();
    final RpcRequests.AppendEntriesResponse response = RpcRequests.AppendEntriesResponse.newBuilder() //
        .setSuccess(false) //
        .setLastLogIndex(12) //
        .setTerm(2) //
        .build();
    this.id.unlock();

    Replicator.onRpcReturned(this.id, Replicator.RequestType.AppendEntries, new Status(-1, "test error"), request,
        response, 0, 0, Utils.monotonicMs());
    assertEquals(r.statInfo.runningState, Replicator.RunningState.BLOCKING);
    assertNotNull(r.getBlockTimer());
    return r;
}
 
Example #18
Source Project: sofa-jraft   Author: sofastack   File: BaseCliRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
protected Node getNode(String groupId, PeerId peerId, Status st) {
    Node node = null;

    if (peerId != null) {
        node = NodeManager.getInstance().get(groupId, peerId);
        if (node == null) {
            st.setError(RaftError.ENOENT, "Fail to find node %s in group %s", peerId, groupId);
        }
    } else {
        List<Node> nodes = NodeManager.getInstance().getNodesByGroupId(groupId);
        if (nodes == null || nodes.isEmpty()) {
            st.setError(RaftError.ENOENT, "Empty nodes in group %s", groupId);
        } else if (nodes.size() > 1) {
            st.setError(RaftError.EINVAL, "Peer must be specified since there're %d nodes in group %s",
                nodes.size(), groupId);
        } else {
            node = nodes.get(0);
        }

    }
    if (node != null && node.getOptions().isDisableCli()) {
        st.setError(RaftError.EACCES, "Cli service is not allowed to access node %s", node.getNodeId());
    }
    return node;
}
 
Example #19
Source Project: sofa-jraft   Author: sofastack   File: LocalSnapshotCopierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testCancelByRemote() throws Exception {
    final FutureImpl<Message> future = new FutureImpl<>();
    final RpcRequests.GetFileRequest.Builder rb = RpcRequests.GetFileRequest.newBuilder().setReaderId(99)
        .setFilename(Snapshot.JRAFT_SNAPSHOT_META_FILE).setCount(Integer.MAX_VALUE).setOffset(0)
        .setReadPartly(true);

    //mock get metadata
    final ArgumentCaptor<RpcResponseClosure> argument = ArgumentCaptor.forClass(RpcResponseClosure.class);
    Mockito.when(
        this.raftClientService.getFile(eq(new Endpoint("localhost", 8081)), eq(rb.build()),
            eq(this.copyOpts.getTimeoutMs()), argument.capture())).thenReturn(future);
    this.copier.start();
    Thread.sleep(500);
    final RpcResponseClosure<RpcRequests.GetFileResponse> closure = argument.getValue();

    closure.run(new Status(RaftError.ECANCELED, "test cancel"));

    this.copier.join();
    //start timer
    final SnapshotReader reader = this.copier.getReader();
    assertNull(reader);
    Assert.assertEquals(RaftError.ECANCELED.getNumber(), this.copier.getCode());
    Assert.assertEquals("test cancel", this.copier.getErrorMsg());
}
 
Example #20
Source Project: sofa-jraft   Author: sofastack   File: CliServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Status removeLearners(final String groupId, final Configuration conf, final List<PeerId> learners) {
    checkLearnersOpParams(groupId, conf, learners);

    final PeerId leaderId = new PeerId();
    final Status st = getLeader(groupId, conf, leaderId);
    if (!st.isOk()) {
        return st;
    }

    if (!this.cliClientService.connect(leaderId.getEndpoint())) {
        return new Status(-1, "Fail to init channel to leader %s", leaderId);
    }
    final RemoveLearnersRequest.Builder rb = RemoveLearnersRequest.newBuilder() //
        .setGroupId(groupId) //
        .setLeaderId(leaderId.toString());
    for (final PeerId peer : learners) {
        rb.addLearners(peer.toString());
    }

    try {
        final Message result = this.cliClientService.removeLearners(leaderId.getEndpoint(), rb.build(), null).get();
        return processLearnersOpResponse(groupId, result, "removing learners: %s", learners);

    } catch (final Exception e) {
        return new Status(-1, e.getMessage());
    }
}
 
Example #21
Source Project: sofa-jraft   Author: sofastack   File: AddLearnersRequestProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void verify(final String interest, final Node node, final ArgumentCaptor<Closure> doneArg) {
    assertEquals(interest, AddLearnersRequest.class.getName());
    Mockito.verify(node).addLearners(
        eq(Arrays.asList(new PeerId("learner", 8082), new PeerId("test", 8182), new PeerId("test", 8183))),
        doneArg.capture());
    Closure done = doneArg.getValue();
    assertNotNull(done);
    done.run(Status.OK());
    assertNotNull(this.asyncContext.getResponseObject());
    assertEquals("[learner:8081, learner:8082, learner:8083]", this.asyncContext.as(LearnersOpResponse.class)
        .getOldLearnersList().toString());
    assertEquals("[learner:8081, learner:8082, learner:8083, test:8182, test:8183]",
        this.asyncContext.as(LearnersOpResponse.class).getNewLearnersList().toString());
}
 
Example #22
Source Project: sofa-jraft   Author: sofastack   File: DefaultRheaKVRpcService.java    License: Apache License 2.0 5 votes vote down vote up
private <V> void internalCallAsyncWithRpc(final Endpoint endpoint, final BaseRequest request,
                                          final FailoverClosure<V> closure) {
    final InvokeContext invokeCtx = new InvokeContext();
    invokeCtx.put(BoltRpcClient.BOLT_CTX, ExtSerializerSupports.getInvokeContext());
    final InvokeCallback invokeCallback = new InvokeCallback() {

        @Override
        public void complete(final Object result, final Throwable err) {
            if (err == null) {
                final BaseResponse<?> response = (BaseResponse<?>) result;
                if (response.isSuccess()) {
                    closure.setData(response.getValue());
                    closure.run(Status.OK());
                } else {
                    closure.setError(response.getError());
                    closure.run(new Status(-1, "RPC failed with address: %s, response: %s", endpoint, response));
                }
            } else {
                closure.failure(err);
            }
        }

        @Override
        public Executor executor() {
            return rpcCallbackExecutor;
        }
    };

    try {
        this.rpcClient.invokeAsync(endpoint, request, invokeCtx, invokeCallback, this.rpcTimeoutMillis);
    } catch (final Throwable t) {
        closure.failure(t);
    }
}
 
Example #23
Source Project: sofa-jraft   Author: sofastack   File: IteratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSetErrorAndRollback() {
    testNext();
    assertFalse(iterImpl.hasError());
    this.iter.setErrorAndRollback(5, new Status(-1, "test"));
    assertTrue(iterImpl.hasError());
    Assert.assertEquals(EnumOutter.ErrorType.ERROR_TYPE_STATE_MACHINE, iterImpl.getError().getType());
    Assert.assertEquals(RaftError.ESTATEMACHINE.getNumber(), iterImpl.getError().getStatus().getCode());
    Assert
        .assertEquals(
            "StateMachine meet critical error when applying one or more tasks since index=6, Status[UNKNOWN<-1>: test]",
            iterImpl.getError().getStatus().getErrorMsg());
    assertEquals(6, iter.getIndex());
}
 
Example #24
Source Project: sofa-jraft   Author: sofastack   File: AddPeerRequestProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void verify(String interest, Node node, ArgumentCaptor<Closure> doneArg) {
    assertEquals(interest, AddPeerRequest.class.getName());
    Mockito.verify(node).addPeer(eq(new PeerId("test", 8181)), doneArg.capture());
    Closure done = doneArg.getValue();
    assertNotNull(done);
    done.run(Status.OK());
    assertNotNull(this.asyncContext.getResponseObject());
    assertEquals("[localhost:8081, localhost:8082, localhost:8083]", this.asyncContext.as(AddPeerResponse.class)
        .getOldPeersList().toString());
    assertEquals("[localhost:8081, localhost:8082, localhost:8083, test:8181]",
        this.asyncContext.as(AddPeerResponse.class).getNewPeersList().toString());
}
 
Example #25
Source Project: sofa-jraft   Author: sofastack   File: NodeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void readIndex(final byte[] requestContext, final ReadIndexClosure done) {
    if (this.shutdownLatch != null) {
        Utils.runClosureInThread(done, new Status(RaftError.ENODESHUTDOWN, "Node is shutting down."));
        throw new IllegalStateException("Node is shutting down");
    }
    Requires.requireNonNull(done, "Null closure");
    this.readOnlyService.addRequest(requestContext, done);
}
 
Example #26
Source Project: sofa-jraft   Author: sofastack   File: IteratorImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void setErrorAndRollback(final long ntail, final Status st) {
    Requires.requireTrue(ntail > 0, "Invalid ntail=" + ntail);
    if (this.currEntry == null || this.currEntry.getType() != EnumOutter.EntryType.ENTRY_TYPE_DATA) {
        this.currentIndex -= ntail;
    } else {
        this.currentIndex -= ntail - 1;
    }
    this.currEntry = null;
    getOrCreateError().setType(EnumOutter.ErrorType.ERROR_TYPE_STATE_MACHINE);
    getOrCreateError().getStatus().setError(RaftError.ESTATEMACHINE,
        "StateMachine meet critical error when applying one or more tasks since index=%d, %s", this.currentIndex,
        st != null ? st.toString() : "none");

}
 
Example #27
Source Project: sofa-jraft   Author: sofastack   File: GetValueRequestProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RpcContext rpcCtx, final GetValueRequest request) {
    final CounterClosure closure = new CounterClosure() {
        @Override
        public void run(Status status) {
            rpcCtx.sendResponse(getValueResponse());
        }
    };

    this.counterService.get(request.isReadOnlySafe(), closure);
}
 
Example #28
Source Project: sofa-jraft   Author: sofastack   File: DefaultRegionKVService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handlePutIfAbsentRequest(final PutIfAbsentRequest request,
                                     final RequestProcessClosure<BaseRequest, BaseResponse<?>> closure) {
    final PutIfAbsentResponse response = new PutIfAbsentResponse();
    response.setRegionId(getRegionId());
    response.setRegionEpoch(getRegionEpoch());
    try {
        KVParameterRequires.requireSameEpoch(request, getRegionEpoch());
        final byte[] key = KVParameterRequires.requireNonNull(request.getKey(), "putIfAbsent.key");
        final byte[] value = KVParameterRequires.requireNonNull(request.getValue(), "putIfAbsent.value");
        this.rawKVStore.putIfAbsent(key, value, new BaseKVStoreClosure() {

            @Override
            public void run(final Status status) {
                if (status.isOk()) {
                    response.setValue((byte[]) getData());
                } else {
                    setFailure(request, response, status, getError());
                }
                closure.sendResponse(response);
            }
        });
    } catch (final Throwable t) {
        LOG.error("Failed to handle: {}, {}.", request, StackTraceUtil.stackTrace(t));
        response.setError(Errors.forException(t));
        closure.sendResponse(response);
    }
}
 
Example #29
Source Project: sofa-jraft   Author: sofastack   File: DefaultRegionKVService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleGetAndPutRequest(final GetAndPutRequest request,
                                   final RequestProcessClosure<BaseRequest, BaseResponse<?>> closure) {
    final GetAndPutResponse response = new GetAndPutResponse();
    response.setRegionId(getRegionId());
    response.setRegionEpoch(getRegionEpoch());
    try {
        KVParameterRequires.requireSameEpoch(request, getRegionEpoch());
        final byte[] key = KVParameterRequires.requireNonNull(request.getKey(), "getAndPut.key");
        final byte[] value = KVParameterRequires.requireNonNull(request.getValue(), "getAndPut.value");
        this.rawKVStore.getAndPut(key, value, new BaseKVStoreClosure() {

            @Override
            public void run(final Status status) {
                if (status.isOk()) {
                    response.setValue((byte[]) getData());
                } else {
                    setFailure(request, response, status, getError());
                }
                closure.sendResponse(response);
            }
        });
    } catch (final Throwable t) {
        LOG.error("Failed to handle: {}, {}.", request, StackTraceUtil.stackTrace(t));
        response.setError(Errors.forException(t));
        closure.sendResponse(response);
    }
}
 
Example #30
Source Project: sofa-jraft   Author: sofastack   File: DefaultRegionKVService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleCompareAndPutRequest(final CompareAndPutRequest request,
                                       final RequestProcessClosure<BaseRequest, BaseResponse<?>> closure) {
    final CompareAndPutResponse response = new CompareAndPutResponse();
    response.setRegionId(getRegionId());
    response.setRegionEpoch(getRegionEpoch());
    try {
        KVParameterRequires.requireSameEpoch(request, getRegionEpoch());
        final byte[] key = KVParameterRequires.requireNonNull(request.getKey(), "compareAndPut.key");
        final byte[] expect = KVParameterRequires.requireNonNull(request.getExpect(), "compareAndPut.expect");
        final byte[] update = KVParameterRequires.requireNonNull(request.getUpdate(), "compareAndPut.update");
        this.rawKVStore.compareAndPut(key, expect, update, new BaseKVStoreClosure() {

            @Override
            public void run(final Status status) {
                if (status.isOk()) {
                    response.setValue((Boolean) getData());
                } else {
                    setFailure(request, response, status, getError());
                }
                closure.sendResponse(response);
            }
        });
    } catch (final Throwable t) {
        LOG.error("Failed to handle: {}, {}.", request, StackTraceUtil.stackTrace(t));
        response.setError(Errors.forException(t));
        closure.sendResponse(response);
    }
}