Java Code Examples for com.alipay.sofa.jraft.Status#isOk()

The following examples show how to use com.alipay.sofa.jraft.Status#isOk() . 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 File: FailoverClosureImpl.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void run(final Status status) {
    if (status.isOk()) {
        success((T) getData());
        return;
    }

    final Errors error = getError();
    if (this.retriesLeft > 0
        && (ErrorsHelper.isInvalidPeer(error) || (this.retryOnInvalidEpoch && ErrorsHelper.isInvalidEpoch(error)))) {
        LOG.warn("[Failover] status: {}, error: {}, [{}] retries left.", status, error, this.retriesLeft);
        this.retryRunner.run(error);
    } else {
        if (this.retriesLeft <= 0) {
            LOG.error("[InvalidEpoch-Failover] status: {}, error: {}, {} retries left.", status, error,
                this.retriesLeft);
        }
        failure(error);
    }
}
 
Example 2
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void run(final Status status) {
    if (this.isDone) {
        return;
    }
    if (status.isOk() && getResponse().getSuccess()) {
        this.ackSuccess++;
    } else {
        this.ackFailures++;
    }
    // Include leader self vote yes.
    if (this.ackSuccess + 1 >= this.quorum) {
        this.respBuilder.setSuccess(true);
        this.closure.setResponse(this.respBuilder.build());
        this.closure.run(Status.OK());
        this.isDone = true;
    } else if (this.ackFailures >= this.failPeersThreshold) {
        this.respBuilder.setSuccess(false);
        this.closure.setResponse(this.respBuilder.build());
        this.closure.run(Status.OK());
        this.isDone = true;
    }
}
 
Example 3
Source File: RaftExchanger.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
/**
 * api for remove meta node
 * @param ipAddress
 */
public void removePeer(String ipAddress) {
    try {
        if (cliService != null) {
            PeerId peer = new PeerId(ipAddress, metaServerConfig.getRaftServerPort());
            Status status = cliService.removePeer(getGroup(), getCurrentConfiguration(), peer);
            if (!status.isOk()) {
                LOGGER.error("CliService remove peer fail!error message {}",
                    status.getErrorMsg());
                throw new RuntimeException("CliService remove peer fail!error message "
                                           + status.getErrorMsg());
            }
        } else {
            LOGGER.error("cliService can't be null,it must be init first!");
            throw new RuntimeException("cliService can't be null,it must be init first!");
        }
    } catch (Exception e) {
        LOGGER.error("CliService remove peer error!", e);
        throw new RuntimeException("CliService remove peer error!", e);
    }
}
 
Example 4
Source File: AbstractPlacementDriverClient.java    From sofa-jraft with 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 5
Source File: RaftClient.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
public static PeerId refreshLeader(CliClientService cliClientService, String groupId,
                                   int timeout) {
    try {
        Status status = RouteTable.getInstance().refreshLeader(cliClientService, groupId,
            timeout);
        if (!status.isOk()) {
            throw new IllegalStateException(String.format("Refresh leader failed,error=%s",
                status.getErrorMsg()));
        }
        PeerId leader = RouteTable.getInstance().selectLeader(groupId);
        LOGGER.info("Leader is {}", leader);

        //avoid refresh leader config ip list must be current list,list maybe change by manage
        status = RouteTable.getInstance().refreshConfiguration(cliClientService, groupId,
            timeout);
        if (!status.isOk()) {
            throw new IllegalStateException(String.format(
                "Refresh configuration failed, error=%s", status.getErrorMsg()));
        }

        return leader;
    } catch (Exception e) {
        LOGGER.error("Refresh leader failed", e);
        throw new IllegalStateException("Refresh leader failed", e);
    }
}
 
Example 6
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final Status status) {
    NodeImpl.this.metrics.recordLatency("request-vote", Utils.monotonicMs() - this.startMs);
    if (!status.isOk()) {
        LOG.warn("Node {} RequestVote to {} error: {}.", this.node.getNodeId(), this.peer, status);
    } else {
        this.node.handleRequestVoteResponse(this.peer, this.term, getResponse());
    }
}
 
