[ISSUE #11057]Add update instance and update service trace event for naming. (#11069)

* [ISSUE #11057]Add update instance and update service trace event for naming.

* [ISSUE #11057]Add license.

* [ISSUE #11057]Remove unused imports.

* [ISSUE #11057]Improve the logic.

* [ISSUE #11057]Fix checkStyle.

* [ISSUE #11057]Perfect unit test.

* [ISSUE #11057]Improve the logic.

* [ISSUE #11057]Improve the logic.

* [ISSUE #11057]UpdateInstanceTraceEvent add metadata.

* [ISSUE #11057]UpdateServiceTraceEvent.java add metadata.
This commit is contained in:
阿魁 2023-09-06 17:01:16 +08:00 committed by GitHub
parent 52a4666c94
commit 02fcbb0915
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 383 additions and 151 deletions

View File

@ -0,0 +1,64 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.trace.event.naming;
import java.util.Map;
/**
* Naming update instance trace event.
*
* @author stone-98
* @date 2023/8/31
*/
public class UpdateInstanceTraceEvent extends NamingTraceEvent {
private static final long serialVersionUID = -6995370254824508523L;
private final Map<String, String> metadata;
private final String clientIp;
private final String instanceIp;
private final int instancePort;
public String getClientIp() {
return clientIp;
}
public String getInstanceIp() {
return instanceIp;
}
public int getInstancePort() {
return instancePort;
}
public String toInetAddr() {
return instanceIp + ":" + instancePort;
}
public UpdateInstanceTraceEvent(long eventTime, String clientIp, String serviceNamespace, String serviceGroup,
String serviceName, String instanceIp, int instancePort, Map<String, String> metadata) {
super("UPDATE_INSTANCE_TRACE_EVENT", eventTime, serviceNamespace, serviceGroup, serviceName);
this.clientIp = clientIp;
this.instanceIp = instanceIp;
this.instancePort = instancePort;
this.metadata = metadata;
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.trace.event.naming;
import java.util.Map;
/**
* Naming update service trace event.
*
* @author stone-98
* @date 2023/8/31
*/
public class UpdateServiceTraceEvent extends NamingTraceEvent {
private static final long serialVersionUID = -6792054530665003857L;
private final Map<String, String> metadata;
public UpdateServiceTraceEvent(long eventTime, String serviceNamespace, String serviceGroup, String serviceName,
Map<String, String> metadata) {
super("UPDATE_SERVICE_TRACE_EVENT", eventTime, serviceNamespace, serviceGroup, serviceName);
this.metadata = metadata;
}
}

View File

@ -27,6 +27,7 @@ import com.alibaba.nacos.common.spi.NacosServiceLoader;
import com.alibaba.nacos.common.trace.DeregisterInstanceReason; import com.alibaba.nacos.common.trace.DeregisterInstanceReason;
import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.UpdateInstanceTraceEvent;
import com.alibaba.nacos.common.utils.ConvertUtils; import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
@ -102,8 +103,8 @@ public class InstanceController {
@Secured(action = ActionTypes.WRITE) @Secured(action = ActionTypes.WRITE)
public String register(HttpServletRequest request) throws Exception { public String register(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); Constants.DEFAULT_NAMESPACE_ID);
final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
NamingUtils.checkServiceNameFormat(serviceName); NamingUtils.checkServiceNameFormat(serviceName);
@ -158,6 +159,9 @@ public class InstanceController {
Instance instance = HttpRequestInstanceBuilder.newBuilder() Instance instance = HttpRequestInstanceBuilder.newBuilder()
.setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build(); .setDefaultInstanceEphemeral(switchDomain.isDefaultInstanceEphemeral()).setRequest(request).build();
getInstanceOperator().updateInstance(namespaceId, serviceName, instance); getInstanceOperator().updateInstance(namespaceId, serviceName, instance);
NotifyCenter.publishEvent(new UpdateInstanceTraceEvent(System.currentTimeMillis(), "", namespaceId,
NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), instance.getIp(),
instance.getPort(), instance.getMetadata()));
return "ok"; return "ok";
} }
@ -173,8 +177,8 @@ public class InstanceController {
@PutMapping(value = "/metadata/batch") @PutMapping(value = "/metadata/batch")
@Secured(action = ActionTypes.WRITE) @Secured(action = ActionTypes.WRITE)
public ObjectNode batchUpdateInstanceMetadata(HttpServletRequest request) throws Exception { public ObjectNode batchUpdateInstanceMetadata(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
String consistencyType = WebUtils.optional(request, "consistencyType", StringUtils.EMPTY); String consistencyType = WebUtils.optional(request, "consistencyType", StringUtils.EMPTY);
String instances = WebUtils.optional(request, "instances", StringUtils.EMPTY); String instances = WebUtils.optional(request, "instances", StringUtils.EMPTY);
@ -183,8 +187,8 @@ public class InstanceController {
Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(metadata); Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(metadata);
InstanceOperationInfo instanceOperationInfo = buildOperationInfo(serviceName, consistencyType, targetInstances); InstanceOperationInfo instanceOperationInfo = buildOperationInfo(serviceName, consistencyType, targetInstances);
List<String> operatedInstances = getInstanceOperator() List<String> operatedInstances = getInstanceOperator().batchUpdateMetadata(namespaceId, instanceOperationInfo,
.batchUpdateMetadata(namespaceId, instanceOperationInfo, targetMetadata); targetMetadata);
ObjectNode result = JacksonUtils.createEmptyJsonNode(); ObjectNode result = JacksonUtils.createEmptyJsonNode();
ArrayNode ipArray = JacksonUtils.createEmptyArrayNode(); ArrayNode ipArray = JacksonUtils.createEmptyArrayNode();
for (String ip : operatedInstances) { for (String ip : operatedInstances) {
@ -206,8 +210,8 @@ public class InstanceController {
@DeleteMapping("/metadata/batch") @DeleteMapping("/metadata/batch")
@Secured(action = ActionTypes.WRITE) @Secured(action = ActionTypes.WRITE)
public ObjectNode batchDeleteInstanceMetadata(HttpServletRequest request) throws Exception { public ObjectNode batchDeleteInstanceMetadata(HttpServletRequest request) throws Exception {
final String namespaceId = WebUtils final String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
String consistencyType = WebUtils.optional(request, "consistencyType", StringUtils.EMPTY); String consistencyType = WebUtils.optional(request, "consistencyType", StringUtils.EMPTY);
String instances = WebUtils.optional(request, "instances", StringUtils.EMPTY); String instances = WebUtils.optional(request, "instances", StringUtils.EMPTY);
@ -215,8 +219,8 @@ public class InstanceController {
String metadata = WebUtils.required(request, METADATA); String metadata = WebUtils.required(request, METADATA);
Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(metadata); Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(metadata);
InstanceOperationInfo instanceOperationInfo = buildOperationInfo(serviceName, consistencyType, targetInstances); InstanceOperationInfo instanceOperationInfo = buildOperationInfo(serviceName, consistencyType, targetInstances);
List<String> operatedInstances = getInstanceOperator() List<String> operatedInstances = getInstanceOperator().batchDeleteMetadata(namespaceId, instanceOperationInfo,
.batchDeleteMetadata(namespaceId, instanceOperationInfo, targetMetadata); targetMetadata);
ObjectNode result = JacksonUtils.createEmptyJsonNode(); ObjectNode result = JacksonUtils.createEmptyJsonNode();
ArrayNode ipArray = JacksonUtils.createEmptyArrayNode(); ArrayNode ipArray = JacksonUtils.createEmptyArrayNode();
@ -336,8 +340,8 @@ public class InstanceController {
String ip = WebUtils.required(request, "ip"); String ip = WebUtils.required(request, "ip");
int port = Integer.parseInt(WebUtils.required(request, "port")); int port = Integer.parseInt(WebUtils.required(request, "port"));
com.alibaba.nacos.api.naming.pojo.Instance instance = getInstanceOperator() com.alibaba.nacos.api.naming.pojo.Instance instance = getInstanceOperator().getInstance(namespaceId,
.getInstance(namespaceId, serviceName, cluster, ip, port); serviceName, cluster, ip, port);
ObjectNode result = JacksonUtils.createEmptyJsonNode(); ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.put("service", serviceName); result.put("service", serviceName);
result.put("ip", ip); result.put("ip", ip);
@ -370,8 +374,8 @@ public class InstanceController {
if (StringUtils.isNotBlank(beat)) { if (StringUtils.isNotBlank(beat)) {
clientBeat = JacksonUtils.toObj(beat, RsInfo.class); clientBeat = JacksonUtils.toObj(beat, RsInfo.class);
} }
String clusterName = WebUtils String clusterName = WebUtils.optional(request, CommonParams.CLUSTER_NAME,
.optional(request, CommonParams.CLUSTER_NAME, UtilsAndCommons.DEFAULT_CLUSTER_NAME); UtilsAndCommons.DEFAULT_CLUSTER_NAME);
String ip = WebUtils.optional(request, "ip", StringUtils.EMPTY); String ip = WebUtils.optional(request, "ip", StringUtils.EMPTY);
int port = Integer.parseInt(WebUtils.optional(request, "port", "0")); int port = Integer.parseInt(WebUtils.optional(request, "port", "0"));
if (clientBeat != null) { if (clientBeat != null) {
@ -391,8 +395,8 @@ public class InstanceController {
serviceName, namespaceId); serviceName, namespaceId);
BeatInfoInstanceBuilder builder = BeatInfoInstanceBuilder.newBuilder(); BeatInfoInstanceBuilder builder = BeatInfoInstanceBuilder.newBuilder();
builder.setRequest(request); builder.setRequest(request);
int resultCode = getInstanceOperator() int resultCode = getInstanceOperator().handleBeat(namespaceId, serviceName, ip, port, clusterName, clientBeat,
.handleBeat(namespaceId, serviceName, ip, port, clusterName, clientBeat, builder); builder);
result.put(CommonParams.CODE, resultCode); result.put(CommonParams.CODE, resultCode);
result.put(SwitchEntry.CLIENT_BEAT_INTERVAL, result.put(SwitchEntry.CLIENT_BEAT_INTERVAL,
getInstanceOperator().getHeartBeatInterval(namespaceId, serviceName, ip, port, clusterName)); getInstanceOperator().getHeartBeatInterval(namespaceId, serviceName, ip, port, clusterName));
@ -422,8 +426,8 @@ public class InstanceController {
} }
NamingUtils.checkServiceNameFormat(serviceName); NamingUtils.checkServiceNameFormat(serviceName);
List<? extends com.alibaba.nacos.api.naming.pojo.Instance> ips = getInstanceOperator() List<? extends com.alibaba.nacos.api.naming.pojo.Instance> ips = getInstanceOperator().listAllInstances(
.listAllInstances(namespaceId, serviceName); namespaceId, serviceName);
ObjectNode result = JacksonUtils.createEmptyJsonNode(); ObjectNode result = JacksonUtils.createEmptyJsonNode();
ArrayNode ipArray = JacksonUtils.createEmptyArrayNode(); ArrayNode ipArray = JacksonUtils.createEmptyArrayNode();

View File

@ -27,6 +27,7 @@ import com.alibaba.nacos.common.model.RestResultUtils;
import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.trace.event.naming.DeregisterServiceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.DeregisterServiceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.RegisterServiceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.RegisterServiceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.UpdateServiceTraceEvent;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.NumberUtils; import com.alibaba.nacos.common.utils.NumberUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
@ -179,15 +180,17 @@ public class ServiceController {
public String update(HttpServletRequest request) throws Exception { public String update(HttpServletRequest request) throws Exception {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
Map<String, String> metadata = UtilsAndCommons.parseMetadata(
WebUtils.optional(request, "metadata", StringUtils.EMPTY));
ServiceMetadata serviceMetadata = new ServiceMetadata(); ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setProtectThreshold(NumberUtils.toFloat(WebUtils.required(request, "protectThreshold"))); serviceMetadata.setProtectThreshold(NumberUtils.toFloat(WebUtils.required(request, "protectThreshold")));
serviceMetadata.setExtendData( serviceMetadata.setExtendData(metadata);
UtilsAndCommons.parseMetadata(WebUtils.optional(request, "metadata", StringUtils.EMPTY)));
serviceMetadata.setSelector(parseSelector(WebUtils.optional(request, "selector", StringUtils.EMPTY))); serviceMetadata.setSelector(parseSelector(WebUtils.optional(request, "selector", StringUtils.EMPTY)));
com.alibaba.nacos.naming.core.v2.pojo.Service service = com.alibaba.nacos.naming.core.v2.pojo.Service com.alibaba.nacos.naming.core.v2.pojo.Service service = com.alibaba.nacos.naming.core.v2.pojo.Service.newService(
.newService(namespaceId, NamingUtils.getGroupName(serviceName), namespaceId, NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName));
NamingUtils.getServiceName(serviceName));
getServiceOperator().update(service, serviceMetadata); getServiceOperator().update(service, serviceMetadata);
NotifyCenter.publishEvent(new UpdateServiceTraceEvent(System.currentTimeMillis(), namespaceId,
NamingUtils.getGroupName(serviceName), NamingUtils.getServiceName(serviceName), metadata));
return "ok"; return "ok";
} }
@ -236,8 +239,8 @@ public class ServiceController {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
boolean aggregation = Boolean boolean aggregation = Boolean.parseBoolean(
.parseBoolean(WebUtils.optional(request, "aggregation", String.valueOf(Boolean.TRUE))); WebUtils.optional(request, "aggregation", String.valueOf(Boolean.TRUE)));
ObjectNode result = JacksonUtils.createEmptyJsonNode(); ObjectNode result = JacksonUtils.createEmptyJsonNode();

View File

@ -33,6 +33,7 @@ import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.trace.DeregisterInstanceReason; import com.alibaba.nacos.common.trace.DeregisterInstanceReason;
import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.UpdateInstanceTraceEvent;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl; import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl;
@ -103,10 +104,12 @@ public class InstanceControllerV2 {
checkWeight(instanceForm.getWeight()); checkWeight(instanceForm.getWeight());
// build instance // build instance
Instance instance = buildInstance(instanceForm); Instance instance = buildInstance(instanceForm);
instanceServiceV2.registerInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm), instance); instanceServiceV2.registerInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm),
NotifyCenter.publishEvent(new RegisterInstanceTraceEvent(System.currentTimeMillis(), "", instance);
false, instanceForm.getNamespaceId(), instanceForm.getGroupName(), instanceForm.getServiceName(), NotifyCenter.publishEvent(
instance.getIp(), instance.getPort())); new RegisterInstanceTraceEvent(System.currentTimeMillis(), "", false, instanceForm.getNamespaceId(),
instanceForm.getGroupName(), instanceForm.getServiceName(), instance.getIp(),
instance.getPort()));
return Result.success("ok"); return Result.success("ok");
} }
@ -122,9 +125,10 @@ public class InstanceControllerV2 {
checkWeight(instanceForm.getWeight()); checkWeight(instanceForm.getWeight());
// build instance // build instance
Instance instance = buildInstance(instanceForm); Instance instance = buildInstance(instanceForm);
instanceServiceV2.removeInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm), instance); instanceServiceV2.removeInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm),
NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), "", instance);
false, DeregisterInstanceReason.REQUEST, instanceForm.getNamespaceId(), instanceForm.getGroupName(), NotifyCenter.publishEvent(new DeregisterInstanceTraceEvent(System.currentTimeMillis(), "", false,
DeregisterInstanceReason.REQUEST, instanceForm.getNamespaceId(), instanceForm.getGroupName(),
instanceForm.getServiceName(), instance.getIp(), instance.getPort())); instanceForm.getServiceName(), instance.getIp(), instance.getPort()));
return Result.success("ok"); return Result.success("ok");
} }
@ -141,7 +145,12 @@ public class InstanceControllerV2 {
checkWeight(instanceForm.getWeight()); checkWeight(instanceForm.getWeight());
// build instance // build instance
Instance instance = buildInstance(instanceForm); Instance instance = buildInstance(instanceForm);
instanceServiceV2.updateInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm), instance); instanceServiceV2.updateInstance(instanceForm.getNamespaceId(), buildCompositeServiceName(instanceForm),
instance);
NotifyCenter.publishEvent(
new UpdateInstanceTraceEvent(System.currentTimeMillis(), "", instanceForm.getNamespaceId(),
instanceForm.getGroupName(), instanceForm.getServiceName(), instance.getIp(),
instance.getPort(), instance.getMetadata()));
return Result.success("ok"); return Result.success("ok");
} }
@ -157,11 +166,12 @@ public class InstanceControllerV2 {
List<Instance> targetInstances = parseBatchInstances(form.getInstances()); List<Instance> targetInstances = parseBatchInstances(form.getInstances());
Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(form.getMetadata()); Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(form.getMetadata());
InstanceOperationInfo instanceOperationInfo = buildOperationInfo(buildCompositeServiceName(form), form.getConsistencyType(), targetInstances); InstanceOperationInfo instanceOperationInfo = buildOperationInfo(buildCompositeServiceName(form),
form.getConsistencyType(), targetInstances);
List<String> operatedInstances = instanceServiceV2
.batchUpdateMetadata(form.getNamespaceId(), instanceOperationInfo, targetMetadata); List<String> operatedInstances = instanceServiceV2.batchUpdateMetadata(form.getNamespaceId(),
instanceOperationInfo, targetMetadata);
ArrayList<String> ipList = new ArrayList<>(operatedInstances); ArrayList<String> ipList = new ArrayList<>(operatedInstances);
return Result.success(new InstanceMetadataBatchOperationVo(ipList)); return Result.success(new InstanceMetadataBatchOperationVo(ipList));
} }
@ -177,9 +187,10 @@ public class InstanceControllerV2 {
form.validate(); form.validate();
List<Instance> targetInstances = parseBatchInstances(form.getInstances()); List<Instance> targetInstances = parseBatchInstances(form.getInstances());
Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(form.getMetadata()); Map<String, String> targetMetadata = UtilsAndCommons.parseMetadata(form.getMetadata());
InstanceOperationInfo instanceOperationInfo = buildOperationInfo(buildCompositeServiceName(form), form.getConsistencyType(), targetInstances); InstanceOperationInfo instanceOperationInfo = buildOperationInfo(buildCompositeServiceName(form),
List<String> operatedInstances = instanceServiceV2 form.getConsistencyType(), targetInstances);
.batchDeleteMetadata(form.getNamespaceId(), instanceOperationInfo, targetMetadata); List<String> operatedInstances = instanceServiceV2.batchDeleteMetadata(form.getNamespaceId(),
instanceOperationInfo, targetMetadata);
ArrayList<String> ipList = new ArrayList<>(operatedInstances); ArrayList<String> ipList = new ArrayList<>(operatedInstances);
return Result.success(new InstanceMetadataBatchOperationVo(ipList)); return Result.success(new InstanceMetadataBatchOperationVo(ipList));
} }
@ -248,6 +259,7 @@ public class InstanceControllerV2 {
/** /**
* Get all instance of input service. * Get all instance of input service.
*
* @param namespaceId namespace id * @param namespaceId namespace id
* @param groupName group name * @param groupName group name
* @param serviceName service name * @param serviceName service name
@ -261,7 +273,8 @@ public class InstanceControllerV2 {
*/ */
@GetMapping("/list") @GetMapping("/list")
@Secured(action = ActionTypes.READ) @Secured(action = ActionTypes.READ)
public Result<ServiceInfo> list(@RequestParam(value = "namespaceId", defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId, public Result<ServiceInfo> list(
@RequestParam(value = "namespaceId", defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName, @RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName,
@RequestParam("serviceName") String serviceName, @RequestParam("serviceName") String serviceName,
@RequestParam(value = "clusterName", defaultValue = StringUtils.EMPTY) String clusterName, @RequestParam(value = "clusterName", defaultValue = StringUtils.EMPTY) String clusterName,
@ -277,7 +290,8 @@ public class InstanceControllerV2 {
String compositeServiceName = NamingUtils.getGroupedName(serviceName, groupName); String compositeServiceName = NamingUtils.getGroupedName(serviceName, groupName);
Subscriber subscriber = new Subscriber(ip + ":" + port, userAgent, app, ip, namespaceId, compositeServiceName, Subscriber subscriber = new Subscriber(ip + ":" + port, userAgent, app, ip, namespaceId, compositeServiceName,
port, clusterName); port, clusterName);
return Result.success(instanceServiceV2.listInstance(namespaceId, compositeServiceName, subscriber, clusterName, healthyOnly)); return Result.success(instanceServiceV2.listInstance(namespaceId, compositeServiceName, subscriber, clusterName,
healthyOnly));
} }
/** /**
@ -293,14 +307,15 @@ public class InstanceControllerV2 {
*/ */
@GetMapping @GetMapping
@Secured(action = ActionTypes.READ) @Secured(action = ActionTypes.READ)
public Result<InstanceDetailInfoVo> detail(@RequestParam(value = "namespaceId", defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId, public Result<InstanceDetailInfoVo> detail(
@RequestParam(value = "namespaceId", defaultValue = Constants.DEFAULT_NAMESPACE_ID) String namespaceId,
@RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName, @RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName,
@RequestParam("serviceName") String serviceName, @RequestParam("serviceName") String serviceName,
@RequestParam(value = "clusterName", defaultValue = UtilsAndCommons.DEFAULT_CLUSTER_NAME) String clusterName, @RequestParam(value = "clusterName", defaultValue = UtilsAndCommons.DEFAULT_CLUSTER_NAME) String clusterName,
@RequestParam("ip") String ip, @RequestParam("port") Integer port) throws NacosException { @RequestParam("ip") String ip, @RequestParam("port") Integer port) throws NacosException {
String compositeServiceName = NamingUtils.getGroupedName(serviceName, groupName); String compositeServiceName = NamingUtils.getGroupedName(serviceName, groupName);
Instance instance = instanceServiceV2.getInstance(namespaceId, compositeServiceName, clusterName, ip, port); Instance instance = instanceServiceV2.getInstance(namespaceId, compositeServiceName, clusterName, ip, port);
InstanceDetailInfoVo instanceDetailInfoVo = new InstanceDetailInfoVo(); InstanceDetailInfoVo instanceDetailInfoVo = new InstanceDetailInfoVo();
@ -357,8 +372,8 @@ public class InstanceControllerV2 {
Loggers.SRV_LOG.debug("[CLIENT-BEAT] full arguments: beat: {}, serviceName: {}, namespaceId: {}", clientBeat, Loggers.SRV_LOG.debug("[CLIENT-BEAT] full arguments: beat: {}, serviceName: {}, namespaceId: {}", clientBeat,
serviceName, namespaceId); serviceName, namespaceId);
BeatInfoInstanceBuilder builder = BeatInfoInstanceBuilder.newBuilder(); BeatInfoInstanceBuilder builder = BeatInfoInstanceBuilder.newBuilder();
int resultCode = instanceServiceV2 int resultCode = instanceServiceV2.handleBeat(namespaceId, serviceName, ip, port, clusterName, clientBeat,
.handleBeat(namespaceId, serviceName, ip, port, clusterName, clientBeat, builder); builder);
result.put(CommonParams.CODE, resultCode); result.put(CommonParams.CODE, resultCode);
result.put(SwitchEntry.CLIENT_BEAT_INTERVAL, result.put(SwitchEntry.CLIENT_BEAT_INTERVAL,
instanceServiceV2.getHeartBeatInterval(namespaceId, serviceName, ip, port, clusterName)); instanceServiceV2.getHeartBeatInterval(namespaceId, serviceName, ip, port, clusterName));
@ -402,24 +417,20 @@ public class InstanceControllerV2 {
private void checkWeight(Double weight) throws NacosException { private void checkWeight(Double weight) throws NacosException {
if (weight > com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE if (weight > com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE
|| weight < com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE) { || weight < com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE) {
throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.WEIGHT_ERROR, "instance format invalid: The weights range from " throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.WEIGHT_ERROR,
+ com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE + " to " "instance format invalid: The weights range from "
+ com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE); + com.alibaba.nacos.naming.constants.Constants.MIN_WEIGHT_VALUE + " to "
+ com.alibaba.nacos.naming.constants.Constants.MAX_WEIGHT_VALUE);
} }
} }
private Instance buildInstance(InstanceForm instanceForm) throws NacosException { private Instance buildInstance(InstanceForm instanceForm) throws NacosException {
Instance instance = InstanceBuilder.newBuilder() Instance instance = InstanceBuilder.newBuilder().setServiceName(buildCompositeServiceName(instanceForm))
.setServiceName(buildCompositeServiceName(instanceForm)) .setIp(instanceForm.getIp()).setClusterName(instanceForm.getClusterName())
.setIp(instanceForm.getIp()) .setPort(instanceForm.getPort()).setHealthy(instanceForm.getHealthy())
.setClusterName(instanceForm.getClusterName()) .setWeight(instanceForm.getWeight()).setEnabled(instanceForm.getEnabled())
.setPort(instanceForm.getPort())
.setHealthy(instanceForm.getHealthy())
.setWeight(instanceForm.getWeight())
.setEnabled(instanceForm.getEnabled())
.setMetadata(UtilsAndCommons.parseMetadata(instanceForm.getMetadata())) .setMetadata(UtilsAndCommons.parseMetadata(instanceForm.getMetadata()))
.setEphemeral(instanceForm.getEphemeral()) .setEphemeral(instanceForm.getEphemeral()).build();
.build();
if (instanceForm.getEphemeral() == null) { if (instanceForm.getEphemeral() == null) {
instance.setEphemeral((switchDomain.isDefaultInstanceEphemeral())); instance.setEphemeral((switchDomain.isDefaultInstanceEphemeral()));
} }

View File

@ -27,6 +27,7 @@ import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.trace.event.naming.DeregisterServiceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.DeregisterServiceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.RegisterServiceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.RegisterServiceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.UpdateServiceTraceEvent;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl; import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
@ -51,6 +52,7 @@ import org.springframework.web.bind.annotation.RestController;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Collection; import java.util.Collection;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@ -85,9 +87,8 @@ public class ServiceControllerV2 {
serviceMetadata.setSelector(parseSelector(serviceForm.getSelector())); serviceMetadata.setSelector(parseSelector(serviceForm.getSelector()));
serviceMetadata.setExtendData(UtilsAndCommons.parseMetadata(serviceForm.getMetadata())); serviceMetadata.setExtendData(UtilsAndCommons.parseMetadata(serviceForm.getMetadata()));
serviceMetadata.setEphemeral(serviceForm.getEphemeral()); serviceMetadata.setEphemeral(serviceForm.getEphemeral());
serviceOperatorV2.create(Service serviceOperatorV2.create(Service.newService(serviceForm.getNamespaceId(), serviceForm.getGroupName(),
.newService(serviceForm.getNamespaceId(), serviceForm.getGroupName(), serviceForm.getServiceName(), serviceForm.getServiceName(), serviceForm.getEphemeral()), serviceMetadata);
serviceForm.getEphemeral()), serviceMetadata);
NotifyCenter.publishEvent( NotifyCenter.publishEvent(
new RegisterServiceTraceEvent(System.currentTimeMillis(), serviceForm.getNamespaceId(), new RegisterServiceTraceEvent(System.currentTimeMillis(), serviceForm.getNamespaceId(),
serviceForm.getGroupName(), serviceForm.getServiceName())); serviceForm.getGroupName(), serviceForm.getServiceName()));
@ -120,8 +121,8 @@ public class ServiceControllerV2 {
@RequestParam("serviceName") String serviceName, @RequestParam("serviceName") String serviceName,
@RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName) @RequestParam(value = "groupName", defaultValue = Constants.DEFAULT_GROUP) String groupName)
throws Exception { throws Exception {
ServiceDetailInfo result = serviceOperatorV2 ServiceDetailInfo result = serviceOperatorV2.queryService(
.queryService(Service.newService(namespaceId, groupName, serviceName)); Service.newService(namespaceId, groupName, serviceName));
return Result.success(result); return Result.success(result);
} }
@ -152,13 +153,16 @@ public class ServiceControllerV2 {
@Secured(action = ActionTypes.WRITE) @Secured(action = ActionTypes.WRITE)
public Result<String> update(ServiceForm serviceForm) throws Exception { public Result<String> update(ServiceForm serviceForm) throws Exception {
serviceForm.validate(); serviceForm.validate();
Map<String, String> metadata = UtilsAndCommons.parseMetadata(serviceForm.getMetadata());
ServiceMetadata serviceMetadata = new ServiceMetadata(); ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setProtectThreshold(serviceForm.getProtectThreshold()); serviceMetadata.setProtectThreshold(serviceForm.getProtectThreshold());
serviceMetadata.setExtendData(UtilsAndCommons.parseMetadata(serviceForm.getMetadata())); serviceMetadata.setExtendData(metadata);
serviceMetadata.setSelector(parseSelector(serviceForm.getSelector())); serviceMetadata.setSelector(parseSelector(serviceForm.getSelector()));
Service service = Service Service service = Service.newService(serviceForm.getNamespaceId(), serviceForm.getGroupName(),
.newService(serviceForm.getNamespaceId(), serviceForm.getGroupName(), serviceForm.getServiceName()); serviceForm.getServiceName());
serviceOperatorV2.update(service, serviceMetadata); serviceOperatorV2.update(service, serviceMetadata);
NotifyCenter.publishEvent(new UpdateServiceTraceEvent(System.currentTimeMillis(), serviceForm.getNamespaceId(),
serviceForm.getGroupName(), serviceForm.getServiceName(), metadata));
return Result.success("ok"); return Result.success("ok");
} }

View File

@ -25,6 +25,7 @@ import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.SmartSubscriber; import com.alibaba.nacos.common.notify.listener.SmartSubscriber;
import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.DeregisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent; import com.alibaba.nacos.common.trace.event.naming.RegisterInstanceTraceEvent;
import com.alibaba.nacos.common.trace.event.naming.UpdateInstanceTraceEvent;
import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.BaseTest;
@ -64,13 +65,13 @@ public class InstanceControllerTest extends BaseTest {
@Mock @Mock
private HttpServletRequest request; private HttpServletRequest request;
private SmartSubscriber subscriber;
private volatile boolean eventReceived = false;
@InjectMocks @InjectMocks
private InstanceController instanceController; private InstanceController instanceController;
private SmartSubscriber subscriber;
private volatile Class<? extends Event> eventReceivedClass;
@Before @Before
public void before() { public void before() {
super.before(); super.before();
@ -81,12 +82,13 @@ public class InstanceControllerTest extends BaseTest {
List<Class<? extends Event>> result = new LinkedList<>(); List<Class<? extends Event>> result = new LinkedList<>();
result.add(RegisterInstanceTraceEvent.class); result.add(RegisterInstanceTraceEvent.class);
result.add(DeregisterInstanceTraceEvent.class); result.add(DeregisterInstanceTraceEvent.class);
result.add(UpdateInstanceTraceEvent.class);
return result; return result;
} }
@Override @Override
public void onEvent(Event event) { public void onEvent(Event event) {
eventReceived = true; eventReceivedClass = event.getClass();
} }
}; };
NotifyCenter.registerSubscriber(subscriber); NotifyCenter.registerSubscriber(subscriber);
@ -100,7 +102,8 @@ public class InstanceControllerTest extends BaseTest {
NotifyCenter.deregisterSubscriber(subscriber); NotifyCenter.deregisterSubscriber(subscriber);
NotifyCenter.deregisterPublisher(RegisterInstanceTraceEvent.class); NotifyCenter.deregisterPublisher(RegisterInstanceTraceEvent.class);
NotifyCenter.deregisterPublisher(DeregisterInstanceTraceEvent.class); NotifyCenter.deregisterPublisher(DeregisterInstanceTraceEvent.class);
eventReceived = false; NotifyCenter.deregisterPublisher(UpdateInstanceTraceEvent.class);
eventReceivedClass = null;
} }
private void mockRequestParameter(String key, String value) { private void mockRequestParameter(String key, String value) {
@ -110,29 +113,28 @@ public class InstanceControllerTest extends BaseTest {
@Test @Test
public void testRegister() throws Exception { public void testRegister() throws Exception {
assertEquals("ok", instanceController.register(request)); assertEquals("ok", instanceController.register(request));
verify(instanceServiceV2) verify(instanceServiceV2).registerInstance(eq(Constants.DEFAULT_NAMESPACE_ID),
.registerInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Instance.class));
any(Instance.class));
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
assertTrue(eventReceived); assertEquals(eventReceivedClass, RegisterInstanceTraceEvent.class);
} }
@Test @Test
public void testDeregister() throws Exception { public void testDeregister() throws Exception {
assertEquals("ok", instanceController.deregister(request)); assertEquals("ok", instanceController.deregister(request));
verify(instanceServiceV2) verify(instanceServiceV2).removeInstance(eq(Constants.DEFAULT_NAMESPACE_ID),
.removeInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Instance.class));
any(Instance.class));
TimeUnit.SECONDS.sleep(1); TimeUnit.SECONDS.sleep(1);
assertTrue(eventReceived); assertEquals(eventReceivedClass, DeregisterInstanceTraceEvent.class);
} }
@Test @Test
public void testUpdate() throws Exception { public void testUpdate() throws Exception {
assertEquals("ok", instanceController.update(request)); assertEquals("ok", instanceController.update(request));
verify(instanceServiceV2) verify(instanceServiceV2).updateInstance(eq(Constants.DEFAULT_NAMESPACE_ID),
.updateInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Instance.class));
any(Instance.class)); TimeUnit.SECONDS.sleep(1);
assertEquals(eventReceivedClass, UpdateInstanceTraceEvent.class);
} }
@Test @Test
@ -144,8 +146,8 @@ public class InstanceControllerTest extends BaseTest {
String instanceJson = JacksonUtils.toJson(mockInstance); String instanceJson = JacksonUtils.toJson(mockInstance);
mockRequestParameter("instances", instanceJson); mockRequestParameter("instances", instanceJson);
mockRequestParameter("metadata", "{}"); mockRequestParameter("metadata", "{}");
when(instanceServiceV2.batchUpdateMetadata(eq(Constants.DEFAULT_NAMESPACE_ID), any(), anyMap())) when(instanceServiceV2.batchUpdateMetadata(eq(Constants.DEFAULT_NAMESPACE_ID), any(), anyMap())).thenReturn(
.thenReturn(Collections.singletonList("1.1.1.1:3306:unknown:DEFAULT:ephemeral")); Collections.singletonList("1.1.1.1:3306:unknown:DEFAULT:ephemeral"));
ObjectNode actual = instanceController.batchUpdateInstanceMetadata(request); ObjectNode actual = instanceController.batchUpdateInstanceMetadata(request);
assertEquals("1.1.1.1:3306:unknown:DEFAULT:ephemeral", actual.get("updated").get(0).textValue()); assertEquals("1.1.1.1:3306:unknown:DEFAULT:ephemeral", actual.get("updated").get(0).textValue());
} }
@ -153,8 +155,8 @@ public class InstanceControllerTest extends BaseTest {
@Test @Test
public void testBatchDeleteInstanceMetadata() throws Exception { public void testBatchDeleteInstanceMetadata() throws Exception {
mockRequestParameter("metadata", "{}"); mockRequestParameter("metadata", "{}");
when(instanceServiceV2.batchDeleteMetadata(eq(Constants.DEFAULT_NAMESPACE_ID), any(), anyMap())) when(instanceServiceV2.batchDeleteMetadata(eq(Constants.DEFAULT_NAMESPACE_ID), any(), anyMap())).thenReturn(
.thenReturn(Collections.singletonList("1.1.1.1:3306:unknown:DEFAULT:ephemeral")); Collections.singletonList("1.1.1.1:3306:unknown:DEFAULT:ephemeral"));
ObjectNode actual = instanceController.batchDeleteInstanceMetadata(request); ObjectNode actual = instanceController.batchDeleteInstanceMetadata(request);
assertEquals("1.1.1.1:3306:unknown:DEFAULT:ephemeral", actual.get("updated").get(0).textValue()); assertEquals("1.1.1.1:3306:unknown:DEFAULT:ephemeral", actual.get("updated").get(0).textValue());
} }
@ -167,9 +169,8 @@ public class InstanceControllerTest extends BaseTest {
mockRequestParameter("healthy", "false"); mockRequestParameter("healthy", "false");
mockRequestParameter("enabled", "false"); mockRequestParameter("enabled", "false");
assertEquals("ok", instanceController.patch(request)); assertEquals("ok", instanceController.patch(request));
verify(instanceServiceV2) verify(instanceServiceV2).patchInstance(eq(Constants.DEFAULT_NAMESPACE_ID),
.patchInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(InstancePatchObject.class));
any(InstancePatchObject.class));
} }
@Test @Test
@ -179,9 +180,9 @@ public class InstanceControllerTest extends BaseTest {
instance.setPort(3306); instance.setPort(3306);
ServiceInfo expected = new ServiceInfo(); ServiceInfo expected = new ServiceInfo();
expected.setHosts(Collections.singletonList(instance)); expected.setHosts(Collections.singletonList(instance));
when(instanceServiceV2 when(instanceServiceV2.listInstance(eq(Constants.DEFAULT_NAMESPACE_ID),
.listInstance(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), any(Subscriber.class), eq(StringUtils.EMPTY),
any(Subscriber.class), eq(StringUtils.EMPTY), eq(false))).thenReturn(expected); eq(false))).thenReturn(expected);
assertEquals(expected, instanceController.list(request)); assertEquals(expected, instanceController.list(request));
} }
@ -200,17 +201,16 @@ public class InstanceControllerTest extends BaseTest {
assertEquals(3306, actual.get("port").intValue()); assertEquals(3306, actual.get("port").intValue());
assertEquals(UtilsAndCommons.DEFAULT_CLUSTER_NAME, actual.get("clusterName").textValue()); assertEquals(UtilsAndCommons.DEFAULT_CLUSTER_NAME, actual.get("clusterName").textValue());
assertEquals(1.0D, actual.get("weight").doubleValue(), 0.1); assertEquals(1.0D, actual.get("weight").doubleValue(), 0.1);
assertEquals(true, actual.get("healthy").booleanValue()); assertTrue(actual.get("healthy").booleanValue());
assertEquals("testId", actual.get("instanceId").textValue()); assertEquals("testId", actual.get("instanceId").textValue());
assertEquals("{}", actual.get("metadata").toString()); assertEquals("{}", actual.get("metadata").toString());
} }
@Test @Test
public void testBeat() throws Exception { public void testBeat() throws Exception {
when(instanceServiceV2 when(instanceServiceV2.handleBeat(eq(Constants.DEFAULT_NAMESPACE_ID),
.handleBeat(eq(Constants.DEFAULT_NAMESPACE_ID), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq("1.1.1.1"), eq(3306),
eq("1.1.1.1"), eq(3306), eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME), any(), any())) eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME), any(), any())).thenReturn(200);
.thenReturn(200);
when(instanceServiceV2.getHeartBeatInterval(eq(Constants.DEFAULT_NAMESPACE_ID), when(instanceServiceV2.getHeartBeatInterval(eq(Constants.DEFAULT_NAMESPACE_ID),
eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq("1.1.1.1"), eq(3306), eq(TEST_GROUP_NAME + "@@" + TEST_SERVICE_NAME), eq("1.1.1.1"), eq(3306),
eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME))).thenReturn(10000L); eq(UtilsAndCommons.DEFAULT_CLUSTER_NAME))).thenReturn(10000L);

View File

@ -18,11 +18,16 @@ package com.alibaba.nacos.naming.controllers;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.SmartSubscriber;
import com.alibaba.nacos.common.trace.event.naming.UpdateServiceTraceEvent;
import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl; import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
import com.alibaba.nacos.naming.core.SubscribeManager; import com.alibaba.nacos.naming.core.SubscribeManager;
import com.alibaba.nacos.naming.pojo.Subscriber; import com.alibaba.nacos.naming.pojo.Subscriber;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -35,6 +40,11 @@ import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ServiceControllerTest extends BaseTest { public class ServiceControllerTest extends BaseTest {
@ -48,9 +58,34 @@ public class ServiceControllerTest extends BaseTest {
@Mock @Mock
private SubscribeManager subscribeManager; private SubscribeManager subscribeManager;
private SmartSubscriber subscriber;
private volatile Class<? extends Event> eventReceivedClass;
@Before @Before
public void before() { public void before() {
super.before(); super.before();
subscriber = new SmartSubscriber() {
@Override
public List<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> result = new LinkedList<>();
result.add(UpdateServiceTraceEvent.class);
return result;
}
@Override
public void onEvent(Event event) {
eventReceivedClass = event.getClass();
}
};
NotifyCenter.registerSubscriber(subscriber);
}
@After
public void tearDown() throws Exception {
NotifyCenter.deregisterSubscriber(subscriber);
NotifyCenter.deregisterPublisher(UpdateServiceTraceEvent.class);
eventReceivedClass = null;
} }
@Test @Test
@ -104,7 +139,7 @@ public class ServiceControllerTest extends BaseTest {
} }
@Test @Test
public void testUpdate() { public void testUpdate() throws Exception {
MockHttpServletRequest servletRequest = new MockHttpServletRequest(); MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME);
servletRequest.addParameter("protectThreshold", "0.01"); servletRequest.addParameter("protectThreshold", "0.01");
@ -115,13 +150,14 @@ public class ServiceControllerTest extends BaseTest {
e.printStackTrace(); e.printStackTrace();
Assert.fail(e.getMessage()); Assert.fail(e.getMessage());
} }
TimeUnit.SECONDS.sleep(1);
assertEquals(eventReceivedClass, UpdateServiceTraceEvent.class);
} }
@Test @Test
public void testSearchService() { public void testSearchService() {
try { try {
Mockito.when( Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString()))
serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString()))
.thenReturn(Collections.singletonList("result")); .thenReturn(Collections.singletonList("result"));
ObjectNode objectNode = serviceController.searchService(TEST_NAMESPACE, ""); ObjectNode objectNode = serviceController.searchService(TEST_NAMESPACE, "");
@ -132,8 +168,7 @@ public class ServiceControllerTest extends BaseTest {
} }
try { try {
Mockito.when( Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString()))
serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString()))
.thenReturn(Arrays.asList("re1", "re2")); .thenReturn(Arrays.asList("re1", "re2"));
Mockito.when(serviceOperatorV2.listAllNamespace()).thenReturn(Arrays.asList("re1", "re2")); Mockito.when(serviceOperatorV2.listAllNamespace()).thenReturn(Arrays.asList("re1", "re2"));

View File

@ -20,6 +20,10 @@ import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.model.v2.Result; import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.SmartSubscriber;
import com.alibaba.nacos.common.trace.event.naming.UpdateInstanceTraceEvent;
import com.alibaba.nacos.naming.BaseTest; import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl; import com.alibaba.nacos.naming.core.InstanceOperatorClientImpl;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
@ -27,6 +31,7 @@ import com.alibaba.nacos.naming.model.form.InstanceForm;
import com.alibaba.nacos.naming.model.form.InstanceMetadataBatchOperationForm; import com.alibaba.nacos.naming.model.form.InstanceMetadataBatchOperationForm;
import com.alibaba.nacos.naming.model.vo.InstanceDetailInfoVo; import com.alibaba.nacos.naming.model.vo.InstanceDetailInfoVo;
import com.alibaba.nacos.naming.model.vo.InstanceMetadataBatchOperationVo; import com.alibaba.nacos.naming.model.vo.InstanceMetadataBatchOperationVo;
import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -41,6 +46,9 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -59,16 +67,42 @@ public class InstanceControllerV2Test extends BaseTest {
private MockMvc mockmvc; private MockMvc mockmvc;
private SmartSubscriber subscriber;
private volatile Class<? extends Event> eventReceivedClass;
@Before @Before
public void before() { public void before() {
super.before(); super.before();
ReflectionTestUtils.setField(instanceControllerV2, "instanceServiceV2", instanceServiceV2); ReflectionTestUtils.setField(instanceControllerV2, "instanceServiceV2", instanceServiceV2);
mockmvc = MockMvcBuilders.standaloneSetup(instanceControllerV2).build(); mockmvc = MockMvcBuilders.standaloneSetup(instanceControllerV2).build();
subscriber = new SmartSubscriber() {
@Override
public List<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> result = new LinkedList<>();
result.add(UpdateInstanceTraceEvent.class);
return result;
}
@Override
public void onEvent(Event event) {
eventReceivedClass = event.getClass();
}
};
NotifyCenter.registerSubscriber(subscriber);
}
@After
public void tearDown() throws Exception {
NotifyCenter.deregisterSubscriber(subscriber);
NotifyCenter.deregisterPublisher(UpdateInstanceTraceEvent.class);
eventReceivedClass = null;
} }
@Test @Test
public void registerInstance() throws Exception { public void registerInstance() throws Exception {
InstanceForm instanceForm = new InstanceForm(); InstanceForm instanceForm = new InstanceForm();
instanceForm.setNamespaceId(TEST_NAMESPACE); instanceForm.setNamespaceId(TEST_NAMESPACE);
instanceForm.setGroupName("DEFAULT_GROUP"); instanceForm.setGroupName("DEFAULT_GROUP");
@ -83,7 +117,7 @@ public class InstanceControllerV2Test extends BaseTest {
instanceForm.setEphemeral(true); instanceForm.setEphemeral(true);
Result<String> result = instanceControllerV2.register(instanceForm); Result<String> result = instanceControllerV2.register(instanceForm);
verify(instanceServiceV2).registerInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any()); verify(instanceServiceV2).registerInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
@ -105,11 +139,11 @@ public class InstanceControllerV2Test extends BaseTest {
instanceForm.setEnabled(true); instanceForm.setEnabled(true);
instanceForm.setMetadata(TEST_METADATA); instanceForm.setMetadata(TEST_METADATA);
instanceForm.setEphemeral(true); instanceForm.setEphemeral(true);
Result<String> result = instanceControllerV2.deregister(instanceForm); Result<String> result = instanceControllerV2.deregister(instanceForm);
verify(instanceServiceV2).removeInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any()); verify(instanceServiceV2).removeInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals("ok", result.getData()); assertEquals("ok", result.getData());
@ -129,18 +163,20 @@ public class InstanceControllerV2Test extends BaseTest {
instanceForm.setEnabled(true); instanceForm.setEnabled(true);
instanceForm.setMetadata(TEST_METADATA); instanceForm.setMetadata(TEST_METADATA);
instanceForm.setEphemeral(true); instanceForm.setEphemeral(true);
Result<String> result = instanceControllerV2.update(instanceForm); Result<String> result = instanceControllerV2.update(instanceForm);
verify(instanceServiceV2).updateInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any()); verify(instanceServiceV2).updateInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals("ok", result.getData()); assertEquals("ok", result.getData());
TimeUnit.SECONDS.sleep(1);
assertEquals(eventReceivedClass, UpdateInstanceTraceEvent.class);
} }
@Test @Test
public void batchUpdateInstanceMetadata() throws Exception { public void batchUpdateInstanceMetadata() throws Exception {
InstanceMetadataBatchOperationForm form = new InstanceMetadataBatchOperationForm(); InstanceMetadataBatchOperationForm form = new InstanceMetadataBatchOperationForm();
form.setNamespaceId(TEST_NAMESPACE); form.setNamespaceId(TEST_NAMESPACE);
form.setGroupName("DEFAULT"); form.setGroupName("DEFAULT");
@ -148,7 +184,7 @@ public class InstanceControllerV2Test extends BaseTest {
form.setConsistencyType("ephemeral"); form.setConsistencyType("ephemeral");
form.setInstances(TEST_INSTANCE_INFO_LIST); form.setInstances(TEST_INSTANCE_INFO_LIST);
form.setMetadata(TEST_METADATA); form.setMetadata(TEST_METADATA);
ArrayList<String> ipList = new ArrayList<>(); ArrayList<String> ipList = new ArrayList<>();
ipList.add(TEST_IP); ipList.add(TEST_IP);
when(instanceServiceV2.batchUpdateMetadata(eq(TEST_NAMESPACE), any(), any())).thenReturn(ipList); when(instanceServiceV2.batchUpdateMetadata(eq(TEST_NAMESPACE), any(), any())).thenReturn(ipList);
@ -157,7 +193,7 @@ public class InstanceControllerV2Test extends BaseTest {
Result<InstanceMetadataBatchOperationVo> result = instanceControllerV2.batchUpdateInstanceMetadata(form); Result<InstanceMetadataBatchOperationVo> result = instanceControllerV2.batchUpdateInstanceMetadata(form);
verify(instanceServiceV2).batchUpdateMetadata(eq(TEST_NAMESPACE), any(), any()); verify(instanceServiceV2).batchUpdateMetadata(eq(TEST_NAMESPACE), any(), any());
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(expectUpdate.getUpdated().size(), result.getData().getUpdated().size()); assertEquals(expectUpdate.getUpdated().size(), result.getData().getUpdated().size());
assertEquals(expectUpdate.getUpdated().get(0), result.getData().getUpdated().get(0)); assertEquals(expectUpdate.getUpdated().get(0), result.getData().getUpdated().get(0));
@ -177,35 +213,37 @@ public class InstanceControllerV2Test extends BaseTest {
@Test @Test
public void listInstance() throws Exception { public void listInstance() throws Exception {
ServiceInfo serviceInfo = new ServiceInfo(); ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setName("serviceInfo"); serviceInfo.setName("serviceInfo");
when(instanceServiceV2.listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME), eq(false)))
.thenReturn(serviceInfo);
Result<ServiceInfo> result = instanceControllerV2 when(instanceServiceV2.listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME),
.list(TEST_NAMESPACE, "DEFAULT_GROUP", "test-service", TEST_CLUSTER_NAME, TEST_IP, 9999, false, "", "", ""); eq(false))).thenReturn(serviceInfo);
Result<ServiceInfo> result = instanceControllerV2.list(TEST_NAMESPACE, "DEFAULT_GROUP", "test-service",
TEST_CLUSTER_NAME, TEST_IP, 9999, false, "", "", "");
verify(instanceServiceV2).listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME),
eq(false));
verify(instanceServiceV2).listInstance(eq(TEST_NAMESPACE), eq(TEST_SERVICE_NAME), any(), eq(TEST_CLUSTER_NAME), eq(false));
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(serviceInfo.getName(), result.getData().getName()); assertEquals(serviceInfo.getName(), result.getData().getName());
} }
@Test @Test
public void detail() throws Exception { public void detail() throws Exception {
Instance instance = new Instance(); Instance instance = new Instance();
instance.setInstanceId("test-id"); instance.setInstanceId("test-id");
when(instanceServiceV2.getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP, 9999)).thenReturn(instance);
Result<InstanceDetailInfoVo> result = instanceControllerV2 when(instanceServiceV2.getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP,
.detail(TEST_NAMESPACE, "DEFAULT_GROUP", "test-service", TEST_CLUSTER_NAME, TEST_IP, 9999); 9999)).thenReturn(instance);
Result<InstanceDetailInfoVo> result = instanceControllerV2.detail(TEST_NAMESPACE, "DEFAULT_GROUP",
"test-service", TEST_CLUSTER_NAME, TEST_IP, 9999);
verify(instanceServiceV2).getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP, 9999); verify(instanceServiceV2).getInstance(TEST_NAMESPACE, TEST_SERVICE_NAME, TEST_CLUSTER_NAME, TEST_IP, 9999);
assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), result.getCode());
assertEquals(instance.getInstanceId(), result.getData().getInstanceId()); assertEquals(instance.getInstanceId(), result.getData().getInstanceId());
} }

