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

The following examples show how to use com.alipay.sofa.jraft.Status#OK . 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
@Override
public Status rangeSplit(final long regionId, final long newRegionId, final String groupId, final Configuration conf) {
    final PeerId leaderId = new PeerId();
    final Status st = this.cliService.getLeader(groupId, conf, leaderId);
    if (!st.isOk()) {
        throw new IllegalStateException(st.getErrorMsg());
    }
    final RangeSplitRequest request = new RangeSplitRequest();
    request.setRegionId(regionId);
    request.setNewRegionId(newRegionId);
    try {
        final BaseResponse<?> response = (BaseResponse<?>) this.rpcClient.invokeSync(leaderId.getEndpoint(),
            request, this.opts.getTimeoutMs());
        if (response.isSuccess()) {
            return Status.OK();
        }
        return new Status(-1, "Fail to range split on region %d, error: %s", regionId, response);
    } catch (final Exception e) {
        LOG.error("Fail to range split on exception: {}.", StackTraceUtil.stackTrace(e));
        return new Status(-1, "fail to range split on region %d", regionId);
    }
}
 
Example 2
Source Project: sofa-jraft   File: LogManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Status checkConsistency() {
    this.readLock.lock();
    try {
        Requires.requireTrue(this.firstLogIndex > 0);
        Requires.requireTrue(this.lastLogIndex >= 0);
        if (this.lastSnapshotId.equals(new LogId(0, 0))) {
            if (this.firstLogIndex == 1) {
                return Status.OK();
            }
            return new Status(RaftError.EIO, "Missing logs in (0, %d)", this.firstLogIndex);
        } else {
            if (this.lastSnapshotId.getIndex() >= this.firstLogIndex - 1
                && this.lastSnapshotId.getIndex() <= this.lastLogIndex) {
                return Status.OK();
            }
            return new Status(RaftError.EIO, "There's a gap between snapshot={%d, %d} and log=[%d, %d] ",
                this.lastSnapshotId.toString(), this.lastSnapshotId.getTerm(), this.firstLogIndex,
                this.lastLogIndex);
        }
    } finally {
        this.readLock.unlock();
    }
}
 
Example 3
Source Project: sofa-jraft   File: CliServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Status getLeader(final String groupId, final Configuration conf, final PeerId leaderId) {
    final PeerId ret = this.rebalancedLeaderIds.get(groupId);
    if (ret != null) {
        leaderId.parse(ret.toString());
    } else {
        leaderId.parse(this.initialLeaderId.toString());
    }
    return Status.OK();
}
 
Example 4
Source Project: sofa-jraft   File: NodeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Status resetPeers(final Configuration newPeers) {
    Requires.requireNonNull(newPeers, "Null new peers");
    Requires.requireTrue(!newPeers.isEmpty(), "Empty new peers");
    Requires.requireTrue(newPeers.isValid(), "Invalid new peers: %s", newPeers);
    this.writeLock.lock();
    try {
        if (newPeers.isEmpty()) {
            LOG.warn("Node {} set empty peers.", getNodeId());
            return new Status(RaftError.EINVAL, "newPeers is empty");
        }
        if (!this.state.isActive()) {
            LOG.warn("Node {} is in state {}, can't set peers.", getNodeId(), this.state);
            return new Status(RaftError.EPERM, "Bad state: %s", this.state);
        }
        // bootstrap?
        if (this.conf.getConf().isEmpty()) {
            LOG.info("Node {} set peers to {} from empty.", getNodeId(), newPeers);
            this.conf.setConf(newPeers);
            stepDown(this.currTerm + 1, false, new Status(RaftError.ESETPEER, "Set peer from empty configuration"));
            return Status.OK();
        }
        if (this.state == State.STATE_LEADER && this.confCtx.isBusy()) {
            LOG.warn("Node {} set peers need wait current conf changing.", getNodeId());
            return new Status(RaftError.EBUSY, "Changing to another configuration");
        }
        // check equal, maybe retry direct return
        if (this.conf.getConf().equals(newPeers)) {
            return Status.OK();
        }
        final Configuration newConf = new Configuration(newPeers);
        LOG.info("Node {} set peers from {} to {}.", getNodeId(), this.conf.getConf(), newPeers);
        this.conf.setConf(newConf);
        this.conf.getOldConf().reset();
        stepDown(this.currTerm + 1, false, new Status(RaftError.ESETPEER, "Raft node set peer normally"));
        return Status.OK();
    } finally {
        this.writeLock.unlock();
    }
}
 