Example 7
Source File: RegionEngine.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
public boolean transferLeadershipTo(final Endpoint endpoint) {
    final PeerId peerId = new PeerId(endpoint, 0);
    final Status status = this.node.transferLeadershipTo(peerId);
    final boolean isOk = status.isOk();
    if (isOk) {
        LOG.info("Transfer-leadership succeeded: [{} --> {}].", this.storeEngine.getSelfEndpoint(), endpoint);
    } else {
        LOG.error("Transfer-leadership failed: {}, [{} --> {}].", status, this.storeEngine.getSelfEndpoint(),
            endpoint);
    }
    return isOk;
}
 
Example 8
Source File: CliServiceImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public Status transferLeader(final String groupId, final Configuration conf, final PeerId peer) {
    Requires.requireTrue(!StringUtils.isBlank(groupId), "Blank group id");
    Requires.requireNonNull(conf, "Null configuration");
    Requires.requireNonNull(peer, "Null peer");

    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 TransferLeaderRequest.Builder rb = TransferLeaderRequest.newBuilder() //
        .setGroupId(groupId) //
        .setLeaderId(leaderId.toString());
    if (!peer.isEmpty()) {
        rb.setPeerId(peer.toString());
    }

    try {
        final Message result = this.cliClientService.transferLeader(leaderId.getEndpoint(), rb.build(), null).get();
        return statusFromResponse(result);
    } catch (final Exception e) {
        return new Status(-1, e.getMessage());
    }
}
 
Example 9
Source File: CliServiceImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public Status resetLearners(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 ResetLearnersRequest.Builder rb = ResetLearnersRequest.newBuilder() //
        .setGroupId(groupId) //
        .setLeaderId(leaderId.toString());
    for (final PeerId peer : learners) {
        rb.addLearners(peer.toString());
    }

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

    } catch (final Exception e) {
        return new Status(-1, e.getMessage());
    }
}
 
Example 10
Source File: CliServiceImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public Status addLearners(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 AddLearnersRequest.Builder rb = AddLearnersRequest.newBuilder() //
        .setGroupId(groupId) //
        .setLeaderId(leaderId.toString());
    for (final PeerId peer : learners) {
        rb.addLearners(peer.toString());
    }

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

    } catch (final Exception e) {
        return new Status(-1, e.getMessage());
    }
}
 
Example 11
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final Status status) {
    if (status.isOk()) {
        onConfigurationChangeDone(this.term);
        if (this.leaderStart) {
            getOptions().getFsm().onLeaderStart(this.term);
        }
    } else {
        LOG.error("Fail to run ConfigurationChangeDone, status: {}.", status);
    }
}
 
Example 12
Source File: ReadOnlyServiceImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
/**
 * Called when ReadIndex response returns.
 */
@Override
public void run(final Status status) {
    if (!status.isOk()) {
        notifyFail(status);
        return;
    }
    final ReadIndexResponse readIndexResponse = getResponse();
    if (!readIndexResponse.getSuccess()) {
        notifyFail(new Status(-1, "Fail to run ReadIndex task, maybe the leader stepped down."));
        return;
    }
    // Success
    final ReadIndexStatus readIndexStatus = new ReadIndexStatus(this.states, this.request,
        readIndexResponse.getIndex());
    for (final ReadIndexState state : this.states) {
        // Records current commit log index.
        state.setIndex(readIndexResponse.getIndex());
    }

    boolean doUnlock = true;
    ReadOnlyServiceImpl.this.lock.lock();
    try {
        if (readIndexStatus.isApplied(ReadOnlyServiceImpl.this.fsmCaller.getLastAppliedIndex())) {
            // Already applied, notify readIndex request.
            ReadOnlyServiceImpl.this.lock.unlock();
            doUnlock = false;
            notifySuccess(readIndexStatus);
        } else {
            // Not applied, add it to pending-notify cache.
            ReadOnlyServiceImpl.this.pendingNotifyStatus
                .computeIfAbsent(readIndexStatus.getIndex(), k -> new ArrayList<>(10)) //
                .add(readIndexStatus);
        }
    } finally {
        if (doUnlock) {
            ReadOnlyServiceImpl.this.lock.unlock();
        }
    }
}
 