View File

@ -19,6 +19,10 @@ package com.alibaba.nacos.naming.controllers.v2;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.model.v2.ErrorCode; import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.alibaba.nacos.api.model.v2.Result; import com.alibaba.nacos.api.model.v2.Result;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.SmartSubscriber;
import com.alibaba.nacos.common.trace.event.naming.UpdateServiceTraceEvent;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl; import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata; import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.core.v2.pojo.Service;
@ -26,6 +30,7 @@ import com.alibaba.nacos.naming.model.form.ServiceForm;
import com.alibaba.nacos.naming.pojo.ServiceDetailInfo; import com.alibaba.nacos.naming.pojo.ServiceDetailInfo;
import com.alibaba.nacos.naming.pojo.ServiceNameView; import com.alibaba.nacos.naming.pojo.ServiceNameView;
import com.alibaba.nacos.naming.selector.SelectorManager; import com.alibaba.nacos.naming.selector.SelectorManager;
import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -33,6 +38,9 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -51,14 +59,39 @@ public class ServiceControllerV2Test {
private ServiceControllerV2 serviceController; private ServiceControllerV2 serviceController;
private SmartSubscriber subscriber;
private volatile Class<? extends Event> eventReceivedClass;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
serviceController = new ServiceControllerV2(serviceOperatorV2, selectorManager); serviceController = new ServiceControllerV2(serviceOperatorV2, selectorManager);
subscriber = new SmartSubscriber() {
@Override
public List<Class<? extends Event>> subscribeTypes() {
List<Class<? extends Event>> result = new LinkedList<>();
result.add(UpdateServiceTraceEvent.class);
return result;
}
@Override
public void onEvent(Event event) {
eventReceivedClass = event.getClass();
}
};
NotifyCenter.registerSubscriber(subscriber);
}
@After
public void tearDown() throws Exception {
NotifyCenter.deregisterSubscriber(subscriber);
NotifyCenter.deregisterPublisher(UpdateServiceTraceEvent.class);
eventReceivedClass = null;
} }
@Test @Test
public void testCreate() throws Exception { public void testCreate() throws Exception {
ServiceForm serviceForm = new ServiceForm(); ServiceForm serviceForm = new ServiceForm();
serviceForm.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID); serviceForm.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID);
serviceForm.setServiceName("service"); serviceForm.setServiceName("service");
@ -67,21 +100,21 @@ public class ServiceControllerV2Test {
serviceForm.setProtectThreshold(0.0F); serviceForm.setProtectThreshold(0.0F);
serviceForm.setMetadata(""); serviceForm.setMetadata("");
serviceForm.setSelector(""); serviceForm.setSelector("");
Result<String> actual = serviceController.create(serviceForm); Result<String> actual = serviceController.create(serviceForm);
verify(serviceOperatorV2) verify(serviceOperatorV2).create(
.create(eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")), eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")),
any(ServiceMetadata.class)); any(ServiceMetadata.class));
assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode());
assertEquals("ok", actual.getData()); assertEquals("ok", actual.getData());
} }
@Test @Test
public void testRemove() throws Exception { public void testRemove() throws Exception {
Result<String> actual = serviceController Result<String> actual = serviceController.remove(Constants.DEFAULT_NAMESPACE_ID, "service",
.remove(Constants.DEFAULT_NAMESPACE_ID, "service", Constants.DEFAULT_GROUP); Constants.DEFAULT_GROUP);
verify(serviceOperatorV2) verify(serviceOperatorV2).delete(
.delete(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")); Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service"));
assertEquals("ok", actual.getData()); assertEquals("ok", actual.getData());
assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode());
} }
@ -89,11 +122,11 @@ public class ServiceControllerV2Test {
@Test @Test
public void testDetail() throws Exception { public void testDetail() throws Exception {
ServiceDetailInfo expected = new ServiceDetailInfo(); ServiceDetailInfo expected = new ServiceDetailInfo();
when(serviceOperatorV2 when(serviceOperatorV2.queryService(
.queryService(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service"))) Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service"))).thenReturn(
.thenReturn(expected); expected);
Result<ServiceDetailInfo> actual = serviceController Result<ServiceDetailInfo> actual = serviceController.detail(Constants.DEFAULT_NAMESPACE_ID, "service",
.detail(Constants.DEFAULT_NAMESPACE_ID, "service", Constants.DEFAULT_GROUP); Constants.DEFAULT_GROUP);
assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode());
assertEquals(expected, actual.getData()); assertEquals(expected, actual.getData());
} }
@ -103,7 +136,8 @@ public class ServiceControllerV2Test {
when(serviceOperatorV2.listService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "")).thenReturn( when(serviceOperatorV2.listService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "")).thenReturn(
Collections.singletonList("serviceName")); Collections.singletonList("serviceName"));
Result<ServiceNameView> actual = serviceController.list(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "", 1, 10); Result<ServiceNameView> actual = serviceController.list(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP,
"", 1, 10);
assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode());
assertEquals(1, actual.getData().getCount()); assertEquals(1, actual.getData().getCount());
assertEquals(1, actual.getData().getServices().size()); assertEquals(1, actual.getData().getServices().size());
@ -119,12 +153,13 @@ public class ServiceControllerV2Test {
serviceForm.setProtectThreshold(0.0f); serviceForm.setProtectThreshold(0.0f);
serviceForm.setMetadata(""); serviceForm.setMetadata("");
serviceForm.setSelector(""); serviceForm.setSelector("");
Result<String> actual = serviceController Result<String> actual = serviceController.update(serviceForm);
.update(serviceForm); verify(serviceOperatorV2).update(
verify(serviceOperatorV2) eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")),
.update(eq(Service.newService(Constants.DEFAULT_NAMESPACE_ID, Constants.DEFAULT_GROUP, "service")), any(ServiceMetadata.class));
any(ServiceMetadata.class));
assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode()); assertEquals(ErrorCode.SUCCESS.getCode(), actual.getCode());
assertEquals("ok", actual.getData()); assertEquals("ok", actual.getData());
TimeUnit.SECONDS.sleep(1);
assertEquals(eventReceivedClass, UpdateServiceTraceEvent.class);
} }
} }