use of com.alipay.sofa.jraft.Closure in project nacos by alibaba.
the class NacosStateMachine method onApply.
@Override
public void onApply(Iterator iter) {
int index = 0;
int applied = 0;
Message message;
NacosClosure closure = null;
try {
while (iter.hasNext()) {
Status status = Status.OK();
try {
if (iter.done() != null) {
closure = (NacosClosure) iter.done();
message = closure.getMessage();
} else {
final ByteBuffer data = iter.getData();
message = ProtoMessageUtil.parse(data.array());
if (message instanceof ReadRequest) {
// 'iter.done() == null' means current node is follower, ignore read operation
applied++;
index++;
iter.next();
continue;
}
}
LoggerUtils.printIfDebugEnabled(Loggers.RAFT, "receive log : {}", message);
if (message instanceof WriteRequest) {
Response response = processor.onApply((WriteRequest) message);
postProcessor(response, closure);
}
if (message instanceof ReadRequest) {
Response response = processor.onRequest((ReadRequest) message);
postProcessor(response, closure);
}
} catch (Throwable e) {
index++;
status.setError(RaftError.UNKNOWN, e.toString());
Optional.ofNullable(closure).ifPresent(closure1 -> closure1.setThrowable(e));
throw e;
} finally {
Optional.ofNullable(closure).ifPresent(closure1 -> closure1.run(status));
}
applied++;
index++;
iter.next();
}
} catch (Throwable t) {
Loggers.RAFT.error("processor : {}, stateMachine meet critical error: {}.", processor, t);
iter.setErrorAndRollback(index - applied, new Status(RaftError.ESTATEMACHINE, "StateMachine meet critical error: %s.", ExceptionUtil.getStackTrace(t)));
}
}
use of com.alipay.sofa.jraft.Closure in project nacos by alibaba.
the class NacosStateMachine method adapterToJRaftSnapshot.
private void adapterToJRaftSnapshot(Collection<SnapshotOperation> userOperates) {
List<JSnapshotOperation> tmp = new ArrayList<>();
for (SnapshotOperation item : userOperates) {
if (item == null) {
Loggers.RAFT.error("Existing SnapshotOperation for null");
continue;
}
tmp.add(new JSnapshotOperation() {
@Override
public void onSnapshotSave(SnapshotWriter writer, Closure done) {
final Writer wCtx = new Writer(writer.getPath());
// Do a layer of proxy operation to shield different Raft
// components from implementing snapshots
final BiConsumer<Boolean, Throwable> callFinally = (result, t) -> {
boolean[] results = new boolean[wCtx.listFiles().size()];
int[] index = new int[] { 0 };
wCtx.listFiles().forEach((file, meta) -> {
try {
results[index[0]++] = writer.addFile(file, buildMetadata(meta));
} catch (Exception e) {
throw new ConsistencyException(e);
}
});
final Status status = result && !Arrays.asList(results).stream().anyMatch(Boolean.FALSE::equals) ? Status.OK() : new Status(RaftError.EIO, "Fail to compress snapshot at %s, error is %s", writer.getPath(), t == null ? "" : t.getMessage());
done.run(status);
};
item.onSnapshotSave(wCtx, callFinally);
}
@Override
public boolean onSnapshotLoad(SnapshotReader reader) {
final Map<String, LocalFileMeta> metaMap = new HashMap<>(reader.listFiles().size());
for (String fileName : reader.listFiles()) {
final LocalFileMetaOutter.LocalFileMeta meta = (LocalFileMetaOutter.LocalFileMeta) reader.getFileMeta(fileName);
byte[] bytes = meta.getUserMeta().toByteArray();
final LocalFileMeta fileMeta;
if (bytes == null || bytes.length == 0) {
fileMeta = new LocalFileMeta();
} else {
fileMeta = JacksonUtils.toObj(bytes, LocalFileMeta.class);
}
metaMap.put(fileName, fileMeta);
}
final Reader rCtx = new Reader(reader.getPath(), metaMap);
return item.onSnapshotLoad(rCtx);
}
@Override
public String info() {
return item.toString();
}
});
}
this.operations = Collections.unmodifiableList(tmp);
}
use of com.alipay.sofa.jraft.Closure in project sofa-jraft by sofastack.
the class AddLearnersRequestProcessorTest method verify.
@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());
}
use of com.alipay.sofa.jraft.Closure in project sofa-jraft by sofastack.
the class ChangePeersRequestProcessorTest method verify.
@Override
public void verify(String interest, Node node, ArgumentCaptor<Closure> doneArg) {
assertEquals(interest, ChangePeersRequest.class.getName());
Mockito.verify(node).changePeers(eq(JRaftUtils.getConfiguration("localhost:8084,localhost:8085")), 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(ChangePeersResponse.class).getOldPeersList().toString());
assertEquals("[localhost:8084, localhost:8085]", this.asyncContext.as(ChangePeersResponse.class).getNewPeersList().toString());
}
use of com.alipay.sofa.jraft.Closure in project sofa-jraft by sofastack.
the class ResetLearnersRequestProcessorTest method verify.
@Override
public void verify(final String interest, final Node node, final ArgumentCaptor<Closure> doneArg) {
assertEquals(interest, ResetLearnersRequest.class.getName());
Mockito.verify(node).resetLearners(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:8082, test:8182, test:8183]", this.asyncContext.as(LearnersOpResponse.class).getNewLearnersList().toString());
}
Aggregations