diff --git a/client/src/main/java/com/alibaba/nacos/client/logging/AbstractNacosLogging.java b/client/src/main/java/com/alibaba/nacos/client/logging/AbstractNacosLogging.java index 4d5a78db6..fa7427748 100644 --- a/client/src/main/java/com/alibaba/nacos/client/logging/AbstractNacosLogging.java +++ b/client/src/main/java/com/alibaba/nacos/client/logging/AbstractNacosLogging.java @@ -19,6 +19,8 @@ package com.alibaba.nacos.client.logging; import com.alibaba.nacos.common.utils.ConvertUtils; import com.alibaba.nacos.common.utils.StringUtils; +import java.io.File; + /** * Abstract nacos logging. * @@ -31,13 +33,13 @@ public abstract class AbstractNacosLogging { private static final String NACOS_LOGGING_DEFAULT_CONFIG_ENABLED_PROPERTY = "nacos.logging.default.config.enabled"; - private static final String NACOS_LOGGING_PATH_PROPERTY = "nacos.logging.path"; + private static final String NACOS_LOGGING_PATH_PROPERTY = "JM.LOG.PATH"; static { String loggingPath = System.getProperty(NACOS_LOGGING_PATH_PROPERTY); if (StringUtils.isBlank(loggingPath)) { String userHome = System.getProperty("user.home"); - System.setProperty(NACOS_LOGGING_PATH_PROPERTY, userHome + "/logs/nacos"); + System.setProperty(NACOS_LOGGING_PATH_PROPERTY, userHome + File.separator + "logs"); } } diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java index 19ec45d4d..0ba34aa64 100644 --- a/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java +++ b/client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java @@ -39,6 +39,7 @@ import com.alibaba.nacos.client.utils.ValidatorUtils; import com.alibaba.nacos.common.utils.ConvertUtils; import com.alibaba.nacos.common.utils.StringUtils; +import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -151,9 +152,13 @@ public class NacosNamingService implements NamingService { } private void initCacheDir() { - cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir"); - if (StringUtils.isEmpty(cacheDir)) { - cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace; + String jmSnapshotPath = System.getProperty("JM.SNAPSHOT.PATH"); + if (!StringUtils.isBlank(jmSnapshotPath)) { + cacheDir = jmSnapshotPath + File.separator + "nacos" + File.separator + "naming" + + File.separator + namespace; + } else { + cacheDir = System.getProperty("user.home") + File.separator + "nacos" + File.separator + "naming" + + File.separator + namespace; } } diff --git a/client/src/main/resources/nacos-log4j2.xml b/client/src/main/resources/nacos-log4j2.xml index bf325e9ea..4c431c439 100644 --- a/client/src/main/resources/nacos-log4j2.xml +++ b/client/src/main/resources/nacos-log4j2.xml @@ -17,8 +17,8 @@ - + %d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n @@ -31,8 +31,8 @@ - + %d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n diff --git a/client/src/main/resources/nacos-logback.xml b/client/src/main/resources/nacos-logback.xml index eb5589632..237700a1e 100644 --- a/client/src/main/resources/nacos-logback.xml +++ b/client/src/main/resources/nacos-logback.xml @@ -19,10 +19,10 @@ nacos - ${nacos.logging.path}/config.log + ${JM.LOG.PATH}/nacos/config.log - ${nacos.logging.path}/config.log.%i + ${JM.LOG.PATH}/nacos/config.log.%i ${JM.LOG.RETAIN.COUNT:-7} @@ -36,10 +36,10 @@ - ${nacos.logging.path}/naming.log + ${JM.LOG.PATH}/nacos/naming.log - ${nacos.logging.path}/naming.log.%i + ${JM.LOG.PATH}/nacos/naming.log.%i ${JM.LOG.RETAIN.COUNT:-7} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java index 90d42a3bd..95c775d05 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/ConfigController.java @@ -43,6 +43,7 @@ import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.config.server.utils.MD5Util; import com.alibaba.nacos.config.server.utils.ParamUtils; import com.alibaba.nacos.config.server.utils.RequestUtil; +import com.alibaba.nacos.config.server.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; @@ -90,8 +91,6 @@ public class ConfigController { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigController.class); - private static final String NAMESPACE_PUBLIC_KEY = "public"; - private static final String EXPORT_CONFIG_FILE_NAME = "nacos_config_export_"; private static final String EXPORT_CONFIG_FILE_NAME_EXT = ".zip"; @@ -175,7 +174,7 @@ public class ConfigController { .notifyConfigChange(new ConfigDataChangeEvent(true, dataId, group, tenant, time.getTime())); } ConfigTraceService - .logPersistenceEvent(dataId, group, tenant, requestIpApp, time.getTime(), InetUtils.getSelfIp(), + .logPersistenceEvent(dataId, group, tenant, requestIpApp, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_PUB, content); return true; } @@ -196,7 +195,7 @@ public class ConfigController { throws IOException, ServletException, NacosException { // check tenant ParamUtils.checkTenant(tenant); - tenant = processTenant(tenant); + tenant = NamespaceUtil.processNamespaceParameter(tenant); // check params ParamUtils.checkParam(dataId, group, "datumId", "content"); ParamUtils.checkParam(tag); @@ -469,7 +468,7 @@ public class ConfigController { @RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant, @RequestParam(value = "ids", required = false) List ids) { ids.removeAll(Collections.singleton(null)); - tenant = processTenant(tenant); + tenant = NamespaceUtil.processNamespaceParameter(tenant); List dataList = persistService.findAllConfigInfo4Export(dataId, group, tenant, appName, ids); List zipItemList = new ArrayList<>(); StringBuilder metaData = null; @@ -527,12 +526,12 @@ public class ConfigController { return ResultBuilder.buildResult(ResultCodeEnum.DATA_EMPTY, failedData); } - if (StringUtils.isNotBlank(namespace)) { - if (persistService.tenantInfoCountByTenantId(namespace) <= 0) { - failedData.put("succCount", 0); - return ResultBuilder.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, 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); } + List configInfoList = null; try { ZipUtils.UnZipResult unziped = ZipUtils.unzip(file.getBytes()); @@ -598,7 +597,7 @@ public class ConfigController { configInfo.getTenant(), time.getTime())); ConfigTraceService .logPersistenceEvent(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), - requestIpApp, time.getTime(), InetUtils.getSelfIp(), + requestIpApp, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent()); } return ResultBuilder.buildSuccessResult("导入成功", saveResult); @@ -628,10 +627,9 @@ public class ConfigController { return ResultBuilder.buildResult(ResultCodeEnum.NO_SELECTED_CONFIG, failedData); } configBeansList.removeAll(Collections.singleton(null)); - - if (NAMESPACE_PUBLIC_KEY.equalsIgnoreCase(namespace)) { - namespace = ""; - } else if (persistService.tenantInfoCountByTenantId(namespace) <= 0) { + + namespace = NamespaceUtil.processNamespaceParameter(namespace); + if (StringUtils.isNotBlank(namespace) && persistService.tenantInfoCountByTenantId(namespace) <= 0) { failedData.put("succCount", 0); return ResultBuilder.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData); } @@ -684,17 +682,10 @@ public class ConfigController { configInfo.getTenant(), time.getTime())); ConfigTraceService .logPersistenceEvent(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), - requestIpApp, time.getTime(), InetUtils.getSelfIp(), + requestIpApp, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent()); } return ResultBuilder.buildSuccessResult("Clone Completed Successfully", saveResult); } - private String processTenant(String tenant) { - if (StringUtils.isEmpty(tenant) || NAMESPACE_PUBLIC_KEY.equalsIgnoreCase(tenant)) { - return ""; - } - return tenant; - } - } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java b/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java index 10870b977..1fa35f643 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/controller/HealthController.java @@ -69,7 +69,7 @@ public class HealthController { sb.append("master db (").append(dbStatus.split(":")[1]).append(") down. "); } if (!memberManager.isInIpList()) { - sb.append("server ip ").append(InetUtils.getSelfIp()) + sb.append("server ip ").append(InetUtils.getSelfIP()) .append(" is not in the serverList of address server. "); } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/model/app/ApplicationInfo.java b/config/src/main/java/com/alibaba/nacos/config/server/model/app/ApplicationInfo.java index 0100068ad..acc318d7b 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/model/app/ApplicationInfo.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/model/app/ApplicationInfo.java @@ -102,7 +102,7 @@ public class ApplicationInfo { */ public boolean canCurrentServerOwnTheLock() { boolean currentOwnerIsMe = - subInfoCollectLockOwner == null || InetUtils.getSelfIp().equals(subInfoCollectLockOwner); + subInfoCollectLockOwner == null || InetUtils.getSelfIP().equals(subInfoCollectLockOwner); if (currentOwnerIsMe) { return true; @@ -115,7 +115,7 @@ public class ApplicationInfo { } public String currentServer() { - return InetUtils.getSelfIp(); + return InetUtils.getSelfIP(); } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java index f5d14285e..4470269db 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/dump/DumpService.java @@ -419,7 +419,7 @@ public abstract class DumpService { } } else { // remove config info - persistService.removeConfigInfo(dataId, group, tenant, InetUtils.getSelfIp(), null); + persistService.removeConfigInfo(dataId, group, tenant, InetUtils.getSelfIP(), null); LOGGER.warn( "[merge-delete] delete config info because no datum. dataId=" + dataId + ", groupId=" + group); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java index ef34f1d01..e08a56020 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeDatumService.java @@ -106,7 +106,7 @@ public class MergeDatumService { return; } for (ConfigInfoChanged item : persistService.findAllAggrGroup()) { - addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), InetUtils.getSelfIp()); + addMergeTask(item.getDataId(), item.getGroup(), item.getTenant(), InetUtils.getSelfIP()); } } @@ -163,7 +163,7 @@ public class MergeDatumService { ContentUtils.truncateContent(cf.getContent())); } else { // remove - persistService.removeConfigInfo(dataId, group, tenant, InetUtils.getSelfIp(), null); + persistService.removeConfigInfo(dataId, group, tenant, InetUtils.getSelfIP(), null); LOGGER.warn("[merge-delete] delete config info because no datum. dataId=" + dataId + ", groupId=" + group); } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java index 063a244f8..f2f14808b 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/merge/MergeTaskProcessor.java @@ -84,7 +84,7 @@ public class MergeTaskProcessor implements NacosTaskProcessor { ContentUtils.truncateContent(cf.getContent())); ConfigTraceService - .logPersistenceEvent(dataId, group, tenant, null, time.getTime(), InetUtils.getSelfIp(), + .logPersistenceEvent(dataId, group, tenant, null, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_MERGE, cf.getContent()); } else { // remove @@ -98,7 +98,7 @@ public class MergeTaskProcessor implements NacosTaskProcessor { "[merge-delete] delete config info because no datum. dataId=" + dataId + ", groupId=" + group); ConfigTraceService - .logPersistenceEvent(dataId, group, tenant, null, time.getTime(), InetUtils.getSelfIp(), + .logPersistenceEvent(dataId, group, tenant, null, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_REMOVE, null); } NotifyCenter.publishEvent(new ConfigDataChangeEvent(false, dataId, group, tenant, tag, time.getTime())); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java index 102da8fc2..1f26e6afe 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java @@ -127,14 +127,14 @@ public class AsyncNotifyService { if (unHealthNeedDelay) { // target ip is unhealthy, then put it in the notification list ConfigTraceService.logNotifyEvent(task.getDataId(), task.getGroup(), task.getTenant(), null, - task.getLastModified(), InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_UNHEALTH, + task.getLastModified(), InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_UNHEALTH, 0, task.target); // get delay time and set fail count to the task asyncTaskExecute(task); } else { Header header = Header.newInstance(); header.addParam(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, String.valueOf(task.getLastModified())); - header.addParam(NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIp()); + header.addParam(NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIP()); if (task.isBeta) { header.addParam("isBeta", "true"); } @@ -168,13 +168,13 @@ public class AsyncNotifyService { if (result.ok()) { ConfigTraceService.logNotifyEvent(task.getDataId(), task.getGroup(), task.getTenant(), null, - task.getLastModified(), InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_OK, delayed, + task.getLastModified(), InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_OK, delayed, task.target); } else { LOGGER.error("[notify-error] target:{} dataId:{} group:{} ts:{} code:{}", task.target, task.getDataId(), task.getGroup(), task.getLastModified(), result.getCode()); ConfigTraceService.logNotifyEvent(task.getDataId(), task.getGroup(), task.getTenant(), null, - task.getLastModified(), InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_ERROR, delayed, + task.getLastModified(), InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_ERROR, delayed, task.target); //get delay time and set fail count to the task @@ -196,7 +196,7 @@ public class AsyncNotifyService { task.getGroup(), task.getLastModified(), ex.toString()); ConfigTraceService .logNotifyEvent(task.getDataId(), task.getGroup(), task.getTenant(), null, task.getLastModified(), - InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_EXCEPTION, delayed, task.target); + InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_EXCEPTION, delayed, task.target); //get delay time and set fail count to the task asyncTaskExecute(task); diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java index 79bdd56c4..02282693f 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java @@ -73,13 +73,13 @@ public class NotifyTaskProcessor implements NacosTaskProcessor { */ List headers = Arrays .asList(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, String.valueOf(lastModified), - NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIp()); + NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIP()); String urlString = MessageFormat .format(URL_PATTERN, serverIp, ApplicationUtils.getContextPath(), dataId, group); RestResult result = NotifyService.invokeURL(urlString, headers, Constants.ENCODE); if (result.ok()) { - ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIp(), + ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_OK, delayed, serverIp); MetricsMonitor.getNotifyRtTimer().record(delayed, TimeUnit.MILLISECONDS); @@ -89,7 +89,7 @@ public class NotifyTaskProcessor implements NacosTaskProcessor { MetricsMonitor.getConfigNotifyException().increment(); LOGGER.error("[notify-error] {}, {}, to {}, result {}", new Object[] {dataId, group, serverIp, result.getCode()}); - ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIp(), + ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_ERROR, delayed, serverIp); return false; } @@ -97,7 +97,7 @@ public class NotifyTaskProcessor implements NacosTaskProcessor { MetricsMonitor.getConfigNotifyException().increment(); LOGGER.error("[notify-exception] " + dataId + ", " + group + ", to " + serverIp + ", " + e.toString()); LOGGER.debug("[notify-exception] " + dataId + ", " + group + ", to " + serverIp + ", " + e.toString(), e); - ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIp(), + ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIP(), ConfigTraceService.NOTIFY_EVENT_EXCEPTION, delayed, serverIp); return false; } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePersistServiceImpl.java b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePersistServiceImpl.java index 22c9a6ea7..276b61afe 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePersistServiceImpl.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalStoragePersistServiceImpl.java @@ -2292,7 +2292,7 @@ public class ExternalStoragePersistServiceImpl implements PersistService { .queryForObject(sqlFetchRows, new Object[] {nid}, HISTORY_DETAIL_ROW_MAPPER); return historyInfo; } catch (DataAccessException e) { - LogUtil.FATAL_LOG.error("[list-config-history] error, nid:{}", new Object[] {nid}, e); + LogUtil.FATAL_LOG.error("[detail-config-history] error, nid:{}", new Object[] {nid}, e); throw e; } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java index d1ae51f42..e36f82f4b 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/trace/ConfigTraceService.java @@ -87,7 +87,7 @@ public class ConfigTraceService { // (md5) String md5 = content == null ? null : MD5Utils.md5Hex(content, Constants.ENCODE); - LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIp(), dataId, group, tenant, + LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, handleIp, "persist", type, -1, md5); } @@ -116,7 +116,7 @@ public class ConfigTraceService { } //localIp | dataid | group | tenant | requestIpAppName | ts | handleIp | event | type | [delayed] | ext // (targetIp) - LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIp(), dataId, group, tenant, + LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, handleIp, "notify", type, delayed, targetIp); } @@ -143,7 +143,7 @@ public class ConfigTraceService { tenant = null; } //localIp | dataid | group | tenant | requestIpAppName | ts | handleIp | event | type | [delayed] | length - LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIp(), dataId, group, tenant, + LogUtil.TRACE_LOG.info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, handleIp, "dump", type, delayed, length); } @@ -169,7 +169,7 @@ public class ConfigTraceService { } //localIp | dataid | group | tenant | requestIpAppName | ts | handleIp | event | type | [delayed = -1] LogUtil.TRACE_LOG - .info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIp(), dataId, group, tenant, requestIpAppName, + .info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, handleIp, "dump-all", type, -1); } @@ -196,7 +196,7 @@ public class ConfigTraceService { } //localIp | dataid | group | tenant| requestIpAppName| ts | event | type | [delayed] | ext(clientIp) LogUtil.TRACE_LOG - .info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIp(), dataId, group, tenant, requestIpAppName, + .info("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", InetUtils.getSelfIP(), dataId, group, tenant, requestIpAppName, ts, "pull", type, delayed, clientIp); } } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java new file mode 100644 index 000000000..2fc0277ef --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/NamespaceUtil.java @@ -0,0 +1,47 @@ +/* + * 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.utils; + +import org.apache.commons.lang3.StringUtils; + +/** + * namespace(tenant) util. + * Because config and naming treat namespace(tenant) differently, + * this tool class can only be used by the config module. + * @author klw(213539@qq.com) + * @date 2020/10/12 17:56 + */ +public class NamespaceUtil { + + private static final String NAMESPACE_PUBLIC_KEY = "public"; + + private static final String NAMESPACE_NULL_KEY = "null"; + + /** + * Treat the namespace(tenant) parameters with values of "public" and "null" as an empty string. + * @param tenant namespace(tenant) id + * @return java.lang.String A namespace(tenant) string processed + */ + public static String processNamespaceParameter(String tenant) { + if (StringUtils.isBlank(tenant) || NAMESPACE_PUBLIC_KEY.equalsIgnoreCase(tenant) || NAMESPACE_NULL_KEY + .equalsIgnoreCase(tenant)) { + return ""; + } + return tenant.trim(); + } + +} diff --git a/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java b/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java new file mode 100644 index 000000000..16bbd700d --- /dev/null +++ b/config/src/test/java/com/alibaba/nacos/config/server/utils/NamespaceUtilTest.java @@ -0,0 +1,47 @@ +/* + * 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.utils; + +import org.junit.Assert; +import org.junit.Test; + +/** + * test NamespaceUtil. + * + * @author klw(213539 @ qq.com) + * @date 2020/10/13 9:46 + */ +public class NamespaceUtilTest { + + @Test + public void testProcessTenantParameter() { + String strPublic = "public"; + String strNull = "null"; + String strEmpty = ""; + String strAbc = "abc"; + String strdef123 = "def123"; + String strAbcHasSpace = " abc "; + Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strPublic)); + Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strNull)); + Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(strEmpty)); + Assert.assertEquals(strEmpty, NamespaceUtil.processNamespaceParameter(null)); + Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbc)); + Assert.assertEquals(strdef123, NamespaceUtil.processNamespaceParameter(strdef123)); + Assert.assertEquals(strAbc, NamespaceUtil.processNamespaceParameter(strAbcHasSpace)); + } + +} diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java index 1d93db643..82343d1c3 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java @@ -38,9 +38,5 @@ public class MemberMetaDataConstants { public static final String VERSION = "version"; - public static final String[] META_KEY_LIST = new String[] {SITE_KEY, AD_WEIGHT, RAFT_PORT, WEIGHT, - LAST_REFRESH_TIME, VERSION}; - - public static final String[] META_KEY_LIST_WITHOUT_LAST_REFRESH_TIME = new String[] {SITE_KEY, AD_WEIGHT, RAFT_PORT, - WEIGHT, VERSION}; + public static final String[] BASIC_META_KEYS = new String[] {SITE_KEY, AD_WEIGHT, RAFT_PORT, WEIGHT, VERSION}; } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java index 02d2fbf10..f7eb4790c 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java @@ -28,6 +28,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; @@ -236,40 +237,40 @@ public class MemberUtils { } /** - * Judge whether two member is full equals. + * Judge whether basic info has changed. * * @param actual actual member * @param expected expected member * @return true if all content is same, otherwise false */ - public static boolean fullEquals(Member actual, Member expected) { + public static boolean isBasicInfoChanged(Member actual, Member expected) { if (null == expected) { return null == actual; } if (!expected.getIp().equals(actual.getIp())) { - return false; + return true; } if (expected.getPort() != actual.getPort()) { - return false; + return true; } if (!expected.getAddress().equals(actual.getAddress())) { - return false; + return true; } if (!expected.getState().equals(actual.getState())) { - return false; + return true; } - return equalsExtendInfo(expected, actual); + return isBasicInfoChangedInExtendInfo(expected, actual); } - private static boolean equalsExtendInfo(Member expected, Member actual) { - for (String each : MemberMetaDataConstants.META_KEY_LIST_WITHOUT_LAST_REFRESH_TIME) { + private static boolean isBasicInfoChangedInExtendInfo(Member expected, Member actual) { + for (String each : MemberMetaDataConstants.BASIC_META_KEYS) { if (expected.getExtendInfo().containsKey(each) != actual.getExtendInfo().containsKey(each)) { - return false; + return true; } - if (null != expected.getExtendVal(each) && !expected.getExtendVal(each).equals(actual.getExtendVal(each))) { - return false; + if (!Objects.equals(expected.getExtendVal(each), actual.getExtendVal(each))) { + return true; } } - return true; + return false; } } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java b/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java index 0101d2683..5af963296 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java @@ -78,7 +78,8 @@ import java.util.concurrent.ConcurrentSkipListMap; @Component(value = "serverMemberManager") public class ServerMemberManager implements ApplicationListener { - private final NacosAsyncRestTemplate asyncRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(Loggers.CORE); + private final NacosAsyncRestTemplate asyncRestTemplate = HttpClientBeanHolder + .getNacosAsyncRestTemplate(Loggers.CORE); /** * Cluster node list. @@ -131,7 +132,7 @@ public class ServerMemberManager implements ApplicationListener() { @Override public void onEvent(InetUtils.IPChangeEvent event) { - String newAddress = event.getNewIp() + ":" + port; + String newAddress = event.getNewIP() + ":" + port; ServerMemberManager.this.localAddress = newAddress; ApplicationUtils.setLocalAddress(localAddress); - + Member self = ServerMemberManager.this.self; - self.setIp(event.getNewIp()); - - String oldAddress = event.getOldIp() + ":" + port; + self.setIp(event.getNewIP()); + + String oldAddress = event.getOldIP() + ":" + port; ServerMemberManager.this.serverList.remove(oldAddress); ServerMemberManager.this.serverList.put(newAddress, self); @@ -209,10 +210,11 @@ public class ServerMemberManager implements ApplicationListener PREFERRED_NETWORKS = new ArrayList(); @@ -82,55 +83,56 @@ public class InetUtils { Runnable ipAutoRefresh = new Runnable() { @Override public void run() { - String nacosIp = System.getProperty(NACOS_SERVER_IP); - if (StringUtils.isBlank(nacosIp)) { - nacosIp = ApplicationUtils.getProperty(IP_ADDRESS); + String nacosIP = System.getProperty(NACOS_SERVER_IP); + if (StringUtils.isBlank(nacosIP)) { + nacosIP = ApplicationUtils.getProperty(IP_ADDRESS); } - if (!StringUtils.isBlank(nacosIp) && !isIP(nacosIp)) { - throw new RuntimeException("nacos address " + nacosIp + " is not ip"); + boolean illegalIP = !StringUtils.isBlank(nacosIP) && !(isIP(nacosIP) || isDomain(nacosIP)); + if (illegalIP) { + throw new RuntimeException("nacos address " + nacosIP + " is not ip"); } - String tmpSelfIp = nacosIp; - if (StringUtils.isBlank(tmpSelfIp)) { - preferHostnameOverIp = Boolean.getBoolean(SYSTEM_PREFER_HOSTNAME_OVER_IP); + String tmpSelfIP = nacosIP; + if (StringUtils.isBlank(tmpSelfIP)) { + preferHostnameOverIP = Boolean.getBoolean(SYSTEM_PREFER_HOSTNAME_OVER_IP); - if (!preferHostnameOverIp) { - preferHostnameOverIp = Boolean + if (!preferHostnameOverIP) { + preferHostnameOverIP = Boolean .parseBoolean(ApplicationUtils.getProperty(PREFER_HOSTNAME_OVER_IP)); } - if (preferHostnameOverIp) { + if (preferHostnameOverIP) { InetAddress inetAddress; try { inetAddress = InetAddress.getLocalHost(); if (inetAddress.getHostName().equals(inetAddress.getCanonicalHostName())) { - tmpSelfIp = inetAddress.getHostName(); + tmpSelfIP = inetAddress.getHostName(); } else { - tmpSelfIp = inetAddress.getCanonicalHostName(); + tmpSelfIP = inetAddress.getCanonicalHostName(); } } catch (UnknownHostException ignore) { LOG.warn("Unable to retrieve localhost"); } } else { - tmpSelfIp = Objects.requireNonNull(findFirstNonLoopbackAddress()).getHostAddress(); + tmpSelfIP = Objects.requireNonNull(findFirstNonLoopbackAddress()).getHostAddress(); } } - if (!Objects.equals(selfIp, tmpSelfIp) && Objects.nonNull(selfIp)) { + if (!Objects.equals(selfIP, tmpSelfIP) && Objects.nonNull(selfIP)) { IPChangeEvent event = new IPChangeEvent(); - event.setOldIp(selfIp); - event.setNewIp(tmpSelfIp); + event.setOldIP(selfIP); + event.setNewIP(tmpSelfIP); NotifyCenter.publishEvent(event); } - selfIp = tmpSelfIp; + selfIP = tmpSelfIP; } }; ipAutoRefresh.run(); } - public static String getSelfIp() { - return selfIp; + public static String getSelfIP() { + return selfIP; } /** @@ -219,35 +221,50 @@ public class InetUtils { return matcher.matches(); } + /** + * juege str is right domain. + * + * @param str nacosIP + * @return nacosIP is domain + */ + public static boolean isDomain(String str) { + InetSocketAddress address = new InetSocketAddress(str, 0); + boolean unResolved = address.isUnresolved(); + if (unResolved) { + LOG.warn("the domain: '" + str + "' can not be resolved"); + } + return !unResolved; + } + /** * {@link com.alibaba.nacos.core.cluster.ServerMemberManager} is listener. */ @SuppressWarnings({"PMD.ClassNamingShouldBeCamelRule", "checkstyle:AbbreviationAsWordInName"}) public static class IPChangeEvent extends SlowEvent { - private String oldIp; + private String oldIP; - private String newIp; + private String newIP; - public String getOldIp() { - return oldIp; + public String getOldIP() { + return oldIP; } - public void setOldIp(String oldIp) { - this.oldIp = oldIp; + public void setOldIP(String oldIP) { + this.oldIP = oldIP; } - public String getNewIp() { - return newIp; + public String getNewIP() { + return newIP; } - public void setNewIp(String newIp) { - this.newIp = newIp; + public void setNewIP(String newIP) { + this.newIP = newIP; } @Override public String toString() { - return "IPChangeEvent{" + "oldIp='" + oldIp + '\'' + ", newIp='" + newIp + '\'' + '}'; + return "IPChangeEvent{" + "oldIP='" + oldIP + '\'' + ", newIP='" + newIP + '\'' + '}'; } } diff --git a/test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java b/test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java index 6afce7ee6..95e41ce61 100644 --- a/test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/config/ConfigDerbyRaft_DITCase.java @@ -357,7 +357,7 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest { // transfer leader to ip:8807 Map transfer = new HashMap<>(); - transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIp() + ":9847"); + transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9847"); RestResult result = protocol7.execute(transfer); System.out.println(result); Assert.assertTrue(result.ok()); @@ -372,7 +372,7 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest { // transfer leader to ip:8808 transfer = new HashMap<>(); - transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIp() + ":9848"); + transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9848"); result = protocol8.execute(transfer); System.out.println(result); Assert.assertTrue(result.ok()); @@ -387,7 +387,7 @@ public class ConfigDerbyRaft_DITCase extends BaseClusterTest { // transfer leader to ip:8809 transfer = new HashMap<>(); - transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIp() + ":9849"); + transfer.put(JRaftConstants.TRANSFER_LEADER, InetUtils.getSelfIP() + ":9849"); result = protocol9.execute(transfer); System.out.println(result); Assert.assertTrue(result.ok()); diff --git a/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java b/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java index cf1c2fead..def842773 100644 --- a/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java +++ b/test/src/test/java/com/alibaba/nacos/test/core/BaseClusterTest.java @@ -90,7 +90,7 @@ public class BaseClusterTest extends HttpClient4Test { static { System.getProperties().setProperty("nacos.core.auth.enabled", "false"); System.getProperties().setProperty("embeddedStorage", "true"); - String ip = InetUtils.getSelfIp(); + String ip = InetUtils.getSelfIP(); clusterInfo = "nacos.member.list=" + ip + ":8847," + ip + ":8848," + ip + ":8849"; NotifyCenter.registerSubscriber(new Subscriber() { diff --git a/test/src/test/java/com/alibaba/nacos/test/core/InetUtils_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/core/InetUtils_ITCase.java index 1e912809e..f1c520977 100644 --- a/test/src/test/java/com/alibaba/nacos/test/core/InetUtils_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/core/InetUtils_ITCase.java @@ -39,7 +39,7 @@ public class InetUtils_ITCase { static { System.setProperty("nacos.core.inet.auto-refresh", "3"); // For load InetUtils.class - InetUtils.getSelfIp(); + InetUtils.getSelfIP(); } @Test @@ -53,10 +53,10 @@ public class InetUtils_ITCase { Subscriber subscribe = new Subscriber() { @Override public void onEvent(InetUtils.IPChangeEvent event) { - if (Objects.nonNull(event.getOldIp())) { + if (Objects.nonNull(event.getOldIP())) { try { System.out.println(event); - reference.set(event.getNewIp()); + reference.set(event.getNewIP()); } finally { latch.countDown(); @@ -74,7 +74,7 @@ public class InetUtils_ITCase { latch.await(10_000L, TimeUnit.MILLISECONDS); Assert.assertEquals(testIp, reference.get()); - Assert.assertEquals(testIp, InetUtils.getSelfIp()); + Assert.assertEquals(testIp, InetUtils.getSelfIP()); } } diff --git a/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java index 033343c99..08a04c3a1 100644 --- a/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/core/cluster/MemberLookup_ITCase.java @@ -69,7 +69,7 @@ public class MemberLookup_ITCase extends BaseTest { DiskUtils.forceMkdir(Paths.get(path, "conf").toString()); File file = Paths.get(path, "conf", name).toFile(); DiskUtils.touch(file); - String ip = InetUtils.getSelfIp(); + String ip = InetUtils.getSelfIP(); DiskUtils.writeFile(file, (ip + ":8848," + ip + ":8847," + ip + ":8849").getBytes( StandardCharsets.UTF_8), false);