Search in sources :

Example 96 with Status

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

the class GetLeaderRequestProcessor method processRequest.

@Override
public Message processRequest(final GetLeaderRequest request, final RpcRequestClosure done) {
    List<Node> nodes = new ArrayList<>();
    final String groupId = getGroupId(request);
    if (request.hasPeerId()) {
        final String peerIdStr = getPeerId(request);
        final PeerId peer = new PeerId();
        if (peer.parse(peerIdStr)) {
            final Status st = new Status();
            nodes.add(getNode(groupId, peer, st));
            if (!st.isOk()) {
                return // 
                RpcFactoryHelper.responseFactory().newResponse(defaultResp(), st);
            }
        } else {
            return // 
            RpcFactoryHelper.responseFactory().newResponse(defaultResp(), RaftError.EINVAL, "Fail to parse peer id %s", peerIdStr);
        }
    } else {
        nodes = NodeManager.getInstance().getNodesByGroupId(groupId);
    }
    if (nodes == null || nodes.isEmpty()) {
        return // 
        RpcFactoryHelper.responseFactory().newResponse(defaultResp(), RaftError.ENOENT, "No nodes in group %s", groupId);
    }
    for (final Node node : nodes) {
        final PeerId leader = node.getLeaderId();
        if (leader != null && !leader.isEmpty()) {
            return GetLeaderResponse.newBuilder().setLeaderId(leader.toString()).build();
        }
    }
    return // 
    RpcFactoryHelper.responseFactory().newResponse(defaultResp(), RaftError.EAGAIN, "Unknown leader");
}
Also used : Status(com.alipay.sofa.jraft.Status) Node(com.alipay.sofa.jraft.Node) ArrayList(java.util.ArrayList) PeerId(com.alipay.sofa.jraft.entity.PeerId)

Example 97 with Status

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

the class SnapshotExecutorImpl method reportError.

private void reportError(final int errCode, final String fmt, final Object... args) {
    final RaftException error = new RaftException(ErrorType.ERROR_TYPE_SNAPSHOT);
    error.setStatus(new Status(errCode, fmt, args));
    this.fsmCaller.onError(error);
}
Also used : Status(com.alipay.sofa.jraft.Status) RaftException(com.alipay.sofa.jraft.error.RaftException)

Example 98 with Status

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

the class SnapshotExecutorImpl method loadDownloadingSnapshot.

void loadDownloadingSnapshot(final DownloadingSnapshot ds, final SnapshotMeta meta) {
    SnapshotReader reader;
    this.lock.lock();
    try {
        if (ds != this.downloadingSnapshot.get()) {
            // It is interrupted and response by other request,just return
            return;
        }
        Requires.requireNonNull(this.curCopier, "curCopier");
        reader = this.curCopier.getReader();
        if (!this.curCopier.isOk()) {
            if (this.curCopier.getCode() == RaftError.EIO.getNumber()) {
                reportError(this.curCopier.getCode(), this.curCopier.getErrorMsg());
            }
            Utils.closeQuietly(reader);
            ds.done.run(this.curCopier);
            Utils.closeQuietly(this.curCopier);
            this.curCopier = null;
            this.downloadingSnapshot.set(null);
            this.runningJobs.countDown();
            return;
        }
        Utils.closeQuietly(this.curCopier);
        this.curCopier = null;
        if (reader == null || !reader.isOk()) {
            Utils.closeQuietly(reader);
            this.downloadingSnapshot.set(null);
            ds.done.sendResponse(// 
            RpcFactoryHelper.responseFactory().newResponse(InstallSnapshotResponse.getDefaultInstance(), RaftError.EINTERNAL, "Fail to copy snapshot from %s", ds.request.getUri()));
            this.runningJobs.countDown();
            return;
        }
        this.loadingSnapshot = true;
        this.loadingSnapshotMeta = meta;
    } finally {
        this.lock.unlock();
    }
    final InstallSnapshotDone installSnapshotDone = new InstallSnapshotDone(reader);
    if (!this.fsmCaller.onSnapshotLoad(installSnapshotDone)) {
        LOG.warn("Fail to call fsm onSnapshotLoad.");
        installSnapshotDone.run(new Status(RaftError.EHOSTDOWN, "This raft node is down"));
    }
}
Also used : Status(com.alipay.sofa.jraft.Status)