Example 13
Source File: KVClosureAdapter.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Status status) {
    if (status.isOk()) {
        setError(Errors.NONE);
    } else {
        LOG.error("Fail status: {}.", status);
        if (getError() == null) {
            switch (status.getRaftError()) {
                case SUCCESS:
                    setError(Errors.NONE);
                    break;
                case EINVAL:
                    setError(Errors.INVALID_REQUEST);
                    break;
                case EIO:
                    setError(Errors.STORAGE_ERROR);
                    break;
                default:
                    setError(Errors.LEADER_NOT_AVAILABLE);
                    break;
            }
        }
    }
    if (done != null) {
        done.run(status);
    }
}
 
Example 14
Source File: DefaultRegionKVService.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void handleScanRequest(final ScanRequest request,
                              final RequestProcessClosure<BaseRequest, BaseResponse<?>> closure) {
    final ScanResponse response = new ScanResponse();
    response.setRegionId(getRegionId());
    response.setRegionEpoch(getRegionEpoch());
    try {
        KVParameterRequires.requireSameEpoch(request, getRegionEpoch());
        final BaseKVStoreClosure kvStoreClosure = new BaseKVStoreClosure() {

            @SuppressWarnings("unchecked")
            @Override
            public void run(final Status status) {
                if (status.isOk()) {
                    response.setValue((List<KVEntry>) getData());
                } else {
                    setFailure(request, response, status, getError());
                }
                closure.sendResponse(response);
            }
        };
        if (request.isReverse()) {
            this.rawKVStore.reverseScan(request.getStartKey(), request.getEndKey(), request.getLimit(),
                request.isReadOnlySafe(), request.isReturnValue(), kvStoreClosure);
        } else {
            this.rawKVStore.scan(request.getStartKey(), request.getEndKey(), request.getLimit(),
                request.isReadOnlySafe(), request.isReturnValue(), kvStoreClosure);
        }
    } catch (final Throwable t) {
        LOG.error("Failed to handle: {}, {}.", request, StackTraceUtil.stackTrace(t));
        response.setError(Errors.forException(t));
        closure.sendResponse(response);
    }
}
 
Example 15
Source File: RaftExchanger.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * api for change meta node
 */
public void changePeer(List<String> ipAddressList) {
    try {
        if (cliService != null) {
            Configuration peersConf = new Configuration();
            for (String ipAddress : ipAddressList) {
                PeerId peer = new PeerId(ipAddress, metaServerConfig.getRaftServerPort());
                peersConf.addPeer(peer);
            }

            Status status = cliService.changePeers(getGroup(), getCurrentConfiguration(),
                peersConf);

            if (!status.isOk()) {
                LOGGER.error("CliService change peer fail!error message {}",
                    status.getErrorMsg());
                throw new RuntimeException("CliService change peer fail!error message "
                                           + status.getErrorMsg());
            }
        } else {
            LOGGER.error("cliService can't be null,it must be init first!");
            throw new RuntimeException("cliService can't be null,it must be init first!");
        }
    } catch (Exception e) {
        LOGGER.error("CliService change peer error!", e);
        throw new RuntimeException("CliService change peer error!", e);
    }
}
 
Example 16
Source File: NodeImpl.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final Status status) {
    NodeImpl.this.metrics.recordLatency("pre-vote", Utils.monotonicMs() - this.startMs);
    if (!status.isOk()) {
        LOG.warn("Node {} PreVote to {} error: {}.", getNodeId(), this.peer, status);
    } else {
        handlePreVoteResponse(this.peer, this.term, getResponse());
    }
}
 
