Merge remote-tracking branch 'upstream/develop' into feature_support_grpc_core

# Conflicts:
#	client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java
#	client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingMaintainService.java
#	client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java
#	config/src/main/java/com/alibaba/nacos/config/server/auth/ConfigResourceParser.java
#	config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java
#	config/src/main/java/com/alibaba/nacos/config/server/result/ResultBuilder.java
#	core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java
#	naming/src/main/java/com/alibaba/nacos/naming/controllers/CatalogController.java
#	naming/src/main/java/com/alibaba/nacos/naming/healthcheck/ClientBeatCheckTask.java
#	naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HealthCheckCommon.java
#	naming/src/main/java/com/alibaba/nacos/naming/web/NamingResourceParser.java
#	sys/src/main/java/com/alibaba/nacos/sys/utils/ApplicationUtils.java
#	test/src/test/java/com/alibaba/nacos/test/naming/AutoDeregisterInstance_ITCase.java
This commit is contained in:
KomachiSion 2020-12-03 18:41:41 +08:00
commit d6fcac85c5
118 changed files with 1521 additions and 1151 deletions

View File

@ -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.
*
* <p>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)}
*
* <p>etc:
* <p>serviceName | groupName | result</p>
* <p>serviceA | groupA | groupA@@serviceA</p>
* <p>nil | groupA | threw IllegalArgumentException</p>
*
* @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'
* <p>This method works similar with {@link com.alibaba.nacos.api.naming.utils.NamingUtils#getGroupedName} But not verify any parameters.
*
* </p> etc:
* <p>serviceName | groupName | result</p>
* <p>serviceA | groupA | groupA@@serviceA</p>
* <p>nil | groupA | groupA@@</p>
* <p>nil | nil | @@</p>
*
* @return 'groupName@@serviceName'
*/
public static String getGroupedNameOptional(final String serviceName, final String groupName) {
return groupName + Constants.SERVICE_INFO_SPLITER + serviceName;
}
}

View File

@ -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");
}
}

View File

@ -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

View File

@ -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<String> result) {

View File

@ -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);
}
}
}

View File

@ -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);
}

View File

@ -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();

View File

@ -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";
}

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.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(""));
}
}

View File

@ -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.<T>builder().withCode(200).withData(data).build();
}
public static <T> RestResult<T> success(String msg, T data) {
return RestResult.<T>builder().withCode(200).withMsg(msg).withData(data).build();
}
public static <T> RestResult<T> success(int code, T data) {
return RestResult.<T>builder().withCode(code).withData(data).build();
}
@ -55,4 +61,7 @@ public class RestResultUtils {
return RestResult.<T>builder().withCode(code).withMsg(errMsg).build();
}
public static <T> RestResult<T> buildResult(IResultCode resultCode, T data) {
return RestResult.<T>builder().withCode(resultCode.getCode()).withMsg(resultCode.getCodeMsg()).withData(data).build();
}
}

View File

@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.alibaba.nacos.config.server.result.core;
package com.alibaba.nacos.common.model.core;
/**
* IResultCode.

View File

@ -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.

View File

@ -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;

View File

@ -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) {

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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<String, Object> 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<ConfigAllInfo> 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<String, Object> 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<Long> 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<ConfigAllInfo> 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);
}
}

View File

@ -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> T.
* @return RestResult.
*/
public static <T extends Object> RestResult<T> buildResult(IResultCode resultCode, T resultData) {
Assert.notNull(resultCode, "the resultCode can not be null");
RestResult<T> rr = new RestResult<>(resultCode.getCode(), resultCode.getCodeMsg(), resultData);
return rr;
}
public static <T extends Object> RestResult<T> buildSuccessResult(T resultData) {
return buildResult(ResultCodeEnum.SUCCESS, resultData);
}
/**
* BuildSuccessResult.
*
* @param successMsg successMsg string value.
* @param resultData resultData.
* @param <T> T.
* @return RestResult.
*/
public static <T extends Object> RestResult<T> buildSuccessResult(String successMsg, T resultData) {
RestResult<T> rr = buildResult(ResultCodeEnum.SUCCESS, resultData);
rr.setMessage(successMsg);
return rr;
}
public static <T extends Object> RestResult<T> buildSuccessResult() {
return buildResult(ResultCodeEnum.SUCCESS, null);
}
/**
* BuildSuccessResult.
*
* @param successMsg successMsg string value.
* @param <T> T.
* @return RestResult.
*/
public static <T extends Object> RestResult<T> buildSuccessResult(String successMsg) {
RestResult<T> rr = buildResult(ResultCodeEnum.SUCCESS, null);
rr.setMessage(successMsg);
return rr;
}
}