Example 99 with Status

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

the class AbstractClientService method invokeWithDone.

public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) {
    final RpcClient rc = this.rpcClient;
    final FutureImpl<Message> future = new FutureImpl<>();
    final Executor currExecutor = rpcExecutor != null ? rpcExecutor : this.rpcExecutor;
    try {
        if (rc == null) {
            future.failure(new IllegalStateException("Client service is uninitialized."));
            // should be in another thread to avoid dead locking.
            RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Client service is uninitialized."));
            return future;
        }
        rc.invokeAsync(endpoint, request, ctx, new InvokeCallback() {

            @SuppressWarnings({ "unchecked", "ConstantConditions" })
            @Override
            public void complete(final Object result, final Throwable err) {
                if (future.isCancelled()) {
                    onCanceled(request, done);
                    return;
                }
                if (err == null) {
                    Status status = Status.OK();
                    Message msg;
                    if (result instanceof ErrorResponse) {
                        status = handleErrorResponse((ErrorResponse) result);
                        msg = (Message) result;
                    } else if (result instanceof Message) {
                        final Descriptors.FieldDescriptor fd = // 
                        ((Message) result).getDescriptorForType().findFieldByNumber(RpcResponseFactory.ERROR_RESPONSE_NUM);
                        if (fd != null && ((Message) result).hasField(fd)) {
                            final ErrorResponse eResp = (ErrorResponse) ((Message) result).getField(fd);
                            status = handleErrorResponse(eResp);
                            msg = eResp;
                        } else {
                            msg = (T) result;
                        }
                    } else {
                        msg = (T) result;
                    }
                    if (done != null) {
                        try {
                            if (status.isOk()) {
                                done.setResponse((T) msg);
                            }
                            done.run(status);
                        } catch (final Throwable t) {
                            LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
                        }
                    }
                    if (!future.isDone()) {
                        future.setResult(msg);
                    }
                } else {
                    if (done != null) {
                        try {
                            done.run(new Status(err instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT : RaftError.EINTERNAL, "RPC exception:" + err.getMessage()));
                        } catch (final Throwable t) {
                            LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t);
                        }
                    }
                    if (!future.isDone()) {
                        future.failure(err);
                    }
                }
            }

            @Override
            public Executor executor() {
                return currExecutor;
            }
        }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        future.failure(e);
        // should be in another thread to avoid dead locking.
        RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTR, "Sending rpc was interrupted"));
    } catch (final RemotingException e) {
        future.failure(e);
        // should be in another thread to avoid dead locking.
        RpcUtils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage()));
    }
    return future;
}
Also used : Status(com.alipay.sofa.jraft.Status) InvokeCallback(com.alipay.sofa.jraft.rpc.InvokeCallback) InvokeTimeoutException(com.alipay.sofa.jraft.error.InvokeTimeoutException) Message(com.google.protobuf.Message) ErrorResponse(com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Executor(java.util.concurrent.Executor) RemotingException(com.alipay.sofa.jraft.error.RemotingException) Descriptors(com.google.protobuf.Descriptors) RpcClient(com.alipay.sofa.jraft.rpc.RpcClient)

Example 100 with Status

use of com.alipay.sofa.jraft.Status in project jdchain-core by blockchain-jd-com.

the class BlockCommitService method commitBlock.

public boolean commitBlock(Block block, BlockClosure done) throws BlockCommittedException {
    boolean result = true;
    long latestBlockHeight = ledgerRepository.retrieveLatestBlockHeight();
    if (latestBlockHeight >= block.getHeight()) {
        throw new BlockCommittedException(block.getHeight());
    }
    if (latestBlockHeight + 1 != block.getHeight()) {
        notifyCatchUp(block.getHeight());
        LOGGER.error("commit block ignore. expect height:{}, latest block: {}", block.getHeight(), latestBlockHeight);
        return false;
    }
    RaftConsensusMessageContext context = RaftConsensusMessageContext.createContext(realmName);
    context.setTimestamp(block.getProposalTimestamp());
    String batch = messageHandle.beginBatch(context);
    context.setBatchId(batch);
    LoggerUtils.debugIfEnabled(LOGGER, "commit block start, batchId: {}", batch);
    Status status = Status.OK();
    try {
        int msgId = 0;
        for (byte[] tx : block.getTxs()) {
            AsyncFuture<byte[]> asyncFuture = messageHandle.processOrdered(msgId++, tx, context);
            Optional.ofNullable(done).ifPresent(d -> d.addFuture(asyncFuture));
        }
        messageHandle.completeBatch(context);
        // todo ?
        messageHandle.commitBatch(context);
        LedgerBlock repositoryLatestBlock = ledgerRepository.getLatestBlock();
        assert repositoryLatestBlock.getHeight() == block.getHeight();
        block.setPreBlockHash(repositoryLatestBlock.getPreviousHash());
        block.setCurrentBlockHash(repositoryLatestBlock.getHash());
        blockCommitCallbackList.forEach(c -> c.commitCallBack(block, true));
    } catch (Exception e) {
        LOGGER.error("commitBlock error", e);
        result = false;
        messageHandle.rollbackBatch(TransactionState.CONSENSUS_ERROR.CODE, context);
        status = new Status(TransactionState.CONSENSUS_ERROR.CODE, e.getMessage());
        blockCommitCallbackList.forEach(c -> c.commitCallBack(block, false));
    }
    LoggerUtils.debugIfEnabled(LOGGER, "commit block end, batchId: {}, blockHeight: {}, status: {}", batch, block.getHeight(), status);
    if (done != null) {
        done.run(status);
    }
    return result;
}
Also used : Status(com.alipay.sofa.jraft.Status) Longs(com.google.common.primitives.Longs) Logger(org.slf4j.Logger) MessageHandle(com.jd.blockchain.consensus.service.MessageHandle) TransactionState(com.jd.blockchain.ledger.TransactionState) BlockCommitCallback(com.jd.blockchain.consensus.raft.consensus.BlockCommitCallback) MessageBus(com.jd.blockchain.consensus.raft.msgbus.MessageBus) BlockCommittedException(com.jd.blockchain.consensus.raft.consensus.BlockCommittedException) LoggerFactory(org.slf4j.LoggerFactory) LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) LedgerRepository(com.jd.blockchain.ledger.core.LedgerRepository) Status(com.alipay.sofa.jraft.Status) LoggerUtils(com.jd.blockchain.consensus.raft.util.LoggerUtils) ArrayList(java.util.ArrayList) List(java.util.List) AsyncFuture(utils.concurrent.AsyncFuture) BLOCK_CATCH_UP_TOPIC(com.jd.blockchain.consensus.raft.msgbus.MessageBus.BLOCK_CATCH_UP_TOPIC) Block(com.jd.blockchain.consensus.raft.consensus.Block) Optional(java.util.Optional) BlockCommitter(com.jd.blockchain.consensus.raft.consensus.BlockCommitter) LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) BlockCommittedException(com.jd.blockchain.consensus.raft.consensus.BlockCommittedException) BlockCommittedException(com.jd.blockchain.consensus.raft.consensus.BlockCommittedException)

