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");
}
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);
}
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"));
}
}
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;
}
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;
}
Aggregations