View File

@ -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.

View File

@ -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);

View File

@ -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<SampleResult> runCollectionJob(String url, Map<String, String> params,

View File

@ -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);

View File

@ -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();

View File

@ -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;
}

View File

@ -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

View File

@ -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);

View File

@ -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;

View File

@ -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<String> result = NotifyService.invokeURL(urlString, headers, Constants.ENCODE);
if (result.ok()) {

View File

@ -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<String, RowMapper> 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 <D> RowMapper<D> getRowMapper(String classFullName) {
return (RowMapper<D>) mapperMap.get(classFullName);
}
public static final class MapRowMapper implements RowMapper<Map<String, Object>> {
@Override
public Map<String, Object> mapRow(ResultSet resultSet, int rowNum) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
Map<String, Object> 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<ConfigInfoWrapper> {
@Override

View File

@ -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;

View File

@ -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<String> getTenantIdList(int page, int pageSize) {
String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id LIMIT ?, ?";
PaginationHelper<Map<String, Object>> 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<Map<String, Object>> 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<String> getGroupIdList(int page, int pageSize) {
String sql = "SELECT group_id FROM config_info WHERE tenant_id ='' GROUP BY group_id LIMIT ?, ?";
PaginationHelper<Map<String, Object>> 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<Map<String, Object>> 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

View File

@ -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<E> implements PaginationHelper {
}
private boolean isDerby() {
return (ApplicationUtils.getStandaloneMode() && !PropertyUtil.isUseExternalDB()) || PropertyUtil
return (EnvUtil.getStandaloneMode() && !PropertyUtil.isUseExternalDB()) || PropertyUtil
.isEmbeddedStorage();
}

View File

@ -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<ConfigInfo> configInfos) {
if (!ApplicationUtils.getStandaloneMode()) {
if (!EnvUtil.getStandaloneMode()) {
List<ConfigDumpEvent> 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();

View File

@ -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 {

View File

@ -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 ApplicationContextInitializer<ConfigurableA
/**
* Inline storage value = ${nacos.standalone}.
*/
private static boolean embeddedStorage = ApplicationUtils.getStandaloneMode();
private static boolean embeddedStorage = EnvUtil.getStandaloneMode();
/**
* Getter method for property <tt>pushContent</tt>.
@ -242,7 +242,7 @@ public class PropertyUtil implements ApplicationContextInitializer<ConfigurableA
}
public static boolean isStandaloneMode() {
return ApplicationUtils.getStandaloneMode();
return EnvUtil.getStandaloneMode();
}
public static boolean isUseExternalDB() {
@ -262,7 +262,7 @@ public class PropertyUtil implements ApplicationContextInitializer<ConfigurableA
// if use raft+derby, Reduce leader read pressure
public static boolean isDirectRead() {
return ApplicationUtils.getStandaloneMode() && isEmbeddedStorage();
return EnvUtil.getStandaloneMode() && isEmbeddedStorage();
}
public static void setEmbeddedStorage(boolean embeddedStorage) {
@ -271,15 +271,15 @@ public class PropertyUtil implements ApplicationContextInitializer<ConfigurableA
private void loadSetting() {
try {
setNotifyConnectTimeout(Integer.parseInt(ApplicationUtils.getProperty("notifyConnectTimeout", "100")));
setNotifyConnectTimeout(Integer.parseInt(EnvUtil.getProperty("notifyConnectTimeout", "100")));
LOGGER.info("notifyConnectTimeout:{}", notifyConnectTimeout);
setNotifySocketTimeout(Integer.parseInt(ApplicationUtils.getProperty("notifySocketTimeout", "200")));
setNotifySocketTimeout(Integer.parseInt(EnvUtil.getProperty("notifySocketTimeout", "200")));
LOGGER.info("notifySocketTimeout:{}", notifySocketTimeout);
setHealthCheck(Boolean.parseBoolean(ApplicationUtils.getProperty("isHealthCheck", "true")));
setHealthCheck(Boolean.parseBoolean(EnvUtil.getProperty("isHealthCheck", "true")));
LOGGER.info("isHealthCheck:{}", isHealthCheck);
setMaxHealthCheckFailCount(Integer.parseInt(ApplicationUtils.getProperty("maxHealthCheckFailCount", "12")));
setMaxHealthCheckFailCount(Integer.parseInt(EnvUtil.getProperty("maxHealthCheckFailCount", "12")));
LOGGER.info("maxHealthCheckFailCount:{}", maxHealthCheckFailCount);
setMaxContent(Integer.parseInt(ApplicationUtils.getProperty("maxContent", String.valueOf(maxContent))));
setMaxContent(Integer.parseInt(EnvUtil.getProperty("maxContent", String.valueOf(maxContent))));
LOGGER.info("maxContent:{}", maxContent);
// 容量管理
setManageCapacity(getBoolean("isManageCapacity", isManageCapacity));
@ -339,16 +339,15 @@ public class PropertyUtil implements ApplicationContextInitializer<ConfigurableA
}
public String getProperty(String key) {
return ApplicationUtils.getProperty(key);
return EnvUtil.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return ApplicationUtils.getProperty(key, defaultValue);
return EnvUtil.getProperty(key, defaultValue);
}
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ApplicationUtils.injectEnvironment(configurableApplicationContext.getEnvironment());
loadSetting();
}
}

View File

@ -19,7 +19,7 @@ package com.alibaba.nacos.config.server.model;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.consistency.IdGenerator;
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;
@ -28,7 +28,7 @@ public class ConfigInfoTest {
@Test
public void testPrecisionIssue() throws Exception {
ApplicationUtils.injectEnvironment(new StandardEnvironment());
EnvUtil.setEnvironment(new StandardEnvironment());
IdGenerator generator = new SnowFlowerIdGenerator();
long expected = generator.nextId();
ConfigInfo configInfo = new ConfigInfo();

View File

@ -21,7 +21,7 @@ import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
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;
import org.junit.Assert;
import org.junit.Test;
@ -49,7 +49,7 @@ public class ConfigChangePublisherTest {
});
// nacos is standalone mode and use embedded storage
ApplicationUtils.setIsStandalone(true);
EnvUtil.setIsStandalone(true);
PropertyUtil.setEmbeddedStorage(true);
ConfigChangePublisher
@ -59,7 +59,7 @@ public class ConfigChangePublisherTest {
reference.set(null);
// nacos is standalone mode and use external storage
ApplicationUtils.setIsStandalone(true);
EnvUtil.setIsStandalone(true);
PropertyUtil.setEmbeddedStorage(false);
ConfigChangePublisher
.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis()));
@ -68,7 +68,7 @@ public class ConfigChangePublisherTest {
reference.set(null);
// nacos is cluster mode and use embedded storage
ApplicationUtils.setIsStandalone(false);
EnvUtil.setIsStandalone(false);
PropertyUtil.setEmbeddedStorage(true);
ConfigChangePublisher
.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis()));
@ -77,7 +77,7 @@ public class ConfigChangePublisherTest {
reference.set(null);
// nacos is cluster mode and use external storage
ApplicationUtils.setIsStandalone(false);
EnvUtil.setIsStandalone(false);
PropertyUtil.setEmbeddedStorage(false);
ConfigChangePublisher
.notifyConfigChange(new ConfigDataChangeEvent("chuntaojun", "chuntaojun", System.currentTimeMillis()));

View File

@ -308,7 +308,7 @@ class NameSpace extends React.Component {
<div style={{ textAlign: 'right', marginBottom: 10 }}>
<Button
type="primary"
style={{ marginRight: 0, marginTop: 10 }}
style={{ marginRight: 20, marginTop: 10 }}
onClick={this.addNameSpace.bind(this)}
>
{namespaceAdd}

View File

@ -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<String, String> 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);

View File

@ -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);
}

View File

@ -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<Class<? extends ResourceParser>, 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;
}
}

View File

@ -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<Member>, 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() {

View File

@ -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));
}

View File

@ -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<WebServerInitial
public ServerMemberManager(ServletContext servletContext) throws Exception {
this.serverList = new ConcurrentSkipListMap<>();
ApplicationUtils.setContextPath(servletContext.getContextPath());
EnvUtil.setContextPath(servletContext.getContextPath());
MemberUtils.setManager(this);
init();
@ -132,7 +132,7 @@ public class ServerMemberManager implements ApplicationListener<WebServerInitial
protected void init() throws NacosException {
Loggers.CORE.info("Nacos-related cluster resource initialization");
this.port = ApplicationUtils.getProperty("server.port", Integer.class, 8848);
this.port = EnvUtil.getProperty("server.port", Integer.class, 8848);
this.localAddress = InetUtils.getSelfIP() + ":" + port;
this.self = MemberUtils.singleParse(this.localAddress);
this.self.setExtendVal(MemberMetaDataConstants.VERSION, VersionUtils.version);
@ -166,7 +166,7 @@ public class ServerMemberManager implements ApplicationListener<WebServerInitial
private void registerClusterEvent() {
// Register node change events
NotifyCenter.registerToPublisher(MembersChangeEvent.class,
ApplicationUtils.getProperty("nacos.member-change-event.queue.size", Integer.class, 128));
EnvUtil.getProperty("nacos.member-change-event.queue.size", Integer.class, 128));
// The address information of this node needs to be dynamically modified
// when registering the IP change of this node
@ -175,7 +175,7 @@ public class ServerMemberManager implements ApplicationListener<WebServerInitial
public void onEvent(InetUtils.IPChangeEvent event) {
String newAddress = event.getNewIP() + ":" + port;
ServerMemberManager.this.localAddress = newAddress;
ApplicationUtils.setLocalAddress(localAddress);
EnvUtil.setLocalAddress(localAddress);
Member self = ServerMemberManager.this.self;
self.setIp(event.getNewIP());
@ -381,11 +381,11 @@ public class ServerMemberManager implements ApplicationListener<WebServerInitial
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
getSelf().setState(NodeState.UP);
if (!ApplicationUtils.getStandaloneMode()) {
if (!EnvUtil.getStandaloneMode()) {
GlobalExecutor.scheduleByCommon(this.infoReportTask, 5_000L);
}
ApplicationUtils.setPort(event.getWebServer().getPort());
ApplicationUtils.setLocalAddress(this.localAddress);
EnvUtil.setPort(event.getWebServer().getPort());
EnvUtil.setLocalAddress(this.localAddress);
Loggers.CLUSTER.info("This node is ready to provide external services");
}
@ -453,7 +453,7 @@ public class ServerMemberManager implements ApplicationListener<WebServerInitial
Loggers.CLUSTER.debug("report the metadata to the node : {}", target.getAddress());
final String url = HttpUtils
.buildUrl(false, target.getAddress(), ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT,
.buildUrl(false, target.getAddress(), EnvUtil.getContextPath(), Commons.NACOS_CORE_CONTEXT,
"/cluster/report");
try {

View File

@ -28,7 +28,7 @@ import com.alibaba.nacos.core.cluster.MemberUtils;
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.utils.ApplicationUtils;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.Reader;
@ -69,7 +69,7 @@ public class AddressServerMemberLookup extends AbstractMemberLookup {
@Override
public void start() throws NacosException {
if (start.compareAndSet(false, true)) {
this.maxFailCount = Integer.parseInt(ApplicationUtils.getProperty("maxHealthCheckFailCount", "12"));
this.maxFailCount = Integer.parseInt(EnvUtil.getProperty("maxHealthCheckFailCount", "12"));
initAddressSys();
run();
}
@ -78,19 +78,19 @@ public class AddressServerMemberLookup extends AbstractMemberLookup {
private void initAddressSys() {
String envDomainName = System.getenv("address_server_domain");
if (StringUtils.isBlank(envDomainName)) {
domainName = ApplicationUtils.getProperty("address.server.domain", "jmenv.tbsite.net");
domainName = EnvUtil.getProperty("address.server.domain", "jmenv.tbsite.net");
} else {
domainName = envDomainName;
}
String envAddressPort = System.getenv("address_server_port");
if (StringUtils.isBlank(envAddressPort)) {
addressPort = ApplicationUtils.getProperty("address.server.port", "8080");
addressPort = EnvUtil.getProperty("address.server.port", "8080");
} else {
addressPort = envAddressPort;
}
String envAddressUrl = System.getenv("address_server_url");
if (StringUtils.isBlank(envAddressUrl)) {
addressUrl = ApplicationUtils.getProperty("address.server.url", ApplicationUtils.getContextPath() + "/" + "serverlist");
addressUrl = EnvUtil.getProperty("address.server.url", EnvUtil.getContextPath() + "/" + "serverlist");
} else {
addressUrl = envAddressUrl;
}
@ -107,7 +107,7 @@ public class AddressServerMemberLookup extends AbstractMemberLookup {
// Repeat three times, successfully jump out
boolean success = false;
Throwable ex = null;
int maxRetry = ApplicationUtils.getProperty("nacos.core.address-server.retry", Integer.class, 5);
int maxRetry = EnvUtil.getProperty("nacos.core.address-server.retry", Integer.class, 5);
for (int i = 0; i < maxRetry; i++) {
try {
syncFromAddressUrl();
@ -147,7 +147,7 @@ public class AddressServerMemberLookup extends AbstractMemberLookup {
isAddressServerHealth = true;
Reader reader = new StringReader(result.getData());
try {
afterLookup(MemberUtils.readServerConf(ApplicationUtils.analyzeClusterConf(reader)));
afterLookup(MemberUtils.readServerConf(EnvUtil.analyzeClusterConf(reader)));
} catch (Throwable e) {
Loggers.CLUSTER.error("[serverlist] exception for analyzeClusterConf, error : {}",
ExceptionUtil.getAllExceptionMsg(e));

View File

@ -20,11 +20,11 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.core.cluster.AbstractMemberLookup;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberUtils;
import com.alibaba.nacos.sys.env.EnvUtil;
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.core.utils.Loggers;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
@ -58,7 +58,7 @@ public class FileConfigMemberLookup extends AbstractMemberLookup {
// Use the inotify mechanism to monitor file changes and automatically
// trigger the reading of cluster.conf
try {
WatchFileCenter.registerWatcher(ApplicationUtils.getConfFilePath(), watcher);
WatchFileCenter.registerWatcher(EnvUtil.getConfPath(), watcher);
} catch (Throwable e) {
Loggers.CLUSTER.error("An exception occurred in the launch file monitor : {}", e.getMessage());
}
@ -67,13 +67,13 @@ public class FileConfigMemberLookup extends AbstractMemberLookup {
@Override
public void destroy() throws NacosException {
WatchFileCenter.deregisterWatcher(ApplicationUtils.getConfFilePath(), watcher);
WatchFileCenter.deregisterWatcher(EnvUtil.getConfPath(), watcher);
}
private void readClusterConfFromDisk() {
Collection<Member> tmpMembers = new ArrayList<>();
try {
List<String> tmp = ApplicationUtils.readClusterConf();
List<String> tmp = EnvUtil.readClusterConf();
tmpMembers = MemberUtils.readServerConf(tmp);
} catch (Throwable e) {
Loggers.CLUSTER

View File

@ -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;

View File

@ -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)));
}
}

View File

@ -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<RequestMappingInfo> requestMappingInfos = urlLookup.get(urlKey);
if (CollectionUtils.isEmpty(requestMappingInfos)) {
return null;

View File

@ -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 <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 0.2.2
*/
public class SpringApplicationRunListener implements org.springframework.boot.SpringApplicationRunListener, Ordered {
private final SpringApplication application;
private final String[] args;
private List<NacosApplicationListener> 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;
}
}

View File

@ -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,7 +46,6 @@ 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);
@ -54,7 +53,7 @@ public class StandaloneProfileApplicationListener
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());
}
}

View File

@ -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<String>() {
@Override

View File

@ -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;
}

View File

@ -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;

View File

@ -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();

View File

@ -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";

View File

@ -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'");
}

View File

@ -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 <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @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;
}
}