Aggregations

Status (com.alipay.sofa.jraft.Status)213 Test (org.junit.Test)63 PeerId (com.alipay.sofa.jraft.entity.PeerId)55 CountDownLatch (java.util.concurrent.CountDownLatch)36 BaseKVStoreClosure (com.alipay.sofa.jraft.rhea.storage.BaseKVStoreClosure)33 Configuration (com.alipay.sofa.jraft.conf.Configuration)25 Message (com.google.protobuf.Message)24 ReadIndexClosure (com.alipay.sofa.jraft.closure.ReadIndexClosure)22 ArrayList (java.util.ArrayList)22 Node (com.alipay.sofa.jraft.Node)21 Closure (com.alipay.sofa.jraft.Closure)17 Task (com.alipay.sofa.jraft.entity.Task)17 ByteBuffer (java.nio.ByteBuffer)16 Endpoint (com.alipay.sofa.jraft.util.Endpoint)15 List (java.util.List)15 RaftException (com.alipay.sofa.jraft.error.RaftException)14 LogEntry (com.alipay.sofa.jraft.entity.LogEntry)12 LogId (com.alipay.sofa.jraft.entity.LogId)12 KVStoreClosure (com.alipay.sofa.jraft.rhea.storage.KVStoreClosure)12 JRaftException (com.alipay.sofa.jraft.error.JRaftException)11