Example 5
Source Project: sofa-jraft   File: FSMCallerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOnStartStopFollowing() throws Exception {
    final LeaderChangeContext ctx = new LeaderChangeContext(null, 11, Status.OK());
    this.fsmCaller.onStartFollowing(ctx);
    this.fsmCaller.flush();
    Mockito.verify(this.fsm).onStartFollowing(ctx);

    this.fsmCaller.onStopFollowing(ctx);
    this.fsmCaller.flush();
    Mockito.verify(this.fsm).onStopFollowing(ctx);
}
 
Example 6
Source Project: sofa-jraft   File: CliServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Status getLeader(final String groupId, final Configuration conf, final PeerId leaderId) {
    final PeerId ret = this.rebalancedLeaderIds.get(groupId);
    if (ret != null) {
        leaderId.parse(ret.toString());
    } else {
        leaderId.parse(this.initialLeaderId.toString());
    }
    return Status.OK();
}
 
Example 7
Source Project: sofa-jraft   File: CliServiceTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Status transferLeader(final String groupId, final Configuration conf, final PeerId peer) {
    return Status.OK();
}
 
Example 8
Source Project: sofa-jraft   File: RaftException.java    License: Apache License 2.0 4 votes vote down vote up
public RaftException() {
    this.type = EnumOutter.ErrorType.ERROR_TYPE_NONE;
    this.status = Status.OK();
}
 
Example 9
Source Project: sofa-jraft   File: CliServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Status rebalance(final Set<String> balanceGroupIds, final Configuration conf,
                        final Map<String, PeerId> rebalancedLeaderIds) {
    Requires.requireNonNull(balanceGroupIds, "Null balance group ids");
    Requires.requireTrue(!balanceGroupIds.isEmpty(), "Empty balance group ids");
    Requires.requireNonNull(conf, "Null configuration");
    Requires.requireTrue(!conf.isEmpty(), "No peers of configuration");

    LOG.info("Rebalance start with raft groups={}.", balanceGroupIds);

    final long start = Utils.monotonicMs();
    int transfers = 0;
    Status failedStatus = null;
    final Queue<String> groupDeque = new ArrayDeque<>(balanceGroupIds);
    final LeaderCounter leaderCounter = new LeaderCounter(balanceGroupIds.size(), conf.size());
    for (;;) {
        final String groupId = groupDeque.poll();
        if (groupId == null) { // well done
            break;
        }

        final PeerId leaderId = new PeerId();
        final Status leaderStatus = getLeader(groupId, conf, leaderId);
        if (!leaderStatus.isOk()) {
            failedStatus = leaderStatus;
            break;
        }

        if (rebalancedLeaderIds != null) {
            rebalancedLeaderIds.put(groupId, leaderId);
        }

        if (leaderCounter.incrementAndGet(leaderId) <= leaderCounter.getExpectedAverage()) {
            // The num of leaders is less than the expected average, we are going to deal with others
            continue;
        }

        // Find the target peer and try to transfer the leader to this peer
        final PeerId targetPeer = findTargetPeer(leaderId, groupId, conf, leaderCounter);
        if (!targetPeer.isEmpty()) {
            final Status transferStatus = transferLeader(groupId, conf, targetPeer);
            transfers++;
            if (!transferStatus.isOk()) {
                // The failure of `transfer leader` usually means the node is busy,
                // so we return failure status and should try `rebalance` again later.
                failedStatus = transferStatus;
                break;
            }

            LOG.info("Group {} transfer leader to {}.", groupId, targetPeer);
            leaderCounter.decrementAndGet(leaderId);
            groupDeque.add(groupId);
            if (rebalancedLeaderIds != null) {
                rebalancedLeaderIds.put(groupId, targetPeer);
            }
        }
    }

    final Status status = failedStatus != null ? failedStatus : Status.OK();
    if (LOG.isInfoEnabled()) {
        LOG.info(
            "Rebalanced raft groups={}, status={}, number of transfers={}, elapsed time={} ms, rebalanced result={}.",
            balanceGroupIds, status, transfers, Utils.monotonicMs() - start, rebalancedLeaderIds);
    }
    return status;
}
 