View File

@ -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);
}

View File

@ -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 <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @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<String> 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<String> 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);
}
}
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");
}
}

View File

@ -263,7 +263,7 @@
</springProfile>
<logger name="com.alibaba.nacos.core.code.StartingSpringApplicationRunListener">
<logger name="com.alibaba.nacos.core.listener.StartingApplicationListener">
<appender-ref ref="CONSOLE"/>
<level value="INFO"/>
</logger>

View File

@ -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
com.alibaba.nacos.core.code.SpringApplicationRunListener

View File

@ -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();
}

View File

@ -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());

View File

@ -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

View File

@ -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<String> instanceList = ApplicationUtils.readClusterConf();
List<String> instanceList = EnvUtil.readClusterConf();
Assert.assertEquals(instanceList.get(0), "192.168.1.2:8848");
Assert.assertEquals(instanceList.get(1), "192.168.1.3");
}

View File

@ -681,7 +681,7 @@
</logger>
</springProfile>
<logger name="com.alibaba.nacos.core.code.StartingSpringApplicationRunListener">
<logger name="com.alibaba.nacos.core.listener.StartingApplicationListener">
<appender-ref ref="CONSOLE"/>
<level value="INFO"/>
</logger>

View File

@ -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<Member> 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;
}

View File

@ -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<Member> 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;
}

