use of com.alibaba.nacos.consistency.entity.WriteRequest 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.alibaba.nacos.consistency.entity.WriteRequest in project nacos by alibaba.
the class ProtoMessageUtilTest method testParseWriteRequest.
@Test
public void testParseWriteRequest() {
String group = "test";
ByteString data = ByteString.copyFrom("data".getBytes());
WriteRequest testCase = WriteRequest.newBuilder().setGroup(group).setData(data).build();
Object actual = ProtoMessageUtil.parse(testCase.toByteArray());
assertEquals(WriteRequest.class, testCase.getClass());
assertEquals(group, ((WriteRequest) actual).getGroup());
assertEquals(data, ((WriteRequest) actual).getData());
}
use of com.alibaba.nacos.consistency.entity.WriteRequest in project nacos by alibaba.
the class ProtoMessageUtilTest method testParseWriteRequestWithRequestTypeField.
@Test
public void testParseWriteRequestWithRequestTypeField() {
String group = "test";
ByteString data = ByteString.copyFrom("data".getBytes());
WriteRequest testCase = WriteRequest.newBuilder().setGroup(group).setData(data).build();
byte[] requestTypeFieldBytes = new byte[2];
requestTypeFieldBytes[0] = ProtoMessageUtil.REQUEST_TYPE_FIELD_TAG;
requestTypeFieldBytes[1] = ProtoMessageUtil.REQUEST_TYPE_WRITE;
byte[] dataBytes = testCase.toByteArray();
ByteBuffer byteBuffer = (ByteBuffer) ByteBuffer.allocate(requestTypeFieldBytes.length + dataBytes.length).put(requestTypeFieldBytes).put(dataBytes).position(0);
Object actual = ProtoMessageUtil.parse(byteBuffer.array());
assertEquals(WriteRequest.class, testCase.getClass());
assertEquals(group, ((WriteRequest) actual).getGroup());
assertEquals(data, ((WriteRequest) actual).getData());
}
use of com.alibaba.nacos.consistency.entity.WriteRequest in project nacos by alibaba.
the class JRaftServerTest method testCommit.
@Test
public void testCommit() throws NoSuchFieldException, IllegalAccessException, TimeoutException, InterruptedException {
WriteRequest.Builder writeRequestBuilder = WriteRequest.newBuilder();
WriteRequest writeRequest = writeRequestBuilder.build();
// No group is set, and make sure that an IllegalArgumentException will be thrown.
CompletableFuture<Response> future = server.commit(groupId, writeRequest, this.future);
verify(future).completeExceptionally(any(IllegalArgumentException.class));
// Set an group.
Collection<RequestProcessor4CP> processors = Collections.singletonList(mockProcessor4CP);
server.createMultiRaftGroup(processors);
Field cliClientServiceField = JRaftServer.class.getDeclaredField("cliClientService");
cliClientServiceField.setAccessible(true);
cliClientServiceField.set(server, cliClientServiceMock);
// Make the node leader and verify the invokeToLeader is never called.
NodeImpl node = (NodeImpl) server.findNodeByGroup(groupId);
Field stateField = NodeImpl.class.getDeclaredField("state");
stateField.setAccessible(true);
stateField.set(node, State.STATE_LEADER);
server.commit(groupId, writeRequest, future);
verify(cliClientServiceMock, never()).getRpcClient();
// make the node follower and verify the invokeToLeader is called.
node = (NodeImpl) server.findNodeByGroup(groupId);
stateField.setAccessible(true);
stateField.set(node, State.STATE_FOLLOWER);
RouteTable.getInstance().updateLeader(groupId, peerId1);
server.commit(groupId, writeRequest, future);
verify(cliClientServiceMock).getRpcClient();
}
use of com.alibaba.nacos.consistency.entity.WriteRequest in project nacos by alibaba.
the class ServiceMetadataProcessorTest method testOnApply.
@Test
public void testOnApply() throws NoSuchFieldException, IllegalAccessException {
WriteRequest defaultInstance = WriteRequest.getDefaultInstance();
Class<WriteRequest> writeRequestClass = WriteRequest.class;
Field operation = writeRequestClass.getDeclaredField("operation_");
operation.setAccessible(true);
operation.set(defaultInstance, "ADD");
MetadataOperation<ServiceMetadata> metadataOperation = new MetadataOperation<>();
ServiceMetadata serviceMetadata = new ServiceMetadata();
metadataOperation.setMetadata(serviceMetadata);
metadataOperation.setServiceName("nacos");
metadataOperation.setNamespace("namespace");
metadataOperation.setGroup("group");
Serializer aDefault = SerializeFactory.getDefault();
ByteString bytes = ByteString.copyFrom(aDefault.serialize(metadataOperation));
Field data = writeRequestClass.getDeclaredField("data_");
data.setAccessible(true);
data.set(defaultInstance, bytes);
// ADD
Response addResponse = serviceMetadataProcessor.onApply(defaultInstance);
Service service = Service.newService(metadataOperation.getNamespace(), metadataOperation.getGroup(), metadataOperation.getServiceName(), metadataOperation.getMetadata().isEphemeral());
Service singleton = ServiceManager.getInstance().getSingleton(service);
namingMetadataManager.updateServiceMetadata(singleton, metadataOperation.getMetadata());
Assert.assertTrue(addResponse.getSuccess());
verify(namingMetadataManager).getServiceMetadata(service);
verify(namingMetadataManager).updateServiceMetadata(service, serviceMetadata);
verify(context).getBean(DoubleWriteEventListener.class);
// CHANGE
operation.set(defaultInstance, "CHANGE");
Response changeResponse = serviceMetadataProcessor.onApply(defaultInstance);
Assert.assertTrue(changeResponse.getSuccess());
verify(namingMetadataManager, times(2)).getServiceMetadata(service);
verify(namingMetadataManager).updateServiceMetadata(service, serviceMetadata);
verify(context, times(2)).getBean(DoubleWriteEventListener.class);
// DELETE
operation.set(defaultInstance, "DELETE");
Response deleteResponse = serviceMetadataProcessor.onApply(defaultInstance);
Assert.assertTrue(deleteResponse.getSuccess());
verify(namingMetadataManager).removeServiceMetadata(service);
verify(serviceStorage).removeData(service);
// VERIFY
operation.set(defaultInstance, "VERIFY");
Response otherResponse = serviceMetadataProcessor.onApply(defaultInstance);
Assert.assertFalse(otherResponse.getSuccess());
}
Aggregations