Example 17
Source File: Replicator.java    From sofa-jraft with Apache License 2.0 4 votes vote down vote up
static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request,
                                final AppendEntriesResponse response, final long rpcSendTime) {
    if (id == null) {
        // replicator already was destroyed.
        return;
    }
    final long startTimeMs = Utils.nowMs();
    Replicator r;
    if ((r = (Replicator) id.lock()) == null) {
        return;
    }
    boolean doUnlock = true;
    try {
        final boolean isLogDebugEnabled = LOG.isDebugEnabled();
        StringBuilder sb = null;
        if (isLogDebugEnabled) {
            sb = new StringBuilder("Node ") //
                .append(r.options.getGroupId()) //
                .append(':') //
                .append(r.options.getServerId()) //
                .append(" received HeartbeatResponse from ") //
                .append(r.options.getPeerId()) //
                .append(" prevLogIndex=") //
                .append(request.getPrevLogIndex()) //
                .append(" prevLogTerm=") //
                .append(request.getPrevLogTerm());
        }
        if (!status.isOk()) {
            if (isLogDebugEnabled) {
                sb.append(" fail, sleep, status=") //
                    .append(status);
                LOG.debug(sb.toString());
            }
            r.state = State.Probe;
            notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status);
            if (++r.consecutiveErrorTimes % 10 == 0) {
                LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(),
                    r.consecutiveErrorTimes, status);
            }
            r.startHeartbeatTimer(startTimeMs);
            return;
        }
        r.consecutiveErrorTimes = 0;
        if (response.getTerm() > r.options.getTerm()) {
            if (isLogDebugEnabled) {
                sb.append(" fail, greater term ") //
                    .append(response.getTerm()) //
                    .append(" expect term ") //
                    .append(r.options.getTerm());
                LOG.debug(sb.toString());
            }
            final NodeImpl node = r.options.getNode();
            r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true);
            r.destroy();
            node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE,
                "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId()));
            return;
        }
        if (!response.getSuccess() && response.hasLastLogIndex()) {
            if (isLogDebugEnabled) {
                sb.append(" fail, response term ") //
                    .append(response.getTerm()) //
                    .append(" lastLogIndex ") //
                    .append(response.getLastLogIndex());
                LOG.debug(sb.toString());
            }
            LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId());
            doUnlock = false;
            r.sendEmptyEntries(false);
            r.startHeartbeatTimer(startTimeMs);
            return;
        }
        if (isLogDebugEnabled) {
            LOG.debug(sb.toString());
        }
        if (rpcSendTime > r.lastRpcSendTimestamp) {
            r.lastRpcSendTimestamp = rpcSendTime;
        }
        r.startHeartbeatTimer(startTimeMs);
    } finally {
        if (doUnlock) {
            id.unlock();
        }
    }
}
 
Example 18
Source File: SnapshotExecutorImpl.java    From sofa-jraft with Apache License 2.0 4 votes vote down vote up
private void onSnapshotLoadDone(final Status st) {
    DownloadingSnapshot m;
    boolean doUnlock = true;
    this.lock.lock();
    try {
        Requires.requireTrue(this.loadingSnapshot, "Not loading snapshot");
        m = this.downloadingSnapshot.get();
        if (st.isOk()) {
            this.lastSnapshotIndex = this.loadingSnapshotMeta.getLastIncludedIndex();
            this.lastSnapshotTerm = this.loadingSnapshotMeta.getLastIncludedTerm();
            doUnlock = false;
            this.lock.unlock();
            this.logManager.setSnapshot(this.loadingSnapshotMeta); // should be out of lock
            doUnlock = true;
            this.lock.lock();
        }
        final StringBuilder sb = new StringBuilder();
        if (this.node != null) {
            sb.append("Node ").append(this.node.getNodeId()).append(" ");
        }
        sb.append("onSnapshotLoadDone, ").append(this.loadingSnapshotMeta);
        LOG.info(sb.toString());
        doUnlock = false;
        this.lock.unlock();
        if (this.node != null) {
            this.node.updateConfigurationAfterInstallingSnapshot();
        }
        doUnlock = true;
        this.lock.lock();
        this.loadingSnapshot = false;
        this.downloadingSnapshot.set(null);

    } finally {
        if (doUnlock) {
            this.lock.unlock();
        }
    }
    if (m != null) {
        // Respond RPC
        if (!st.isOk()) {
            m.done.run(st);
        } else {
            m.responseBuilder.setSuccess(true);
            m.done.sendResponse(m.responseBuilder.build());
        }
    }
    this.runningJobs.countDown();
}
 