View File

@ -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;
}
}

View File

@ -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 <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
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<byte[]> keys = serializer
.deserialize(request.getData().toByteArray(), TypeUtils.parameterize(List.class, byte[].class));
final Lock lock = readLock;
lock.lock();
try {
final Map<byte[], byte[]> 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<byte[]> keys = request.getKeys();
final List<byte[]> 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<SnapshotOperation> 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);
}
}
}

View File

@ -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 <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@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<byte[]> keys = serializer
.deserialize(request.getData().toByteArray(), TypeUtils.parameterize(List.class, byte[].class));
final Lock lock = readLock;
lock.lock();
try {
final Map<byte[], byte[]> 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<byte[]> keys = request.getKeys();
final List<byte[]> 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<SnapshotOperation> 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);
}
}
}

View File

@ -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 <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@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<byte[]> 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<byte[]> 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;
}
}

View File

@ -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();
}
}

View File

@ -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) {

View File

@ -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);
}
}

View File

@ -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());
}

View File

@ -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<String, String> 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<String> result = HttpClient.httpGet(url, null, params);
if (!result.ok()) {
@ -68,9 +68,9 @@ public class RaftProxy {
public void proxy(String server, String api, Map<String, String> 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<String> 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<String> result = HttpClient.httpPostLarge(url, headers, content);
if (!result.ok()) {

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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<String> 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<String> 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();
}
}

View File

@ -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<String> result = HttpClient.httpGet(
"http://" + server.getAddress() + ApplicationUtils.getContextPath()
"http://" + server.getAddress() + EnvUtil.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + SUBSCRIBER_ON_SYNC_URL, new ArrayList<>(),
paramValues);

View File

@ -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:

View File

@ -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) {

View File

@ -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)

View File

@ -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<String>() {
@Override
public void onReceive(RestResult<String> 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<String, String> params = new HashMap<>(8);
params.put("keys", StringUtils.join(keys, ","));
RestResult<String> 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<String, String> params = new HashMap<>(8);
RestResult<String> 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<String> 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<String> 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<String> 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<String> 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) {

View File

@ -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();
}
}

View File

@ -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";
}

View File

@ -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);

View File

@ -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";

View File

@ -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";

View File

@ -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) {

View File

@ -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);
}

View File

@ -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

View File

@ -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

View File

@ -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;

View File

@ -166,8 +166,8 @@
<tomcat-embed-jasper.version>9.0.37</tomcat-embed-jasper.version>
<truth.version>0.30</truth.version>
<HikariCP.version>3.4.2</HikariCP.version>
<jraft-core.version>1.3.2</jraft-core.version>
<rpc-grpc-impl.version>1.3.2</rpc-grpc-impl.version>
<jraft-core.version>1.3.5</jraft-core.version>
<rpc-grpc-impl.version>1.3.5</rpc-grpc-impl.version>
</properties>
<!-- == -->
<!-- =========================================================Build plugins================================================ -->

View File

@ -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);
}

Some files were not shown because too many files have changed in this diff Show More