#269 Register instance with tenant info

This commit is contained in:
nkorange 2018-12-19 11:02:31 +08:00
parent 53eb990328
commit 947e0439b0
40 changed files with 402 additions and 621 deletions

View File

@ -19,6 +19,7 @@ import java.util.Map;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public class Entity { public class Entity {

View File

@ -17,6 +17,7 @@ package com.alibaba.nacos.api.cmdb.pojo;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public class EntityEvent { public class EntityEvent {

View File

@ -17,6 +17,7 @@ package com.alibaba.nacos.api.cmdb.pojo;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public enum EntityEventType { public enum EntityEventType {
/** /**

View File

@ -19,6 +19,7 @@ import java.util.Set;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public class Label { public class Label {

View File

@ -17,6 +17,7 @@ package com.alibaba.nacos.api.cmdb.pojo;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public enum PreservedEntityTypes { public enum PreservedEntityTypes {
/** /**

View File

@ -27,6 +27,7 @@ import java.util.Set;
* Service to visit CMDB store * Service to visit CMDB store
* *
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public interface CmdbService { public interface CmdbService {

View File

@ -127,4 +127,7 @@ public class Constants {
public static final String NAMING_HTTP_HEADER_SPILIER = "\\|"; public static final String NAMING_HTTP_HEADER_SPILIER = "\\|";
public static final String NAMING_DEFAULT_CLUSTER_NAME = "DEFAULT"; public static final String NAMING_DEFAULT_CLUSTER_NAME = "DEFAULT";
public static final String REQUEST_PARAM_TENANT_ID = "tid";
public static final String REQUEST_PARAM_SERVICE_NAME = "serviceName";
} }

View File

@ -195,6 +195,7 @@ public interface NamingService {
* @param selector selector to filter the resource * @param selector selector to filter the resource
* @return list of service names * @return list of service names
* @throws NacosException * @throws NacosException
* @since 0.7.0
*/ */
ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException; ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException;

View File

@ -190,13 +190,13 @@ public class ServiceInfo {
@JSONField(serialize = false) @JSONField(serialize = false)
public String getKey() { public String getKey() {
return getKey(name, clusters, env, isAllIPs()); return getKey(name, clusters, env);
} }
@JSONField(serialize = false) @JSONField(serialize = false)
public String getKeyEncoded() { public String getKeyEncoded() {
try { try {
return getKey(URLEncoder.encode(name, "UTF-8"), clusters, env, isAllIPs()); return getKey(URLEncoder.encode(name, "UTF-8"), clusters, env);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
return getKey(); return getKey();
} }
@ -204,31 +204,24 @@ public class ServiceInfo {
@JSONField(serialize = false) @JSONField(serialize = false)
public static String getKey(String name, String clusters, String unit) { public static String getKey(String name, String clusters, String unit) {
return getKey(name, clusters, unit, false);
}
@JSONField(serialize = false)
public static String getKey(String name, String clusters, String unit, boolean isAllIPs) {
if (isEmpty(unit)) { if (isEmpty(unit)) {
unit = EMPTY; unit = EMPTY;
} }
if (!isEmpty(clusters) && !isEmpty(unit)) { if (!isEmpty(clusters) && !isEmpty(unit)) {
return isAllIPs ? name + SPLITER + clusters + SPLITER + unit + SPLITER + ALL_IPS return name + SPLITER + clusters + SPLITER + unit;
: name + SPLITER + clusters + SPLITER + unit;
} }
if (!isEmpty(clusters)) { if (!isEmpty(clusters)) {
return isAllIPs ? name + SPLITER + clusters + SPLITER + ALL_IPS : name + SPLITER + clusters; return name + SPLITER + clusters;
} }
if (!isEmpty(unit)) { if (!isEmpty(unit)) {
return isAllIPs ? name + SPLITER + EMPTY + SPLITER + unit + SPLITER + ALL_IPS : return name + SPLITER + EMPTY + SPLITER + unit;
name + SPLITER + EMPTY + SPLITER + unit;
} }
return isAllIPs ? name + SPLITER + ALL_IPS : name; return name;
} }
@Override @Override

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.api.selector;
* Abstract selector that only contains a type * Abstract selector that only contains a type
* *
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public abstract class AbstractSelector { public abstract class AbstractSelector {

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.api.selector;
* The selector to filter resource with flexible expression. * The selector to filter resource with flexible expression.
* *
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public class ExpressionSelector extends AbstractSelector { public class ExpressionSelector extends AbstractSelector {

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.api.selector;
* The types of selector accepted by Nacos * The types of selector accepted by Nacos
* *
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public enum SelectorType { public enum SelectorType {
/** /**

View File

@ -20,7 +20,6 @@ import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Cluster;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
@ -159,7 +158,7 @@ public class NacosNamingService implements NamingService {
public void registerInstance(String serviceName, Instance instance) throws NacosException { public void registerInstance(String serviceName, Instance instance) throws NacosException {
BeatInfo beatInfo = new BeatInfo(); BeatInfo beatInfo = new BeatInfo();
beatInfo.setDom(serviceName); beatInfo.setServiceName(serviceName);
beatInfo.setIp(instance.getIp()); beatInfo.setIp(instance.getIp());
beatInfo.setPort(instance.getPort()); beatInfo.setPort(instance.getPort());
beatInfo.setCluster(instance.getClusterName()); beatInfo.setCluster(instance.getClusterName());
@ -191,7 +190,7 @@ public class NacosNamingService implements NamingService {
public List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException { public List<Instance> getAllInstances(String serviceName, List<String> clusters) throws NacosException {
ServiceInfo serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","), ServiceInfo serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","),
StringUtils.EMPTY, false); StringUtils.EMPTY);
List<Instance> list; List<Instance> list;
if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
return new ArrayList<Instance>(); return new ArrayList<Instance>();
@ -209,7 +208,7 @@ public class NacosNamingService implements NamingService {
throws NacosException { throws NacosException {
ServiceInfo serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","), ServiceInfo serviceInfo = hostReactor.getServiceInfo(serviceName, StringUtils.join(clusters, ","),
StringUtils.EMPTY, false); StringUtils.EMPTY);
List<Instance> list; List<Instance> list;
if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) { if (serviceInfo == null || CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
return new ArrayList<Instance>(); return new ArrayList<Instance>();

View File

@ -27,7 +27,7 @@ public class BeatInfo {
private int port; private int port;
private String ip; private String ip;
private double weight; private double weight;
private String dom; private String serviceName;
private String cluster; private String cluster;
private Map<String, String> metadata; private Map<String, String> metadata;
@ -36,12 +36,12 @@ public class BeatInfo {
return JSON.toJSONString(this); return JSON.toJSONString(this);
} }
public String getDom() { public String getServiceName() {
return dom; return serviceName;
} }
public void setDom(String dom) { public void setServiceName(String serviceName) {
this.dom = dom; this.serviceName = serviceName;
} }
public String getCluster() { public String getCluster() {

View File

@ -21,6 +21,7 @@ import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.naming.net.NamingProxy; import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.LogUtils; import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs; import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.util.HttpMethod;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -83,6 +84,7 @@ public class BeatReactor {
} }
class BeatTask implements Runnable { class BeatTask implements Runnable {
BeatInfo beatInfo; BeatInfo beatInfo;
public BeatTask(BeatInfo beatInfo) { public BeatTask(BeatInfo beatInfo) {
@ -93,10 +95,10 @@ public class BeatReactor {
public void run() { public void run() {
Map<String, String> params = new HashMap<String, String>(2); Map<String, String> params = new HashMap<String, String>(2);
params.put("beat", JSON.toJSONString(beatInfo)); params.put("beat", JSON.toJSONString(beatInfo));
params.put("dom", beatInfo.getDom()); params.put("serviceName", beatInfo.getServiceName());
try { try {
String result = serverProxy.callAllServers(UtilAndComs.NACOS_URL_BASE + "/api/clientBeat", params); String result = serverProxy.reqAPI(UtilAndComs.NACOS_URL_BASE + "/health", params, HttpMethod.POST);
JSONObject jsonObject = JSON.parseObject(result); JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject != null) { if (jsonObject != null) {

View File

@ -190,53 +190,39 @@ public class HostReactor {
private ServiceInfo getSerivceInfo0(String serviceName, String clusters, String env) { private ServiceInfo getSerivceInfo0(String serviceName, String clusters, String env) {
String key = ServiceInfo.getKey(serviceName, clusters, env, false); String key = ServiceInfo.getKey(serviceName, clusters, env);
return serviceInfoMap.get(key); return serviceInfoMap.get(key);
} }
private ServiceInfo getSerivceInfo0(String serviceName, String clusters, String env, boolean allIPs) { private ServiceInfo getSerivceInfo0(String serviceName, String clusters, String env, boolean allIPs) {
String key = ServiceInfo.getKey(serviceName, clusters, env, allIPs); String key = ServiceInfo.getKey(serviceName, clusters, env);
return serviceInfoMap.get(key); return serviceInfoMap.get(key);
} }
public ServiceInfo getServiceInfo(String serviceName, String clusters, String env) { public ServiceInfo getServiceInfo(final String serviceName, final String clusters) {
return getServiceInfo(serviceName, clusters, env, false); return getServiceInfo(serviceName, clusters, StringUtils.EMPTY);
} }
public ServiceInfo getServiceInfo(String serviceName, String clusters) {
String env = StringUtils.EMPTY;
return getServiceInfo(serviceName, clusters, env, false);
}
public ServiceInfo getServiceInfo(final String serviceName, final String clusters, final String env, public ServiceInfo getServiceInfo(final String serviceName, final String clusters, final String env) {
final boolean allIPs) {
LogUtils.LOG.debug("failover-mode: " + failoverReactor.isFailoverSwitch()); LogUtils.LOG.debug("failover-mode: " + failoverReactor.isFailoverSwitch());
String key = ServiceInfo.getKey(serviceName, clusters, env, allIPs); String key = ServiceInfo.getKey(serviceName, clusters, env);
if (failoverReactor.isFailoverSwitch()) { if (failoverReactor.isFailoverSwitch()) {
return failoverReactor.getService(key); return failoverReactor.getService(key);
} }
ServiceInfo serviceObj = getSerivceInfo0(serviceName, clusters, env, allIPs); ServiceInfo serviceObj = getSerivceInfo0(serviceName, clusters, env);
if (null == serviceObj) { if (null == serviceObj) {
serviceObj = new ServiceInfo(serviceName, clusters, env); serviceObj = new ServiceInfo(serviceName, clusters, env);
if (allIPs) {
serviceObj.setAllIPs(allIPs);
}
serviceInfoMap.put(serviceObj.getKey(), serviceObj); serviceInfoMap.put(serviceObj.getKey(), serviceObj);
updatingMap.put(serviceName, new Object()); updatingMap.put(serviceName, new Object());
updateServiceNow(serviceName, clusters, env);
if (allIPs) {
updateService4AllIPNow(serviceName, clusters, env);
} else {
updateServiceNow(serviceName, clusters, env);
}
updatingMap.remove(serviceName); updatingMap.remove(serviceName);
} else if (updatingMap.containsKey(serviceName)) { } else if (updatingMap.containsKey(serviceName)) {
@ -248,29 +234,29 @@ public class HostReactor {
serviceObj.wait(updateHoldInterval); serviceObj.wait(updateHoldInterval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
LogUtils.LOG.error("[getServiceInfo]", LogUtils.LOG.error("[getServiceInfo]",
"serviceName:" + serviceName + ", clusters:" + clusters + ", allIPs:" + allIPs, e); "serviceName:" + serviceName + ", clusters:" + clusters, e);
} }
} }
} }
} }
scheduleUpdateIfAbsent(serviceName, clusters, env, allIPs); scheduleUpdateIfAbsent(serviceName, clusters, env);
return serviceInfoMap.get(serviceObj.getKey()); return serviceInfoMap.get(serviceObj.getKey());
} }
public void scheduleUpdateIfAbsent(String serviceName, String clusters, String env, boolean allIPs) { public void scheduleUpdateIfAbsent(String serviceName, String clusters, String env) {
if (futureMap.get(ServiceInfo.getKey(serviceName, clusters, env, allIPs)) != null) { if (futureMap.get(ServiceInfo.getKey(serviceName, clusters, env)) != null) {
return; return;
} }
synchronized (futureMap) { synchronized (futureMap) {
if (futureMap.get(ServiceInfo.getKey(serviceName, clusters, env, allIPs)) != null) { if (futureMap.get(ServiceInfo.getKey(serviceName, clusters, env)) != null) {
return; return;
} }
ScheduledFuture<?> future = addTask(new UpdateTask(serviceName, clusters, env, allIPs)); ScheduledFuture<?> future = addTask(new UpdateTask(serviceName, clusters, env));
futureMap.put(ServiceInfo.getKey(serviceName, clusters, env, allIPs), future); futureMap.put(ServiceInfo.getKey(serviceName, clusters, env), future);
} }
} }
@ -314,7 +300,7 @@ public class HostReactor {
ServiceInfo oldService = getSerivceInfo0(serviceName, clusters, env); ServiceInfo oldService = getSerivceInfo0(serviceName, clusters, env);
try { try {
Map<String, String> params = new HashMap<String, String>(8); Map<String, String> params = new HashMap<String, String>(8);
params.put("dom", serviceName); params.put("serviceName", serviceName);
params.put("clusters", clusters); params.put("clusters", clusters);
params.put("udpPort", String.valueOf(pushRecver.getUDPPort())); params.put("udpPort", String.valueOf(pushRecver.getUDPPort()));
params.put("env", env); params.put("env", env);
@ -337,7 +323,7 @@ public class HostReactor {
params.put("checksum", oldService.getChecksum()); params.put("checksum", oldService.getChecksum());
} }
String result = serverProxy.reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/srvIPXT", params); String result = serverProxy.reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params);
if (StringUtils.isNotEmpty(result)) { if (StringUtils.isNotEmpty(result)) {
processServiceJSON(result); processServiceJSON(result);
} }
@ -353,10 +339,10 @@ public class HostReactor {
} }
} }
public void refreshOnly(String serviceName, String clusters, String env, boolean allIPs) { public void refreshOnly(String serviceName, String clusters, String env) {
try { try {
Map<String, String> params = new HashMap<String, String>(16); Map<String, String> params = new HashMap<String, String>(16);
params.put("dom", serviceName); params.put("serviceName", serviceName);
params.put("clusters", clusters); params.put("clusters", clusters);
params.put("udpPort", String.valueOf(pushRecver.getUDPPort())); params.put("udpPort", String.valueOf(pushRecver.getUDPPort()));
params.put("unit", env); params.put("unit", env);
@ -376,11 +362,7 @@ public class HostReactor {
params.put("useEnvId", "true"); params.put("useEnvId", "true");
} }
if (allIPs) { serverProxy.reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params);
serverProxy.reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/srvAllIP", params);
} else {
serverProxy.reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/srvIPXT", params);
}
} catch (Exception e) { } catch (Exception e) {
LogUtils.LOG.error("NA", "failed to update serviceName: " + serviceName, e); LogUtils.LOG.error("NA", "failed to update serviceName: " + serviceName, e);
} }
@ -391,7 +373,6 @@ public class HostReactor {
private String clusters; private String clusters;
private String serviceName; private String serviceName;
private String env; private String env;
private boolean allIPs = false;
public UpdateTask(String serviceName, String clusters, String env) { public UpdateTask(String serviceName, String clusters, String env) {
this.serviceName = serviceName; this.serviceName = serviceName;
@ -399,41 +380,24 @@ public class HostReactor {
this.env = env; this.env = env;
} }
public UpdateTask(String serviceName, String clusters, String env, boolean allIPs) {
this.serviceName = serviceName;
this.clusters = clusters;
this.env = env;
this.allIPs = allIPs;
}
@Override @Override
public void run() { public void run() {
try { try {
ServiceInfo serviceObj = serviceInfoMap.get(ServiceInfo.getKey(serviceName, clusters, env, allIPs)); ServiceInfo serviceObj = serviceInfoMap.get(ServiceInfo.getKey(serviceName, clusters, env));
if (serviceObj == null) { if (serviceObj == null) {
if (allIPs) { updateServiceNow(serviceName, clusters, env);
updateService4AllIPNow(serviceName, clusters, env); executor.schedule(this, DEFAULT_DELAY, TimeUnit.MILLISECONDS);
} else {
updateServiceNow(serviceName, clusters, env);
executor.schedule(this, DEFAULT_DELAY, TimeUnit.MILLISECONDS);
}
return; return;
} }
if (serviceObj.getLastRefTime() <= lastRefTime) { if (serviceObj.getLastRefTime() <= lastRefTime) {
if (allIPs) { updateServiceNow(serviceName, clusters, env);
updateService4AllIPNow(serviceName, clusters, env); serviceObj = serviceInfoMap.get(ServiceInfo.getKey(serviceName, clusters, env));
serviceObj = serviceInfoMap.get(ServiceInfo.getKey(serviceName, clusters, env, true));
} else {
updateServiceNow(serviceName, clusters, env);
serviceObj = serviceInfoMap.get(ServiceInfo.getKey(serviceName, clusters, env));
}
} else { } else {
// if serviceName already updated by push, we should not override it // if serviceName already updated by push, we should not override it
// since the push data may be different from pull through force push // since the push data may be different from pull through force push
refreshOnly(serviceName, clusters, env, allIPs); refreshOnly(serviceName, clusters, env);
} }
executor.schedule(this, serviceObj.getCacheMillis(), TimeUnit.MILLISECONDS); executor.schedule(this, serviceObj.getCacheMillis(), TimeUnit.MILLISECONDS);

View File

@ -18,13 +18,15 @@ package com.alibaba.nacos.client.naming.net;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.selector.AbstractSelector; import com.alibaba.nacos.api.selector.AbstractSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.api.selector.ExpressionSelector; import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.client.naming.utils.*; import com.alibaba.nacos.client.naming.utils.*;
import com.alibaba.nacos.common.util.HttpMethod;
import com.alibaba.nacos.common.util.UuidUtils; import com.alibaba.nacos.common.util.UuidUtils;
import java.io.IOException; import java.io.IOException;
@ -96,9 +98,9 @@ public class NamingProxy {
String urlString = "http://" + endpoint + "/nacos/serverlist"; String urlString = "http://" + endpoint + "/nacos/serverlist";
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION, List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
"Accept-Encoding", "gzip,deflate,sdch", "Accept-Encoding", "gzip,deflate,sdch",
"Connection", "Keep-Alive", "Connection", "Keep-Alive",
"RequestId", UuidUtils.generateUuid()); "RequestId", UuidUtils.generateUuid());
HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null, UtilAndComs.ENCODING); HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null, UtilAndComs.ENCODING);
if (HttpURLConnection.HTTP_OK != result.code) { if (HttpURLConnection.HTTP_OK != result.code) {
@ -167,7 +169,7 @@ public class NamingProxy {
params.put("serviceName", serviceName); params.put("serviceName", serviceName);
params.put("clusterName", instance.getClusterName()); params.put("clusterName", instance.getClusterName());
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, "PUT"); reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.PUT);
} }
public void deregisterService(String serviceName, String ip, int port, String cluster) throws NacosException { public void deregisterService(String serviceName, String ip, int port, String cluster) throws NacosException {
@ -182,7 +184,7 @@ public class NamingProxy {
params.put("serviceName", serviceName); params.put("serviceName", serviceName);
params.put("cluster", cluster); params.put("cluster", cluster);
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, "DELETE"); reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE);
} }
public String queryList(String serviceName, String clusters, boolean healthyOnly) throws NacosException { public String queryList(String serviceName, String clusters, boolean healthyOnly) throws NacosException {
@ -193,7 +195,7 @@ public class NamingProxy {
params.put("clusters", clusters); params.put("clusters", clusters);
params.put("healthyOnly", String.valueOf(healthyOnly)); params.put("healthyOnly", String.valueOf(healthyOnly));
return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params, "GET"); return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params, HttpMethod.GET);
} }
public boolean serverHealthy() { public boolean serverHealthy() {
@ -284,7 +286,7 @@ public class NamingProxy {
} }
public String callServer(String api, Map<String, String> params, String curServer) throws NacosException { public String callServer(String api, Map<String, String> params, String curServer) throws NacosException {
return callServer(api, params, curServer, "GET"); return callServer(api, params, curServer, HttpMethod.GET);
} }
public String callServer(String api, Map<String, String> params, String curServer, String method) public String callServer(String api, Map<String, String> params, String curServer, String method)
@ -323,11 +325,13 @@ public class NamingProxy {
} }
public String reqAPI(String api, Map<String, String> params, List<String> servers) { public String reqAPI(String api, Map<String, String> params, List<String> servers) {
return reqAPI(api, params, servers, "GET"); return reqAPI(api, params, servers, HttpMethod.GET);
} }
public String reqAPI(String api, Map<String, String> params, List<String> servers, String method) { public String reqAPI(String api, Map<String, String> params, List<String> servers, String method) {
params.put(Constants.REQUEST_PARAM_TENANT_ID, getTenantId());
if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(nacosDomain)) { if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(nacosDomain)) {
throw new IllegalArgumentException("no server available"); throw new IllegalArgumentException("no server available");
} }
@ -363,4 +367,11 @@ public class NamingProxy {
} }
private String getTenantId() {
if (UtilAndComs.DEFAULT_NAMESPACE_ID.equals(namespace)) {
return StringUtils.EMPTY;
}
return namespace;
}
} }

View File

@ -16,6 +16,8 @@
package com.alibaba.nacos.client; package com.alibaba.nacos.client;
import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ListView;
@ -25,6 +27,7 @@ import org.junit.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Properties;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
@ -35,7 +38,11 @@ public class NamingTest {
@Ignore @Ignore
public void testServiceList() throws Exception { public void testServiceList() throws Exception {
NamingService namingService = NacosFactory.createNamingService("127.0.0.1:8848"); Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "11.160.165.126:8848");
properties.put(PropertyKeyConst.NAMESPACE, "t1");
NamingService namingService = NacosFactory.createNamingService(properties);
Instance instance = new Instance(); Instance instance = new Instance();
instance.setIp("1.1.1.1"); instance.setIp("1.1.1.1");
@ -48,9 +55,9 @@ public class NamingTest {
namingService.registerInstance("nacos.test.1", instance); namingService.registerInstance("nacos.test.1", instance);
ExpressionSelector expressionSelector = new ExpressionSelector(); // ExpressionSelector expressionSelector = new ExpressionSelector();
expressionSelector.setExpression("INSTANCE.metadata.registerSource = 'dubbo'"); // expressionSelector.setExpression("INSTANCE.metadata.registerSource = 'dubbo'");
ListView<String> serviceList = namingService.getServicesOfServer(1, 10, expressionSelector); // ListView<String> serviceList = namingService.getServicesOfServer(1, 10, expressionSelector);
Thread.sleep(1000000000L); Thread.sleep(1000000000L);
} }

View File

@ -20,6 +20,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
@SpringBootApplication @SpringBootApplication
public class CmdbApp { public class CmdbApp {

View File

@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletRequest;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
@RestController @RestController
@RequestMapping(UtilsAndCommons.NACOS_CMDB_CONTEXT + "/ops") @RequestMapping(UtilsAndCommons.NACOS_CMDB_CONTEXT + "/ops")

View File

@ -17,6 +17,7 @@ package com.alibaba.nacos.cmdb.core;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public class CmdbManager { public class CmdbManager {
} }

View File

@ -20,6 +20,7 @@ import org.springframework.stereotype.Component;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
@Component @Component
public class SwitchAndOptions { public class SwitchAndOptions {

View File

@ -36,6 +36,7 @@ import java.util.concurrent.TimeUnit;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
@Component @Component
public class CmdbProvider implements CmdbReader, CmdbWriter { public class CmdbProvider implements CmdbReader, CmdbWriter {

View File

@ -22,6 +22,7 @@ import java.util.List;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public interface CmdbReader { public interface CmdbReader {

View File

@ -17,6 +17,7 @@ package com.alibaba.nacos.cmdb.service;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public interface CmdbWriter { public interface CmdbWriter {
} }

View File

@ -20,6 +20,7 @@ import org.slf4j.LoggerFactory;
/** /**
* @author nacos * @author nacos
* @since 0.7.0
*/ */
public class Loggers { public class Loggers {

View File

@ -21,6 +21,7 @@ import java.util.concurrent.ThreadFactory;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.7.0
*/ */
public class UtilsAndCommons { public class UtilsAndCommons {

View File

@ -0,0 +1,39 @@
/*
* 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.util;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.8.0
*/
public class HttpMethod {
public static final String GET = "GET";
public static final String HEAD = "HEAD";
public static final String POST = "POST";
public static final String PUT = "PUT";
public static final String PATCH = "PATCH";
public static final String DELETE = "PATCH";
public static final String OPTIONS = "PATCH";
public static final String TRACE = "TRACE";
}

View File

@ -15,8 +15,27 @@
*/ */
package com.alibaba.nacos.naming.controllers; package com.alibaba.nacos.naming.controllers;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.web.ApiCommands;
import com.alibaba.nacos.naming.web.OverrideParameterRequestWrapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.8.0
*/ */
public class HealthController { @RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + UtilsAndCommons.NACOS_NAMING_HEALTH_CONTEXT)
public class HealthController extends ApiCommands {
@RequestMapping(value = "", method = RequestMethod.POST)
public JSONObject update(HttpServletRequest request) throws Exception {
return clientBeat(OverrideParameterRequestWrapper.buildRequest(request, "dom", WebUtils.required(request, "serviceName")));
}
} }

View File

@ -21,10 +21,9 @@ import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.IpAddress; import com.alibaba.nacos.naming.core.IpAddress;
import com.alibaba.nacos.naming.core.VirtualClusterDomain; import com.alibaba.nacos.naming.core.VirtualClusterDomain;
import com.alibaba.nacos.naming.exception.NacosException; import com.alibaba.nacos.naming.exception.NacosException;
import com.alibaba.nacos.naming.healthcheck.HealthCheckMode;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.web.ApiCommands; import com.alibaba.nacos.naming.web.ApiCommands;
import com.alibaba.nacos.naming.web.MockHttpRequest; import com.alibaba.nacos.naming.web.OverrideParameterRequestWrapper;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
@ -32,9 +31,7 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a> * @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
@ -46,67 +43,18 @@ public class InstanceController extends ApiCommands {
@RequestMapping(value = "/instance", method = RequestMethod.PUT) @RequestMapping(value = "/instance", method = RequestMethod.PUT)
public String register(HttpServletRequest request) throws Exception { public String register(HttpServletRequest request) throws Exception {
Map<String, String[]> params = new HashMap<>(request.getParameterMap()); OverrideParameterRequestWrapper requestWrapper = OverrideParameterRequestWrapper.buildRequest(request);
MockHttpRequest mockHttpRequest = MockHttpRequest.buildRequest(params);
String serviceJson = WebUtils.optional(request, "service", StringUtils.EMPTY); String serviceJson = WebUtils.optional(request, "service", StringUtils.EMPTY);
String clusterJson = WebUtils.optional(request, "cluster", StringUtils.EMPTY);
// set service info: // set service info:
if (StringUtils.isNotEmpty(serviceJson)) { if (StringUtils.isNotEmpty(serviceJson)) {
JSONObject service = JSON.parseObject(serviceJson); JSONObject service = JSON.parseObject(serviceJson);
mockHttpRequest.addParameter("dom", service.getString("name")); requestWrapper.addParameter("dom", service.getString("name"));
mockHttpRequest.addParameter("app", service.getString("app"));
mockHttpRequest.addParameter("group", service.getString("group"));
mockHttpRequest.addParameter("protectThreshold", service.getString("protectThreshold"));
String healthCheckMode = service.getString("healthCheckMode");
if (HealthCheckMode.server.name().equals(healthCheckMode)) {
mockHttpRequest.addParameter("enableHealthCheck", "true");
}
if (HealthCheckMode.client.name().equals(healthCheckMode)) {
mockHttpRequest.addParameter("enableClientBeat", "true");
}
if (HealthCheckMode.none.name().equals(healthCheckMode)) {
mockHttpRequest.addParameter("enableHealthCheck", "false");
mockHttpRequest.addParameter("enableClientBeat", "false");
}
mockHttpRequest.addParameter("serviceMetadata", service.getString("metadata"));
} else { } else {
mockHttpRequest.addParameter("dom", WebUtils.required(request, "serviceName")); requestWrapper.addParameter("dom", WebUtils.required(request, "serviceName"));
} }
return regService(requestWrapper);
// set cluster info:
if (StringUtils.isNotEmpty(clusterJson)) {
JSONObject cluster = JSON.parseObject(clusterJson);
String clusterName = cluster.getString("name");
if (StringUtils.isEmpty(clusterName)) {
clusterName = UtilsAndCommons.DEFAULT_CLUSTER_NAME;
}
mockHttpRequest.addParameter("clusterName", clusterName);
JSONObject healthChecker = cluster.getJSONObject("healthChecker");
if (healthChecker == null) {
mockHttpRequest.addParameter("cktype", "TCP");
} else {
for (String key : healthChecker.keySet()) {
mockHttpRequest.addParameter(key, healthChecker.getString(key));
}
mockHttpRequest.addParameter("cktype", healthChecker.getString("type"));
}
mockHttpRequest.addParameter("cluster", StringUtils.EMPTY);
mockHttpRequest.addParameter("defIPPort", cluster.getString("defaultPort"));
mockHttpRequest.addParameter("defCkport", cluster.getString("defaultCheckPort"));
mockHttpRequest.addParameter("ipPort4Check", cluster.getString("useIPPort4Check"));
mockHttpRequest.addParameter("clusterMetadata", cluster.getString("metadata"));
}
return regService(mockHttpRequest);
} }
@RequestMapping(value = "/instance", method = RequestMethod.DELETE) @RequestMapping(value = "/instance", method = RequestMethod.DELETE)
@ -116,21 +64,12 @@ public class InstanceController extends ApiCommands {
@RequestMapping(value = {"/instance/update", "instance"}, method = RequestMethod.POST) @RequestMapping(value = {"/instance/update", "instance"}, method = RequestMethod.POST)
public String update(HttpServletRequest request) throws Exception { public String update(HttpServletRequest request) throws Exception {
String serviceName = WebUtils.required(request, "serviceName"); return regService(OverrideParameterRequestWrapper.buildRequest(request, "dom", WebUtils.required(request, "serviceName")));
Map<String, String[]> params = new HashMap<>(request.getParameterMap());
MockHttpRequest mockHttpRequest = MockHttpRequest.buildRequest(params);
mockHttpRequest.addParameter("dom", serviceName);
return regService(mockHttpRequest);
} }
@RequestMapping(value = {"/instances", "/instance/list"}, method = RequestMethod.GET) @RequestMapping(value = {"/instances", "/instance/list"}, method = RequestMethod.GET)
public JSONObject queryList(HttpServletRequest request) throws Exception { public JSONObject queryList(HttpServletRequest request) throws Exception {
return srvIPXT(OverrideParameterRequestWrapper.buildRequest(request, "dom", WebUtils.required(request, "serviceName")));
Map<String, String[]> params = new HashMap<>(request.getParameterMap());
params.put("dom", params.get("serviceName"));
MockHttpRequest mockHttpRequest = MockHttpRequest.buildRequest(params);
return srvIPXT(mockHttpRequest);
} }
@RequestMapping(value = "/instance", method = RequestMethod.GET) @RequestMapping(value = "/instance", method = RequestMethod.GET)
@ -170,6 +109,5 @@ public class InstanceController extends ApiCommands {
} }
throw new IllegalStateException("no matched ip found!"); throw new IllegalStateException("no matched ip found!");
} }
} }

View File

@ -32,18 +32,18 @@ public class RsInfo {
private double mem; private double mem;
private int port; private int port;
private String ip; private String ip;
private String dom; private String serviceName;
private String ak; private String ak;
private String cluster; private String cluster;
private double weight; private double weight;
private Map<String, String> metadata; private Map<String, String> metadata;
public String getDom() { public String getServiceName() {
return dom; return serviceName;
} }
public void setDom(String dom) { public void setServiceName(String serviceName) {
this.dom = dom; this.serviceName = serviceName;
} }
public String getAk() { public String getAk() {

View File

@ -49,6 +49,8 @@ public class UtilsAndCommons {
public static final String NACOS_NAMING_INSTANCE_CONTEXT = "/instance"; public static final String NACOS_NAMING_INSTANCE_CONTEXT = "/instance";
public static final String NACOS_NAMING_HEALTH_CONTEXT = "/health";
public static final String NACOS_NAMING_RAFT_CONTEXT = "/raft"; public static final String NACOS_NAMING_RAFT_CONTEXT = "/raft";
public static final String NACOS_SERVER_HEADER = "Nacos-Server"; public static final String NACOS_SERVER_HEADER = "Nacos-Server";
@ -104,6 +106,8 @@ public class UtilsAndCommons {
public static final String API_DOM = "/api/dom"; public static final String API_DOM = "/api/dom";
public static final String SERVICE_TENANT_CONNECTOR = "::";
public static final String INSTANCE_LIST_PERSISTED_PROPERTY_KEY = "nacos.instanceListPersisted"; public static final String INSTANCE_LIST_PERSISTED_PROPERTY_KEY = "nacos.instanceListPersisted";
public static final boolean INSTANCE_LIST_PERSISTED = Boolean.getBoolean(INSTANCE_LIST_PERSISTED_PROPERTY_KEY); public static final boolean INSTANCE_LIST_PERSISTED = Boolean.getBoolean(INSTANCE_LIST_PERSISTED_PROPERTY_KEY);

View File

@ -103,7 +103,9 @@ public class ApiCommands {
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
try { try {
result = ApiCommands.this.srvIPXT(MockHttpRequest.buildRequest(params)); result = ApiCommands.this.doSrvIPXT(client.getDom(), client.getAgent(), client.getClusters(),
inetAddress.getHostAddress(), 0, StringUtils.EMPTY, StringUtils.EMPTY, false,
StringUtils.EMPTY, StringUtils.EMPTY, false);
} catch (Exception e) { } catch (Exception e) {
Loggers.SRV_LOG.warn("PUSH-SERVICE: dom is not modified", e); Loggers.SRV_LOG.warn("PUSH-SERVICE: dom is not modified", e);
} }
@ -301,7 +303,7 @@ public class ApiCommands {
//if domain does not exist, register it. //if domain does not exist, register it.
if (virtualClusterDomain == null) { if (virtualClusterDomain == null) {
regDom(MockHttpRequest.buildRequest(stringMap)); regDom(OverrideParameterRequestWrapper.buildRequest(request, stringMap));
Loggers.SRV_LOG.warn("dom not found, register it, dom:" + dom); Loggers.SRV_LOG.warn("dom not found, register it, dom:" + dom);
} }
@ -320,13 +322,13 @@ public class ApiCommands {
ipAddress.setInstanceId(ipAddress.generateInstanceId()); ipAddress.setInstanceId(ipAddress.generateInstanceId());
if (!virtualClusterDomain.getClusterMap().containsKey(ipAddress.getClusterName())) { if (!virtualClusterDomain.getClusterMap().containsKey(ipAddress.getClusterName())) {
doAddCluster4Dom(MockHttpRequest.buildRequest(stringMap)); doAddCluster4Dom(OverrideParameterRequestWrapper.buildRequest(request, stringMap));
} }
if (!virtualClusterDomain.allIPs().contains(ipAddress)) { if (!virtualClusterDomain.allIPs().contains(ipAddress)) {
stringMap.put("ipList", Arrays.asList(JSON.toJSONString(Arrays.asList(ipAddress))).toArray(new String[1])); stringMap.put("ipList", Arrays.asList(JSON.toJSONString(Arrays.asList(ipAddress))).toArray(new String[1]));
stringMap.put("json", Arrays.asList("true").toArray(new String[1])); stringMap.put("json", Arrays.asList("true").toArray(new String[1]));
addIP4Dom(MockHttpRequest.buildRequest(stringMap)); addIP4Dom(OverrideParameterRequestWrapper.buildRequest(request, stringMap));
Loggers.SRV_LOG.warn("ip not found, register it, dom:" + dom + ", ip:" + ipAddress); Loggers.SRV_LOG.warn("ip not found, register it, dom:" + dom + ", ip:" + ipAddress);
} }
@ -518,9 +520,8 @@ public class ApiCommands {
parameterMap.put("ipList", Arrays.asList(JSON.toJSONString(Arrays.asList(ipAddress))).toArray(new String[1])); parameterMap.put("ipList", Arrays.asList(JSON.toJSONString(Arrays.asList(ipAddress))).toArray(new String[1]));
parameterMap.put("json", Arrays.asList("true").toArray(new String[1])); parameterMap.put("json", Arrays.asList("true").toArray(new String[1]));
parameterMap.put("token", Arrays.asList(virtualClusterDomain.getToken()).toArray(new String[1])); parameterMap.put("token", Arrays.asList(virtualClusterDomain.getToken()).toArray(new String[1]));
MockHttpRequest mockHttpRequest = MockHttpRequest.buildRequest(parameterMap);
return remvIP4Dom(mockHttpRequest); return remvIP4Dom(OverrideParameterRequestWrapper.buildRequest(request, parameterMap));
} }
@ -584,7 +585,7 @@ public class ApiCommands {
stringMap.put("json", Arrays.asList("true").toArray(new String[1])); stringMap.put("json", Arrays.asList("true").toArray(new String[1]));
stringMap.put("token", Arrays.asList(virtualClusterDomain.getToken()).toArray(new String[1])); stringMap.put("token", Arrays.asList(virtualClusterDomain.getToken()).toArray(new String[1]));
doAddIP4Dom(MockHttpRequest.buildRequest(stringMap)); doAddIP4Dom(OverrideParameterRequestWrapper.buildRequest(request, stringMap));
} else { } else {
throw new IllegalArgumentException("dom not found: " + dom); throw new IllegalArgumentException("dom not found: " + dom);
} }
@ -1085,32 +1086,11 @@ public class ApiCommands {
return result; return result;
} }
@RequestMapping("/srvIPXT") public JSONObject doSrvIPXT(String dom, String agent, String clusters, String clientIP, int udpPort,
@ResponseBody String error, String env, boolean isCheck, String app, String tid, boolean healthyOnly) throws Exception {
public JSONObject srvIPXT(HttpServletRequest request) throws Exception {
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
if (DistroMapper.getLocalhostIP().equals(UtilsAndCommons.LOCAL_HOST_IP)) {
throw new Exception("invalid localhost ip: " + DistroMapper.getLocalhostIP());
}
String dom = WebUtils.required(request, "dom");
VirtualClusterDomain domObj = (VirtualClusterDomain) domainsManager.getDomain(dom); VirtualClusterDomain domObj = (VirtualClusterDomain) domainsManager.getDomain(dom);
String agent = request.getHeader("Client-Version");
String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY);
String clientIP = WebUtils.optional(request, "clientIP", StringUtils.EMPTY);
Integer udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0"));
String env = WebUtils.optional(request, "env", StringUtils.EMPTY);
String error = WebUtils.optional(request, "unconsistentDom", StringUtils.EMPTY);
boolean isCheck = Boolean.parseBoolean(WebUtils.optional(request, "isCheck", "false"));
String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
String tenant = WebUtils.optional(request, "tid", StringUtils.EMPTY);
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthOnly", "false"));
if (!StringUtils.isEmpty(error)) { if (!StringUtils.isEmpty(error)) {
Loggers.ROLE_LOG.info("ENV-NOT-CONSISTENT", error); Loggers.ROLE_LOG.info("ENV-NOT-CONSISTENT", error);
@ -1128,12 +1108,12 @@ public class ApiCommands {
try { try {
if (udpPort > 0 && PushService.canEnablePush(agent)) { if (udpPort > 0 && PushService.canEnablePush(agent)) {
PushService.addClient(dom, PushService.addClient(dom,
clusters, clusters,
agent, agent,
new InetSocketAddress(clientIP, udpPort), new InetSocketAddress(clientIP, udpPort),
pushDataSource, pushDataSource,
tenant, tid,
app); app);
cacheMillis = Switch.getPushCacheMillis(dom); cacheMillis = Switch.getPushCacheMillis(dom);
} }
} catch (Exception e) { } catch (Exception e) {
@ -1173,7 +1153,7 @@ public class ApiCommands {
if ((float) ipMap.get(Boolean.TRUE).size() / srvedIPs.size() <= threshold) { if ((float) ipMap.get(Boolean.TRUE).size() / srvedIPs.size() <= threshold) {
Loggers.SRV_LOG.warn("protect threshold reached, return all ips, " + Loggers.SRV_LOG.warn("protect threshold reached, return all ips, " +
"dom: " + dom); "dom: " + dom);
if (isCheck) { if (isCheck) {
result.put("reachProtectThreshold", true); result.put("reachProtectThreshold", true);
} }
@ -1229,6 +1209,35 @@ public class ApiCommands {
return result; return result;
} }
@RequestMapping("/srvIPXT")
@ResponseBody
public JSONObject srvIPXT(HttpServletRequest request) throws Exception {
if (DistroMapper.getLocalhostIP().equals(UtilsAndCommons.LOCAL_HOST_IP)) {
throw new Exception("invalid localhost ip: " + DistroMapper.getLocalhostIP());
}
String dom = WebUtils.required(request, "dom");
VirtualClusterDomain domObj = (VirtualClusterDomain) domainsManager.getDomain(dom);
String agent = request.getHeader("Client-Version");
String clusters = WebUtils.optional(request, "clusters", StringUtils.EMPTY);
String clientIP = WebUtils.optional(request, "clientIP", StringUtils.EMPTY);
Integer udpPort = Integer.parseInt(WebUtils.optional(request, "udpPort", "0"));
String env = WebUtils.optional(request, "env", StringUtils.EMPTY);
String error = WebUtils.optional(request, "unconsistentDom", StringUtils.EMPTY);
boolean isCheck = Boolean.parseBoolean(WebUtils.optional(request, "isCheck", "false"));
String app = WebUtils.optional(request, "app", StringUtils.EMPTY);
String tenant = WebUtils.optional(request, "tid", StringUtils.EMPTY);
boolean healthyOnly = Boolean.parseBoolean(WebUtils.optional(request, "healthyOnly", "false"));
return doSrvIPXT(dom, agent, clusters, clientIP, udpPort, error, env, isCheck, app, tenant, healthyOnly);
}
@NeedAuth @NeedAuth
@RequestMapping("/remvIP4Dom") @RequestMapping("/remvIP4Dom")
public String remvIP4Dom(HttpServletRequest request) throws Exception { public String remvIP4Dom(HttpServletRequest request) throws Exception {

View File

@ -34,6 +34,7 @@ import java.util.Map;
* @author nacos * @author nacos
*/ */
public class DistroFilter implements Filter { public class DistroFilter implements Filter {
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {

View File

@ -1,403 +0,0 @@
/*
* 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.naming.web;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.*;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public class MockHttpRequest implements HttpServletRequest {
private Map<String, String[]> params;
public static MockHttpRequest buildRequest(Map<String, String[]> params) {
MockHttpRequest request = new MockHttpRequest();
request.params = params;
request.params.put("encoding", new String[]{"UTF-8"});
return request;
}
public static MockHttpRequest buildRequest2(Map<String, String> params) {
MockHttpRequest request = new MockHttpRequest();
Map<String, String[]> arrayMap = new HashMap<>(16);
for (String key : params.keySet()) {
arrayMap.put(key, new String[]{params.get(key)});
}
request.params = arrayMap;
request.params.put("encoding", new String[]{"UTF-8"});
return request;
}
public void addParameter(String key, String value) {
params.put(key, new String[]{value});
}
@Override
public String getAuthType() {
return null;
}
@Override
public Cookie[] getCookies() {
return new Cookie[0];
}
@Override
public long getDateHeader(String s) {
return 0;
}
@Override
public String getHeader(String s) {
return null;
}
@Override
public Enumeration<String> getHeaders(String s) {
return null;
}
@Override
public Enumeration<String> getHeaderNames() {
return null;
}
@Override
public int getIntHeader(String s) {
return 0;
}
@Override
public String getMethod() {
return null;
}
@Override
public String getPathInfo() {
return null;
}
@Override
public String getPathTranslated() {
return null;
}
@Override
public String getContextPath() {
return null;
}
@Override
public String getQueryString() {
return null;
}
@Override
public String getRemoteUser() {
return null;
}
@Override
public boolean isUserInRole(String s) {
return false;
}
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getRequestedSessionId() {
return null;
}
@Override
public String getRequestURI() {
return null;
}
@Override
public StringBuffer getRequestURL() {
return null;
}
@Override
public String getServletPath() {
return null;
}
@Override
public HttpSession getSession(boolean b) {
return null;
}
@Override
public HttpSession getSession() {
return null;
}
@Override
public String changeSessionId() {
return null;
}
@Override
public boolean isRequestedSessionIdValid() {
return false;
}
@Override
public boolean isRequestedSessionIdFromCookie() {
return false;
}
@Override
public boolean isRequestedSessionIdFromURL() {
return false;
}
@Override
public boolean isRequestedSessionIdFromUrl() {
return false;
}
@Override
public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException {
return false;
}
@Override
public void login(String s, String s1) throws ServletException {
}
@Override
public void logout() throws ServletException {
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
return null;
}
@Override
public Part getPart(String s) throws IOException, ServletException {
return null;
}
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException {
return null;
}
@Override
public Object getAttribute(String s) {
return null;
}
@Override
public Enumeration<String> getAttributeNames() {
return null;
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public void setCharacterEncoding(String s) throws UnsupportedEncodingException {
}
@Override
public int getContentLength() {
return 0;
}
@Override
public long getContentLengthLong() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
return null;
}
@Override
public String getParameter(String s) {
return params.get(s)[0];
}
@Override
public Enumeration<String> getParameterNames() {
return new Vector<>(params.keySet()).elements();
}
@Override
public String[] getParameterValues(String s) {
return params.get(s);
}
@Override
public Map<String, String[]> getParameterMap() {
return params;
}
@Override
public String getProtocol() {
return null;
}
@Override
public String getScheme() {
return null;
}
@Override
public String getServerName() {
return null;
}
@Override
public int getServerPort() {
return 0;
}
@Override
public BufferedReader getReader() throws IOException {
return null;
}
@Override
public String getRemoteAddr() {
return null;
}
@Override
public String getRemoteHost() {
return null;
}
@Override
public void setAttribute(String s, Object o) {
}
@Override
public void removeAttribute(String s) {
}
@Override
public Locale getLocale() {
return null;
}
@Override
public Enumeration<Locale> getLocales() {
return null;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String s) {
return null;
}
@Override
public String getRealPath(String s) {
return null;
}
@Override
public int getRemotePort() {
return 0;
}
@Override
public String getLocalName() {
return null;
}
@Override
public String getLocalAddr() {
return null;
}
@Override
public int getLocalPort() {
return 0;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return null;
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
return null;
}
@Override
public boolean isAsyncStarted() {
return false;
}
@Override
public boolean isAsyncSupported() {
return false;
}
@Override
public AsyncContext getAsyncContext() {
return null;
}
@Override
public DispatcherType getDispatcherType() {
return null;
}
}

View File

@ -51,6 +51,18 @@ public class NamingConfig {
return registration; return registration;
} }
@Bean
public FilterRegistrationBean tenantFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(tenantFilter());
registration.addUrlPatterns("/v1/ns/instance/*", "/v1/ns/service/*", "/v1/ns/cluster/*", "/v1/ns/health/*");
registration.setName("tenantFilter");
registration.setOrder(4);
return registration;
}
@Bean @Bean
public Filter distroFilter() { public Filter distroFilter() {
return new DistroFilter(); return new DistroFilter();
@ -60,4 +72,9 @@ public class NamingConfig {
public Filter authFilter() { public Filter authFilter() {
return new AuthFilter(); return new AuthFilter();
} }
@Bean
public Filter tenantFilter() {
return new TenantFilter();
}
} }

View File

@ -0,0 +1,86 @@
/*
* 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.naming.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
/**
* A request wrapper to override the parameters.
* <p>
* Referenced article is https://blog.csdn.net/xieyuooo/article/details/8447301
*
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.8.0
*/
public class OverrideParameterRequestWrapper extends HttpServletRequestWrapper {
private Map<String, String[]> params = new HashMap<String, String[]>();
/**
* Constructs a request object wrapping the given request.
*
* @param request The request to wrap
* @throws IllegalArgumentException if the request is null
*/
public OverrideParameterRequestWrapper(HttpServletRequest request) {
super(request);
this.params.putAll(request.getParameterMap());
}
public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request) {
return new OverrideParameterRequestWrapper(request);
}
public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request, String name, String value) {
OverrideParameterRequestWrapper requestWrapper = new OverrideParameterRequestWrapper(request);
requestWrapper.addParameter(name, value);
return requestWrapper;
}
public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request, Map<String, String[]> appendParameters) {
OverrideParameterRequestWrapper requestWrapper = new OverrideParameterRequestWrapper(request);
requestWrapper.params.putAll(appendParameters);
return requestWrapper;
}
@Override
public String getParameter(String name) {
String[] values = params.get(name);
if (values == null || values.length == 0) {
return null;
}
return values[0];
}
@Override
public Map<String, String[]> getParameterMap() {
return params;
}
public String[] getParameterValues(String name) {
return params.get(name);
}
public void addParameter(String name, String value) {
if (value != null) {
params.put(name, new String[]{value});
}
}
}

View File

@ -0,0 +1,67 @@
/*
* 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.naming.web;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* A filter to intercept tenant parameter.
*
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
* @since 0.8.0
*/
public class TenantFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String tenantId = WebUtils.optional(req, Constants.REQUEST_PARAM_TENANT_ID, StringUtils.EMPTY);
String serviceName = WebUtils.optional(req, Constants.REQUEST_PARAM_SERVICE_NAME, StringUtils.EMPTY);
if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(serviceName)) {
chain.doFilter(req, resp);
return;
}
OverrideParameterRequestWrapper requestWrapper = new OverrideParameterRequestWrapper(req);
requestWrapper.addParameter(Constants.REQUEST_PARAM_SERVICE_NAME,
serviceName + UtilsAndCommons.SERVICE_TENANT_CONNECTOR + tenantId);
chain.doFilter(requestWrapper, resp);
}
@Override
public void destroy() {
}
}

View File

@ -163,7 +163,7 @@ public class AutoDeregisterInstance_ITCase {
Assert.assertEquals(instances.size(), 1); Assert.assertEquals(instances.size(), 1);
BeatInfo beatInfo = new BeatInfo(); BeatInfo beatInfo = new BeatInfo();
beatInfo.setDom(serviceName); beatInfo.setServiceName(serviceName);
beatInfo.setIp("127.0.0.1"); beatInfo.setIp("127.0.0.1");
beatInfo.setPort(TEST_PORT); beatInfo.setPort(TEST_PORT);
@ -207,7 +207,7 @@ public class AutoDeregisterInstance_ITCase {
Assert.assertEquals(instances.size(), 1); Assert.assertEquals(instances.size(), 1);
BeatInfo beatInfo = new BeatInfo(); BeatInfo beatInfo = new BeatInfo();
beatInfo.setDom(serviceName); beatInfo.setServiceName(serviceName);
beatInfo.setIp("127.0.0.1"); beatInfo.setIp("127.0.0.1");
beatInfo.setPort(TEST_PORT); beatInfo.setPort(TEST_PORT);
beatInfo.setCluster("c1"); beatInfo.setCluster("c1");

View File

@ -15,6 +15,8 @@
*/ */
package com.alibaba.nacos.test.naming; package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory; import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.NamingService;
@ -29,10 +31,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.*; import static com.alibaba.nacos.test.naming.NamingBase.*;
@ -64,7 +63,14 @@ public class RegisterInstance_ITCase {
@Test @Test
@Ignore @Ignore
public void regService() throws NacosException, InterruptedException { public void regService() throws NacosException, InterruptedException {
String serviceName = "dungu.test.99";
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
properties.put(PropertyKeyConst.NAMESPACE, "t3");
naming = NacosFactory.createNamingService(properties);
String serviceName = "dungu.test.8";
naming.registerInstance(serviceName, "127.0.0.1", 80, "c1"); naming.registerInstance(serviceName, "127.0.0.1", 80, "c1");
naming.registerInstance(serviceName, "127.0.0.2", 80, "c2"); naming.registerInstance(serviceName, "127.0.0.2", 80, "c2");
Thread.sleep(100000000L); Thread.sleep(100000000L);