diff --git a/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java b/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java
index 6259d0a87..0ab3bd615 100644
--- a/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java
+++ b/api/src/main/java/com/alibaba/nacos/api/naming/utils/NamingUtils.java
@@ -27,6 +27,19 @@ import com.alibaba.nacos.api.utils.StringUtils;
*/
public class NamingUtils {
+ /**
+ * Returns a combined string with serviceName and groupName. serviceName can not be nil.
+ *
+ *
In most cases, serviceName can not be nil. In other cases, for search or anything, See {@link
+ * com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedNameOptional(String, String)}
+ *
+ *
etc:
+ *
serviceName | groupName | result
+ * serviceA | groupA | groupA@@serviceA
+ * nil | groupA | threw IllegalArgumentException
+ *
+ * @return 'groupName@@serviceName'
+ */
public static String getGroupedName(final String serviceName, final String groupName) {
if (StringUtils.isBlank(serviceName)) {
throw new IllegalArgumentException("Param 'serviceName' is illegal, serviceName is blank");
@@ -73,4 +86,20 @@ public class NamingUtils {
"Param 'serviceName' is illegal, it should be format as 'groupName@@serviceName'");
}
}
+
+ /**
+ * Returns a combined string with serviceName and groupName. Such as 'groupName@@serviceName'
+ * This method works similar with {@link com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedName} But not verify any parameters.
+ *
+ *
etc:
+ * serviceName | groupName | result
+ * serviceA | groupA | groupA@@serviceA
+ * nil | groupA | groupA@@
+ * nil | nil | @@
+ *
+ * @return 'groupName@@serviceName'
+ */
+ public static String getGroupedNameOptional(final String serviceName, final String groupName) {
+ return groupName + Constants.SERVICE_INFO_SPLITER + serviceName;
+ }
}
diff --git a/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java b/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java
new file mode 100644
index 000000000..41c58a556
--- /dev/null
+++ b/api/src/test/java/com/alibaba/nacos/api/naming/utils/NamingUtilsTest.java
@@ -0,0 +1,37 @@
+/*
+ * 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.api.naming.utils;
+
+import com.alibaba.nacos.api.utils.StringUtils;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class NamingUtilsTest {
+
+ @Test
+ public void testGetGroupedNameOptional() {
+ String onlyGroupName = NamingUtils.getGroupedNameOptional(StringUtils.EMPTY, "groupA");
+ assertEquals(onlyGroupName, "groupA@@");
+
+ String onlyServiceName = NamingUtils.getGroupedNameOptional("serviceA", StringUtils.EMPTY);
+ assertEquals(onlyServiceName, "@@serviceA");
+
+ String groupNameAndServiceName = NamingUtils.getGroupedNameOptional("serviceA", "groupA");
+ assertEquals(groupNameAndServiceName, "groupA@@serviceA");
+ }
+}
\ No newline at end of file
diff --git a/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java b/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java
index 721359b36..a13238fd4 100644
--- a/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java
+++ b/auth/src/main/java/com/alibaba/nacos/auth/common/AuthConfigs.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.auth.common;
import com.alibaba.nacos.common.JustForTest;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import io.jsonwebtoken.io.Decoders;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
@@ -89,7 +89,7 @@ public class AuthConfigs {
return BooleanUtils.toBoolean(enabled);
}
return BooleanUtils
- .toBoolean(ApplicationUtils.getProperty("nacos.core.auth.enabled", "false"));
+ .toBoolean(EnvUtil.getProperty("nacos.core.auth.enabled", "false"));
}
/**
@@ -102,7 +102,7 @@ public class AuthConfigs {
return cachingEnabled;
}
return BooleanUtils
- .toBoolean(ApplicationUtils.getProperty("nacos.core.auth.caching.enabled", "true"));
+ .toBoolean(EnvUtil.getProperty("nacos.core.auth.caching.enabled", "true"));
}
@JustForTest
diff --git a/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java b/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java
index 7381167f7..f9e4d7f01 100644
--- a/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java
+++ b/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java
@@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.http;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager;
import com.alibaba.nacos.client.config.impl.ServerListManager;
+import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.common.http.HttpClientConfig;
@@ -212,9 +213,7 @@ public class ServerHttpAgent implements HttpAgent {
}
private String getUrl(String serverAddr, String relativePath) {
- String contextPath = serverListMgr.getContentPath().startsWith("/") ? serverListMgr.getContentPath()
- : "/" + serverListMgr.getContentPath();
- return serverAddr + contextPath + relativePath;
+ return serverAddr + ContextPathUtil.normalizeContextPath(serverListMgr.getContentPath()) + relativePath;
}
private boolean isFail(HttpRestResult result) {
diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java
index 5ee77dfae..89fe4ef3c 100644
--- a/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java
+++ b/client/src/main/java/com/alibaba/nacos/client/config/impl/ServerListManager.java
@@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.EnvUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
@@ -109,7 +110,9 @@ public class ServerListManager implements Closeable {
this.isFixed = false;
this.isStarted = false;
this.name = CUSTOM_NAME + "-" + host + "-" + port;
- this.addressServerUrl = String.format("http://%s:%d/%s/%s", host, port, this.contentPath, this.serverListName);
+ this.addressServerUrl = String
+ .format("http://%s:%d%s/%s", host, port, ContextPathUtil.normalizeContextPath(this.contentPath),
+ this.serverListName);
}
public ServerListManager(String endpoint) throws NacosException {
@@ -128,8 +131,8 @@ public class ServerListManager implements Closeable {
}
if (StringUtils.isBlank(namespace)) {
this.name = endpoint;
- this.addressServerUrl = String
- .format("http://%s:%d/%s/%s", endpoint, this.endpointPort, this.contentPath, this.serverListName);
+ this.addressServerUrl = String.format("http://%s:%d%s/%s", endpoint, this.endpointPort,
+ ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName);
} else {
if (StringUtils.isBlank(endpoint)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "endpoint is blank");
@@ -137,9 +140,8 @@ public class ServerListManager implements Closeable {
this.name = endpoint + "-" + namespace;
this.namespace = namespace;
this.tenant = namespace;
- this.addressServerUrl = String
- .format("http://%s:%d/%s/%s?namespace=%s", endpoint, this.endpointPort, this.contentPath,
- this.serverListName, namespace);
+ this.addressServerUrl = String.format("http://%s:%d%s/%s?namespace=%s", endpoint, this.endpointPort,
+ ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName, namespace);
}
}
@@ -183,16 +185,15 @@ public class ServerListManager implements Closeable {
this.isFixed = false;
if (StringUtils.isBlank(namespace)) {
this.name = endpoint;
- this.addressServerUrl = String
- .format("http://%s:%d/%s/%s", this.endpoint, this.endpointPort, this.contentPath,
- this.serverListName);
+ this.addressServerUrl = String.format("http://%s:%d%s/%s", this.endpoint, this.endpointPort,
+ ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName);
} else {
this.namespace = namespace;
this.tenant = namespace;
this.name = this.endpoint + "-" + namespace;
this.addressServerUrl = String
- .format("http://%s:%d/%s/%s?namespace=%s", this.endpoint, this.endpointPort, this.contentPath,
- this.serverListName, namespace);
+ .format("http://%s:%d%s/%s?namespace=%s", this.endpoint, this.endpointPort,
+ ContextPathUtil.normalizeContextPath(this.contentPath), this.serverListName, namespace);
}
}
}
diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java
index 2a553c22f..ddc521ed9 100644
--- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java
+++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java
@@ -60,7 +60,7 @@ public class NacosNamingMaintainService implements NamingMaintainService {
ValidatorUtils.checkInitParam(properties);
namespace = InitUtils.initNamespaceForNaming(properties);
InitUtils.initSerialization();
- InitUtils.initWebRootContext();
+ InitUtils.initWebRootContext(properties;
ServerListManager serverListManager = new ServerListManager(properties);
serverProxy = new NamingHttpClientProxy(namespace, serverListManager, properties, null);
}
diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java
index dff28674f..b35cb02fc 100644
--- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java
+++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java
@@ -78,7 +78,7 @@ public class NacosNamingService implements NamingService {
ValidatorUtils.checkInitParam(properties);
this.namespace = InitUtils.initNamespaceForNaming(properties);
InitUtils.initSerialization();
- InitUtils.initWebRootContext();
+ InitUtils.initWebRootContext(properties);
initLogName(properties);
this.changeNotifier = new InstancesChangeNotifier();
diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java b/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java
index 61998b755..133b2e04a 100644
--- a/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java
+++ b/client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java
@@ -22,6 +22,7 @@ import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.api.selector.SelectorType;
+import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.TemplateUtils;
@@ -100,15 +101,34 @@ public class InitUtils {
/**
* Init web root context.
+ *
+ * @param properties properties
+ * @since 1.4.1
*/
+ public static void initWebRootContext(Properties properties) {
+ final String webContext = properties.getProperty(PropertyKeyConst.CONTEXT_PATH);
+ TemplateUtils.stringNotEmptyAndThenExecute(webContext, new Runnable() {
+ @Override
+ public void run() {
+ UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext);
+ UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns";
+ UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance";
+ }
+ });
+ initWebRootContext();
+ }
+
+ /**
+ * Init web root context.
+ */
+ @Deprecated
public static void initWebRootContext() {
// support the web context with ali-yun if the app deploy by EDAS
final String webContext = System.getProperty(SystemPropertyKeyConst.NAMING_WEB_CONTEXT);
TemplateUtils.stringNotEmptyAndThenExecute(webContext, new Runnable() {
@Override
public void run() {
- UtilAndComs.webContext = webContext.indexOf("/") > -1 ? webContext : "/" + webContext;
-
+ UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext);
UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns";
UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance";
}
diff --git a/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java b/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java
index f0b956b32..0407ef0b0 100644
--- a/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java
+++ b/client/src/main/java/com/alibaba/nacos/client/security/SecurityProxy.java
@@ -18,6 +18,7 @@ package com.alibaba.nacos.client.security;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
+import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
@@ -88,8 +89,7 @@ public class SecurityProxy {
public SecurityProxy(Properties properties, NacosRestTemplate nacosRestTemplate) {
username = properties.getProperty(PropertyKeyConst.USERNAME, StringUtils.EMPTY);
password = properties.getProperty(PropertyKeyConst.PASSWORD, StringUtils.EMPTY);
- contextPath = properties.getProperty(PropertyKeyConst.CONTEXT_PATH, "/nacos");
- contextPath = contextPath.startsWith("/") ? contextPath : "/" + contextPath;
+ contextPath = ContextPathUtil.normalizeContextPath(properties.getProperty(PropertyKeyConst.CONTEXT_PATH, "/nacos"));
this.nacosRestTemplate = nacosRestTemplate;
}
diff --git a/client/src/main/java/com/alibaba/nacos/client/utils/ContextPathUtil.java b/client/src/main/java/com/alibaba/nacos/client/utils/ContextPathUtil.java
new file mode 100644
index 000000000..265fd4784
--- /dev/null
+++ b/client/src/main/java/com/alibaba/nacos/client/utils/ContextPathUtil.java
@@ -0,0 +1,42 @@
+/*
+ * 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.client.utils;
+
+import com.alibaba.nacos.common.utils.StringUtils;
+
+/**
+ * Context path Util.
+ *
+ * @author Wei.Wang
+ */
+public class ContextPathUtil {
+
+ private static final String ROOT_WEB_CONTEXT_PATH = "/";
+
+ /**
+ * normalize context path.
+ *
+ * @param contextPath origin context path
+ * @return normalized context path
+ */
+ public static String normalizeContextPath(String contextPath) {
+ if (StringUtils.isBlank(contextPath) || ROOT_WEB_CONTEXT_PATH.equals(contextPath)) {
+ return StringUtils.EMPTY;
+ }
+ return contextPath.startsWith("/") ? contextPath : "/" + contextPath;
+ }
+}
diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java
new file mode 100644
index 000000000..c1953d8b1
--- /dev/null
+++ b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java
@@ -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.client.utils;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * ContextPathUtil test.
+ *
+ * @author Wei.Wang
+ * @date 2020/11/26 3:13 PM
+ */
+public class ContextPathUtilTest {
+
+ @Test
+ public void testNormalizeContextPath() {
+ assertEquals("/nacos", ContextPathUtil.normalizeContextPath("/nacos"));
+ assertEquals("/nacos", ContextPathUtil.normalizeContextPath("nacos"));
+ assertEquals("", ContextPathUtil.normalizeContextPath("/"));
+ assertEquals("", ContextPathUtil.normalizeContextPath(""));
+ }
+}
diff --git a/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java b/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java
index 8f3ffa3cf..7b73c50f7 100644
--- a/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java
+++ b/common/src/main/java/com/alibaba/nacos/common/model/RestResultUtils.java
@@ -16,6 +16,8 @@
package com.alibaba.nacos.common.model;
+import com.alibaba.nacos.common.model.core.IResultCode;
+
/**
* Rest result utils.
*
@@ -31,6 +33,10 @@ public class RestResultUtils {
return RestResult.builder().withCode(200).withData(data).build();
}
+ public static RestResult success(String msg, T data) {
+ return RestResult.builder().withCode(200).withMsg(msg).withData(data).build();
+ }
+
public static RestResult success(int code, T data) {
return RestResult.builder().withCode(code).withData(data).build();
}
@@ -54,5 +60,8 @@ public class RestResultUtils {
public static RestResult failedWithMsg(int code, String errMsg) {
return RestResult.builder().withCode(code).withMsg(errMsg).build();
}
-
+
+ public static RestResult buildResult(IResultCode resultCode, T data) {
+ return RestResult.builder().withCode(resultCode.getCode()).withMsg(resultCode.getCodeMsg()).withData(data).build();
+ }
}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/result/core/IResultCode.java b/common/src/main/java/com/alibaba/nacos/common/model/core/IResultCode.java
similarity index 95%
rename from config/src/main/java/com/alibaba/nacos/config/server/result/core/IResultCode.java
rename to common/src/main/java/com/alibaba/nacos/common/model/core/IResultCode.java
index d299fa823..e7d9ed83e 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/result/core/IResultCode.java
+++ b/common/src/main/java/com/alibaba/nacos/common/model/core/IResultCode.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.alibaba.nacos.config.server.result.core;
+package com.alibaba.nacos.common.model.core;
/**
* IResultCode.
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java b/common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java
similarity index 94%
rename from config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java
rename to common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java
index 2fc0277ef..dc6009d2b 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java
+++ b/common/src/main/java/com/alibaba/nacos/common/utils/NamespaceUtil.java
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-package com.alibaba.nacos.config.server.utils;
-
-import org.apache.commons.lang3.StringUtils;
+package com.alibaba.nacos.common.utils;
/**
* namespace(tenant) util.
diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java
similarity index 97%
rename from config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java
rename to common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java
index 16bbd700d..c653a5e1b 100644
--- a/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java
+++ b/common/src/test/java/com/alibaba/nacos/common/utils/NamespaceUtilTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.alibaba.nacos.config.server.utils;
+package com.alibaba.nacos.common.utils;
import org.junit.Assert;
import org.junit.Test;
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java b/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java
index 8f594be82..b4dbbdc7f 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java
@@ -20,6 +20,7 @@ import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.auth.model.Resource;
import com.alibaba.nacos.auth.parser.ResourceParser;
import com.alibaba.nacos.common.utils.ReflectUtils;
+import com.alibaba.nacos.common.utils.NamespaceUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
@@ -42,7 +43,7 @@ public class ConfigResourceParser implements ResourceParser {
String dataId = null;
if (requestObj instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) requestObj;
- namespaceId = req.getParameter("tenant");
+ namespaceId = NamespaceUtil.processNamespaceParameter(req.getParameter("tenant"));
groupName = req.getParameter("group");
dataId = req.getParameter("dataId");
} else if (requestObj instanceof Request) {
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java
index 5d3d0b8a6..cc545f7cc 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionDistributedEmbedStorage.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.config.server.configuration;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
@@ -31,6 +31,6 @@ public class ConditionDistributedEmbedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
- return PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode();
+ return PropertyUtil.isEmbeddedStorage() && !EnvUtil.getStandaloneMode();
}
-}
\ No newline at end of file
+}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java
index 2a6fcf56d..7006cb07c 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/configuration/ConditionStandaloneEmbedStorage.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.config.server.configuration;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
@@ -32,6 +32,6 @@ public class ConditionStandaloneEmbedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
- return PropertyUtil.isEmbeddedStorage() && ApplicationUtils.getStandaloneMode();
+ return PropertyUtil.isEmbeddedStorage() && EnvUtil.getStandaloneMode();
}
}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
index 6f2972e27..4cb1af6cf 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
@@ -22,6 +22,8 @@ import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.auth.common.ActionTypes;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.MapUtil;
+import com.alibaba.nacos.common.model.RestResultUtils;
+import com.alibaba.nacos.common.utils.MapUtils;
import com.alibaba.nacos.config.server.auth.ConfigResourceParser;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.controller.parameters.SameNamespaceCloneConfigBean;
@@ -34,7 +36,6 @@ import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.model.SameConfigPolicy;
import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent;
-import com.alibaba.nacos.config.server.result.ResultBuilder;
import com.alibaba.nacos.config.server.result.code.ResultCodeEnum;
import com.alibaba.nacos.config.server.service.AggrWhitelist;
import com.alibaba.nacos.config.server.service.ConfigChangePublisher;
@@ -45,6 +46,7 @@ import com.alibaba.nacos.config.server.utils.MD5Util;
import com.alibaba.nacos.config.server.utils.NamespaceUtil;
import com.alibaba.nacos.config.server.utils.ParamUtils;
import com.alibaba.nacos.config.server.utils.RequestUtil;
+import com.alibaba.nacos.common.utils.NamespaceUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.config.server.utils.ZipUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
@@ -284,7 +286,7 @@ public class ConfigController {
null, time.getTime(), clientIp, ConfigTraceService.PERSISTENCE_EVENT_REMOVE, null);
}
}
- return ResultBuilder.buildSuccessResult(true);
+ return RestResultUtils.success(true);
}
@GetMapping("/catalog")
@@ -529,13 +531,13 @@ public class ConfigController {
Map failedData = new HashMap<>(4);
if (Objects.isNull(file)) {
- return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
}
namespace = NamespaceUtil.processNamespaceParameter(namespace);
if (StringUtils.isNotBlank(namespace) && persistService.tenantInfoCountByTenantId(namespace) <= 0) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData);
}
List configInfoList = null;
@@ -550,7 +552,7 @@ public class ConfigController {
String[] metaDataItemArr = metaDataItem.split("=");
if (metaDataItemArr.length != 2) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.METADATA_ILLEGAL, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.METADATA_ILLEGAL, failedData);
}
metaDataMap.put(metaDataItemArr[0], metaDataItemArr[1]);
}
@@ -562,7 +564,7 @@ public class ConfigController {
String[] groupAdnDataId = item.getItemName().split("/");
if (!item.getItemName().contains("/") || groupAdnDataId.length != 2) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.DATA_VALIDATION_FAILED, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.DATA_VALIDATION_FAILED, failedData);
}
String group = groupAdnDataId[0];
String dataId = groupAdnDataId[1];
@@ -586,11 +588,11 @@ public class ConfigController {
} catch (IOException e) {
failedData.put("succCount", 0);
LOGGER.error("parsing data failed", e);
- return ResultBuilder.buildResult(ResultCodeEnum.PARSING_DATA_FAILED, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.PARSING_DATA_FAILED, failedData);
}
if (configInfoList == null || configInfoList.isEmpty()) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
}
final String srcIp = RequestUtil.getRemoteIp(request);
String requestIpApp = RequestUtil.getAppName(request);
@@ -606,7 +608,7 @@ public class ConfigController {
requestIpApp, time.getTime(), InetUtils.getSelfIP(),
ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent());
}
- return ResultBuilder.buildSuccessResult("导入成功", saveResult);
+ return RestResultUtils.success("导入成功", saveResult);
}
/**
@@ -630,14 +632,14 @@ public class ConfigController {
Map failedData = new HashMap<>(4);
if (CollectionUtils.isEmpty(configBeansList)) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.NO_SELECTED_CONFIG, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.NO_SELECTED_CONFIG, failedData);
}
configBeansList.removeAll(Collections.singleton(null));
namespace = NamespaceUtil.processNamespaceParameter(namespace);
if (StringUtils.isNotBlank(namespace) && persistService.tenantInfoCountByTenantId(namespace) <= 0) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData);
}
List idList = new ArrayList<>(configBeansList.size());
@@ -651,7 +653,7 @@ public class ConfigController {
if (queryedDataList == null || queryedDataList.isEmpty()) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
}
List configInfoList4Clone = new ArrayList<>(queryedDataList.size());
@@ -675,7 +677,7 @@ public class ConfigController {
if (configInfoList4Clone.isEmpty()) {
failedData.put("succCount", 0);
- return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
+ return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
}
final String srcIp = RequestUtil.getRemoteIp(request);
String requestIpApp = RequestUtil.getAppName(request);
@@ -691,7 +693,7 @@ public class ConfigController {
requestIpApp, time.getTime(), InetUtils.getSelfIP(),
ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent());
}
- return ResultBuilder.buildSuccessResult("Clone Completed Successfully", saveResult);
+ return RestResultUtils.success("Clone Completed Successfully", saveResult);
}
}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java b/config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java
deleted file mode 100644
index 1e64af8a6..000000000
--- a/config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java
+++ /dev/null
@@ -1,83 +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.config.server.result;
-
-import com.alibaba.nacos.common.model.RestResult;
-import com.alibaba.nacos.config.server.result.code.ResultCodeEnum;
-import com.alibaba.nacos.config.server.result.core.IResultCode;
-import org.springframework.util.Assert;
-
-/**
- * ResultBuilder.
- *
- * @author klw
- * @ClassName: ResultBuilder
- * @Description: util for generating {@link RestResult}
- * @date 2019/6/28 14:47
- */
-@Deprecated
-public class ResultBuilder {
-
- /**
- * BuildResult.
- *
- * @param resultCode resultCode.
- * @param resultData resultData.
- * @param T.
- * @return RestResult.
- */
- public static RestResult buildResult(IResultCode resultCode, T resultData) {
- Assert.notNull(resultCode, "the resultCode can not be null");
- RestResult rr = new RestResult<>(resultCode.getCode(), resultCode.getCodeMsg(), resultData);
- return rr;
- }
-
- public static RestResult buildSuccessResult(T resultData) {
- return buildResult(ResultCodeEnum.SUCCESS, resultData);
- }
-
- /**
- * BuildSuccessResult.
- *
- * @param successMsg successMsg string value.
- * @param resultData resultData.
- * @param T.
- * @return RestResult.
- */
- public static RestResult buildSuccessResult(String successMsg, T resultData) {
- RestResult rr = buildResult(ResultCodeEnum.SUCCESS, resultData);
- rr.setMessage(successMsg);
- return rr;
- }
-
- public static RestResult buildSuccessResult() {
- return buildResult(ResultCodeEnum.SUCCESS, null);
- }
-
- /**
- * BuildSuccessResult.
- *
- * @param successMsg successMsg string value.
- * @param T.
- * @return RestResult.
- */
- public static RestResult buildSuccessResult(String successMsg) {
- RestResult rr = buildResult(ResultCodeEnum.SUCCESS, null);
- rr.setMessage(successMsg);
- return rr;
- }
-}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java b/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java
index 202334eb3..19a0f7ac2 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/result/code/ResultCodeEnum.java
@@ -16,7 +16,7 @@
package com.alibaba.nacos.config.server.result.code;
-import com.alibaba.nacos.config.server.result.core.IResultCode;
+import com.alibaba.nacos.common.model.core.IResultCode;
/**
* ResultCodeEnum.
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java
index 928641657..b7fc85c2e 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigChangePublisher.java
@@ -19,7 +19,7 @@ package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
/**
* ConfigChangePublisher.
@@ -34,7 +34,7 @@ public class ConfigChangePublisher {
* @param event ConfigDataChangeEvent instance.
*/
public static void notifyConfigChange(ConfigDataChangeEvent event) {
- if (PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode()) {
+ if (PropertyUtil.isEmbeddedStorage() && !EnvUtil.getStandaloneMode()) {
return;
}
NotifyCenter.publishEvent(event);
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java
index 03b6bc8cb..ba2afba5a 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java
@@ -25,7 +25,7 @@ import com.alibaba.nacos.config.server.utils.ConfigExecutor;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -74,7 +74,7 @@ public class ConfigSubService {
* @return all path.
*/
private String getUrl(String ip, String relativePath) {
- return "http://" + ip + ApplicationUtils.getContextPath() + relativePath;
+ return "http://" + ip + EnvUtil.getContextPath() + relativePath;
}
private List runCollectionJob(String url, Map params,
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java
index 99688fed2..c42393388 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceServiceImpl.java
@@ -22,7 +22,7 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.monitor.MetricsMonitor;
import com.alibaba.nacos.config.server.utils.ConfigExecutor;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
@@ -116,7 +116,7 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
public synchronized void reload() throws IOException {
try {
dataSourceList = new ExternalDataSourceProperties()
- .build(ApplicationUtils.getEnvironment(), (dataSource) -> {
+ .build(EnvUtil.getEnvironment(), (dataSource) -> {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setQueryTimeout(queryTimeout);
jdbcTemplate.setDataSource(dataSource);
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java
index 33224ee78..81f4c1db6 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/datasource/LocalDataSourceServiceImpl.java
@@ -21,7 +21,7 @@ import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.StringUtils;
@@ -77,7 +77,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
if (!initialize) {
LogUtil.DEFAULT_LOG.info("use local db service for init");
final String jdbcUrl =
- "jdbc:derby:" + Paths.get(ApplicationUtils.getNacosHome(), derbyBaseDir).toString()
+ "jdbc:derby:" + Paths.get(EnvUtil.getNacosHome(), derbyBaseDir).toString()
+ ";create=true";
initialize(jdbcUrl);
initialize = true;
@@ -113,7 +113,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
public void cleanAndReopenDerby() throws Exception {
doDerbyClean();
final String jdbcUrl =
- "jdbc:derby:" + Paths.get(ApplicationUtils.getNacosHome(), derbyBaseDir).toString() + ";create=true";
+ "jdbc:derby:" + Paths.get(EnvUtil.getNacosHome(), derbyBaseDir).toString() + ";create=true";
initialize(jdbcUrl);
}
@@ -140,11 +140,11 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
throw e;
}
}
- DiskUtils.deleteDirectory(Paths.get(ApplicationUtils.getNacosHome(), derbyBaseDir).toString());
+ DiskUtils.deleteDirectory(Paths.get(EnvUtil.getNacosHome(), derbyBaseDir).toString());
}
private synchronized void initialize(String jdbcUrl) {
- DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(ApplicationUtils.getEnvironment());
+ DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(EnvUtil.getEnvironment());
poolProperties.setDriverClassName(jdbcDriverName);
poolProperties.setJdbcUrl(jdbcUrl);
poolProperties.setUsername(userName);
@@ -184,7 +184,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
@Override
public String getCurrentDbUrl() {
- return "jdbc:derby:" + ApplicationUtils.getNacosHome() + File.separator + derbyBaseDir + ";create=true";
+ return "jdbc:derby:" + EnvUtil.getNacosHome() + File.separator + derbyBaseDir + ";create=true";
}
@Override
@@ -208,8 +208,8 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
InputStream sqlFileIn = null;
try {
File file = new File(
- ApplicationUtils.getNacosHome() + File.separator + "conf" + File.separator + "schema.sql");
- if (StringUtils.isBlank(ApplicationUtils.getNacosHome()) || !file.exists()) {
+ EnvUtil.getNacosHome() + File.separator + "conf" + File.separator + "schema.sql");
+ if (StringUtils.isBlank(EnvUtil.getNacosHome()) || !file.exists()) {
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource(sqlFile);
sqlFileIn = url.openStream();
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java
index c5f6d7683..5e706e15d 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java
@@ -49,7 +49,7 @@ import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
import com.alibaba.nacos.core.utils.TimerContext;
import org.slf4j.Logger;
@@ -203,7 +203,7 @@ public abstract class DumpService {
"Nacos Server did not start because dumpservice bean construction failure :\n" + e.getMessage(),
e);
}
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
Runnable heartbeat = () -> {
String heartBeatTime = TimeUtils.getCurrentTime().toString();
// write disk
@@ -305,7 +305,7 @@ public abstract class DumpService {
private Boolean isQuickStart() {
try {
String val = null;
- val = ApplicationUtils.getProperty("isQuickStart");
+ val = EnvUtil.getProperty("isQuickStart");
if (val != null && TRUE_STR.equals(val)) {
isQuickStart = true;
}
@@ -317,7 +317,7 @@ public abstract class DumpService {
}
private int getRetentionDays() {
- String val = ApplicationUtils.getProperty("nacos.config.retention.days");
+ String val = EnvUtil.getProperty("nacos.config.retention.days");
if (null == val) {
return retentionDays;
}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java
index 85abd81fa..3c702964d 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/EmbeddedDumpService.java
@@ -28,7 +28,7 @@ import com.alibaba.nacos.consistency.cp.CPProtocol;
import com.alibaba.nacos.consistency.cp.MetadataKey;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.core.distributed.ProtocolManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.core.utils.GlobalExecutor;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
@@ -76,7 +76,7 @@ public class EmbeddedDumpService extends DumpService {
@PostConstruct
@Override
protected void init() throws Throwable {
- if (ApplicationUtils.getStandaloneMode()) {
+ if (EnvUtil.getStandaloneMode()) {
dumpOperate(processor, dumpAllProcessor, dumpAllBetaProcessor, dumpAllTagProcessor);
return;
}
@@ -155,7 +155,7 @@ public class EmbeddedDumpService extends DumpService {
@Override
protected boolean canExecute() {
- if (ApplicationUtils.getStandaloneMode()) {
+ if (EnvUtil.getStandaloneMode()) {
return true;
}
// if is derby + raft mode, only leader can execute
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java
index e08a56020..cb4e115d5 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java
@@ -27,6 +27,7 @@ import com.alibaba.nacos.config.server.utils.ContentUtils;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.core.distributed.ProtocolManager;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.slf4j.Logger;
@@ -114,7 +115,7 @@ public class MergeDatumService {
if (!PropertyUtil.isEmbeddedStorage()) {
return true;
}
- if (ApplicationUtils.getStandaloneMode()) {
+ if (EnvUtil.getStandaloneMode()) {
return true;
}
ProtocolManager protocolManager = ApplicationUtils.getBean(ProtocolManager.class);
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java
index 493430ed7..8fa7e4101 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java
@@ -39,7 +39,7 @@ import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberUtils;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -434,10 +434,10 @@ public class AsyncNotifyService {
LOGGER.error("URLEncoder encode error", e);
}
if (StringUtils.isBlank(tenant)) {
- this.url = MessageFormat.format(URL_PATTERN, target, ApplicationUtils.getContextPath(), dataId, group);
+ this.url = MessageFormat.format(URL_PATTERN, target, EnvUtil.getContextPath(), dataId, group);
} else {
this.url = MessageFormat
- .format(URL_PATTERN_TENANT, target, ApplicationUtils.getContextPath(), dataId, group, tenant);
+ .format(URL_PATTERN_TENANT, target, EnvUtil.getContextPath(), dataId, group, tenant);
}
if (StringUtils.isNotEmpty(tag)) {
url = url + "&tag=" + tag;
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java
index aa505c7fb..673aca553 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java
@@ -24,7 +24,7 @@ import com.alibaba.nacos.config.server.monitor.MetricsMonitor;
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -75,7 +75,7 @@ public class NotifyTaskProcessor implements NacosTaskProcessor {
.asList(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, String.valueOf(lastModified),
NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIP());
String urlString = MessageFormat
- .format(URL_PATTERN, serverIp, ApplicationUtils.getContextPath(), dataId, group);
+ .format(URL_PATTERN, serverIp, EnvUtil.getContextPath(), dataId, group);
RestResult result = NotifyService.invokeURL(urlString, headers, Constants.ENCODE);
if (result.ok()) {
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java
index b86e441f2..5b3c9c302 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/RowMapperManager.java
@@ -35,8 +35,10 @@ import com.alibaba.nacos.config.server.model.TenantInfo;
import com.alibaba.nacos.config.server.model.User;
import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.jdbc.core.RowMapper;
@@ -84,6 +86,8 @@ public final class RowMapperManager {
public static final PermissionRowMapper PERMISSION_ROW_MAPPER = new PermissionRowMapper();
+ public static final MapRowMapper MAP_ROW_MAPPER = new MapRowMapper();
+
public static Map mapperMap = new HashMap<>(16);
static {
@@ -161,12 +165,30 @@ public final class RowMapperManager {
// PERMISSION_ROW_MAPPER
mapperMap.put(PERMISSION_ROW_MAPPER.getClass().getCanonicalName(), PERMISSION_ROW_MAPPER);
+
+ // MAP_ROW_MAPPER
+
+ mapperMap.put(MAP_ROW_MAPPER.getClass().getCanonicalName(), MAP_ROW_MAPPER);
}
public static RowMapper getRowMapper(String classFullName) {
return (RowMapper) mapperMap.get(classFullName);
}
+ public static final class MapRowMapper implements RowMapper> {
+
+ @Override
+ public Map mapRow(ResultSet resultSet, int rowNum) throws SQLException {
+ ResultSetMetaData metaData = resultSet.getMetaData();
+ int columnCount = metaData.getColumnCount();
+ Map map = new LinkedHashMap<>(columnCount);
+ for (int i = 1; i <= columnCount; i++) {
+ map.put(metaData.getColumnLabel(i), resultSet.getObject(i));
+ }
+ return map;
+ }
+ }
+
public static final class ConfigInfoWrapperRowMapper implements RowMapper {
@Override
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java
index 75d6684cf..4575b6c7e 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/DerbySnapshotOperation.java
@@ -27,8 +27,8 @@ import com.alibaba.nacos.consistency.snapshot.Reader;
import com.alibaba.nacos.consistency.snapshot.SnapshotOperation;
import com.alibaba.nacos.consistency.snapshot.Writer;
import com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.core.utils.TimerContext;
import com.alipay.sofa.jraft.util.CRC64;
@@ -61,7 +61,7 @@ public class DerbySnapshotOperation implements SnapshotOperation {
private final String snapshotArchive = "derby_data.zip";
- private final String derbyBaseDir = Paths.get(ApplicationUtils.getNacosHome(), "data", "derby-data").toString();
+ private final String derbyBaseDir = Paths.get(EnvUtil.getNacosHome(), "data", "derby-data").toString();
private final String restoreDB = "jdbc:derby:" + derbyBaseDir;
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java
index 83baef999..6e5d2d039 100755
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedStoragePersistServiceImpl.java
@@ -72,6 +72,7 @@ import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_ADVANCE_INFO_ROW_MAPPER;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_ALL_INFO_ROW_MAPPER;
@@ -88,6 +89,7 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.HISTORY_DETAIL_ROW_MAPPER;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.HISTORY_LIST_ROW_MAPPER;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.TENANT_INFO_ROW_MAPPER;
+import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.MAP_ROW_MAPPER;
import static com.alibaba.nacos.config.server.utils.LogUtil.DEFAULT_LOG;
/**
@@ -1116,16 +1118,30 @@ public class EmbeddedStoragePersistServiceImpl implements PersistService {
@Override
public List getTenantIdList(int page, int pageSize) {
- String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id LIMIT ?, ?";
+ PaginationHelper> helper = createPaginationHelper();
+
+ String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id LIMIT ?,?";
int from = (page - 1) * pageSize;
- return databaseOperate.queryMany(sql, new Object[] {from, pageSize}, String.class);
+
+ Page> pageList = helper
+ .fetchPageLimit(sql, new Object[] {from, pageSize}, page, pageSize, MAP_ROW_MAPPER);
+ return pageList.getPageItems().stream()
+ .map(map -> String.valueOf(map.get("TENANT_ID")))
+ .collect(Collectors.toList());
}
@Override
public List getGroupIdList(int page, int pageSize) {
- String sql = "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT ?, ?";
+ PaginationHelper> helper = createPaginationHelper();
+
+ String sql = "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT ?,?";
int from = (page - 1) * pageSize;
- return databaseOperate.queryMany(sql, new Object[] {from, pageSize}, String.class);
+
+ Page> pageList = helper
+ .fetchPageLimit(sql, new Object[] {from, pageSize}, page, pageSize, MAP_ROW_MAPPER);
+ return pageList.getPageItems().stream()
+ .map(map -> String.valueOf(map.get("GROUP_ID")))
+ .collect(Collectors.toList());
}
@Override
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java
index 18323134e..ca1cc29c5 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePaginationHelperImpl.java
@@ -20,7 +20,7 @@ import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.repository.PaginationHelper;
import com.alibaba.nacos.config.server.service.sql.EmbeddedStorageContextUtils;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
@@ -214,7 +214,7 @@ class ExternalStoragePaginationHelperImpl implements PaginationHelper {
}
private boolean isDerby() {
- return (ApplicationUtils.getStandaloneMode() && !PropertyUtil.isUseExternalDB()) || PropertyUtil
+ return (EnvUtil.getStandaloneMode() && !PropertyUtil.isUseExternalDB()) || PropertyUtil
.isEmbeddedStorage();
}
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java
index 8fe679396..fa2aa3c23 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/service/sql/EmbeddedStorageContextUtils.java
@@ -21,7 +21,7 @@ import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.event.ConfigDumpEvent;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -88,7 +88,7 @@ public class EmbeddedStorageContextUtils {
* @param time Operating time
*/
public static void onModifyConfigInfo(ConfigInfo configInfo, String srcIp, Timestamp time) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
ConfigDumpEvent event = ConfigDumpEvent.builder().remove(false).namespaceId(configInfo.getTenant())
.dataId(configInfo.getDataId()).group(configInfo.getGroup()).isBeta(false)
.content(configInfo.getContent()).type(configInfo.getType()).handleIp(srcIp)
@@ -110,7 +110,7 @@ public class EmbeddedStorageContextUtils {
* @param time Operating time
*/
public static void onModifyConfigBetaInfo(ConfigInfo configInfo, String betaIps, String srcIp, Timestamp time) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
ConfigDumpEvent event = ConfigDumpEvent.builder().remove(false).namespaceId(configInfo.getTenant())
.dataId(configInfo.getDataId()).group(configInfo.getGroup()).isBeta(true).betaIps(betaIps)
.content(configInfo.getContent()).type(configInfo.getType()).handleIp(srcIp)
@@ -132,7 +132,7 @@ public class EmbeddedStorageContextUtils {
* @param time Operating time
*/
public static void onModifyConfigTagInfo(ConfigInfo configInfo, String tag, String srcIp, Timestamp time) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
ConfigDumpEvent event = ConfigDumpEvent.builder().remove(false).namespaceId(configInfo.getTenant())
.dataId(configInfo.getDataId()).group(configInfo.getGroup()).isBeta(false).tag(tag)
.content(configInfo.getContent()).type(configInfo.getType()).handleIp(srcIp)
@@ -156,7 +156,7 @@ public class EmbeddedStorageContextUtils {
*/
public static void onDeleteConfigInfo(String namespaceId, String group, String dataId, String srcIp,
Timestamp time) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
ConfigDumpEvent event = ConfigDumpEvent.builder().remove(true).namespaceId(namespaceId).group(group)
.dataId(dataId).isBeta(false).handleIp(srcIp).lastModifiedTs(time.getTime()).build();
@@ -173,7 +173,7 @@ public class EmbeddedStorageContextUtils {
* @param configInfos {@link ConfigInfo} list
*/
public static void onBatchDeleteConfigInfo(List configInfos) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
List events = new ArrayList<>();
for (ConfigInfo configInfo : configInfos) {
String namespaceId =
@@ -200,7 +200,7 @@ public class EmbeddedStorageContextUtils {
* @param time Operating time
*/
public static void onDeleteConfigBetaInfo(String namespaceId, String group, String dataId, long time) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
ConfigDumpEvent event = ConfigDumpEvent.builder().remove(true).namespaceId(namespaceId).dataId(dataId)
.group(group).isBeta(true).build();
@@ -222,7 +222,7 @@ public class EmbeddedStorageContextUtils {
*/
public static void onDeleteConfigTagInfo(String namespaceId, String group, String dataId, String tag,
String srcIp) {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
ConfigDumpEvent event = ConfigDumpEvent.builder().remove(true).namespaceId(namespaceId).group(group)
.dataId(dataId).isBeta(true).tag(tag).handleIp(srcIp).build();
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java
index 9096a84c6..40bcb646f 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/DiskUtil.java
@@ -19,7 +19,7 @@ package com.alibaba.nacos.config.server.utils;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.alibaba.nacos.config.server.constant.Constants;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
@@ -107,9 +107,9 @@ public class DiskUtil {
public static File targetFile(String dataId, String group, String tenant) {
File file = null;
if (StringUtils.isBlank(tenant)) {
- file = new File(ApplicationUtils.getNacosHome(), BASE_DIR);
+ file = new File(EnvUtil.getNacosHome(), BASE_DIR);
} else {
- file = new File(ApplicationUtils.getNacosHome(), TENANT_BASE_DIR);
+ file = new File(EnvUtil.getNacosHome(), TENANT_BASE_DIR);
file = new File(file, tenant);
}
file = new File(file, group);
@@ -123,9 +123,9 @@ public class DiskUtil {
public static File targetBetaFile(String dataId, String group, String tenant) {
File file = null;
if (StringUtils.isBlank(tenant)) {
- file = new File(ApplicationUtils.getNacosHome(), BETA_DIR);
+ file = new File(EnvUtil.getNacosHome(), BETA_DIR);
} else {
- file = new File(ApplicationUtils.getNacosHome(), TENANT_BETA_DIR);
+ file = new File(EnvUtil.getNacosHome(), TENANT_BETA_DIR);
file = new File(file, tenant);
}
file = new File(file, group);
@@ -139,9 +139,9 @@ public class DiskUtil {
public static File targetTagFile(String dataId, String group, String tenant, String tag) {
File file = null;
if (StringUtils.isBlank(tenant)) {
- file = new File(ApplicationUtils.getNacosHome(), TAG_DIR);
+ file = new File(EnvUtil.getNacosHome(), TAG_DIR);
} else {
- file = new File(ApplicationUtils.getNacosHome(), TENANT_TAG_DIR);
+ file = new File(EnvUtil.getNacosHome(), TENANT_TAG_DIR);
file = new File(file, tenant);
}
file = new File(file, group);
@@ -169,7 +169,7 @@ public class DiskUtil {
}
public static File heartBeatFile() {
- return new File(ApplicationUtils.getNacosHome(), "status" + File.separator + "heartBeat.txt");
+ return new File(EnvUtil.getNacosHome(), "status" + File.separator + "heartBeat.txt");
}
public static String relativePath(String dataId, String group) {
@@ -180,13 +180,13 @@ public class DiskUtil {
* Clear all config file.
*/
public static void clearAll() {
- File file = new File(ApplicationUtils.getNacosHome(), BASE_DIR);
+ File file = new File(EnvUtil.getNacosHome(), BASE_DIR);
if (FileUtils.deleteQuietly(file)) {
LogUtil.DEFAULT_LOG.info("clear all config-info success.");
} else {
LogUtil.DEFAULT_LOG.warn("clear all config-info failed.");
}
- File fileTenant = new File(ApplicationUtils.getNacosHome(), TENANT_BASE_DIR);
+ File fileTenant = new File(EnvUtil.getNacosHome(), TENANT_BASE_DIR);
if (FileUtils.deleteQuietly(fileTenant)) {
LogUtil.DEFAULT_LOG.info("clear all config-info-tenant success.");
} else {
@@ -198,13 +198,13 @@ public class DiskUtil {
* Clear all beta config file.
*/
public static void clearAllBeta() {
- File file = new File(ApplicationUtils.getNacosHome(), BETA_DIR);
+ File file = new File(EnvUtil.getNacosHome(), BETA_DIR);
if (FileUtils.deleteQuietly(file)) {
LogUtil.DEFAULT_LOG.info("clear all config-info-beta success.");
} else {
LogUtil.DEFAULT_LOG.warn("clear all config-info-beta failed.");
}
- File fileTenant = new File(ApplicationUtils.getNacosHome(), TENANT_BETA_DIR);
+ File fileTenant = new File(EnvUtil.getNacosHome(), TENANT_BETA_DIR);
if (FileUtils.deleteQuietly(fileTenant)) {
LogUtil.DEFAULT_LOG.info("clear all config-info-beta-tenant success.");
} else {
@@ -216,13 +216,13 @@ public class DiskUtil {
* Clear all tag config file.
*/
public static void clearAllTag() {
- File file = new File(ApplicationUtils.getNacosHome(), TAG_DIR);
+ File file = new File(EnvUtil.getNacosHome(), TAG_DIR);
if (FileUtils.deleteQuietly(file)) {
LogUtil.DEFAULT_LOG.info("clear all config-info-tag success.");
} else {
LogUtil.DEFAULT_LOG.warn("clear all config-info-tag failed.");
}
- File fileTenant = new File(ApplicationUtils.getNacosHome(), TENANT_TAG_DIR);
+ File fileTenant = new File(EnvUtil.getNacosHome(), TENANT_TAG_DIR);
if (FileUtils.deleteQuietly(fileTenant)) {
LogUtil.DEFAULT_LOG.info("clear all config-info-tag-tenant success.");
} else {
diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java
index 99197597b..46f7277ef 100644
--- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java
+++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java
@@ -16,7 +16,7 @@
package com.alibaba.nacos.config.server.utils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
@@ -101,7 +101,7 @@ public class PropertyUtil implements ApplicationContextInitializerpushContent.
@@ -242,7 +242,7 @@ public class PropertyUtil implements ApplicationContextInitializer
{namespaceAdd}
diff --git a/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java b/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java
index d889d1ad3..c2a83b48e 100644
--- a/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java
+++ b/console/src/main/java/com/alibaba/nacos/console/controller/ServerStateController.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.console.controller;
import com.alibaba.nacos.common.utils.VersionUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -43,10 +43,10 @@ public class ServerStateController {
@GetMapping("/state")
public ResponseEntity serverState() {
Map serverState = new HashMap<>(3);
- serverState.put("standalone_mode", ApplicationUtils.getStandaloneMode() ? ApplicationUtils.STANDALONE_MODE_ALONE
- : ApplicationUtils.STANDALONE_MODE_CLUSTER);
+ serverState.put("standalone_mode",
+ EnvUtil.getStandaloneMode() ? EnvUtil.STANDALONE_MODE_ALONE : EnvUtil.STANDALONE_MODE_CLUSTER);
- serverState.put("function_mode", ApplicationUtils.getFunctionMode());
+ serverState.put("function_mode", EnvUtil.getFunctionMode());
serverState.put("version", VersionUtils.version);
return ResponseEntity.ok().body(serverState);
diff --git a/console/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java b/console/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java
index a55a27027..f68eb9b45 100644
--- a/console/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java
+++ b/console/src/main/java/com/alibaba/nacos/console/utils/PasswordEncoderUtil.java
@@ -25,10 +25,6 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
*/
public class PasswordEncoderUtil {
- public static void main(String[] args) {
- System.out.println(new BCryptPasswordEncoder().encode("nacos"));
- }
-
public static Boolean matches(String raw, String encoded) {
return new BCryptPasswordEncoder().matches(raw, encoded);
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java b/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java
index 535778bb3..d5822a46e 100644
--- a/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java
+++ b/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java
@@ -39,6 +39,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
/**
* Unified filter to handle authentication and authorization.
@@ -57,6 +59,8 @@ public class AuthFilter implements Filter {
@Autowired
private ControllerMethodsCache methodsCache;
+ private Map, ResourceParser> parserInstance = new ConcurrentHashMap<>();
+
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
@@ -96,7 +100,7 @@ public class AuthFilter implements Filter {
String resource = secured.resource();
if (StringUtils.isBlank(resource)) {
- ResourceParser parser = secured.parser().newInstance();
+ ResourceParser parser = getResourceParser(secured.parser());
resource = parser.parseName(req);
}
@@ -124,4 +128,14 @@ public class AuthFilter implements Filter {
return;
}
}
+
+ private ResourceParser getResourceParser(Class extends ResourceParser> parseClass)
+ throws IllegalAccessException, InstantiationException {
+ ResourceParser parser = parserInstance.get(parseClass);
+ if (parser == null) {
+ parser = parseClass.newInstance();
+ parserInstance.put(parseClass, parser);
+ }
+ return parser;
+ }
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java b/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java
index 3bea56abe..78f1c9e99 100644
--- a/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java
+++ b/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java
@@ -16,7 +16,7 @@
package com.alibaba.nacos.core.cluster;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
@@ -46,11 +46,11 @@ public class Member implements Comparable, Cloneable {
public Member() {
String prefix = "nacos.core.member.meta.";
extendInfo.put(MemberMetaDataConstants.SITE_KEY,
- ApplicationUtils.getProperty(prefix + MemberMetaDataConstants.SITE_KEY, "unknow"));
+ EnvUtil.getProperty(prefix + MemberMetaDataConstants.SITE_KEY, "unknow"));
extendInfo.put(MemberMetaDataConstants.AD_WEIGHT,
- ApplicationUtils.getProperty(prefix + MemberMetaDataConstants.AD_WEIGHT, "0"));
+ EnvUtil.getProperty(prefix + MemberMetaDataConstants.AD_WEIGHT, "0"));
extendInfo.put(MemberMetaDataConstants.WEIGHT,
- ApplicationUtils.getProperty(prefix + MemberMetaDataConstants.WEIGHT, "1"));
+ EnvUtil.getProperty(prefix + MemberMetaDataConstants.WEIGHT, "1"));
}
public static MemberBuilder builder() {
diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java
index cbc41dcf1..737765330 100644
--- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java
+++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java
@@ -20,7 +20,7 @@ import com.alibaba.nacos.common.remote.ConnectionType;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.core.utils.Loggers;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDateTime;
@@ -169,7 +169,7 @@ public class MemberUtils {
manager.getMemberAddressInfos().remove(member.getAddress());
cloneMember.setState(NodeState.SUSPICIOUS);
cloneMember.setFailAccessCnt(member.getFailAccessCnt() + 1);
- int maxFailAccessCnt = ApplicationUtils.getProperty("nacos.core.member.fail-access-cnt", Integer.class, 3);
+ int maxFailAccessCnt = EnvUtil.getProperty("nacos.core.member.fail-access-cnt", Integer.class, 3);
// If the number of consecutive failures to access the target node reaches
// a maximum, or the link request is rejected, the state is directly down
@@ -192,7 +192,7 @@ public class MemberUtils {
for (String member : simpleMembers(members)) {
builder.append(member).append(StringUtils.LF);
}
- ApplicationUtils.writeClusterConf(builder.toString());
+ EnvUtil.writeClusterConf(builder.toString());
} catch (Throwable ex) {
Loggers.CLUSTER.error("cluster member node persistence failed : {}", ExceptionUtil.getAllExceptionMsg(ex));
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java b/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java
index 4e4536b79..f0d05eff2 100644
--- a/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java
+++ b/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java
@@ -38,7 +38,7 @@ import com.alibaba.nacos.core.utils.GenericType;
import com.alibaba.nacos.core.utils.GlobalExecutor;
import com.alibaba.nacos.core.utils.Loggers;
import com.alibaba.nacos.sys.env.Constants;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.context.WebServerInitializedEvent;
@@ -124,7 +124,7 @@ public class ServerMemberManager implements ApplicationListener();
- ApplicationUtils.setContextPath(servletContext.getContextPath());
+ EnvUtil.setContextPath(servletContext.getContextPath());
MemberUtils.setManager(this);
init();
@@ -132,7 +132,7 @@ public class ServerMemberManager implements ApplicationListener tmpMembers = new ArrayList<>();
try {
- List tmp = ApplicationUtils.readClusterConf();
+ List tmp = EnvUtil.readClusterConf();
tmpMembers = MemberUtils.readServerConf(tmp);
} catch (Throwable e) {
Loggers.CLUSTER
diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java
index 68fd26938..437247cb9 100644
--- a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java
+++ b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java
@@ -20,7 +20,7 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.core.cluster.MemberLookup;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.core.utils.Loggers;
import java.io.File;
@@ -49,8 +49,8 @@ public final class LookupFactory {
* @throws NacosException NacosException
*/
public static MemberLookup createLookUp(ServerMemberManager memberManager) throws NacosException {
- if (!ApplicationUtils.getStandaloneMode()) {
- String lookupType = ApplicationUtils.getProperty(LOOKUP_MODE_TYPE);
+ if (!EnvUtil.getStandaloneMode()) {
+ String lookupType = EnvUtil.getProperty(LOOKUP_MODE_TYPE);
LookupType type = chooseLookup(lookupType);
LOOK_UP = find(type);
currentLookupType = type;
@@ -113,8 +113,8 @@ public final class LookupFactory {
return type;
}
}
- File file = new File(ApplicationUtils.getClusterConfFilePath());
- if (file.exists() || StringUtils.isNotBlank(ApplicationUtils.getMemberList())) {
+ File file = new File(EnvUtil.getClusterConfFilePath());
+ if (file.exists() || StringUtils.isNotBlank(EnvUtil.getMemberList())) {
return LookupType.FILE_CONFIG;
}
return LookupType.ADDRESS_SERVER;
diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java
index 47dabbc5d..b2643cfad 100644
--- a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java
+++ b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java
@@ -18,7 +18,7 @@ package com.alibaba.nacos.core.cluster.lookup;
import com.alibaba.nacos.core.cluster.AbstractMemberLookup;
import com.alibaba.nacos.core.cluster.MemberUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
import java.util.Collections;
@@ -33,7 +33,7 @@ public class StandaloneMemberLookup extends AbstractMemberLookup {
@Override
public void start() {
if (start.compareAndSet(false, true)) {
- String url = InetUtils.getSelfIP() + ":" + ApplicationUtils.getPort();
+ String url = InetUtils.getSelfIP() + ":" + EnvUtil.getPort();
afterLookup(MemberUtils.readServerConf(Collections.singletonList(url)));
}
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java b/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java
index d8ffdb5d4..e619a3fc7 100644
--- a/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java
+++ b/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java
@@ -21,7 +21,7 @@ import com.alibaba.nacos.core.auth.RequestMappingInfo;
import com.alibaba.nacos.core.auth.RequestMappingInfo.RequestMappingInfoComparator;
import com.alibaba.nacos.core.auth.condition.ParamRequestCondition;
import com.alibaba.nacos.core.auth.condition.PathRequestCondition;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.reflections.Reflections;
import org.slf4j.Logger;
@@ -69,7 +69,7 @@ public class ControllerMethodsCache {
return null;
}
String httpMethod = request.getMethod();
- String urlKey = httpMethod + REQUEST_PATH_SEPARATOR + path.replaceFirst(ApplicationUtils.getContextPath(), "");
+ String urlKey = httpMethod + REQUEST_PATH_SEPARATOR + path.replaceFirst(EnvUtil.getContextPath(), "");
List requestMappingInfos = urlLookup.get(urlKey);
if (CollectionUtils.isEmpty(requestMappingInfos)) {
return null;
diff --git a/core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java
new file mode 100644
index 000000000..43b1477b2
--- /dev/null
+++ b/core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java
@@ -0,0 +1,113 @@
+/*
+ * 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.core.code;
+
+import com.alibaba.nacos.core.listener.LoggingApplicationListener;
+import com.alibaba.nacos.core.listener.NacosApplicationListener;
+import com.alibaba.nacos.core.listener.StartingApplicationListener;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.context.event.EventPublishingRunListener;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.Ordered;
+import org.springframework.core.env.ConfigurableEnvironment;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * {@link org.springframework.boot.SpringApplicationRunListener} before {@link EventPublishingRunListener} execution.
+ *
+ * @author Mercy
+ * @since 0.2.2
+ */
+public class SpringApplicationRunListener implements org.springframework.boot.SpringApplicationRunListener, Ordered {
+
+ private final SpringApplication application;
+
+ private final String[] args;
+
+ private List nacosApplicationListeners = new ArrayList<>();
+
+ {
+ nacosApplicationListeners.add(new LoggingApplicationListener());
+ nacosApplicationListeners.add(new StartingApplicationListener());
+ }
+
+ public SpringApplicationRunListener(SpringApplication application, String[] args) {
+ this.application = application;
+ this.args = args;
+ }
+
+ @Override
+ public void starting() {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.starting();
+ }
+ }
+
+ @Override
+ public void environmentPrepared(ConfigurableEnvironment environment) {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.environmentPrepared(environment);
+ }
+ }
+
+ @Override
+ public void contextPrepared(ConfigurableApplicationContext context) {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.contextPrepared(context);
+ }
+ }
+
+ @Override
+ public void contextLoaded(ConfigurableApplicationContext context) {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.contextLoaded(context);
+ }
+ }
+
+ @Override
+ public void started(ConfigurableApplicationContext context) {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.started(context);
+ }
+ }
+
+ @Override
+ public void running(ConfigurableApplicationContext context) {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.running(context);
+ }
+ }
+
+ @Override
+ public void failed(ConfigurableApplicationContext context, Throwable exception) {
+ for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) {
+ nacosApplicationListener.failed(context, exception);
+ }
+ }
+
+ /**
+ * Before {@link EventPublishingRunListener}.
+ *
+ * @return HIGHEST_PRECEDENCE
+ */
+ @Override
+ public int getOrder() {
+ return HIGHEST_PRECEDENCE;
+ }
+}
diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java
index e741db0e4..43ab8f361 100644
--- a/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java
+++ b/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java
@@ -16,7 +16,7 @@
package com.alibaba.nacos.core.code;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
@@ -46,15 +46,14 @@ public class StandaloneProfileApplicationListener
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
- ApplicationUtils.injectEnvironment(environment);
-
+
if (environment.getProperty(STANDALONE_MODE_PROPERTY_NAME, boolean.class, false)) {
environment.addActiveProfile(STANDALONE_SPRING_PROFILE);
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Spring Environment's active profiles : {} in standalone mode : {}",
- Arrays.asList(environment.getActiveProfiles()), ApplicationUtils.getStandaloneMode());
+ Arrays.asList(environment.getActiveProfiles()), EnvUtil.getStandaloneMode());
}
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java b/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java
index 764677969..fecc83cb2 100644
--- a/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java
+++ b/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java
@@ -29,7 +29,7 @@ import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberUtils;
import com.alibaba.nacos.core.cluster.NodeState;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.core.utils.Commons;
import com.alibaba.nacos.core.utils.GenericType;
import com.alibaba.nacos.core.utils.Loggers;
@@ -160,7 +160,7 @@ public class NacosClusterController {
CountDownLatch latch = new CountDownLatch(notifyList.size());
for (Member member : notifyList) {
final String url = HttpUtils
- .buildUrl(false, member.getAddress(), ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT,
+ .buildUrl(false, member.getAddress(), EnvUtil.getContextPath(), Commons.NACOS_CORE_CONTEXT,
"/cluster/server/leave");
nacosAsyncRestTemplate.post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), new Callback() {
@Override
diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/distro/DistroProtocol.java b/core/src/main/java/com/alibaba/nacos/core/distributed/distro/DistroProtocol.java
index ab5254bda..4382d301f 100644
--- a/core/src/main/java/com/alibaba/nacos/core/distributed/distro/DistroProtocol.java
+++ b/core/src/main/java/com/alibaba/nacos/core/distributed/distro/DistroProtocol.java
@@ -32,7 +32,7 @@ import com.alibaba.nacos.core.distributed.distro.task.load.DistroLoadDataTask;
import com.alibaba.nacos.core.distributed.distro.task.verify.DistroVerifyTask;
import com.alibaba.nacos.core.utils.GlobalExecutor;
import com.alibaba.nacos.core.utils.Loggers;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.stereotype.Component;
/**
@@ -63,7 +63,7 @@ public class DistroProtocol {
}
private void startDistroTask() {
- if (ApplicationUtils.getStandaloneMode()) {
+ if (EnvUtil.getStandaloneMode()) {
isInitialized = true;
return;
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java b/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java
index 4765071c5..6bac4260e 100644
--- a/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java
+++ b/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.core.distributed.id;
import com.alibaba.nacos.consistency.IdGenerator;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
import com.google.common.base.Preconditions;
import org.slf4j.Logger;
@@ -80,7 +80,7 @@ public class SnowFlowerIdGenerator implements IdGenerator {
private long currentId;
{
- long workerId = ApplicationUtils.getProperty("nacos.core.snowflake.worker-id", Integer.class, -1);
+ long workerId = EnvUtil.getProperty("nacos.core.snowflake.worker-id", Integer.class, -1);
if (workerId != -1) {
this.workerId = workerId;
diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java
index 3cceabbb2..a23732940 100644
--- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java
+++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java
@@ -41,7 +41,7 @@ import com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor;
import com.alibaba.nacos.core.distributed.raft.utils.RaftOptionsBuilder;
import com.alibaba.nacos.core.monitor.MetricsMonitor;
import com.alibaba.nacos.core.utils.Loggers;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alipay.sofa.jraft.CliService;
import com.alipay.sofa.jraft.Node;
import com.alipay.sofa.jraft.RaftGroupService;
@@ -50,6 +50,7 @@ import com.alipay.sofa.jraft.RouteTable;
import com.alipay.sofa.jraft.Status;
import com.alipay.sofa.jraft.closure.ReadIndexClosure;
import com.alipay.sofa.jraft.conf.Configuration;
+import com.alipay.sofa.jraft.core.CliServiceImpl;
import com.alipay.sofa.jraft.entity.PeerId;
import com.alipay.sofa.jraft.entity.Task;
import com.alipay.sofa.jraft.error.RaftError;
@@ -190,9 +191,8 @@ public class JRaftServer {
CliOptions cliOptions = new CliOptions();
- this.cliClientService = new CliClientServiceImpl();
- this.cliClientService.init(cliOptions);
this.cliService = RaftServiceFactory.createAndInitCliService(cliOptions);
+ this.cliClientService = (CliClientServiceImpl) ((CliServiceImpl) this.cliService).getCliClientService();
}
synchronized void start() {
@@ -233,7 +233,7 @@ public class JRaftServer {
return;
}
- final String parentPath = Paths.get(ApplicationUtils.getNacosHome(), "data/protocol/raft").toString();
+ final String parentPath = Paths.get(EnvUtil.getNacosHome(), "data/protocol/raft").toString();
for (RequestProcessor4CP processor : processors) {
final String groupName = processor.group();
diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java
index 5ac21a049..2f03eceee 100644
--- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java
+++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java
@@ -154,7 +154,7 @@ public final class RaftSysConstants {
public static final String RAFT_CLI_SERVICE_THREAD_NUM = "cli_service_thread_num";
/**
- * raft linear read strategy, defaults to index
+ * raft linear read strategy, defaults to read_index read
*/
public static final String RAFT_READ_INDEX_TYPE = "read_index_type";
diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java
index b46494a4a..e6af6aaef 100644
--- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java
+++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java
@@ -108,7 +108,7 @@ public class RaftOptionsBuilder {
String readOnySafe = "ReadOnlySafe";
String readOnlyLeaseBased = "ReadOnlyLeaseBased";
- String val = config.getVal(RaftSysConstants.DEFAULT_READ_INDEX_TYPE);
+ String val = config.getVal(RaftSysConstants.RAFT_READ_INDEX_TYPE);
if (StringUtils.isBlank(val) || StringUtils.equals(readOnySafe, val)) {
return ReadOnlyOption.ReadOnlySafe;
@@ -117,8 +117,8 @@ public class RaftOptionsBuilder {
if (StringUtils.equals(readOnlyLeaseBased, val)) {
return ReadOnlyOption.ReadOnlyLeaseBased;
}
- throw new IllegalArgumentException(
- "Illegal Raft system parameters => " + RaftSysConstants.DEFAULT_READ_INDEX_TYPE + " : [" + val + "]");
+ throw new IllegalArgumentException("Illegal Raft system parameters => ReadOnlyOption" + " : [" + val
+ + "], should be 'ReadOnlySafe' or 'ReadOnlyLeaseBased'");
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/LoggingApplicationListener.java
similarity index 66%
rename from core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java
rename to core/src/main/java/com/alibaba/nacos/core/listener/LoggingApplicationListener.java
index 780d8e6fb..d0968b13b 100644
--- a/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java
+++ b/core/src/main/java/com/alibaba/nacos/core/listener/LoggingApplicationListener.java
@@ -14,49 +14,35 @@
* limitations under the License.
*/
-package com.alibaba.nacos.core.code;
+package com.alibaba.nacos.core.listener;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.SpringApplicationRunListener;
-import org.springframework.boot.context.event.EventPublishingRunListener;
import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY;
import static org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX;
/**
- * Logging {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution.
+ * For init logging configuration.
*
- * @author Mercy
- * @since 0.2.2
+ * @author horizonzy
+ * @since 1.4.1
*/
-public class LoggingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered {
+public class LoggingApplicationListener implements NacosApplicationListener {
private static final String DEFAULT_NACOS_LOGBACK_LOCATION = CLASSPATH_URL_PREFIX + "META-INF/logback/nacos.xml";
- private static final Logger LOGGER = LoggerFactory.getLogger(LoggingSpringApplicationRunListener.class);
-
- private final SpringApplication application;
-
- private final String[] args;
-
- public LoggingSpringApplicationRunListener(SpringApplication application, String[] args) {
- this.application = application;
- this.args = args;
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(LoggingApplicationListener.class);
@Override
public void starting() {
+
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
- ApplicationUtils.injectEnvironment(environment);
if (!environment.containsProperty(CONFIG_PROPERTY)) {
System.setProperty(CONFIG_PROPERTY, DEFAULT_NACOS_LOGBACK_LOCATION);
if (LOGGER.isInfoEnabled()) {
@@ -91,14 +77,4 @@ public class LoggingSpringApplicationRunListener implements SpringApplicationRun
public void failed(ConfigurableApplicationContext context, Throwable exception) {
}
-
- /**
- * Before {@link EventPublishingRunListener}.
- *
- * @return HIGHEST_PRECEDENCE
- */
- @Override
- public int getOrder() {
- return HIGHEST_PRECEDENCE;
- }
}
diff --git a/core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java
new file mode 100644
index 000000000..08f74f555
--- /dev/null
+++ b/core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java
@@ -0,0 +1,78 @@
+/*
+ * 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.core.listener;
+
+import com.alibaba.nacos.core.code.SpringApplicationRunListener;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.env.ConfigurableEnvironment;
+
+/**
+ * Nacos Application Listener, execute init process.
+ *
+ * @author horizonzy
+ * @since 1.4.1
+ */
+public interface NacosApplicationListener {
+
+ /**
+ * {@link SpringApplicationRunListener#starting}.
+ */
+ void starting();
+
+ /**
+ * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#environmentPrepared}.
+ *
+ * @param environment environment
+ */
+ void environmentPrepared(ConfigurableEnvironment environment);
+
+ /**
+ * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#contextLoaded}.
+ *
+ * @param context context
+ */
+ void contextPrepared(ConfigurableApplicationContext context);
+
+ /**
+ * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#contextLoaded}.
+ *
+ * @param context context
+ */
+ void contextLoaded(ConfigurableApplicationContext context);
+
+ /**
+ * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#started}.
+ *
+ * @param context context
+ */
+ void started(ConfigurableApplicationContext context);
+
+ /**
+ * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#running}.
+ *
+ * @param context context
+ */
+ void running(ConfigurableApplicationContext context);
+
+ /**
+ * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#failed}.
+ *
+ * @param context context
+ * @param exception exception
+ */
+ void failed(ConfigurableApplicationContext context, Throwable exception);
+}
diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java
similarity index 75%
rename from core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java
rename to core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java
index 8455388a1..850b51fbf 100644
--- a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java
+++ b/core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.alibaba.nacos.core.code;
+package com.alibaba.nacos.core.listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
@@ -24,17 +24,12 @@ import com.alibaba.nacos.common.executor.ThreadPoolManager;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.file.WatchFileCenter;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.SpringApplicationRunListener;
-import org.springframework.boot.context.event.EventPublishingRunListener;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import java.io.File;
@@ -45,14 +40,14 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
- * Logging starting message {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution.
+ * init environment config.
*
* @author hxy1991
* @since 0.5.0
*/
-public class StartingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered {
+public class StartingApplicationListener implements NacosApplicationListener {
- private static final Logger LOGGER = LoggerFactory.getLogger(StartingSpringApplicationRunListener.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(StartingApplicationListener.class);
private static final String MODE_PROPERTY_KEY_STAND_MODE = "nacos.mode";
@@ -60,14 +55,12 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu
private static final String LOCAL_IP_PROPERTY_KEY = "nacos.local.ip";
+ private static final String FIRST_PRE_PROPERTIES = "first_pre";
+
private ScheduledExecutorService scheduledExecutorService;
private volatile boolean starting;
- public StartingSpringApplicationRunListener(SpringApplication application, String[] args) {
-
- }
-
@Override
public void starting() {
starting = true;
@@ -75,33 +68,17 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
- ApplicationUtils.injectEnvironment(environment);
- EnvUtil.setEnvironment(environment);
- try {
- environment.getPropertySources().addLast(new OriginTrackedMapPropertySource("first_pre",
- EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource())));
- } catch (IOException e) {
- throw new NacosRuntimeException(NacosException.SERVER_ERROR, e);
- }
- if (ApplicationUtils.getStandaloneMode()) {
- System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone");
- } else {
- System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster");
- }
- if (ApplicationUtils.getFunctionMode() == null) {
- System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, "All");
- } else if (ApplicationUtils.FUNCTION_MODE_CONFIG.equals(ApplicationUtils.getFunctionMode())) {
- System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, ApplicationUtils.FUNCTION_MODE_CONFIG);
- } else if (ApplicationUtils.FUNCTION_MODE_NAMING.equals(ApplicationUtils.getFunctionMode())) {
- System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, ApplicationUtils.FUNCTION_MODE_NAMING);
- }
+ injectEnvironment(environment);
- System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIP());
+ loadPreProperties(environment);
+
+ initSystemProperty();
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
logClusterConf();
+
logStarting();
}
@@ -113,37 +90,17 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu
@Override
public void started(ConfigurableApplicationContext context) {
starting = false;
- ConfigurableEnvironment env = context.getEnvironment();
closeExecutor();
logFilePath();
-
- // External data sources are used by default in cluster mode
- boolean useExternalStorage = ("mysql".equalsIgnoreCase(env.getProperty("spring.datasource.platform", "")));
-
- // must initialize after setUseExternalDB
- // This value is true in stand-alone mode and false in cluster mode
- // If this value is set to true in cluster mode, nacos's distributed storage engine is turned on
- // default value is depend on ${nacos.standalone}
-
- if (!useExternalStorage) {
- boolean embeddedStorage = ApplicationUtils.getStandaloneMode() || Boolean.getBoolean("embeddedStorage");
- // If the embedded data source storage is not turned on, it is automatically
- // upgraded to the external data source storage, as before
- if (!embeddedStorage) {
- useExternalStorage = true;
- }
- }
-
ApplicationUtils.setStarted(true);
- LOGGER.info("Nacos started successfully in {} mode. use {} storage",
- System.getProperty(MODE_PROPERTY_KEY_STAND_MODE), useExternalStorage ? "external" : "embedded");
+ judgeStorageMode(context.getEnvironment());
}
@Override
public void running(ConfigurableApplicationContext context) {
- EnvUtil.getEnvironment().getPropertySources().remove("first_pre");
+ removePreProperties(context.getEnvironment());
}
@Override
@@ -162,38 +119,50 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu
context.close();
LOGGER.error("Nacos failed to start, please see {} for more details.",
- Paths.get(ApplicationUtils.getNacosHome(), "logs/nacos.log"));
+ Paths.get(EnvUtil.getNacosHome(), "logs/nacos.log"));
}
- /**
- * Before {@link EventPublishingRunListener}.
- *
- * @return HIGHEST_PRECEDENCE
- */
- @Override
- public int getOrder() {
- return HIGHEST_PRECEDENCE;
+ private void injectEnvironment(ConfigurableEnvironment environment) {
+ EnvUtil.setEnvironment(environment);
}
- private void logClusterConf() {
- if (!ApplicationUtils.getStandaloneMode()) {
- try {
- List clusterConf = ApplicationUtils.readClusterConf();
- LOGGER.info("The server IP list of Nacos is {}", clusterConf);
- } catch (IOException e) {
- LOGGER.error("read cluster conf fail", e);
- }
+ private void loadPreProperties(ConfigurableEnvironment environment) {
+ try {
+ environment.getPropertySources().addLast(new OriginTrackedMapPropertySource(FIRST_PRE_PROPERTIES,
+ EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource())));
+ } catch (IOException e) {
+ throw new NacosRuntimeException(NacosException.SERVER_ERROR, e);
}
}
- private void logFilePath() {
- String[] dirNames = new String[] {"logs", "conf", "data"};
- for (String dirName : dirNames) {
- LOGGER.info("Nacos Log files: {}", Paths.get(ApplicationUtils.getNacosHome(), dirName).toString());
+ private void initSystemProperty() {
+ if (EnvUtil.getStandaloneMode()) {
+ System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone");
+ } else {
+ System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster");
+ }
+ if (EnvUtil.getFunctionMode() == null) {
+ System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, "All");
+ } else if (EnvUtil.FUNCTION_MODE_CONFIG.equals(EnvUtil.getFunctionMode())) {
+ System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_CONFIG);
+ } else if (EnvUtil.FUNCTION_MODE_NAMING.equals(EnvUtil.getFunctionMode())) {
+ System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_NAMING);
+ }
+
+ System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIP());
+ }
+
+ private void removePreProperties(ConfigurableEnvironment environment) {
+ environment.getPropertySources().remove(FIRST_PRE_PROPERTIES);
+ }
+
+ private void logClusterConf() {
+ if (!EnvUtil.getStandaloneMode()) {
try {
- DiskUtils.forceMkdir(new File(Paths.get(ApplicationUtils.getNacosHome(), dirName).toUri()));
- } catch (Exception e) {
- throw new RuntimeException(e);
+ List clusterConf = EnvUtil.readClusterConf();
+ LOGGER.info("The server IP list of Nacos is {}", clusterConf);
+ } catch (IOException e) {
+ LOGGER.error("read cluster conf fail", e);
}
}
}
@@ -204,8 +173,20 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu
}
}
+ private void logFilePath() {
+ String[] dirNames = new String[] {"logs", "conf", "data"};
+ for (String dirName : dirNames) {
+ LOGGER.info("Nacos Log files: {}", Paths.get(EnvUtil.getNacosHome(), dirName).toString());
+ try {
+ DiskUtils.forceMkdir(new File(Paths.get(EnvUtil.getNacosHome(), dirName).toUri()));
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
private void logStarting() {
- if (!ApplicationUtils.getStandaloneMode()) {
+ if (!EnvUtil.getStandaloneMode()) {
scheduledExecutorService = ExecutorFactory
.newSingleScheduledExecutorService(new NameThreadFactory("com.alibaba.nacos.core.nacos-starting"));
@@ -217,4 +198,27 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu
}, 1, 1, TimeUnit.SECONDS);
}
}
-}
\ No newline at end of file
+
+ private void judgeStorageMode(ConfigurableEnvironment env) {
+
+ // External data sources are used by default in cluster mode
+ boolean useExternalStorage = ("mysql".equalsIgnoreCase(env.getProperty("spring.datasource.platform", "")));
+
+ // must initialize after setUseExternalDB
+ // This value is true in stand-alone mode and false in cluster mode
+ // If this value is set to true in cluster mode, nacos's distributed storage engine is turned on
+ // default value is depend on ${nacos.standalone}
+
+ if (!useExternalStorage) {
+ boolean embeddedStorage = EnvUtil.getStandaloneMode() || Boolean.getBoolean("embeddedStorage");
+ // If the embedded data source storage is not turned on, it is automatically
+ // upgraded to the external data source storage, as before
+ if (!embeddedStorage) {
+ useExternalStorage = true;
+ }
+ }
+
+ LOGGER.info("Nacos started successfully in {} mode. use {} storage",
+ System.getProperty(MODE_PROPERTY_KEY_STAND_MODE), useExternalStorage ? "external" : "embedded");
+ }
+}
diff --git a/core/src/main/resources/META-INF/logback/nacos.xml b/core/src/main/resources/META-INF/logback/nacos.xml
index 39cffac76..12a782b3f 100644
--- a/core/src/main/resources/META-INF/logback/nacos.xml
+++ b/core/src/main/resources/META-INF/logback/nacos.xml
@@ -263,7 +263,7 @@
-
+
diff --git a/core/src/main/resources/META-INF/spring.factories b/core/src/main/resources/META-INF/spring.factories
index c63c723f2..af6926509 100644
--- a/core/src/main/resources/META-INF/spring.factories
+++ b/core/src/main/resources/META-INF/spring.factories
@@ -3,5 +3,4 @@ org.springframework.context.ApplicationListener=\
com.alibaba.nacos.core.code.StandaloneProfileApplicationListener
# SpringApplicationRunListener
org.springframework.boot.SpringApplicationRunListener=\
-com.alibaba.nacos.core.code.LoggingSpringApplicationRunListener,\
-com.alibaba.nacos.core.code.StartingSpringApplicationRunListener
\ No newline at end of file
+com.alibaba.nacos.core.code.SpringApplicationRunListener
diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilsTest.java
index 490d7153f..8b7aa70b1 100644
--- a/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilsTest.java
+++ b/core/src/test/java/com/alibaba/nacos/core/cluster/MemberUtilsTest.java
@@ -16,7 +16,7 @@
package com.alibaba.nacos.core.cluster;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -41,7 +41,7 @@ public class MemberUtilsTest {
@Before
public void setUp() {
- ApplicationUtils.injectEnvironment(environment);
+ EnvUtil.setEnvironment(environment);
originalMember = buildMember();
}
diff --git a/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java b/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java
index 9d395b8f4..82fc9b835 100644
--- a/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java
+++ b/core/src/test/java/com/alibaba/nacos/core/cluster/ServerMemberManagerTest.java
@@ -19,7 +19,7 @@ package com.alibaba.nacos.core.cluster;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.notify.EventPublisher;
import com.alibaba.nacos.common.notify.NotifyCenter;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -59,7 +59,7 @@ public class ServerMemberManagerTest {
public void setUp() throws Exception {
when(environment.getProperty("server.port", Integer.class, 8848)).thenReturn(8848);
when(environment.getProperty("nacos.member-change-event.queue.size", Integer.class, 128)).thenReturn(128);
- ApplicationUtils.injectEnvironment(environment);
+ EnvUtil.setEnvironment(environment);
when(servletContext.getContextPath()).thenReturn("");
serverMemberManager = new ServerMemberManager(servletContext);
serverMemberManager.updateMember(Member.builder().ip("1.1.1.1").port(8848).state(NodeState.UP).build());
diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java
index af28e0594..a12f85a11 100644
--- a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java
+++ b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/JRaftServerTest.java
@@ -20,7 +20,7 @@ import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.model.RestResultUtils;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.distributed.ProtocolManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -41,7 +41,7 @@ public class JRaftServerTest {
@BeforeClass
public static void beforeClass() {
- ApplicationUtils.injectEnvironment(new MockEnvironment());
+ EnvUtil.setEnvironment(new MockEnvironment());
}
@Before
@@ -111,4 +111,4 @@ public class JRaftServerTest {
Assert.assertFalse(changed.get());
changed.set(false);
}
-}
\ No newline at end of file
+}
diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java
index 5f6843d7a..96aeb5519 100644
--- a/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java
+++ b/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java
@@ -16,6 +16,7 @@
package com.alibaba.nacos.core.utils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
@@ -82,7 +83,7 @@ public class SystemUtilsTest {
@Test
public void testReadClusterConf() throws IOException {
- FileUtils.forceMkdir(new File(ApplicationUtils.getConfFilePath()));
+ FileUtils.forceMkdir(new File(EnvUtil.getConfPath()));
String lineSeparator = System.getProperty("line.separator");
@@ -91,9 +92,8 @@ public class SystemUtilsTest {
* #example
* 192.168.1.1:8848
*/
- ApplicationUtils
- .writeClusterConf("#it is ip" + lineSeparator + "#example" + lineSeparator + "192.168.1.1:8848");
- Assert.assertEquals(ApplicationUtils.readClusterConf().get(0), "192.168.1.1:8848");
+ EnvUtil.writeClusterConf("#it is ip" + lineSeparator + "#example" + lineSeparator + "192.168.1.1:8848");
+ Assert.assertEquals(EnvUtil.readClusterConf().get(0), "192.168.1.1:8848");
/*
* #it is ip
@@ -101,10 +101,10 @@ public class SystemUtilsTest {
* # 192.168.1.1:8848
* 192.168.1.2:8848 # Instance A
*/
- ApplicationUtils.writeClusterConf(
+ EnvUtil.writeClusterConf(
"#it is ip" + lineSeparator + " #example" + lineSeparator + " # 192.168.1.1:8848" + lineSeparator
+ " 192.168.1.2:8848 # Instance A " + lineSeparator + "192.168.1.3#:8848");
- List instanceList = ApplicationUtils.readClusterConf();
+ List instanceList = EnvUtil.readClusterConf();
Assert.assertEquals(instanceList.get(0), "192.168.1.2:8848");
Assert.assertEquals(instanceList.get(1), "192.168.1.3");
}
diff --git a/distribution/conf/nacos-logback.xml b/distribution/conf/nacos-logback.xml
index 95d60dd4f..fce5abb17 100644
--- a/distribution/conf/nacos-logback.xml
+++ b/distribution/conf/nacos-logback.xml
@@ -681,7 +681,7 @@
-
+
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerListManager.java b/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerListManager.java
index 89815ef32..d99ec2d74 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerListManager.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerListManager.java
@@ -25,7 +25,7 @@ import com.alibaba.nacos.core.cluster.MemberChangeListener;
import com.alibaba.nacos.core.cluster.MemberMetaDataConstants;
import com.alibaba.nacos.core.cluster.NodeState;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer;
import com.alibaba.nacos.naming.misc.GlobalExecutor;
import com.alibaba.nacos.naming.misc.Loggers;
@@ -154,7 +154,7 @@ public class ServerListManager extends MemberChangeListener {
this.cursor = (this.cursor + 1) % members.size();
Member target = members.get(cursor);
- if (Objects.equals(target.getAddress(), ApplicationUtils.getLocalAddress())) {
+ if (Objects.equals(target.getAddress(), EnvUtil.getLocalAddress())) {
return;
}
@@ -192,7 +192,7 @@ public class ServerListManager extends MemberChangeListener {
public void run() {
try {
- if (ApplicationUtils.getPort() <= 0) {
+ if (EnvUtil.getPort() <= 0) {
return;
}
@@ -202,21 +202,21 @@ public class ServerListManager extends MemberChangeListener {
}
long curTime = System.currentTimeMillis();
- String status = LOCALHOST_SITE + "#" + ApplicationUtils.getLocalAddress() + "#" + curTime + "#" + weight
+ String status = LOCALHOST_SITE + "#" + EnvUtil.getLocalAddress() + "#" + curTime + "#" + weight
+ "\r\n";
List allServers = getServers();
- if (!contains(ApplicationUtils.getLocalAddress())) {
+ if (!contains(EnvUtil.getLocalAddress())) {
Loggers.SRV_LOG.error("local ip is not in serverlist, ip: {}, serverlist: {}",
- ApplicationUtils.getLocalAddress(), allServers);
+ EnvUtil.getLocalAddress(), allServers);
return;
}
- if (allServers.size() > 0 && !ApplicationUtils.getLocalAddress()
+ if (allServers.size() > 0 && !EnvUtil.getLocalAddress()
.contains(IPUtil.localHostIP())) {
for (Member server : allServers) {
- if (Objects.equals(server.getAddress(), ApplicationUtils.getLocalAddress())) {
+ if (Objects.equals(server.getAddress(), EnvUtil.getLocalAddress())) {
continue;
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgement.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgement.java
index 6788fd38f..1ea1c70ce 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgement.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgement.java
@@ -22,6 +22,7 @@ import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberMetaDataConstants;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.naming.misc.GlobalExecutor;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.stereotype.Component;
import java.util.Collection;
@@ -64,6 +65,11 @@ public class ClusterVersionJudgement {
}
protected void runVersionListener() {
+ // Single machine mode, do upgrade operation directly.
+ if (EnvUtil.getStandaloneMode()) {
+ notifyAllListener();
+ return;
+ }
try {
judge();
} finally {
@@ -72,6 +78,7 @@ public class ClusterVersionJudgement {
}
protected void judge() {
+
Collection members = memberManager.allMembers();
final String oldVersion = "1.4.0";
boolean allMemberIsNewVersion = true;
@@ -83,15 +90,19 @@ public class ClusterVersionJudgement {
}
// can only trigger once
if (allMemberIsNewVersion && !this.allMemberIsNewVersion) {
- this.allMemberIsNewVersion = true;
- Collections.sort(observers);
- for (ConsumerWithPriority consumer : observers) {
- consumer.consumer.accept(true);
- }
- observers.clear();
+ notifyAllListener();
}
}
+ private void notifyAllListener() {
+ this.allMemberIsNewVersion = true;
+ Collections.sort(observers);
+ for (ConsumerWithPriority consumer : observers) {
+ consumer.consumer.accept(true);
+ }
+ observers.clear();
+ }
+
public boolean allMemberIsNewVersion() {
return allMemberIsNewVersion;
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java
index a22d22d26..34e07d8fd 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/PersistentConsistencyServiceDelegateImpl.java
@@ -17,11 +17,15 @@
package com.alibaba.nacos.naming.consistency.persistent;
import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.core.distributed.ProtocolManager;
import com.alibaba.nacos.naming.consistency.Datum;
import com.alibaba.nacos.naming.consistency.RecordListener;
+import com.alibaba.nacos.naming.consistency.persistent.impl.BasePersistentServiceProcessor;
import com.alibaba.nacos.naming.consistency.persistent.impl.PersistentServiceProcessor;
+import com.alibaba.nacos.naming.consistency.persistent.impl.StandalonePersistentServiceProcessor;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftConsistencyServiceImpl;
import com.alibaba.nacos.naming.pojo.Record;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.stereotype.Component;
/**
@@ -36,16 +40,16 @@ public class PersistentConsistencyServiceDelegateImpl implements PersistentConsi
private final RaftConsistencyServiceImpl oldPersistentConsistencyService;
- private final PersistentServiceProcessor newPersistentConsistencyService;
+ private final BasePersistentServiceProcessor newPersistentConsistencyService;
private volatile boolean switchNewPersistentService = false;
public PersistentConsistencyServiceDelegateImpl(ClusterVersionJudgement versionJudgement,
- RaftConsistencyServiceImpl oldPersistentConsistencyService,
- PersistentServiceProcessor newPersistentConsistencyService) {
+ RaftConsistencyServiceImpl oldPersistentConsistencyService, ProtocolManager protocolManager)
+ throws Exception {
this.versionJudgement = versionJudgement;
this.oldPersistentConsistencyService = oldPersistentConsistencyService;
- this.newPersistentConsistencyService = newPersistentConsistencyService;
+ this.newPersistentConsistencyService = createNewPersistentServiceProcessor(protocolManager, versionJudgement);
init();
}
@@ -88,4 +92,13 @@ public class PersistentConsistencyServiceDelegateImpl implements PersistentConsi
private PersistentConsistencyService switchOne() {
return switchNewPersistentService ? newPersistentConsistencyService : oldPersistentConsistencyService;
}
+
+ private BasePersistentServiceProcessor createNewPersistentServiceProcessor(ProtocolManager protocolManager,
+ ClusterVersionJudgement versionJudgement) throws Exception {
+ final BasePersistentServiceProcessor processor =
+ EnvUtil.getStandaloneMode() ? new StandalonePersistentServiceProcessor(versionJudgement)
+ : new PersistentServiceProcessor(protocolManager, versionJudgement);
+ processor.afterConstruct();
+ return processor;
+ }
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/BasePersistentServiceProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/BasePersistentServiceProcessor.java
new file mode 100644
index 000000000..5896c3142
--- /dev/null
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/BasePersistentServiceProcessor.java
@@ -0,0 +1,264 @@
+/*
+ * 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.consistency.persistent.impl;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
+import com.alibaba.nacos.common.notify.NotifyCenter;
+import com.alibaba.nacos.common.utils.ByteUtils;
+import com.alibaba.nacos.consistency.DataOperation;
+import com.alibaba.nacos.consistency.SerializeFactory;
+import com.alibaba.nacos.consistency.Serializer;
+import com.alibaba.nacos.consistency.cp.RequestProcessor4CP;
+import com.alibaba.nacos.consistency.entity.ReadRequest;
+import com.alibaba.nacos.consistency.entity.Response;
+import com.alibaba.nacos.consistency.entity.WriteRequest;
+import com.alibaba.nacos.consistency.snapshot.SnapshotOperation;
+import com.alibaba.nacos.core.exception.KvStorageException;
+import com.alibaba.nacos.core.storage.kv.KvStorage;
+import com.alibaba.nacos.naming.consistency.Datum;
+import com.alibaba.nacos.naming.consistency.KeyBuilder;
+import com.alibaba.nacos.naming.consistency.RecordListener;
+import com.alibaba.nacos.naming.consistency.ValueChangeEvent;
+import com.alibaba.nacos.naming.consistency.persistent.ClusterVersionJudgement;
+import com.alibaba.nacos.naming.consistency.persistent.PersistentConsistencyService;
+import com.alibaba.nacos.naming.consistency.persistent.PersistentNotifier;
+import com.alibaba.nacos.naming.misc.Loggers;
+import com.alibaba.nacos.naming.misc.UtilsAndCommons;
+import com.alibaba.nacos.naming.pojo.Record;
+import com.alibaba.nacos.naming.utils.Constants;
+import com.google.protobuf.ByteString;
+import org.apache.commons.lang3.reflect.TypeUtils;
+
+import java.lang.reflect.Type;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * New service data persistence handler.
+ *
+ * @author liaochuntao
+ */
+public abstract class BasePersistentServiceProcessor extends RequestProcessor4CP
+ implements PersistentConsistencyService {
+
+ enum Op {
+ /**
+ * write ops.
+ */
+ Write("Write"),
+
+ /**
+ * read ops.
+ */
+ Read("Read"),
+
+ /**
+ * delete ops.
+ */
+ Delete("Delete");
+
+ protected final String desc;
+
+ Op(String desc) {
+ this.desc = desc;
+ }
+ }
+
+ protected final KvStorage kvStorage;
+
+ protected final Serializer serializer;
+
+ /**
+ * Whether an unrecoverable error occurred.
+ */
+ protected volatile boolean hasError = false;
+
+ /**
+ * If use old raft, should not notify listener even new listener add.
+ */
+ protected volatile boolean startNotify = false;
+
+ /**
+ * During snapshot processing, the processing of other requests needs to be paused.
+ */
+ protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+
+ protected final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
+
+ protected final ClusterVersionJudgement versionJudgement;
+
+ protected final PersistentNotifier notifier;
+
+ public BasePersistentServiceProcessor(final ClusterVersionJudgement judgement) throws Exception {
+ this.versionJudgement = judgement;
+ this.kvStorage = new NamingKvStorage(Paths.get(UtilsAndCommons.DATA_BASE_DIR, "data").toString());
+ this.serializer = SerializeFactory.getSerializer("JSON");
+ this.notifier = new PersistentNotifier(key -> {
+ try {
+ byte[] data = kvStorage.get(ByteUtils.toBytes(key));
+ Datum datum = serializer.deserialize(data, getDatumTypeFromKey(key));
+ return null != datum ? datum.value : null;
+ } catch (KvStorageException ex) {
+ throw new NacosRuntimeException(ex.getErrCode(), ex.getErrMsg());
+ }
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ public void afterConstruct() {
+ NotifyCenter.registerToPublisher(ValueChangeEvent.class, 16384);
+ listenOldRaftClose();
+ }
+
+ private void listenOldRaftClose() {
+ this.versionJudgement.registerObserver(isNewVersion -> {
+ if (isNewVersion) {
+ NotifyCenter.registerSubscriber(notifier);
+ startNotify = true;
+ }
+ }, 10);
+ }
+
+ @Override
+ public Response onRequest(ReadRequest request) {
+ final List keys = serializer
+ .deserialize(request.getData().toByteArray(), TypeUtils.parameterize(List.class, byte[].class));
+ final Lock lock = readLock;
+ lock.lock();
+ try {
+ final Map result = kvStorage.batchGet(keys);
+ final BatchReadResponse response = new BatchReadResponse();
+ result.forEach(response::append);
+ return Response.newBuilder().setSuccess(true).setData(ByteString.copyFrom(serializer.serialize(response)))
+ .build();
+ } catch (KvStorageException e) {
+ return Response.newBuilder().setSuccess(false).setErrMsg(e.getErrMsg()).build();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public Response onApply(WriteRequest request) {
+ final byte[] data = request.getData().toByteArray();
+ final BatchWriteRequest bwRequest = serializer.deserialize(data, BatchWriteRequest.class);
+ final Op op = Op.valueOf(request.getOperation());
+ final Lock lock = readLock;
+ lock.lock();
+ try {
+ switch (op) {
+ case Write:
+ kvStorage.batchPut(bwRequest.getKeys(), bwRequest.getValues());
+ break;
+ case Delete:
+ kvStorage.batchDelete(bwRequest.getKeys());
+ break;
+ default:
+ return Response.newBuilder().setSuccess(false).setErrMsg("unsupport operation : " + op).build();
+ }
+ publishValueChangeEvent(op, bwRequest);
+ return Response.newBuilder().setSuccess(true).build();
+ } catch (KvStorageException e) {
+ return Response.newBuilder().setSuccess(false).setErrMsg(e.getErrMsg()).build();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void publishValueChangeEvent(final Op op, final BatchWriteRequest request) {
+ final List keys = request.getKeys();
+ final List values = request.getValues();
+ for (int i = 0; i < keys.size(); i++) {
+ final String key = new String(keys.get(i));
+ final Datum datum = serializer.deserialize(values.get(i), getDatumTypeFromKey(key));
+ final Record value = null != datum ? datum.value : null;
+ final ValueChangeEvent event = ValueChangeEvent.builder().key(key).value(value)
+ .action(Op.Delete.equals(op) ? DataOperation.DELETE : DataOperation.CHANGE).build();
+ NotifyCenter.publishEvent(event);
+ }
+ }
+
+ @Override
+ public String group() {
+ return Constants.NAMING_PERSISTENT_SERVICE_GROUP;
+ }
+
+ @Override
+ public List loadSnapshotOperate() {
+ return Collections.singletonList(new NamingSnapshotOperation(this.kvStorage, lock));
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ super.onError(error);
+ hasError = true;
+ }
+
+ protected Type getDatumTypeFromKey(String key) {
+ return TypeUtils.parameterize(Datum.class, getClassOfRecordFromKey(key));
+ }
+
+ protected Class extends Record> getClassOfRecordFromKey(String key) {
+ if (KeyBuilder.matchSwitchKey(key)) {
+ return com.alibaba.nacos.naming.misc.SwitchDomain.class;
+ } else if (KeyBuilder.matchServiceMetaKey(key)) {
+ return com.alibaba.nacos.naming.core.Service.class;
+ } else if (KeyBuilder.matchInstanceListKey(key)) {
+ return com.alibaba.nacos.naming.core.Instances.class;
+ }
+ return Record.class;
+ }
+
+ protected void notifierDatumIfAbsent(String key, RecordListener listener) throws NacosException {
+ if (KeyBuilder.SERVICE_META_KEY_PREFIX.equals(key)) {
+ notifierAllServiceMeta(listener);
+ } else {
+ Datum datum = get(key);
+ if (null != datum) {
+ notifierDatum(key, datum, listener);
+ }
+ }
+ }
+
+ /**
+ * This notify should only notify once during startup. See {@link com.alibaba.nacos.naming.core.ServiceManager#init()}
+ */
+ private void notifierAllServiceMeta(RecordListener listener) throws NacosException {
+ for (byte[] each : kvStorage.allKeys()) {
+ String key = new String(each);
+ if (listener.interests(key)) {
+ Datum datum = get(key);
+ if (null != datum) {
+ notifierDatum(key, datum, listener);
+ }
+ }
+ }
+ }
+
+ private void notifierDatum(String key, Datum datum, RecordListener listener) {
+ try {
+ listener.onChange(key, datum.value);
+ } catch (Exception e) {
+ Loggers.RAFT.error("NACOS-RAFT failed to notify listener", e);
+ }
+ }
+}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java
index e90211c6e..4b2cc3fa6 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/PersistentServiceProcessor.java
@@ -1,167 +1,79 @@
/*
- * Copyright 1999-2018 Alibaba Group Holding Ltd.
+ * 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
+ * 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
+ * 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.
+ * 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.consistency.persistent.impl;
import com.alibaba.nacos.api.exception.NacosException;
-import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.ByteUtils;
import com.alibaba.nacos.common.utils.StringUtils;
-import com.alibaba.nacos.consistency.DataOperation;
-import com.alibaba.nacos.consistency.SerializeFactory;
-import com.alibaba.nacos.consistency.Serializer;
import com.alibaba.nacos.consistency.cp.CPProtocol;
-import com.alibaba.nacos.consistency.cp.RequestProcessor4CP;
import com.alibaba.nacos.consistency.cp.MetadataKey;
import com.alibaba.nacos.consistency.entity.ReadRequest;
import com.alibaba.nacos.consistency.entity.Response;
import com.alibaba.nacos.consistency.entity.WriteRequest;
-import com.alibaba.nacos.consistency.snapshot.SnapshotOperation;
import com.alibaba.nacos.core.distributed.ProtocolManager;
import com.alibaba.nacos.core.exception.ErrorCode;
-import com.alibaba.nacos.core.exception.KvStorageException;
-import com.alibaba.nacos.core.storage.kv.KvStorage;
import com.alibaba.nacos.naming.consistency.Datum;
-import com.alibaba.nacos.naming.consistency.KeyBuilder;
import com.alibaba.nacos.naming.consistency.RecordListener;
-import com.alibaba.nacos.naming.consistency.ValueChangeEvent;
import com.alibaba.nacos.naming.consistency.persistent.ClusterVersionJudgement;
-import com.alibaba.nacos.naming.consistency.persistent.PersistentConsistencyService;
-import com.alibaba.nacos.naming.consistency.persistent.PersistentNotifier;
import com.alibaba.nacos.naming.misc.Loggers;
-import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.pojo.Record;
import com.alibaba.nacos.naming.utils.Constants;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.google.protobuf.ByteString;
-import org.apache.commons.lang3.reflect.TypeUtils;
-import org.springframework.stereotype.Service;
-import java.lang.reflect.Type;
-import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
- * New service data persistence handler.
+ * In cluster mode, start the Raft protocol.
*
* @author liaochuntao
*/
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
-@Service
-public class PersistentServiceProcessor extends RequestProcessor4CP implements PersistentConsistencyService {
-
- enum Op {
- /**
- * write ops.
- */
- Write("Write"),
-
- /**
- * read ops.
- */
- Read("Read"),
-
- /**
- * delete ops.
- */
- Delete("Delete");
-
- private final String desc;
-
- Op(String desc) {
- this.desc = desc;
- }
- }
+public class PersistentServiceProcessor extends BasePersistentServiceProcessor {
private final CPProtocol protocol;
- private final KvStorage kvStorage;
-
- private final ClusterVersionJudgement versionJudgement;
-
- private final Serializer serializer;
-
- /**
- * During snapshot processing, the processing of other requests needs to be paused.
- */
- private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
-
- private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
-
- private final PersistentNotifier notifier;
-
/**
* Is there a leader node currently.
*/
private volatile boolean hasLeader = false;
- /**
- * Whether an unrecoverable error occurred.
- */
- private volatile boolean hasError = false;
-
- /**
- * If use old raft, should not notify listener even new listener add.
- */
- private volatile boolean startNotify = false;
-
- public PersistentServiceProcessor(final ProtocolManager protocolManager,
- final ClusterVersionJudgement versionJudgement) throws Exception {
+ public PersistentServiceProcessor(ProtocolManager protocolManager, ClusterVersionJudgement versionJudgement)
+ throws Exception {
+ super(versionJudgement);
this.protocol = protocolManager.getCpProtocol();
- this.versionJudgement = versionJudgement;
- this.kvStorage = new NamingKvStorage(Paths.get(UtilsAndCommons.DATA_BASE_DIR, "data").toString());
- this.serializer = SerializeFactory.getSerializer("JSON");
- this.notifier = new PersistentNotifier(key -> {
- try {
- byte[] data = kvStorage.get(ByteUtils.toBytes(key));
- Datum datum = serializer.deserialize(data, getDatumTypeFromKey(key));
- return null != datum ? datum.value : null;
- } catch (KvStorageException ex) {
- throw new NacosRuntimeException(ex.getErrCode(), ex.getErrMsg());
- }
- });
- init();
}
- @SuppressWarnings("unchecked")
- private void init() {
- NotifyCenter.registerToPublisher(ValueChangeEvent.class, 16384);
+ @Override
+ public void afterConstruct() {
+ super.afterConstruct();
this.protocol.addLogProcessors(Collections.singletonList(this));
this.protocol.protocolMetaData()
.subscribe(Constants.NAMING_PERSISTENT_SERVICE_GROUP, MetadataKey.LEADER_META_DATA,
(o, arg) -> hasLeader = StringUtils.isNotBlank(String.valueOf(arg)));
// If you choose to use the new RAFT protocol directly, there will be no compatible logical execution
- if (ApplicationUtils.getProperty(Constants.NACOS_NAMING_USE_NEW_RAFT_FIRST, Boolean.class, false)) {
+ if (EnvUtil.getProperty(Constants.NACOS_NAMING_USE_NEW_RAFT_FIRST, Boolean.class, false)) {
NotifyCenter.registerSubscriber(notifier);
waitLeader();
startNotify = true;
- } else {
- this.versionJudgement.registerObserver(isNewVersion -> {
- if (isNewVersion) {
- NotifyCenter.registerSubscriber(notifier);
- startNotify = true;
- }
- }, 10);
}
}
@@ -175,75 +87,6 @@ public class PersistentServiceProcessor extends RequestProcessor4CP implements P
}
}
- @Override
- public Response onRequest(ReadRequest request) {
- final List keys = serializer
- .deserialize(request.getData().toByteArray(), TypeUtils.parameterize(List.class, byte[].class));
- final Lock lock = readLock;
- lock.lock();
- try {
- final Map result = kvStorage.batchGet(keys);
- final BatchReadResponse response = new BatchReadResponse();
- result.forEach(response::append);
- return Response.newBuilder().setSuccess(true).setData(ByteString.copyFrom(serializer.serialize(response)))
- .build();
- } catch (KvStorageException e) {
- return Response.newBuilder().setSuccess(false).setErrMsg(e.getErrMsg()).build();
- } finally {
- lock.unlock();
- }
- }
-
- @Override
- public Response onApply(WriteRequest request) {
- final byte[] data = request.getData().toByteArray();
- final BatchWriteRequest bwRequest = serializer.deserialize(data, BatchWriteRequest.class);
- final Op op = Op.valueOf(request.getOperation());
- final Lock lock = readLock;
- lock.lock();
- try {
- switch (op) {
- case Write:
- kvStorage.batchPut(bwRequest.getKeys(), bwRequest.getValues());
- break;
- case Delete:
- kvStorage.batchDelete(bwRequest.getKeys());
- break;
- default:
- return Response.newBuilder().setSuccess(false).setErrMsg("unsupport operation : " + op).build();
- }
- publishValueChangeEvent(op, bwRequest);
- return Response.newBuilder().setSuccess(true).build();
- } catch (KvStorageException e) {
- return Response.newBuilder().setSuccess(false).setErrMsg(e.getErrMsg()).build();
- } finally {
- lock.unlock();
- }
- }
-
- private void publishValueChangeEvent(final Op op, final BatchWriteRequest request) {
- final List keys = request.getKeys();
- final List values = request.getValues();
- for (int i = 0; i < keys.size(); i++) {
- final String key = new String(keys.get(i));
- final Datum datum = serializer.deserialize(values.get(i), getDatumTypeFromKey(key));
- final Record value = null != datum ? datum.value : null;
- final ValueChangeEvent event = ValueChangeEvent.builder().key(key).value(value)
- .action(Op.Delete.equals(op) ? DataOperation.DELETE : DataOperation.CHANGE).build();
- NotifyCenter.publishEvent(event);
- }
- }
-
- @Override
- public String group() {
- return Constants.NAMING_PERSISTENT_SERVICE_GROUP;
- }
-
- @Override
- public List loadSnapshotOperate() {
- return Collections.singletonList(new NamingSnapshotOperation(this.kvStorage, lock));
- }
-
@Override
public void put(String key, Record value) throws NacosException {
final BatchWriteRequest req = new BatchWriteRequest();
@@ -304,63 +147,8 @@ public class PersistentServiceProcessor extends RequestProcessor4CP implements P
notifier.deregisterListener(key, listener);
}
- @Override
- public void onError(Throwable error) {
- super.onError(error);
- hasError = true;
- }
-
@Override
public boolean isAvailable() {
return hasLeader && !hasError;
}
-
- private Type getDatumTypeFromKey(String key) {
- return TypeUtils.parameterize(Datum.class, getClassOfRecordFromKey(key));
- }
-
- private Class extends Record> getClassOfRecordFromKey(String key) {
- if (KeyBuilder.matchSwitchKey(key)) {
- return com.alibaba.nacos.naming.misc.SwitchDomain.class;
- } else if (KeyBuilder.matchServiceMetaKey(key)) {
- return com.alibaba.nacos.naming.core.Service.class;
- } else if (KeyBuilder.matchInstanceListKey(key)) {
- return com.alibaba.nacos.naming.core.Instances.class;
- }
- return Record.class;
- }
-
- private void notifierDatumIfAbsent(String key, RecordListener listener) throws NacosException {
- if (KeyBuilder.SERVICE_META_KEY_PREFIX.equals(key)) {
- notifierAllServiceMeta(listener);
- } else {
- Datum datum = get(key);
- if (null != datum) {
- notifierDatum(key, datum, listener);
- }
- }
- }
-
- /**
- * This notify should only notify once during startup. See {@link com.alibaba.nacos.naming.core.ServiceManager#init()}
- */
- private void notifierAllServiceMeta(RecordListener listener) throws NacosException {
- for (byte[] each : kvStorage.allKeys()) {
- String key = new String(each);
- if (listener.interests(key)) {
- Datum datum = get(key);
- if (null != datum) {
- notifierDatum(key, datum, listener);
- }
- }
- }
- }
-
- private void notifierDatum(String key, Datum datum, RecordListener listener) {
- try {
- listener.onChange(key, datum.value);
- } catch (Exception e) {
- Loggers.RAFT.error("NACOS-RAFT failed to notify listener", e);
- }
- }
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/StandalonePersistentServiceProcessor.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/StandalonePersistentServiceProcessor.java
new file mode 100644
index 000000000..aa50a966c
--- /dev/null
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/impl/StandalonePersistentServiceProcessor.java
@@ -0,0 +1,110 @@
+/*
+ * 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.consistency.persistent.impl;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.common.utils.ByteUtils;
+import com.alibaba.nacos.consistency.entity.ReadRequest;
+import com.alibaba.nacos.consistency.entity.Response;
+import com.alibaba.nacos.consistency.entity.WriteRequest;
+import com.alibaba.nacos.core.exception.ErrorCode;
+import com.alibaba.nacos.naming.consistency.Datum;
+import com.alibaba.nacos.naming.consistency.RecordListener;
+import com.alibaba.nacos.naming.consistency.persistent.ClusterVersionJudgement;
+import com.alibaba.nacos.naming.pojo.Record;
+import com.alibaba.nacos.naming.utils.Constants;
+import com.google.protobuf.ByteString;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Persistent service manipulation layer in stand-alone mode.
+ *
+ * @author liaochuntao
+ */
+@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
+public class StandalonePersistentServiceProcessor extends BasePersistentServiceProcessor {
+
+ public StandalonePersistentServiceProcessor(final ClusterVersionJudgement judgement) throws Exception {
+ super(judgement);
+ }
+
+ @Override
+ public void put(String key, Record value) throws NacosException {
+ final BatchWriteRequest req = new BatchWriteRequest();
+ Datum datum = Datum.createDatum(key, value);
+ req.append(ByteUtils.toBytes(key), serializer.serialize(datum));
+ final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req)))
+ .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP).setOperation(Op.Write.desc).build();
+ try {
+ onApply(request);
+ } catch (Exception e) {
+ throw new NacosException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage());
+ }
+ }
+
+ @Override
+ public void remove(String key) throws NacosException {
+ final BatchWriteRequest req = new BatchWriteRequest();
+ req.append(ByteUtils.toBytes(key), ByteUtils.EMPTY);
+ final WriteRequest request = WriteRequest.newBuilder().setData(ByteString.copyFrom(serializer.serialize(req)))
+ .setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP).setOperation(Op.Delete.desc).build();
+ try {
+ onApply(request);
+ } catch (Exception e) {
+ throw new NacosException(ErrorCode.ProtoSubmitError.getCode(), e.getMessage());
+ }
+ }
+
+ @Override
+ public Datum get(String key) throws NacosException {
+ final List keys = Collections.singletonList(ByteUtils.toBytes(key));
+ final ReadRequest req = ReadRequest.newBuilder().setGroup(Constants.NAMING_PERSISTENT_SERVICE_GROUP)
+ .setData(ByteString.copyFrom(serializer.serialize(keys))).build();
+ try {
+ final Response resp = onRequest(req);
+ if (resp.getSuccess()) {
+ BatchReadResponse response = serializer
+ .deserialize(resp.getData().toByteArray(), BatchReadResponse.class);
+ final List rValues = response.getValues();
+ return rValues.isEmpty() ? null : serializer.deserialize(rValues.get(0), getDatumTypeFromKey(key));
+ }
+ throw new NacosException(ErrorCode.ProtoReadError.getCode(), resp.getErrMsg());
+ } catch (Throwable e) {
+ throw new NacosException(ErrorCode.ProtoReadError.getCode(), e.getMessage());
+ }
+ }
+
+ @Override
+ public void listen(String key, RecordListener listener) throws NacosException {
+ notifier.registerListener(key, listener);
+ if (startNotify) {
+ notifierDatumIfAbsent(key, listener);
+ }
+ }
+
+ @Override
+ public void unListen(String key, RecordListener listener) throws NacosException {
+ notifier.deregisterListener(key, listener);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return !hasError;
+ }
+}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java
index e90dd9c32..da7277b84 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftConsistencyServiceImpl.java
@@ -28,7 +28,7 @@ import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.pojo.Record;
import com.alibaba.nacos.naming.utils.Constants;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
@@ -73,7 +73,7 @@ public class RaftConsistencyServiceImpl implements PersistentConsistencyService
@PostConstruct
protected void init() throws Exception {
- if (ApplicationUtils.getProperty(Constants.NACOS_NAMING_USE_NEW_RAFT_FIRST, Boolean.class, false)) {
+ if (EnvUtil.getProperty(Constants.NACOS_NAMING_USE_NEW_RAFT_FIRST, Boolean.class, false)) {
this.raftCore.shutdown();
}
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java
index 9ff1eaba3..aeafeeb21 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java
@@ -44,7 +44,7 @@ import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
import com.alibaba.nacos.naming.pojo.Record;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -127,6 +127,8 @@ public class RaftCore implements Closeable {
private final EventPublisher publisher;
+ private final RaftListener raftListener;
+
private boolean initialized = false;
private volatile boolean stopWork = false;
@@ -136,7 +138,7 @@ public class RaftCore implements Closeable {
private ScheduledFuture heartbeatTask = null;
public RaftCore(RaftPeerSet peers, SwitchDomain switchDomain, GlobalConfig globalConfig, RaftProxy raftProxy,
- RaftStore raftStore, ClusterVersionJudgement versionJudgement) {
+ RaftStore raftStore, ClusterVersionJudgement versionJudgement, RaftListener raftListener) {
this.peers = peers;
this.switchDomain = switchDomain;
this.globalConfig = globalConfig;
@@ -145,6 +147,7 @@ public class RaftCore implements Closeable {
this.versionJudgement = versionJudgement;
this.notifier = new PersistentNotifier(key -> null == getDatum(key) ? null : getDatum(key).value);
this.publisher = NotifyCenter.registerToPublisher(ValueChangeEvent.class, 16384);
+ this.raftListener = raftListener;
}
/**
@@ -175,6 +178,7 @@ public class RaftCore implements Closeable {
if (stopWork) {
try {
shutdown();
+ raftListener.removeOldRaftMetadata();
} catch (NacosException e) {
throw new NacosRuntimeException(NacosException.SERVER_ERROR, e);
}
@@ -610,7 +614,7 @@ public class RaftCore implements Closeable {
private void sendBeat() throws IOException, InterruptedException {
RaftPeer local = peers.local();
- if (ApplicationUtils.getStandaloneMode() || local.state != RaftPeer.State.LEADER) {
+ if (EnvUtil.getStandaloneMode() || local.state != RaftPeer.State.LEADER) {
return;
}
if (Loggers.RAFT.isDebugEnabled()) {
@@ -1005,9 +1009,9 @@ public class RaftCore implements Closeable {
*/
public static String buildUrl(String ip, String api) {
if (!IPUtil.containsPort(ip)) {
- ip = ip + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ ip = ip + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
- return "http://" + ip + ApplicationUtils.getContextPath() + api;
+ return "http://" + ip + EnvUtil.getContextPath() + api;
}
public Datum> getDatum(String key) {
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftListener.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftListener.java
index fa3a0d37d..11d545147 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftListener.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftListener.java
@@ -21,12 +21,15 @@ import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.naming.consistency.persistent.ClusterVersionJudgement;
import com.alibaba.nacos.naming.misc.Loggers;
+import com.alibaba.nacos.naming.utils.Constants;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Inject the raft information from the naming module into the outlier information of the node.
@@ -38,14 +41,21 @@ import java.util.Map;
@Component
public class RaftListener implements SmartApplicationListener {
- private static final String GROUP = "naming";
-
private final ServerMemberManager memberManager;
private final ClusterVersionJudgement versionJudgement;
private volatile boolean stopUpdate = false;
+ /**
+ * Avoid multithreading mode. Old Raft information data cannot be properly removed.
+ */
+ private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+
+ private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
+
+ private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
+
public RaftListener(ServerMemberManager memberManager, ClusterVersionJudgement versionJudgement) {
this.memberManager = memberManager;
this.versionJudgement = versionJudgement;
@@ -54,12 +64,15 @@ public class RaftListener implements SmartApplicationListener {
private void init() {
this.versionJudgement.registerObserver(isAllNewVersion -> {
- stopUpdate = isAllNewVersion;
- if (stopUpdate) {
- Loggers.RAFT.warn("start to move old raft protocol metadata");
- Member self = memberManager.getSelf();
- self.delExtendVal(GROUP);
- memberManager.update(self);
+ final Lock lock = this.writeLock;
+ lock.lock();
+ try {
+ stopUpdate = isAllNewVersion;
+ if (stopUpdate) {
+ removeOldRaftMetadata();
+ }
+ } finally {
+ lock.unlock();
}
}, -2);
}
@@ -71,14 +84,30 @@ public class RaftListener implements SmartApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
- if (event instanceof BaseRaftEvent && !stopUpdate) {
- BaseRaftEvent raftEvent = (BaseRaftEvent) event;
- RaftPeer local = raftEvent.getLocal();
- String json = JacksonUtils.toJson(local);
- Map map = JacksonUtils.toObj(json, HashMap.class);
- Member self = memberManager.getSelf();
- self.setExtendVal(GROUP, map);
- memberManager.update(self);
+ final Lock lock = readLock;
+ lock.lock();
+ try {
+ if (event instanceof BaseRaftEvent && !stopUpdate) {
+ BaseRaftEvent raftEvent = (BaseRaftEvent) event;
+ RaftPeer local = raftEvent.getLocal();
+ String json = JacksonUtils.toJson(local);
+ Map map = JacksonUtils.toObj(json, HashMap.class);
+ Member self = memberManager.getSelf();
+ self.setExtendVal(Constants.OLD_NAMING_RAFT_GROUP, map);
+ memberManager.update(self);
+ }
+ if (stopUpdate) {
+ removeOldRaftMetadata();
+ }
+ } finally {
+ lock.unlock();
}
}
+
+ void removeOldRaftMetadata() {
+ Loggers.RAFT.warn("start to move old raft protocol metadata");
+ Member self = memberManager.getSelf();
+ self.delExtendVal(Constants.OLD_NAMING_RAFT_GROUP);
+ memberManager.update(self);
+ }
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSet.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSet.java
index 3b344c77f..9a6ba1711 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSet.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSet.java
@@ -29,6 +29,7 @@ import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.naming.misc.HttpClient;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.NetUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.commons.collections.SortedBag;
import org.apache.commons.collections.bag.TreeBag;
@@ -93,7 +94,7 @@ public class RaftPeerSet extends MemberChangeListener implements Closeable {
}
public RaftPeer getLeader() {
- if (ApplicationUtils.getStandaloneMode()) {
+ if (EnvUtil.getStandaloneMode()) {
return local();
}
return leader;
@@ -136,7 +137,7 @@ public class RaftPeerSet extends MemberChangeListener implements Closeable {
* @return true if is leader or stand alone, otherwise false
*/
public boolean isLeader(String ip) {
- if (ApplicationUtils.getStandaloneMode()) {
+ if (EnvUtil.getStandaloneMode()) {
return true;
}
@@ -271,8 +272,8 @@ public class RaftPeerSet extends MemberChangeListener implements Closeable {
* @return local raft peer
*/
public RaftPeer local() {
- RaftPeer peer = peers.get(ApplicationUtils.getLocalAddress());
- if (peer == null && ApplicationUtils.getStandaloneMode()) {
+ RaftPeer peer = peers.get(EnvUtil.getLocalAddress());
+ if (peer == null && EnvUtil.getStandaloneMode()) {
RaftPeer localPeer = new RaftPeer();
localPeer.ip = NetUtils.localServer();
localPeer.term.set(localTerm.get());
@@ -350,7 +351,7 @@ public class RaftPeerSet extends MemberChangeListener implements Closeable {
raftPeer.ip = address;
// first time meet the local server:
- if (ApplicationUtils.getLocalAddress().equals(address)) {
+ if (EnvUtil.getLocalAddress().equals(address)) {
raftPeer.term.set(localTerm.get());
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftProxy.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftProxy.java
index 2cd6d87e5..2e54b7036 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftProxy.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftProxy.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.naming.consistency.persistent.raft;
import com.alibaba.nacos.common.utils.IPUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.naming.misc.HttpClient;
import org.springframework.http.HttpMethod;
@@ -46,9 +46,9 @@ public class RaftProxy {
public void proxyGet(String server, String api, Map params) throws Exception {
// do proxy
if (!IPUtil.containsPort(server)) {
- server = server + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ server = server + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
- String url = "http://" + server + ApplicationUtils.getContextPath() + api;
+ String url = "http://" + server + EnvUtil.getContextPath() + api;
RestResult result = HttpClient.httpGet(url, null, params);
if (!result.ok()) {
@@ -68,9 +68,9 @@ public class RaftProxy {
public void proxy(String server, String api, Map params, HttpMethod method) throws Exception {
// do proxy
if (!IPUtil.containsPort(server)) {
- server = server + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ server = server + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
- String url = "http://" + server + ApplicationUtils.getContextPath() + api;
+ String url = "http://" + server + EnvUtil.getContextPath() + api;
RestResult result;
switch (method) {
case GET:
@@ -104,9 +104,9 @@ public class RaftProxy {
throws Exception {
// do proxy
if (!IPUtil.containsPort(server)) {
- server = server + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ server = server + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
- String url = "http://" + server + ApplicationUtils.getContextPath() + api;
+ String url = "http://" + server + EnvUtil.getContextPath() + api;
RestResult result = HttpClient.httpPostLarge(url, headers, content);
if (!result.ok()) {
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java
index 8b0e39fac..59d487217 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/HealthController.java
@@ -22,7 +22,7 @@ import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.auth.common.ActionTypes;
import com.alibaba.nacos.common.utils.JacksonUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.core.utils.WebUtils;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
@@ -75,7 +75,7 @@ public class HealthController {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
result.put("msg",
"Hello! I am Nacos-Naming and healthy! total services: raft " + serviceManager.getServiceCount()
- + ", local port:" + ApplicationUtils.getPort());
+ + ", local port:" + EnvUtil.getPort());
return result;
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java b/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java
index fe73cb751..82d2d6921 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/controllers/OperatorController.java
@@ -35,7 +35,7 @@ import com.alibaba.nacos.naming.misc.SwitchEntry;
import com.alibaba.nacos.naming.misc.SwitchManager;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.push.PushService;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -191,9 +191,9 @@ public class OperatorController {
result.put("raftNotifyTaskCount", raftCore.getNotifyTaskCount());
result.put("responsibleServiceCount", responsibleDomCount);
result.put("responsibleInstanceCount", responsibleIpCount);
- result.put("cpu", ApplicationUtils.getCPU());
- result.put("load", ApplicationUtils.getLoad());
- result.put("mem", ApplicationUtils.getMem());
+ result.put("cpu", EnvUtil.getCPU());
+ result.put("load", EnvUtil.getLoad());
+ result.put("mem", EnvUtil.getMem());
return result;
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java b/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java
index 4dc79e6b4..db663680a 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/core/DistroMapper.java
@@ -22,7 +22,7 @@ import com.alibaba.nacos.core.cluster.MemberUtils;
import com.alibaba.nacos.core.cluster.MembersChangeEvent;
import com.alibaba.nacos.core.cluster.NodeState;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import org.apache.commons.collections.CollectionUtils;
@@ -83,7 +83,7 @@ public class DistroMapper extends MemberChangeListener {
public boolean responsible(String responsibleTag) {
final List servers = healthyList;
- if (!switchDomain.isDistroEnabled() || ApplicationUtils.getStandaloneMode()) {
+ if (!switchDomain.isDistroEnabled() || EnvUtil.getStandaloneMode()) {
return true;
}
@@ -92,8 +92,8 @@ public class DistroMapper extends MemberChangeListener {
return false;
}
- int index = servers.indexOf(ApplicationUtils.getLocalAddress());
- int lastIndex = servers.lastIndexOf(ApplicationUtils.getLocalAddress());
+ int index = servers.indexOf(EnvUtil.getLocalAddress());
+ int lastIndex = servers.lastIndexOf(EnvUtil.getLocalAddress());
if (lastIndex < 0 || index < 0) {
return true;
}
@@ -112,16 +112,16 @@ public class DistroMapper extends MemberChangeListener {
final List servers = healthyList;
if (CollectionUtils.isEmpty(servers) || !switchDomain.isDistroEnabled()) {
- return ApplicationUtils.getLocalAddress();
+ return EnvUtil.getLocalAddress();
}
try {
int index = distroHash(responsibleTag) % servers.size();
return servers.get(index);
} catch (Throwable e) {
- Loggers.SRV_LOG.warn("[NACOS-DISTRO] distro mapper failed, return localhost: " + ApplicationUtils
+ Loggers.SRV_LOG.warn("[NACOS-DISTRO] distro mapper failed, return localhost: " + EnvUtil
.getLocalAddress(), e);
- return ApplicationUtils.getLocalAddress();
+ return EnvUtil.getLocalAddress();
}
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/SubscribeManager.java b/naming/src/main/java/com/alibaba/nacos/naming/core/SubscribeManager.java
index 8079d1fa9..3db2994cd 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/core/SubscribeManager.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/core/SubscribeManager.java
@@ -21,7 +21,7 @@ import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.naming.misc.HttpClient;
import com.alibaba.nacos.naming.misc.NetUtils;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
@@ -106,7 +106,7 @@ public class SubscribeManager {
}
RestResult result = HttpClient.httpGet(
- "http://" + server.getAddress() + ApplicationUtils.getContextPath()
+ "http://" + server.getAddress() + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + SUBSCRIBER_ON_SYNC_URL, new ArrayList<>(),
paramValues);
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java
index 44638f39f..caf8feaed 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java
@@ -20,6 +20,8 @@ import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
+import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.naming.consistency.KeyBuilder;
import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.Instance;
@@ -136,7 +138,7 @@ public class ClientBeatCheckTask implements BeatCheckTask {
.appendParam("ephemeral", "true").appendParam("clusterName", instance.getClusterName())
.appendParam("serviceName", service.getName()).appendParam("namespaceId", service.getNamespaceId());
- String url = "http://" + IPUtil.localHostIP() + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort() + ApplicationUtils.getContextPath()
+ String url = "http://" + IPUtil.localHostIP() + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort() + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance?" + request.toUrl();
// delete instance asynchronously:
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/GlobalExecutor.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/GlobalExecutor.java
index 64fa8dfd9..ea628e4d7 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/GlobalExecutor.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/GlobalExecutor.java
@@ -143,8 +143,8 @@ public class GlobalExecutor {
NAMING_TIMER_EXECUTOR.scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
}
- public static void submitClusterVersionJudge(Runnable runnable, long delay) {
- NAMING_TIMER_EXECUTOR.schedule(runnable, delay, TimeUnit.MILLISECONDS);
+ public static ScheduledFuture submitClusterVersionJudge(Runnable runnable, long delay) {
+ return NAMING_TIMER_EXECUTOR.schedule(runnable, delay, TimeUnit.MILLISECONDS);
}
public static void submitDistroNotifyTask(Runnable runnable) {
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java
index 7d7a740f5..09db2f2f7 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/HttpClient.java
@@ -27,7 +27,7 @@ import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.VersionUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
@@ -101,7 +101,7 @@ public class HttpClient {
header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
header.addParam(HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version);
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, UtilsAndCommons.SERVER_VERSION);
- header.addParam(HttpHeaderConsts.REQUEST_SOURCE_HEADER, ApplicationUtils.getLocalAddress());
+ header.addParam(HttpHeaderConsts.REQUEST_SOURCE_HEADER, EnvUtil.getLocalAddress());
header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, encoding);
HttpClientConfig httpClientConfig = HttpClientConfig.builder().setConTimeOutMillis(connectTimeout)
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java
index 7db6f9c1c..98c459765 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/NamingProxy.java
@@ -22,7 +22,7 @@ import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
@@ -73,14 +73,14 @@ public class NamingProxy {
headers.put(HttpHeaderConsts.CONNECTION, "Keep-Alive");
HttpClient.asyncHttpPutLarge(
- "http://" + server + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + server + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ TIMESTAMP_SYNC_URL + "?source=" + NetUtils.localServer(), headers, checksums,
new Callback() {
@Override
public void onReceive(RestResult result) {
if (!result.ok()) {
Loggers.DISTRO.error("failed to req API: {}, code: {}, msg: {}",
- "http://" + server + ApplicationUtils.getContextPath()
+ "http://" + server + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + TIMESTAMP_SYNC_URL,
result.getCode(), result.getMessage());
}
@@ -89,7 +89,7 @@ public class NamingProxy {
@Override
public void onError(Throwable throwable) {
Loggers.DISTRO
- .error("failed to req API:" + "http://" + server + ApplicationUtils.getContextPath()
+ .error("failed to req API:" + "http://" + server + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + TIMESTAMP_SYNC_URL, throwable);
}
@@ -116,14 +116,14 @@ public class NamingProxy {
Map params = new HashMap<>(8);
params.put("keys", StringUtils.join(keys, ","));
RestResult result = HttpClient.httpGetLarge(
- "http://" + server + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + server + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ DATA_GET_URL, new HashMap<>(8), JacksonUtils.toJson(params));
if (result.ok()) {
return result.getData().getBytes();
}
- throw new IOException("failed to req API: " + "http://" + server + ApplicationUtils.getContextPath()
+ throw new IOException("failed to req API: " + "http://" + server + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + DATA_GET_URL + ". code: " + result.getCode() + " msg: "
+ result.getMessage());
}
@@ -139,14 +139,14 @@ public class NamingProxy {
Map params = new HashMap<>(8);
RestResult result = HttpClient.httpGet(
- "http://" + server + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + server + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ ALL_DATA_GET_URL, new ArrayList<>(), params);
if (result.ok()) {
return result.getData().getBytes();
}
- throw new IOException("failed to req API: " + "http://" + server + ApplicationUtils.getContextPath()
+ throw new IOException("failed to req API: " + "http://" + server + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + ALL_DATA_GET_URL + ". code: " + result.getCode() + " msg: "
+ result.getMessage());
}
@@ -169,7 +169,7 @@ public class NamingProxy {
try {
RestResult result = HttpClient.httpPutLarge(
- "http://" + curServer + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + curServer + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ DATA_ON_SYNC_URL, headers, data);
if (result.ok()) {
return true;
@@ -177,7 +177,7 @@ public class NamingProxy {
if (HttpURLConnection.HTTP_NOT_MODIFIED == result.getCode()) {
return true;
}
- throw new IOException("failed to req API:" + "http://" + curServer + ApplicationUtils.getContextPath()
+ throw new IOException("failed to req API:" + "http://" + curServer + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + DATA_ON_SYNC_URL + ". code:" + result.getCode() + " msg: "
+ result.getData());
} catch (Exception e) {
@@ -204,7 +204,7 @@ public class NamingProxy {
RestResult result;
if (!IPUtil.containsPort(curServer)) {
- curServer = curServer + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ curServer = curServer + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
result = HttpClient.httpGet("http://" + curServer + api, headers, params);
@@ -246,16 +246,16 @@ public class NamingProxy {
RestResult result;
if (!IPUtil.containsPort(curServer)) {
- curServer = curServer + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ curServer = curServer + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
if (isPost) {
result = HttpClient.httpPost(
- "http://" + curServer + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + curServer + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "/api/" + api, headers, params);
} else {
result = HttpClient.httpGet(
- "http://" + curServer + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + curServer + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "/api/" + api, headers, params);
}
@@ -267,7 +267,7 @@ public class NamingProxy {
return StringUtils.EMPTY;
}
- throw new IOException("failed to req API:" + "http://" + curServer + ApplicationUtils.getContextPath()
+ throw new IOException("failed to req API:" + "http://" + curServer + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/" + api + ". code:" + result.getCode() + " msg: "
+ result.getMessage());
} catch (Exception e) {
@@ -296,16 +296,16 @@ public class NamingProxy {
RestResult result;
if (!IPUtil.containsPort(curServer)) {
- curServer = curServer + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ curServer = curServer + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
if (isPost) {
result = HttpClient.httpPost(
- "http://" + curServer + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + curServer + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ path, headers, params);
} else {
result = HttpClient.httpGet(
- "http://" + curServer + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "http://" + curServer + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ path, headers, params);
}
@@ -317,7 +317,7 @@ public class NamingProxy {
return StringUtils.EMPTY;
}
- throw new IOException("failed to req API:" + "http://" + curServer + ApplicationUtils.getContextPath()
+ throw new IOException("failed to req API:" + "http://" + curServer + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + path + ". code:" + result.getCode() + " msg: "
+ result.getMessage());
} catch (Exception e) {
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/NetUtils.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/NetUtils.java
index 8f2df6f5e..924438e8d 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/NetUtils.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/NetUtils.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.naming.misc;
import com.alibaba.nacos.common.utils.IPUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.InetUtils;
/**
@@ -33,7 +33,7 @@ public class NetUtils {
* @return local server address
*/
public static String localServer() {
- return InetUtils.getSelfIP() + IPUtil.IP_PORT_SPLITER + ApplicationUtils.getPort();
+ return InetUtils.getSelfIP() + IPUtil.IP_PORT_SPLITER + EnvUtil.getPort();
}
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/ServerStatusSynchronizer.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/ServerStatusSynchronizer.java
index 35c6b1ae6..3244ba919 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/ServerStatusSynchronizer.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/ServerStatusSynchronizer.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.naming.misc;
import com.alibaba.nacos.common.utils.IPUtil;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult;
import org.springframework.util.StringUtils;
@@ -43,11 +43,11 @@ public class ServerStatusSynchronizer implements Synchronizer {
params.put("serverStatus", msg.getData());
- String url = "http://" + serverIP + ":" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath()
+ String url = "http://" + serverIP + ":" + EnvUtil.getPort() + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/operator/server/status";
if (IPUtil.containsPort(serverIP)) {
- url = "http://" + serverIP + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ url = "http://" + serverIP + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "/operator/server/status";
}
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/ServiceStatusSynchronizer.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/ServiceStatusSynchronizer.java
index d5139845d..e83d21324 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/ServiceStatusSynchronizer.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/ServiceStatusSynchronizer.java
@@ -20,7 +20,7 @@ import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.http.Callback;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.utils.JacksonUtils;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
@@ -44,11 +44,11 @@ public class ServiceStatusSynchronizer implements Synchronizer {
params.put("statuses", msg.getData());
params.put("clientIP", NetUtils.localServer());
- String url = "http://" + serverIP + ":" + ApplicationUtils.getPort() + ApplicationUtils.getContextPath()
+ String url = "http://" + serverIP + ":" + EnvUtil.getPort() + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/service/status";
if (IPUtil.containsPort(serverIP)) {
- url = "http://" + serverIP + ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ url = "http://" + serverIP + EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ "/service/status";
}
@@ -95,7 +95,7 @@ public class ServiceStatusSynchronizer implements Synchronizer {
Loggers.SRV_LOG.debug("[STATUS-SYNCHRONIZE] sync service status from: {}, service: {}", serverIP, key);
}
result = NamingProxy
- .reqApi(ApplicationUtils.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/"
+ .reqApi(EnvUtil.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/"
+ "statuses", params, serverIP);
} catch (Exception e) {
Loggers.SRV_LOG.warn("[STATUS-SYNCHRONIZE] Failed to get service status from " + serverIP, e);
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java
index 528feaea4..4740defe0 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/misc/UtilsAndCommons.java
@@ -22,7 +22,7 @@ import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.VersionUtils;
import com.alibaba.nacos.naming.selector.LabelSelector;
import com.alibaba.nacos.naming.selector.NoneSelector;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
@@ -120,7 +120,7 @@ public class UtilsAndCommons {
public static final String PERSIST = "persist";
public static final String DATA_BASE_DIR =
- ApplicationUtils.getNacosHome() + File.separator + "data" + File.separator + "naming";
+ EnvUtil.getNacosHome() + File.separator + "data" + File.separator + "naming";
public static final String RAFT_CACHE_FILE_PREFIX = "com.alibaba.nacos.naming";
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java b/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java
index 2a3884479..d8647b64d 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/utils/Constants.java
@@ -28,6 +28,8 @@ public final class Constants {
public static final String INSTANCE_METADATA = "naming_instance_metadata";
+ public static final String OLD_NAMING_RAFT_GROUP = "naming";
+
public static final String NAMING_PERSISTENT_SERVICE_GROUP = "naming_persistent_service";
public static final String NACOS_NAMING_USE_NEW_RAFT_FIRST = "nacos.naming.use-new-raft.first";
diff --git a/naming/src/main/java/com/alibaba/nacos/naming/web/NamingResourceParser.java b/naming/src/main/java/com/alibaba/nacos/naming/web/NamingResourceParser.java
index 4b50cdbf2..2e782eb0f 100644
--- a/naming/src/main/java/com/alibaba/nacos/naming/web/NamingResourceParser.java
+++ b/naming/src/main/java/com/alibaba/nacos/naming/web/NamingResourceParser.java
@@ -22,6 +22,7 @@ import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.auth.model.Resource;
import com.alibaba.nacos.auth.parser.ResourceParser;
import com.alibaba.nacos.common.utils.ReflectUtils;
+import com.alibaba.nacos.common.utils.NamespaceUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
@@ -44,7 +45,7 @@ public class NamingResourceParser implements ResourceParser {
String groupName = null;
if (requestObj instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) requestObj;
- namespaceId = req.getParameter(CommonParams.NAMESPACE_ID);
+ namespaceId = NamespaceUtil.processNamespaceParameter(req.getParameter(CommonParams.NAMESPACE_ID));
serviceName = req.getParameter(CommonParams.SERVICE_NAME);
groupName = req.getParameter(CommonParams.GROUP_NAME);
} else if (requestObj instanceof Request) {
diff --git a/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java b/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java
index 8b32f7c2e..50f18ef53 100644
--- a/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java
+++ b/naming/src/test/java/com/alibaba/nacos/naming/BaseTest.java
@@ -25,6 +25,7 @@ import com.alibaba.nacos.naming.healthcheck.HealthCheckProcessorDelegate;
import com.alibaba.nacos.naming.misc.NetUtils;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.push.PushService;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Before;
import org.junit.Rule;
@@ -82,7 +83,7 @@ public class BaseTest {
@Before
public void before() {
- ApplicationUtils.injectEnvironment(environment);
+ EnvUtil.setEnvironment(environment);
ApplicationUtils.injectContext(context);
}
diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgementTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgementTest.java
index 0d0f8bad9..788a5a8f4 100644
--- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgementTest.java
+++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/ClusterVersionJudgementTest.java
@@ -20,7 +20,7 @@ import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberMetaDataConstants;
import com.alibaba.nacos.core.cluster.NodeState;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -40,7 +40,7 @@ public class ClusterVersionJudgementTest {
@BeforeClass
public static void beforeClass() {
- ApplicationUtils.injectEnvironment(new MockEnvironment());
+ EnvUtil.setEnvironment(new MockEnvironment());
}
@Before
diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java
index 6d1bea0cf..9d1d1eda2 100644
--- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java
+++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/impl/NamingSnapshotOperationTest.java
@@ -21,7 +21,7 @@ import com.alibaba.nacos.consistency.snapshot.Writer;
import com.alibaba.nacos.core.distributed.raft.RaftConfig;
import com.alibaba.nacos.core.distributed.raft.utils.RaftExecutor;
import com.alibaba.nacos.core.storage.kv.KvStorage;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
import org.junit.After;
import org.junit.Assert;
@@ -40,27 +40,27 @@ public class NamingSnapshotOperationTest {
static {
RaftExecutor.init(new RaftConfig());
- ApplicationUtils.injectEnvironment(new MockEnvironment());
+ EnvUtil.setEnvironment(new MockEnvironment());
}
@Mock
private KvStorage storage;
- private final String tmpDir = Paths.get(ApplicationUtils.getNacosTmpDir(), "rocks_test").toString();
+ private final String tmpDir = Paths.get(EnvUtil.getNacosTmpDir(), "rocks_test").toString();
- private final String snapshotDir = Paths.get(ApplicationUtils.getNacosTmpDir(), "rocks_snapshot_test").toString();
+ private final String snapshotDir = Paths.get(EnvUtil.getNacosTmpDir(), "rocks_snapshot_test").toString();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
@Before
public void init() {
- DiskUtils.deleteQuietly(Paths.get(ApplicationUtils.getNacosTmpDir()));
+ DiskUtils.deleteQuietly(Paths.get(EnvUtil.getNacosTmpDir()));
}
@After
public void after() {
storage.shutdown();
- DiskUtils.deleteQuietly(Paths.get(ApplicationUtils.getNacosTmpDir()));
+ DiskUtils.deleteQuietly(Paths.get(EnvUtil.getNacosTmpDir()));
}
@Test
diff --git a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSetTest.java b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSetTest.java
index 7fc9bb458..d60c448c5 100644
--- a/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSetTest.java
+++ b/naming/src/test/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftPeerSetTest.java
@@ -18,6 +18,7 @@ package com.alibaba.nacos.naming.consistency.persistent.raft;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Assert;
import org.junit.Before;
@@ -36,7 +37,7 @@ public class RaftPeerSetTest {
@BeforeClass
public static void beforeClass() {
ApplicationUtils.injectContext(new StaticApplicationContext());
- ApplicationUtils.injectEnvironment(new MockEnvironment());
+ EnvUtil.setEnvironment(new MockEnvironment());
}
private ServerMemberManager memberManager;
@@ -113,4 +114,4 @@ public class RaftPeerSetTest {
}
}
-}
\ No newline at end of file
+}
diff --git a/pom.xml b/pom.xml
index 807e6cf31..eb8d8a940 100644
--- a/pom.xml
+++ b/pom.xml
@@ -166,8 +166,8 @@
9.0.37
0.30
3.4.2
- 1.3.2
- 1.3.2
+ 1.3.5
+ 1.3.5
diff --git a/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java b/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java
index 8fcb97b41..550930797 100644
--- a/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java
+++ b/sys/src/main/java/com/alibaba/nacos/sys/env/EnvUtil.java
@@ -91,6 +91,10 @@ public class EnvUtil {
EnvUtil.environment = environment;
}
+ public static boolean containsProperty(String key) {
+ return environment.containsProperty(key);
+ }
+
public static String getProperty(String key) {
return environment.getProperty(key);
}
@@ -357,19 +361,31 @@ public class EnvUtil {
private static final String FILE_PREFIX = "file:";
public static Resource getApplicationConfFileResource() {
+ Resource customResource = getCustomFileResource();
+ return customResource == null ? getDefaultResource() : customResource;
+ }
+
+ private static Resource getCustomFileResource() {
String path = getProperty("spring.config.location");
- InputStream inputStream = null;
if (StringUtils.isNotBlank(path) && path.contains(FILE_PREFIX)) {
String[] paths = path.split(",");
path = paths[paths.length - 1].substring(FILE_PREFIX.length());
+ return getRelativePathResource(path, "application.properties");
}
+ return null;
+ }
+
+ private static Resource getRelativePathResource(String parentPath, String path) {
try {
- inputStream = new FileInputStream(new File(path + "application.properties"));
+ InputStream inputStream = new FileInputStream(Paths.get(parentPath, path).toFile());
+ return new InputStreamResource(inputStream);
} catch (Exception ignore) {
}
- if (inputStream == null) {
- inputStream = EnvUtil.class.getResourceAsStream("/application.properties");
- }
+ return null;
+ }
+
+ private static Resource getDefaultResource() {
+ InputStream inputStream = EnvUtil.class.getResourceAsStream("/application.properties");
return new InputStreamResource(inputStream);
}
diff --git a/sys/src/main/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoader.java b/sys/src/main/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoader.java
index a82919b54..c75b07cec 100644
--- a/sys/src/main/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoader.java
+++ b/sys/src/main/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoader.java
@@ -21,7 +21,6 @@ import com.alibaba.nacos.common.JustForTest;
import com.alibaba.nacos.sys.file.FileChangeEvent;
import com.alibaba.nacos.sys.file.FileWatcher;
import com.alibaba.nacos.sys.file.WatchFileCenter;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertySourceLoader;
@@ -57,7 +56,7 @@ public class NacosAutoRefreshPropertySourceLoader implements PropertySourceLoade
properties.putAll(tmp);
try {
- WatchFileCenter.registerWatcher(ApplicationUtils.getConfFilePath(), new FileWatcher() {
+ WatchFileCenter.registerWatcher(EnvUtil.getConfPath(), new FileWatcher() {
@Override
public void onChange(FileChangeEvent event) {
try {
diff --git a/sys/src/main/java/com/alibaba/nacos/sys/utils/ApplicationUtils.java b/sys/src/main/java/com/alibaba/nacos/sys/utils/ApplicationUtils.java
index 6a43b9214..86ea24ca7 100644
--- a/sys/src/main/java/com/alibaba/nacos/sys/utils/ApplicationUtils.java
+++ b/sys/src/main/java/com/alibaba/nacos/sys/utils/ApplicationUtils.java
@@ -16,11 +16,6 @@
package com.alibaba.nacos.sys.utils;
-import com.alibaba.nacos.common.JustForTest;
-import com.alibaba.nacos.common.utils.IoUtils;
-import com.alibaba.nacos.common.utils.StringUtils;
-import com.alibaba.nacos.sys.env.Constants;
-import com.sun.management.OperatingSystemMXBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@@ -32,26 +27,12 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.core.ResolvableType;
-import org.springframework.core.env.ConfigurableEnvironment;
-import org.springframework.core.env.Profiles;
import org.springframework.core.io.Resource;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
import java.lang.annotation.Annotation;
-import java.lang.management.ManagementFactory;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Objects;
import java.util.function.Consumer;
/**
@@ -62,44 +43,10 @@ import java.util.function.Consumer;
@SuppressWarnings("all")
public class ApplicationUtils implements ApplicationContextInitializer {
- public static final String STANDALONE_MODE_ALONE = "standalone";
-
- public static final String STANDALONE_MODE_CLUSTER = "cluster";
-
- public static final String FUNCTION_MODE_CONFIG = "config";
-
- public static final String FUNCTION_MODE_NAMING = "naming";
-
- /**
- * The key of nacos home.
- */
- public static final String NACOS_HOME_KEY = "nacos.home";
-
private static ApplicationContext applicationContext;
- private static ConfigurableEnvironment environment;
-
- private static String localAddress = "";
-
- private static int port = -1;
-
- private static Boolean isStandalone = null;
-
private static boolean started = false;
- private static String functionModeType = null;
-
- private static String contextPath = null;
-
- @JustForTest
- private static String confPath = "";
-
- @JustForTest
- private static String NACOS_HOME_PATH = null;
-
- private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory
- .getOperatingSystemMXBean();
-
public static String getId() {
return applicationContext.getId();
}
@@ -283,271 +230,6 @@ public class ApplicationUtils implements ApplicationContextInitializer T getProperty(String key, Class targetType) {
- return environment.getProperty(key, targetType);
- }
-
- public static T getProperty(String key, Class targetType, T defaultValue) {
- return environment.getProperty(key, targetType, defaultValue);
- }
-
- public static String getRequiredProperty(String key) throws IllegalStateException {
- return environment.getRequiredProperty(key);
- }
-
- public static T getRequiredProperty(String key, Class targetType) throws IllegalStateException {
- return environment.getRequiredProperty(key, targetType);
- }
-
- public static String resolvePlaceholders(String text) {
- return environment.resolvePlaceholders(text);
- }
-
- public static String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
- return environment.resolveRequiredPlaceholders(text);
- }
-
- public static List getPropertyList(String key) {
- List valueList = new ArrayList<>();
-
- for (int i = 0; i < Integer.MAX_VALUE; i++) {
- String value = environment.getProperty(key + "[" + i + "]");
- if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
- break;
- }
-
- valueList.add(value);
- }
-
- return valueList;
- }
-
- public static String getLocalAddress() {
- if (StringUtils.isBlank(localAddress)) {
- localAddress = InetUtils.getSelfIP() + ":" + getPort();
- }
- return localAddress;
- }
-
- public static void setLocalAddress(String localAddress) {
- ApplicationUtils.localAddress = localAddress;
- }
-
- public static int getPort() {
- if (port == -1) {
- port = getProperty("server.port", Integer.class, 8848);
- }
- return port;
- }
-
- public static void setPort(int port) {
- ApplicationUtils.port = port;
- }
-
- public static String getContextPath() {
- if (Objects.isNull(contextPath)) {
- contextPath = getProperty(Constants.WEB_CONTEXT_PATH, "/nacos");
- if (Constants.ROOT_WEB_CONTEXT_PATH.equals(contextPath)) {
- contextPath = StringUtils.EMPTY;
- }
- }
- return contextPath;
- }
-
- public static void setContextPath(String contextPath) {
- ApplicationUtils.contextPath = contextPath;
- }
-
- @JustForTest
- public static void setIsStandalone(Boolean isStandalone) {
- ApplicationUtils.isStandalone = isStandalone;
- }
-
- /**
- * Standalone mode or not
- */
- public static boolean getStandaloneMode() {
- if (Objects.isNull(isStandalone)) {
- isStandalone = Boolean.getBoolean(Constants.STANDALONE_MODE_PROPERTY_NAME);
- }
- return isStandalone;
- }
-
- /**
- * server
- */
- public static String getFunctionMode() {
- if (StringUtils.isEmpty(functionModeType)) {
- functionModeType = System.getProperty(Constants.FUNCTION_MODE_PROPERTY_NAME);
- }
- return functionModeType;
- }
-
- private static String nacosTmpDir;
-
- public static String getNacosTmpDir() {
- if (StringUtils.isBlank(nacosTmpDir)) {
- nacosTmpDir = Paths.get(getNacosHome(), "data", "tmp").toString();
- }
- return nacosTmpDir;
- }
-
- public static String getNacosHome() {
- if (StringUtils.isBlank(NACOS_HOME_PATH)) {
- String nacosHome = System.getProperty(NACOS_HOME_KEY);
- if (StringUtils.isBlank(nacosHome)) {
- nacosHome = Paths.get(System.getProperty("user.home"), "nacos").toString();
- }
- return nacosHome;
- }
- // test-first
- return NACOS_HOME_PATH;
- }
-
- @JustForTest
- public static void setNacosHomePath(String nacosHomePath) {
- NACOS_HOME_PATH = nacosHomePath;
- }
-
- public static List getIPsBySystemEnv(String key) {
- String env = getSystemEnv(key);
- List ips = new ArrayList<>();
- if (StringUtils.isNotEmpty(env)) {
- ips = Arrays.asList(env.split(","));
- }
- return ips;
- }
-
- public static String getSystemEnv(String key) {
- return System.getenv(key);
- }
-
- public static float getLoad() {
- return (float) operatingSystemMXBean.getSystemLoadAverage();
- }
-
- public static float getCPU() {
- return (float) operatingSystemMXBean.getSystemCpuLoad();
- }
-
- public static float getMem() {
- return (float) (1 - (double) operatingSystemMXBean.getFreePhysicalMemorySize() / (double) operatingSystemMXBean
- .getTotalPhysicalMemorySize());
- }
-
- public static String getConfFilePath() {
- if (StringUtils.isNotBlank(ApplicationUtils.confPath)) {
- return ApplicationUtils.confPath;
- }
- ApplicationUtils.confPath = Paths.get(getNacosHome(), "conf").toString();
- return confPath;
- }
-
- public static void setConfFilePath(final String confPath) {
- ApplicationUtils.confPath = confPath;
- }
-
- public static String getClusterConfFilePath() {
- return Paths.get(getNacosHome(), "conf", "cluster.conf").toString();
- }
-
- public static List readClusterConf() throws IOException {
- try (Reader reader = new InputStreamReader(new FileInputStream(new File(getClusterConfFilePath())),
- StandardCharsets.UTF_8)) {
- return analyzeClusterConf(reader);
- } catch (FileNotFoundException ignore) {
- List tmp = new ArrayList<>();
- String clusters = ApplicationUtils.getMemberList();
- if (StringUtils.isNotBlank(clusters)) {
- String[] details = clusters.split(",");
- for (String item : details) {
- tmp.add(item.trim());
- }
- }
- return tmp;
- }
- }
-
- public static List analyzeClusterConf(Reader reader) throws IOException {
- List instanceList = new ArrayList();
- List lines = IoUtils.readLines(reader);
- String comment = "#";
- for (String line : lines) {
- String instance = line.trim();
- if (instance.startsWith(comment)) {
- // # it is ip
- continue;
- }
- if (instance.contains(comment)) {
- // 192.168.71.52:8848 # Instance A
- instance = instance.substring(0, instance.indexOf(comment));
- instance = instance.trim();
- }
- int multiIndex = instance.indexOf(Constants.COMMA_DIVISION);
- if (multiIndex > 0) {
- // support the format: ip1:port,ip2:port # multi inline
- instanceList.addAll(Arrays.asList(instance.split(Constants.COMMA_DIVISION)));
- } else {
- //support the format: 192.168.71.52:8848
- instanceList.add(instance);
- }
- }
- return instanceList;
- }
-
- public static void writeClusterConf(String content) throws IOException {
- DiskUtils.writeFile(new File(getClusterConfFilePath()), content.getBytes(StandardCharsets.UTF_8), false);
- }
-
- public static String getMemberList() {
- String val = null;
- if (environment == null) {
- val = System.getenv("nacos.member.list");
- if (StringUtils.isBlank(val)) {
- val = System.getProperty("nacos.member.list");
- }
- } else {
- val = getProperty("nacos.member.list");
- }
- return val;
- }
-
- public static void injectEnvironment(ConfigurableEnvironment environment) {
- ApplicationUtils.environment = environment;
- }
-
public static void injectContext(ConfigurableApplicationContext context) {
ApplicationUtils.applicationContext = context;
}
@@ -555,7 +237,5 @@ public class ApplicationUtils implements ApplicationContextInitializer networks = ApplicationUtils.getPropertyList(Constants.PREFERRED_NETWORKS);
+ List networks = EnvUtil.getPropertyList(Constants.PREFERRED_NETWORKS);
PREFERRED_NETWORKS.addAll(networks);
- List interfaces = ApplicationUtils.getPropertyList(Constants.IGNORED_INTERFACES);
+ List interfaces = EnvUtil.getPropertyList(Constants.IGNORED_INTERFACES);
IGNORED_INTERFACES.addAll(interfaces);
final long delayMs = Long.getLong("nacos.core.inet.auto-refresh", 30_000L);
@@ -79,7 +80,7 @@ public class InetUtils {
public void run() {
String nacosIP = System.getProperty(NACOS_SERVER_IP);
if (StringUtils.isBlank(nacosIP)) {
- nacosIP = ApplicationUtils.getProperty(IP_ADDRESS);
+ nacosIP = EnvUtil.getProperty(IP_ADDRESS);
}
if (!StringUtils.isBlank(nacosIP)) {
if (!(IPUtil.isIP(nacosIP) || isDomain(nacosIP))) {
@@ -92,7 +93,7 @@ public class InetUtils {
if (!preferHostnameOverIP) {
preferHostnameOverIP = Boolean
- .parseBoolean(ApplicationUtils.getProperty(PREFER_HOSTNAME_OVER_IP));
+ .parseBoolean(EnvUtil.getProperty(PREFER_HOSTNAME_OVER_IP));
}
if (preferHostnameOverIP) {
diff --git a/sys/src/test/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoaderTest.java b/sys/src/test/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoaderTest.java
index 8d3720f9b..6645116da 100644
--- a/sys/src/test/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoaderTest.java
+++ b/sys/src/test/java/com/alibaba/nacos/sys/env/NacosAutoRefreshPropertySourceLoaderTest.java
@@ -22,7 +22,6 @@ import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.sys.file.FileChangeEvent;
import com.alibaba.nacos.sys.file.FileWatcher;
import com.alibaba.nacos.sys.file.WatchFileCenter;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.sys.utils.DiskUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.AfterClass;
@@ -52,19 +51,19 @@ public class NacosAutoRefreshPropertySourceLoaderTest {
@BeforeClass
public static void before() throws URISyntaxException {
- oldConfPath = ApplicationUtils.getConfFilePath();
- ApplicationUtils.setConfFilePath(new File(ClassLoader.getSystemResource("application.properties").toURI()).getParent());
+ oldConfPath = EnvUtil.getConfPath();
+ EnvUtil.setConfPath(new File(ClassLoader.getSystemResource("application.properties").toURI()).getParent());
}
@AfterClass
public static void after() {
- ApplicationUtils.setConfFilePath(oldConfPath);
+ EnvUtil.setConfPath(oldConfPath);
}
@Test
public void testConfigFileAutoRefresh() throws URISyntaxException, InterruptedException, NacosException, IOException {
final URL url = ClassLoader.getSystemResource("application.properties");
- ApplicationUtils.setContextPath(url.getPath());
+ EnvUtil.setContextPath(url.getPath());
final String val1 = environment.getProperty("name");
Assert.assertEquals("test-1", val1);
final File file = new File(url.toURI());
@@ -72,7 +71,7 @@ public class NacosAutoRefreshPropertySourceLoaderTest {
final String newVal = System.currentTimeMillis() + "-lessspring";
DiskUtils.writeFile(file, ByteUtils.toBytes("\n" + newKey + "=" + newVal), true);
CountDownLatch latch = new CountDownLatch(1);
- WatchFileCenter.registerWatcher(ApplicationUtils.getConfFilePath(), new FileWatcher() {
+ WatchFileCenter.registerWatcher(EnvUtil.getConfPath(), new FileWatcher() {
@Override
public void onChange(FileChangeEvent event) {
latch.countDown();
@@ -89,4 +88,4 @@ public class NacosAutoRefreshPropertySourceLoaderTest {
Assert.assertEquals(newVal, val2);
}
-}
\ No newline at end of file
+}
diff --git a/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java b/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java
index eb44faa72..d8446f52c 100644
--- a/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_CITCase.java
@@ -37,6 +37,7 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
@@ -71,6 +72,9 @@ public class ConfigAPI_CITCase {
String group = "yanlin";
+ @Value("${server.servlet.context-path}")
+ private String contextPath;
+
@LocalServerPort
private int port;
@@ -83,7 +87,7 @@ public class ConfigAPI_CITCase {
public void setUp() throws Exception {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
- properties.put(PropertyKeyConst.CONTEXT_PATH, "/nacos");
+ properties.put(PropertyKeyConst.CONTEXT_PATH, contextPath);
iconfig = NacosFactory.createConfigService(properties);
agent = new MetricsHttpAgent(new ServerHttpAgent(properties));
agent.start();
@@ -517,6 +521,7 @@ public class ConfigAPI_CITCase {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
properties.put(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG, "true");
+ properties.put(PropertyKeyConst.CONTEXT_PATH, contextPath);
ConfigService iconfig = NacosFactory.createConfigService(properties);
final AtomicInteger count = new AtomicInteger(0);
diff --git a/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_With_RootContextPath_CITCase.java b/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_With_RootContextPath_CITCase.java
new file mode 100644
index 000000000..fa9c4e184
--- /dev/null
+++ b/test/src/test/java/com/alibaba/nacos/test/config/ConfigAPI_With_RootContextPath_CITCase.java
@@ -0,0 +1,30 @@
+/*
+ * 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.test.config;
+
+import org.springframework.test.context.TestPropertySource;
+
+
+/**
+ * Test context path is '/'.
+ *
+ * @see #4171
+ */
+@TestPropertySource( properties = {"server.servlet.context-path=/", "server.port=7007"})
+public class ConfigAPI_With_RootContextPath_CITCase extends ConfigAPI_CITCase {
+
+}
diff --git a/test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java b/test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java
index 4e808b0b9..c1ec86af8 100644
--- a/test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/config/ConfigExportAndImportAPI_CITCase.java
@@ -27,14 +27,24 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.github.keran213539.commonOkHttp.CommonOkHttpClient;
import com.github.keran213539.commonOkHttp.CommonOkHttpClientBuilder;
import com.github.keran213539.commonOkHttp.UploadByteFile;
-import org.junit.*;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.HttpURLConnection;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
/**
* @author klw
diff --git a/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java b/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java
index def842773..82ef7a38b 100644
--- a/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java
+++ b/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java
@@ -29,7 +29,7 @@ import com.alibaba.nacos.config.server.model.event.RaftDbErrorEvent;
import com.alibaba.nacos.config.server.service.repository.embedded.DistributedDatabaseOperateImpl;
import com.alibaba.nacos.consistency.cp.CPProtocol;
import com.alibaba.nacos.consistency.cp.MetadataKey;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
import com.alibaba.nacos.test.base.HttpClient4Test;
@@ -186,7 +186,7 @@ public class BaseClusterTest extends HttpClient4Test {
private static void run(final int index, final CountDownLatch latch, final Class> cls) {
Runnable runnable = () -> {
try {
- ApplicationUtils.setIsStandalone(false);
+ EnvUtil.setIsStandalone(false);
final String path = Paths.get(System.getProperty("user.home"), "/nacos-" + index + "/").toString();
DiskUtils.deleteDirectory(path);
diff --git a/test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java
index 573b7c61c..a09c1a2f4 100644
--- a/test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/core/SnowFlowerIdGenerator_ITCase.java
@@ -17,7 +17,7 @@
package com.alibaba.nacos.test.core;
import com.alibaba.nacos.core.distributed.id.SnowFlowerIdGenerator;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
@@ -29,7 +29,7 @@ public class SnowFlowerIdGenerator_ITCase {
@Test
public void test_idGenerator() {
- ApplicationUtils.injectEnvironment(new StandardEnvironment());
+ EnvUtil.setEnvironment(new StandardEnvironment());
SnowFlowerIdGenerator generator1 = new SnowFlowerIdGenerator();
SnowFlowerIdGenerator generator2 = new SnowFlowerIdGenerator();
SnowFlowerIdGenerator generator3 = new SnowFlowerIdGenerator();
diff --git a/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java
index 08a04c3a1..66cd2121f 100644
--- a/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java
@@ -24,6 +24,7 @@ import com.alibaba.nacos.core.cluster.lookup.FileConfigMemberLookup;
import com.alibaba.nacos.core.cluster.lookup.LookupFactory;
import com.alibaba.nacos.core.cluster.MemberLookup;
import com.alibaba.nacos.core.cluster.lookup.StandaloneMemberLookup;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.alibaba.nacos.sys.utils.InetUtils;
@@ -60,9 +61,9 @@ public class MemberLookup_ITCase extends BaseTest {
@Before
public void before() throws Exception {
System.setProperty("nacos.home", path);
- ApplicationUtils.injectEnvironment(new StandardEnvironment());
- ApplicationUtils.setIsStandalone(false);
- System.out.println(ApplicationUtils.getStandaloneMode());
+ EnvUtil.setEnvironment(new StandardEnvironment());
+ EnvUtil.setIsStandalone(false);
+ System.out.println(EnvUtil.getStandaloneMode());
System.out.println(Arrays.toString(LookupFactory.LookupType.values()));
DiskUtils.forceMkdir(path);
@@ -107,14 +108,14 @@ public class MemberLookup_ITCase extends BaseTest {
@Test
public void test_b_lookup_standalone() throws Exception {
- ApplicationUtils.setIsStandalone(true);
+ EnvUtil.setIsStandalone(true);
try {
LookupFactory.createLookUp(memberManager);
}
catch (Throwable ignore) {
} finally {
- ApplicationUtils.setIsStandalone(false);
+ EnvUtil.setIsStandalone(false);
}
MemberLookup lookup = LookupFactory.getLookUp();
System.out.println(lookup);
@@ -123,10 +124,10 @@ public class MemberLookup_ITCase extends BaseTest {
@Test
public void test_c_lookup_address_server() throws Exception {
- ApplicationUtils.setIsStandalone(false);
- System.out.println(ApplicationUtils.getClusterConfFilePath());
+ EnvUtil.setIsStandalone(false);
+ System.out.println(EnvUtil.getClusterConfFilePath());
DiskUtils.deleteFile(Paths.get(path, "conf").toString(), "cluster.conf");
- System.out.println(new File(ApplicationUtils.getClusterConfFilePath()).exists());
+ System.out.println(new File(EnvUtil.getClusterConfFilePath()).exists());
try {
LookupFactory.createLookUp(memberManager);
}
diff --git a/test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java
index 295571569..b5411537e 100644
--- a/test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/core/cluster/ServerMemberManager_ITCase.java
@@ -24,7 +24,7 @@ import com.alibaba.nacos.core.cluster.MembersChangeEvent;
import com.alibaba.nacos.core.cluster.MemberUtils;
import com.alibaba.nacos.core.cluster.NodeState;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import com.alibaba.nacos.sys.env.Constants;
import org.junit.After;
import org.junit.AfterClass;
@@ -64,8 +64,8 @@ public class ServerMemberManager_ITCase {
public static void initClass() throws Exception {
System.setProperty(Constants.NACOS_SERVER_IP, "127.0.0.1");
System.setProperty("server.port", "8847");
- ApplicationUtils.setIsStandalone(true);
- ApplicationUtils.injectEnvironment(new StandardEnvironment());
+ EnvUtil.setIsStandalone(true);
+ EnvUtil.setEnvironment(new StandardEnvironment());
}
@AfterClass
diff --git a/test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheTest.java b/test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheTest.java
index 88c364980..40743fe8c 100644
--- a/test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheTest.java
+++ b/test/src/test/java/com/alibaba/nacos/test/core/code/ControllerMethodsCacheTest.java
@@ -19,7 +19,7 @@ package com.alibaba.nacos.test.core.code;
import static org.junit.Assert.assertEquals;
import com.alibaba.nacos.core.code.ControllerMethodsCache;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@@ -40,7 +40,7 @@ public class ControllerMethodsCacheTest {
@Before
public void setUp() throws Exception {
methodsCache = new ControllerMethodsCache();
- ApplicationUtils.setContextPath("/nacos");
+ EnvUtil.setContextPath("/nacos");
methodsCache.initClassMethod("com.alibaba.nacos.config.server.controller");
}
diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java
index 044b599b4..451630959 100644
--- a/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java
@@ -25,6 +25,7 @@ import com.alibaba.nacos.client.naming.NacosNamingService;
import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.test.utils.NamingTestUtils;
+import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -69,7 +70,7 @@ public class AutoDeregisterInstance_ITCase {
}
while (true) {
- if (!"UP".equals(naming.getServerStatus()) || ApplicationUtils.getPort() == 0) {
+ if (!"UP".equals(naming.getServerStatus()) || EnvUtil.getPort() == 0) {
Thread.sleep(1000L);
continue;
}
diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_ITCase.java
index 179c007cc..ac74ed1c1 100644
--- a/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_ITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_ITCase.java
@@ -16,20 +16,22 @@
package com.alibaba.nacos.test.naming;
import com.alibaba.nacos.Nacos;
+import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
+import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.test.naming.NamingBase.TEST_PORT;
@@ -49,15 +51,21 @@ public class DeregisterInstance_ITCase {
private NamingService naming;
@LocalServerPort
private int port;
-
+
+ @Value("${server.servlet.context-path}")
+ private String contextPath;
+
@Before
public void init() throws Exception {
-
- NamingBase.prepareServer(port);
+
+ NamingBase.prepareServer(port, contextPath);
if (naming == null) {
+ Properties properties = new Properties();
+ properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
+ properties.put(PropertyKeyConst.CONTEXT_PATH, contextPath);
//TimeUnit.SECONDS.sleep(10);
- naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
+ naming = NamingFactory.createNamingService(properties);
}
while (true) {
diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_With_RootContextPath_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_With_RootContextPath_ITCase.java
new file mode 100644
index 000000000..af1b8bc5e
--- /dev/null
+++ b/test/src/test/java/com/alibaba/nacos/test/naming/DeregisterInstance_With_RootContextPath_ITCase.java
@@ -0,0 +1,29 @@
+/*
+ * 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.test.naming;
+
+import org.springframework.test.context.TestPropertySource;
+
+/**
+ * Test context path is '/'.
+ *
+ * @see #4171
+ */
+@TestPropertySource( properties = {"server.servlet.context-path=/"})
+public class DeregisterInstance_With_RootContextPath_ITCase extends DeregisterInstance_ITCase {
+
+}
diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java b/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java
index a952bec27..d16fa28de 100644
--- a/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/naming/NamingBase.java
@@ -21,6 +21,7 @@ import com.alibaba.nacos.common.constant.HttpHeaderConsts;
import com.alibaba.nacos.common.http.HttpRestResult;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
+import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.test.base.HttpClient4Test;
import org.apache.http.HttpStatus;
import org.junit.Assert;
@@ -172,26 +173,34 @@ public class NamingBase extends HttpClient4Test {
}
public static void prepareServer(int localPort) throws Exception{
- prepareServer(localPort, "UP");
+ prepareServer(localPort, "UP", "/nacos");
+ }
+
+ public static void prepareServer(int localPort,String contextPath) throws Exception{
+ prepareServer(localPort, "UP", contextPath);
}
- public static void prepareServer(int localPort, String status) throws Exception {
- String url = "http://127.0.0.1:" + localPort + "/nacos/v1/ns/operator/switches?entry=overriddenServerStatus&value=" + status;
+ public static void prepareServer(int localPort, String status,String contextPath) throws Exception {
+ String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=overriddenServerStatus&value=" + status;
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server");
HttpRestResult result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class);
System.out.println(result);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
- url = "http://127.0.0.1:" + localPort + "/nacos/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false;
+ url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + false;
result = nacosRestTemplate.putForm(url, header, new HashMap<>(), String.class);
System.out.println(result);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
}
-
+
public static void destoryServer(int localPort) throws Exception{
- String url = "http://127.0.0.1:" + localPort + "/nacos/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true;
+ destoryServer(localPort, "/nacos");
+ }
+
+ public static void destoryServer(int localPort, String contextPath) throws Exception{
+ String url = "http://127.0.0.1:" + localPort + normalizeContextPath(contextPath) + "/v1/ns/operator/switches?entry=autoChangeHealthCheckEnabled&value=" + true;
Header header = Header.newInstance();
header.addParam(HttpHeaderConsts.USER_AGENT_HEADER, "Nacos-Server");
@@ -199,4 +208,11 @@ public class NamingBase extends HttpClient4Test {
System.out.println(result);
Assert.assertEquals(HttpStatus.SC_OK, result.getCode());
}
+
+ public static String normalizeContextPath(String contextPath) {
+ if (StringUtils.isBlank(contextPath) || "/".equals(contextPath)) {
+ return StringUtils.EMPTY;
+ }
+ return contextPath.startsWith("/") ? contextPath : "/" + contextPath;
+ }
}
diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_ITCase.java
index 0227f3a60..f5a672456 100644
--- a/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_ITCase.java
+++ b/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_ITCase.java
@@ -22,20 +22,22 @@ import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.naming.pojo.Instance;
-import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
-import java.util.*;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
import java.util.concurrent.TimeUnit;
-import static com.alibaba.nacos.test.naming.NamingBase.*;
-
/**
* Created by wangtong.wt on 2018/6/20.
*
@@ -43,23 +45,29 @@ import static com.alibaba.nacos.test.naming.NamingBase.*;
* @date 2018/6/20
*/
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = Nacos.class, properties = {"server.servlet.context-path=/nacos"},
- webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@SpringBootTest(classes = Nacos.class, properties = {
+ "server.servlet.context-path=/nacos"}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RegisterInstance_ITCase {
-
+
private NamingService naming;
- private NamingService naming2;
+
+ @Value("${server.servlet.context-path}")
+ private String contextPath;
+
@LocalServerPort
private int port;
@Before
public void init() throws Exception {
- NamingBase.prepareServer(port);
+ NamingBase.prepareServer(port, contextPath);
if (naming == null) {
TimeUnit.SECONDS.sleep(10);
- naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
+ Properties properties = new Properties();
+ properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1" + ":" + port);
+ properties.put(PropertyKeyConst.CONTEXT_PATH, contextPath);
+ naming = NamingFactory.createNamingService(properties);
}
while (true) {
@@ -77,6 +85,7 @@ public class RegisterInstance_ITCase {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port);
properties.put(PropertyKeyConst.NAMESPACE, "t3");
+ properties.put(PropertyKeyConst.CONTEXT_PATH, contextPath);
naming = NamingFactory.createNamingService(properties);
TimeUnit.SECONDS.sleep(10);
@@ -96,9 +105,9 @@ public class RegisterInstance_ITCase {
*/
@Test
public void regDomTest() throws Exception {
- String serviceName = randomDomainName();
+ String serviceName = NamingBase.randomDomainName();
System.out.println(serviceName);
- naming.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT);
+ naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT);
TimeUnit.SECONDS.sleep(3);
@@ -107,8 +116,8 @@ public class RegisterInstance_ITCase {
Assert.assertEquals(1, instances.size());
Assert.assertTrue(instances.get(0).getInstanceId().contains(serviceName));
//Assert.assertEquals(instances.get(0).getService().getName(), serviceName);
- Assert.assertEquals(instances.get(0).getIp(), TEST_IP_4_DOM_1);
- Assert.assertEquals(instances.get(0).getPort(), TEST_PORT);
+ Assert.assertEquals(instances.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1);
+ Assert.assertEquals(instances.get(0).getPort(), NamingBase.TEST_PORT);
}
/**
@@ -119,11 +128,11 @@ public class RegisterInstance_ITCase {
@Test
public void regDomClusterTest() throws Exception {
- String serviceName = randomDomainName();
+ String serviceName = NamingBase.randomDomainName();
System.out.println(serviceName);
- naming.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT, TEST_NEW_CLUSTER_4_DOM_1);
+ naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT, NamingBase.TEST_NEW_CLUSTER_4_DOM_1);
TimeUnit.SECONDS.sleep(3);
@@ -132,17 +141,17 @@ public class RegisterInstance_ITCase {
Assert.assertEquals(1, instances.size());
Assert.assertTrue(instances.get(0).getInstanceId().contains(serviceName));
//Assert.assertEquals(instances2.get(0).getService().getName(), serviceName);
- Assert.assertEquals(instances.get(0).getIp(), TEST_IP_4_DOM_1);
- Assert.assertEquals(instances.get(0).getPort(), TEST_PORT);
+ Assert.assertEquals(instances.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1);
+ Assert.assertEquals(instances.get(0).getPort(), NamingBase.TEST_PORT);
//Assert.assertEquals(instances.get(0).getCluster().getName(), TEST_NEW_CLUSTER_4_DOM_1);
- List instances2 = naming.getAllInstances(serviceName, Arrays.asList(TEST_NEW_CLUSTER_4_DOM_1));
+ List instances2 = naming.getAllInstances(serviceName, Arrays.asList(NamingBase.TEST_NEW_CLUSTER_4_DOM_1));
Assert.assertEquals(instances2.size(), 1);
Assert.assertTrue(instances2.get(0).getInstanceId().contains(serviceName));
//Assert.assertEquals(instances2.get(0).getService().getName(), serviceName);
- Assert.assertEquals(instances2.get(0).getIp(), TEST_IP_4_DOM_1);
- Assert.assertEquals(instances2.get(0).getPort(), TEST_PORT);
+ Assert.assertEquals(instances2.get(0).getIp(), NamingBase.TEST_IP_4_DOM_1);
+ Assert.assertEquals(instances2.get(0).getPort(), NamingBase.TEST_PORT);
//Assert.assertEquals(instances2.get(0).getCluster().getName(), TEST_NEW_CLUSTER_4_DOM_1);
}
@@ -153,9 +162,9 @@ public class RegisterInstance_ITCase {
*/
@Test
public void regDomWithInstance() throws Exception {
- String serviceName = randomDomainName();
+ String serviceName = NamingBase.randomDomainName();
- Instance i1 = getInstance(serviceName);
+ Instance i1 = NamingBase.getInstance(serviceName);
naming.registerInstance(serviceName, i1);
TimeUnit.SECONDS.sleep(3);
@@ -164,7 +173,7 @@ public class RegisterInstance_ITCase {
Assert.assertEquals(instances.size(), 1);
- Assert.assertTrue(verifyInstance(i1, instances.get(0)));
+ Assert.assertTrue(NamingBase.verifyInstance(i1, instances.get(0)));
}
@@ -175,11 +184,11 @@ public class RegisterInstance_ITCase {
*/
@Test
public void regDomNotHealth() throws Exception {
- String serviceName = randomDomainName();
+ String serviceName = NamingBase.randomDomainName();
System.out.println(serviceName);
naming.registerInstance(serviceName, "1.1.1.1", 2000);
- naming.registerInstance(serviceName, TEST_IP_4_DOM_1, TEST_PORT);
+ naming.registerInstance(serviceName, NamingBase.TEST_IP_4_DOM_1, NamingBase.TEST_PORT);
TimeUnit.SECONDS.sleep(3);
@@ -191,7 +200,7 @@ public class RegisterInstance_ITCase {
@Test
public void regServiceWithMetadata() throws Exception {
- String serviceName = randomDomainName();
+ String serviceName = NamingBase.randomDomainName();
System.out.println(serviceName);
Instance instance = new Instance();
@@ -216,7 +225,7 @@ public class RegisterInstance_ITCase {
@Test
public void regServiceWithTTL() throws Exception {
- String serviceName = randomDomainName();
+ String serviceName = NamingBase.randomDomainName();
System.out.println(serviceName);
Instance instance = new Instance();
diff --git a/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_With_RootContextPath_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_With_RootContextPath_ITCase.java
new file mode 100644
index 000000000..ab220dbca
--- /dev/null
+++ b/test/src/test/java/com/alibaba/nacos/test/naming/RegisterInstance_With_RootContextPath_ITCase.java
@@ -0,0 +1,29 @@
+/*
+ * 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.test.naming;
+
+import org.springframework.test.context.TestPropertySource;
+
+/**
+ * Test context path is '/'.
+ *
+ * @see #4171
+ */
+@TestPropertySource(properties = {"server.servlet.context-path=/"})
+public class RegisterInstance_With_RootContextPath_ITCase extends RegisterInstance_ITCase {
+
+}