Example 10
Source Project: sofa-jraft   File: NodeImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Status transferLeadershipTo(final PeerId peer) {
    Requires.requireNonNull(peer, "Null peer");
    this.writeLock.lock();
    try {
        if (this.state != State.STATE_LEADER) {
            LOG.warn("Node {} can't transfer leadership to peer {} as it is in state {}.", getNodeId(), peer,
                this.state);
            return new Status(this.state == State.STATE_TRANSFERRING ? RaftError.EBUSY : RaftError.EPERM,
                    "Not a leader");
        }
        if (this.confCtx.isBusy()) {
            // It's very messy to deal with the case when the |peer| received
            // TimeoutNowRequest and increase the term while somehow another leader
            // which was not replicated with the newest configuration has been
            // elected. If no add_peer with this very |peer| is to be invoked ever
            // after nor this peer is to be killed, this peer will spin in the voting
            // procedure and make the each new leader stepped down when the peer
            // reached vote timeout and it starts to vote (because it will increase
            // the term of the group)
            // To make things simple, refuse the operation and force users to
            // invoke transfer_leadership_to after configuration changing is
            // completed so that the peer's configuration is up-to-date when it
            // receives the TimeOutNowRequest.
            LOG.warn(
                "Node {} refused to transfer leadership to peer {} when the leader is changing the configuration.",
                getNodeId(), peer);
            return new Status(RaftError.EBUSY, "Changing the configuration");
        }

        PeerId peerId = peer.copy();
        // if peer_id is ANY_PEER(0.0.0.0:0:0), the peer with the largest
        // last_log_id will be selected.
        if (peerId.equals(PeerId.ANY_PEER)) {
            LOG.info("Node {} starts to transfer leadership to any peer.", getNodeId());
            if ((peerId = this.replicatorGroup.findTheNextCandidate(this.conf)) == null) {
                return new Status(-1, "Candidate not found for any peer");
            }
        }
        if (peerId.equals(this.serverId)) {
            LOG.info("Node {} transferred leadership to self.", this.serverId);
            return Status.OK();
        }
        if (!this.conf.contains(peerId)) {
            LOG.info("Node {} refused to transfer leadership to peer {} as it is not in {}.", getNodeId(), peer,
                this.conf);
            return new Status(RaftError.EINVAL, "Not in current configuration");
        }

        final long lastLogIndex = this.logManager.getLastLogIndex();
        if (!this.replicatorGroup.transferLeadershipTo(peerId, lastLogIndex)) {
            LOG.warn("No such peer {}.", peer);
            return new Status(RaftError.EINVAL, "No such peer %s", peer);
        }
        this.state = State.STATE_TRANSFERRING;
        final Status status = new Status(RaftError.ETRANSFERLEADERSHIP,
            "Raft leader is transferring leadership to %s", peerId);
        onLeaderStop(status);
        LOG.info("Node {} starts to transfer leadership to peer {}.", getNodeId(), peer);
        final StopTransferArg stopArg = new StopTransferArg(this, this.currTerm, peerId);
        this.stopTransferArg = stopArg;
        this.transferTimer = this.timerManager.schedule(() -> onTransferTimeout(stopArg),
            this.options.getElectionTimeoutMs(), TimeUnit.MILLISECONDS);

    } finally {
        this.writeLock.unlock();
    }
    return Status.OK();
}
 
Example 11
Source Project: sofa-jraft   File: CliServiceTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Status transferLeader(final String groupId, final Configuration conf, final PeerId peer) {
    return Status.OK();
}