Example 19
Source File: CopySession.java    From sofa-jraft with Apache License 2.0 4 votes vote down vote up
void onRpcReturned(final Status status, final GetFileResponse response) {
    this.lock.lock();
    try {
        if (this.finished) {
            return;
        }
        if (!status.isOk()) {
            // Reset count to make next rpc retry the previous one
            this.requestBuilder.setCount(0);
            if (status.getCode() == RaftError.ECANCELED.getNumber()) {
                if (this.st.isOk()) {
                    this.st.setError(status.getCode(), status.getErrorMsg());
                    onFinished();
                    return;
                }
            }

            // Throttled reading failure does not increase _retry_times
            if (status.getCode() != RaftError.EAGAIN.getNumber()
                    && ++this.retryTimes >= this.copyOptions.getMaxRetry()) {
                if (this.st.isOk()) {
                    this.st.setError(status.getCode(), status.getErrorMsg());
                    onFinished();
                    return;
                }
            }
            this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(),
                TimeUnit.MILLISECONDS);
            return;
        }
        this.retryTimes = 0;
        Requires.requireNonNull(response, "response");
        // Reset count to |real_read_size| to make next rpc get the right offset
        if (!response.getEof()) {
            this.requestBuilder.setCount(response.getReadSize());
        }
        if (this.outputStream != null) {
            try {
                response.getData().writeTo(this.outputStream);
            } catch (final IOException e) {
                LOG.error("Fail to write into file {}", this.destPath);
                this.st.setError(RaftError.EIO, RaftError.EIO.name());
                onFinished();
                return;
            }
        } else {
            this.destBuf.put(response.getData().asReadOnlyByteBuffer());
        }
        if (response.getEof()) {
            onFinished();
            return;
        }
    } finally {
        this.lock.unlock();
    }
    sendNextRpc();
}
 
Example 20
Source File: Replicator.java    From sofa-jraft with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request,
                                 final TimeoutNowResponse response, final boolean stopAfterFinish) {
    final Replicator r = (Replicator) id.lock();
    if (r == null) {
        return;
    }

    final boolean isLogDebugEnabled = LOG.isDebugEnabled();
    StringBuilder sb = null;
    if (isLogDebugEnabled) {
        sb = new StringBuilder("Node "). //
            append(r.options.getGroupId()).append(":").append(r.options.getServerId()). //
            append(" received TimeoutNowResponse from "). //
            append(r.options.getPeerId());
    }
    if (!status.isOk()) {
        if (isLogDebugEnabled) {
            sb.append(" fail:").append(status);
            LOG.debug(sb.toString());
        }
        notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status);
        if (stopAfterFinish) {
            r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true);
            r.destroy();
        } else {
            id.unlock();
        }
        return;
    }
    if (isLogDebugEnabled) {
        sb.append(response.getSuccess() ? " success" : " fail");
        LOG.debug(sb.toString());
    }
    if (response.getTerm() > r.options.getTerm()) {
        final NodeImpl node = r.options.getNode();
        r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true);
        r.destroy();
        node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE,
            "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId()));
        return;
    }
    if (stopAfterFinish) {
        r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true);
        r.destroy();
    } else {
        id.unlock();
    }

}