Merge branch 'develop' of https://github.com/alibaba/nacos into develop

This commit is contained in:
chuntaojun 2019-08-13 21:41:30 +08:00
commit 2802247d6c
97 changed files with 9892 additions and 758 deletions

View File

@ -16,7 +16,7 @@
<parent> <parent>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<version>1.1.0</version> <version>1.1.3</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -16,7 +16,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -154,7 +154,7 @@ public @interface NacosProperties {
/** /**
* The placeholder of {@link NacosProperties#ENABLE_REMOTE_SYNC_CONFIG enableRemoteSyncConfig}, the value is <code>"${nacos.enableRemoteSyncConfig:}"</code> * The placeholder of {@link NacosProperties#ENABLE_REMOTE_SYNC_CONFIG enableRemoteSyncConfig}, the value is <code>"${nacos.enableRemoteSyncConfig:}"</code>
*/ */
String ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER = "${" + PREFIX + ENABLE_REMOTE_SYNC_CONFIG + "}"; String ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER = "${" + PREFIX + ENABLE_REMOTE_SYNC_CONFIG + ":}";
/** /**
* The property of "endpoint" * The property of "endpoint"

View File

@ -16,7 +16,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

View File

@ -19,7 +19,6 @@ import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ListView;
@ -35,11 +34,14 @@ import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.CollectionUtils; import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.InitUtils; import com.alibaba.nacos.client.naming.utils.InitUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs; import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.client.utils.*; import com.alibaba.nacos.client.utils.StringUtils;
import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.math.NumberUtils;
import java.util.*; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**

View File

@ -57,7 +57,7 @@ public class BeatReactor {
public void addBeatInfo(String serviceName, BeatInfo beatInfo) { public void addBeatInfo(String serviceName, BeatInfo beatInfo) {
NAMING_LOGGER.info("[BEAT] adding beat: {} to beat map.", beatInfo); NAMING_LOGGER.info("[BEAT] adding beat: {} to beat map.", beatInfo);
dom2Beat.put(buildKey(serviceName, beatInfo.getIp(), beatInfo.getPort()), beatInfo); dom2Beat.put(buildKey(serviceName, beatInfo.getIp(), beatInfo.getPort()), beatInfo);
executorService.schedule(new BeatTask(beatInfo), 0, TimeUnit.MILLISECONDS); executorService.schedule(new BeatTask(beatInfo), beatInfo.getPeriod(), TimeUnit.MILLISECONDS);
MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size()); MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size());
} }

View File

@ -105,7 +105,10 @@ public class HostReactor {
return oldService; return oldService;
} }
boolean changed = false;
if (oldService != null) { if (oldService != null) {
if (oldService.getLastRefTime() > serviceInfo.getLastRefTime()) { if (oldService.getLastRefTime() > serviceInfo.getLastRefTime()) {
NAMING_LOGGER.warn("out of date data received, old-t: " + oldService.getLastRefTime() NAMING_LOGGER.warn("out of date data received, old-t: " + oldService.getLastRefTime()
+ ", new-t: " + serviceInfo.getLastRefTime()); + ", new-t: " + serviceInfo.getLastRefTime());
@ -157,18 +160,21 @@ public class HostReactor {
} }
if (newHosts.size() > 0) { if (newHosts.size() > 0) {
changed = true;
NAMING_LOGGER.info("new ips(" + newHosts.size() + ") service: " NAMING_LOGGER.info("new ips(" + newHosts.size() + ") service: "
+ serviceInfo.getName() + " -> " + JSON.toJSONString(newHosts)); + serviceInfo.getKey() + " -> " + JSON.toJSONString(newHosts));
} }
if (remvHosts.size() > 0) { if (remvHosts.size() > 0) {
changed = true;
NAMING_LOGGER.info("removed ips(" + remvHosts.size() + ") service: " NAMING_LOGGER.info("removed ips(" + remvHosts.size() + ") service: "
+ serviceInfo.getName() + " -> " + JSON.toJSONString(remvHosts)); + serviceInfo.getKey() + " -> " + JSON.toJSONString(remvHosts));
} }
if (modHosts.size() > 0) { if (modHosts.size() > 0) {
changed = true;
NAMING_LOGGER.info("modified ips(" + modHosts.size() + ") service: " NAMING_LOGGER.info("modified ips(" + modHosts.size() + ") service: "
+ serviceInfo.getName() + " -> " + JSON.toJSONString(modHosts)); + serviceInfo.getKey() + " -> " + JSON.toJSONString(modHosts));
} }
serviceInfo.setJsonFromServer(json); serviceInfo.setJsonFromServer(json);
@ -179,7 +185,8 @@ public class HostReactor {
} }
} else { } else {
NAMING_LOGGER.info("new ips(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getName() + " -> " + JSON changed = true;
NAMING_LOGGER.info("init new ips(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getKey() + " -> " + JSON
.toJSONString(serviceInfo.getHosts())); .toJSONString(serviceInfo.getHosts()));
serviceInfoMap.put(serviceInfo.getKey(), serviceInfo); serviceInfoMap.put(serviceInfo.getKey(), serviceInfo);
eventDispatcher.serviceChanged(serviceInfo); eventDispatcher.serviceChanged(serviceInfo);
@ -189,8 +196,10 @@ public class HostReactor {
MetricsMonitor.getServiceInfoMapSizeMonitor().set(serviceInfoMap.size()); MetricsMonitor.getServiceInfoMapSizeMonitor().set(serviceInfoMap.size());
NAMING_LOGGER.info("current ips:(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getName() + if (changed) {
" -> " + JSON.toJSONString(serviceInfo.getHosts())); NAMING_LOGGER.info("current ips:(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getKey() +
" -> " + JSON.toJSONString(serviceInfo.getHosts()));
}
return serviceInfo; return serviceInfo;
} }
@ -268,6 +277,7 @@ public class HostReactor {
try { try {
String result = serverProxy.queryList(serviceName, clusters, pushReceiver.getUDPPort(), false); String result = serverProxy.queryList(serviceName, clusters, pushReceiver.getUDPPort(), false);
if (StringUtils.isNotEmpty(result)) { if (StringUtils.isNotEmpty(result)) {
processServiceJSON(result); processServiceJSON(result);
} }

View File

@ -32,6 +32,7 @@ import com.alibaba.nacos.client.config.impl.SpasAdapter;
import com.alibaba.nacos.client.monitor.MetricsMonitor; import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.beat.BeatInfo; import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.client.naming.utils.*; import com.alibaba.nacos.client.naming.utils.*;
import com.alibaba.nacos.client.utils.AppNameUtils;
import com.alibaba.nacos.client.utils.StringUtils; import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.client.utils.TemplateUtils; import com.alibaba.nacos.client.utils.TemplateUtils;
import com.alibaba.nacos.common.util.HttpMethod; import com.alibaba.nacos.common.util.HttpMethod;
@ -481,18 +482,17 @@ public class NamingProxy {
private void checkSignature(Map<String, String> params) { private void checkSignature(Map<String, String> params) {
String ak = getAccessKey(); String ak = getAccessKey();
String sk = getSecretKey(); String sk = getSecretKey();
params.put("app", AppNameUtils.getAppName());
if (StringUtils.isEmpty(ak) && StringUtils.isEmpty(sk)) { if (StringUtils.isEmpty(ak) && StringUtils.isEmpty(sk)) {
return; return;
} }
try { try {
String app = System.getProperty("project.name");
String signData = getSignData(params.get("serviceName")); String signData = getSignData(params.get("serviceName"));
String signature = SignUtil.sign(signData, sk); String signature = SignUtil.sign(signData, sk);
params.put("signature", signature); params.put("signature", signature);
params.put("data", signData); params.put("data", signData);
params.put("ak", ak); params.put("ak", ak);
params.put("app", app);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -15,12 +15,14 @@
*/ */
package com.alibaba.nacos.client.naming.utils; package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.common.util.VersionUtils;
/** /**
* @author xuanyin.zy * @author xuanyin.zy
*/ */
public class UtilAndComs { public class UtilAndComs {
public static final String VERSION = "Nacos-Java-Client:v1.1.1"; public static final String VERSION = "Nacos-Java-Client:v" + VersionUtils.VERSION;
public static String WEB_CONTEXT = "/nacos"; public static String WEB_CONTEXT = "/nacos";

View File

@ -23,31 +23,27 @@ import junit.framework.TestSuite;
* Unit test for simple App. * Unit test for simple App.
*/ */
public class AppTest public class AppTest
extends TestCase extends TestCase {
{
/** /**
* Create the test case * Create the test case
* *
* @param testName name of the test case * @param testName name of the test case
*/ */
public AppTest( String testName ) public AppTest(String testName) {
{ super(testName);
super( testName );
} }
/** /**
* @return the suite of tests being tested * @return the suite of tests being tested
*/ */
public static Test suite() public static Test suite() {
{ return new TestSuite(AppTest.class);
return new TestSuite( AppTest.class );
} }
/** /**
* Rigourous Test :-) * Rigourous Test :-)
*/ */
public void testApp() public void testApp() {
{ assertTrue(true);
assertTrue( true );
} }
} }

View File

@ -18,7 +18,7 @@
<parent> <parent>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -15,7 +15,6 @@
*/ */
package com.alibaba.nacos.cmdb.controllers; package com.alibaba.nacos.cmdb.controllers;
import com.alibaba.nacos.cmdb.core.SwitchAndOptions;
import com.alibaba.nacos.cmdb.memory.CmdbProvider; import com.alibaba.nacos.cmdb.memory.CmdbProvider;
import com.alibaba.nacos.cmdb.utils.UtilsAndCommons; import com.alibaba.nacos.cmdb.utils.UtilsAndCommons;
import com.alibaba.nacos.core.utils.WebUtils; import com.alibaba.nacos.core.utils.WebUtils;

View File

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -68,5 +68,14 @@
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>nacos-version.txt</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>

View File

@ -25,13 +25,15 @@ import java.util.Properties;
public class VersionUtils { public class VersionUtils {
public static String VERSION; public static String VERSION;
/**获取当前version*/ /**
* 获取当前version
*/
public static final String VERSION_DEFAULT = "${project.version}"; public static final String VERSION_DEFAULT = "${project.version}";
static{ static {
InputStream in = null; InputStream in = null;
try{ try {
in = VersionUtils.class.getClassLoader() in = VersionUtils.class.getClassLoader()
.getResourceAsStream("nacos-version.txt"); .getResourceAsStream("nacos-version.txt");
Properties props = new Properties(); Properties props = new Properties();
@ -40,7 +42,7 @@ public class VersionUtils {
if (val != null && !VERSION_DEFAULT.equals(val)) { if (val != null && !VERSION_DEFAULT.equals(val)) {
VERSION = val; VERSION = val;
} }
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {

View File

@ -23,31 +23,27 @@ import junit.framework.TestSuite;
* Unit test for simple App. * Unit test for simple App.
*/ */
public class AppTest public class AppTest
extends TestCase extends TestCase {
{
/** /**
* Create the test case * Create the test case
* *
* @param testName name of the test case * @param testName name of the test case
*/ */
public AppTest( String testName ) public AppTest(String testName) {
{ super(testName);
super( testName );
} }
/** /**
* @return the suite of tests being tested * @return the suite of tests being tested
*/ */
public static Test suite() public static Test suite() {
{ return new TestSuite(AppTest.class);
return new TestSuite( AppTest.class );
} }
/** /**
* Rigourous Test :-) * Rigourous Test :-)
*/ */
public void testApp() public void testApp() {
{ assertTrue(true);
assertTrue( true );
} }
} }

View File

@ -17,7 +17,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -15,8 +15,8 @@
*/ */
package com.alibaba.nacos.config.server.aspect; package com.alibaba.nacos.config.server.aspect;
import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.monitor.MetricsMonitor; import com.alibaba.nacos.config.server.monitor.MetricsMonitor;
import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.MD5;
@ -61,7 +61,7 @@ public class RequestLogAspect {
/** /**
* publishSingle * publishSingle
* */ */
@Around(CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG) @Around(CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG)
public Object interfacePublishSingle(ProceedingJoinPoint pjp, HttpServletRequest request, public Object interfacePublishSingle(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String tenant, HttpServletResponse response, String dataId, String group, String tenant,
@ -73,7 +73,7 @@ public class RequestLogAspect {
/** /**
* removeAll * removeAll
* */ */
@Around(CLIENT_INTERFACE_REMOVE_ALL_CONFIG) @Around(CLIENT_INTERFACE_REMOVE_ALL_CONFIG)
public Object interfaceRemoveAll(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response, public Object interfaceRemoveAll(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response,
String dataId, String group, String tenant) throws Throwable { String dataId, String group, String tenant) throws Throwable {

View File

@ -45,7 +45,9 @@ public class CapacityController {
private final CapacityService capacityService; private final CapacityService capacityService;
@Autowired @Autowired
public CapacityController(CapacityService capacityService) {this.capacityService = capacityService;} public CapacityController(CapacityService capacityService) {
this.capacityService = capacityService;
}
@ResponseBody @ResponseBody
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)

View File

@ -36,6 +36,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@ -227,6 +228,32 @@ public class ConfigController {
return true; return true;
} }
/**
* @author klw
* @Description: delete configuration based on multiple config ids
* @Date 2019/7/5 10:26
* @Param [request, response, dataId, group, tenant, tag]
* @return java.lang.Boolean
*/
@RequestMapping(params = "delType=ids", method = RequestMethod.DELETE)
@ResponseBody
public RestResult<Boolean> deleteConfigs(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "ids")List<Long> ids) {
String clientIp = RequestUtil.getRemoteIp(request);
final Timestamp time = TimeUtils.getCurrentTime();
List<ConfigInfo> configInfoList = persistService.removeConfigInfoByIds(ids, clientIp, null);
if(!CollectionUtils.isEmpty(configInfoList)){
for(ConfigInfo configInfo : configInfoList) {
ConfigTraceService.logPersistenceEvent(configInfo.getDataId(), configInfo.getGroup(),
configInfo.getTenant(), null, time.getTime(), clientIp,
ConfigTraceService.PERSISTENCE_EVENT_REMOVE, null);
EventDispatcher.fireEvent(new ConfigDataChangeEvent(false, configInfo.getDataId(),
configInfo.getGroup(), configInfo.getTenant(), time.getTime()));
}
}
return ResultBuilder.buildSuccessResult(true);
}
@RequestMapping(value = "/catalog", method = RequestMethod.GET) @RequestMapping(value = "/catalog", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public RestResult<ConfigAdvanceInfo> getConfigAdvanceInfo(HttpServletRequest request, HttpServletResponse response, public RestResult<ConfigAdvanceInfo> getConfigAdvanceInfo(HttpServletRequest request, HttpServletResponse response,

View File

@ -45,7 +45,9 @@ public class HealthController {
private String heathWarnStr = "WARN"; private String heathWarnStr = "WARN";
@Autowired @Autowired
public HealthController(DynamicDataSource dynamicDataSource) {this.dynamicDataSource = dynamicDataSource;} public HealthController(DynamicDataSource dynamicDataSource) {
this.dynamicDataSource = dynamicDataSource;
}
@PostConstruct @PostConstruct
public void init() { public void init() {

View File

@ -46,7 +46,9 @@ public class ListenerController {
private final ConfigSubService configSubService; private final ConfigSubService configSubService;
@Autowired @Autowired
public ListenerController(ConfigSubService configSubService) {this.configSubService = configSubService;} public ListenerController(ConfigSubService configSubService) {
this.configSubService = configSubService;
}
/** /**
* 获取客户端订阅配置信息 * 获取客户端订阅配置信息

View File

@ -22,6 +22,8 @@ import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.service.PersistService; import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.dump.DumpService; import com.alibaba.nacos.config.server.service.dump.DumpService;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.core.utils.WebUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -63,4 +65,13 @@ public class OpsController {
return HttpServletResponse.SC_OK + ""; return HttpServletResponse.SC_OK + "";
} }
@RequestMapping(value = "/log", method = RequestMethod.PUT)
@ResponseBody
public String setLogLevel(HttpServletRequest request) {
String logName = WebUtils.required(request, "logName");
String logLevel = WebUtils.required(request, "logLevel");
LogUtil.setLogLevel(logName, logLevel);
return HttpServletResponse.SC_OK + "";
}
} }

View File

@ -75,9 +75,7 @@ public enum FileTypeEnum {
* @author klw * @author klw
* @Description: properties file * @Description: properties file
*/ */
PROPERTIES("properties") PROPERTIES("properties");
;
/** /**
* @author klw * @author klw
@ -85,14 +83,13 @@ public enum FileTypeEnum {
*/ */
private String fileType; private String fileType;
FileTypeEnum(String fileType){ FileTypeEnum(String fileType) {
this.fileType = fileType; this.fileType = fileType;
} }
public String getFileType(){ public String getFileType() {
return this.fileType; return this.fileType;
} }
} }

View File

@ -27,7 +27,8 @@ public class SubscriberStatus {
Boolean status; Boolean status;
String serverIp; String serverIp;
public SubscriberStatus() {} public SubscriberStatus() {
}
public SubscriberStatus(String groupKey, Boolean status, String md5, Long lastTime) { public SubscriberStatus(String groupKey, Boolean status, String md5, Long lastTime) {
this.groupKey = groupKey; this.groupKey = groupKey;

View File

@ -50,7 +50,7 @@ public class MemoryMonitor {
} }
static final long DELAY_SECONDS = 10; private static final long DELAY_SECONDS = 10;
@Scheduled(cron = "0 0 0 * * ?") @Scheduled(cron = "0 0 0 * * ?")
public void clear() { public void clear() {
@ -89,9 +89,7 @@ class NotifyTaskQueueMonitorTask implements Runnable {
@Override @Override
public void run() { public void run() {
int size = ((ScheduledThreadPoolExecutor)notifySingleService.getExecutor()).getQueue().size(); int size = ((ScheduledThreadPoolExecutor)notifySingleService.getExecutor()).getQueue().size();
memoryLog.info("notifySingleServiceThreadPool-{}, toNotifyTaskSize={}", memoryLog.info("toNotifyTaskSize={}", size);
new Object[] {((ScheduledThreadPoolExecutor)notifySingleService.getExecutor()).getClass().getName(),
size});
MetricsMonitor.getNotifyTaskMonitor().set(size); MetricsMonitor.getNotifyTaskMonitor().set(size);
} }
} }

View File

@ -25,11 +25,15 @@ import com.alibaba.nacos.config.server.result.core.IResultCode;
*/ */
public enum ResultCodeEnum implements IResultCode { public enum ResultCodeEnum implements IResultCode {
/** common code **/ /**
* common code
**/
SUCCESS(200, "处理成功"), SUCCESS(200, "处理成功"),
ERROR(500, "服务器内部错误"), ERROR(500, "服务器内部错误"),
/** config use 100001 ~ 100999 **/ /**
* config use 100001 ~ 100999
**/
NAMESPACE_NOT_EXIST(100001, "目标 namespace 不存在"), NAMESPACE_NOT_EXIST(100001, "目标 namespace 不存在"),
METADATA_ILLEGAL(100002, "导入的元数据非法"), METADATA_ILLEGAL(100002, "导入的元数据非法"),
@ -41,14 +45,13 @@ public enum ResultCodeEnum implements IResultCode {
DATA_EMPTY(100005, "导入的文件数据为空"), DATA_EMPTY(100005, "导入的文件数据为空"),
; ;
private int code; private int code;
private String msg; private String msg;
ResultCodeEnum(int code, String codeMsg){ ResultCodeEnum(int code, String codeMsg) {
this.code = code; this.code = code;
this.msg = codeMsg; this.msg = codeMsg;
} }

View File

@ -163,27 +163,27 @@ public class BasicDataSourceServiceImpl implements DataSourceService {
} }
ds.setUrl(val.trim()); ds.setUrl(val.trim());
val = env.getProperty("db.user"); val = env.getProperty("db.user." + i, env.getProperty("db.user"));
if (null == val) { if (null == val) {
fatalLog.error("db.user is null"); fatalLog.error("db.user." + i + " is null");
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
ds.setUsername(val.trim()); ds.setUsername(val.trim());
val = env.getProperty("db.password"); val = env.getProperty("db.password." + i, env.getProperty("db.password"));
if (null == val) { if (null == val) {
fatalLog.error("db.password is null"); fatalLog.error("db.password." + i + " is null");
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
ds.setPassword(val.trim()); ds.setPassword(val.trim());
val = env.getProperty("db.initialSize"); val = env.getProperty("db.initialSize." + i, env.getProperty("db.initialSize"));
ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10"))); ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10")));
val = env.getProperty("db.maxActive"); val = env.getProperty("db.maxActive." + i, env.getProperty("db.maxActive"));
ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20"))); ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20")));
val = env.getProperty("db.maxIdle"); val = env.getProperty("db.maxIdle." + i, env.getProperty("db.maxIdle"));
ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50"))); ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50")));
ds.setMaxWait(3000L); ds.setMaxWait(3000L);
@ -302,7 +302,9 @@ public class BasicDataSourceServiceImpl implements DataSourceService {
@Override @Override
public void run() { public void run() {
defaultLog.info("check master db."); if (defaultLog.isDebugEnabled()) {
defaultLog.debug("check master db.");
}
boolean isFound = false; boolean isFound = false;
int index = -1; int index = -1;
@ -339,7 +341,9 @@ public class BasicDataSourceServiceImpl implements DataSourceService {
@Override @Override
public void run() { public void run() {
defaultLog.info("check db health."); if (defaultLog.isDebugEnabled()) {
defaultLog.debug("check db health.");
}
String sql = "SELECT * FROM config_info_beta WHERE id = 1"; String sql = "SELECT * FROM config_info_beta WHERE id = 1";
for (int i = 0; i < testJTList.size(); i++) { for (int i = 0; i < testJTList.size(); i++) {

View File

@ -23,6 +23,7 @@ import com.alibaba.nacos.config.server.utils.MD5;
import com.alibaba.nacos.config.server.utils.PaginationHelper; import com.alibaba.nacos.config.server.utils.PaginationHelper;
import com.alibaba.nacos.config.server.utils.ParamUtils; import com.alibaba.nacos.config.server.utils.ParamUtils;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -75,6 +76,10 @@ public class PersistService {
private static final String SQL_TENANT_INFO_COUNT_BY_TENANT_ID = "select count(1) from tenant_info where tenant_id = ?"; private static final String SQL_TENANT_INFO_COUNT_BY_TENANT_ID = "select count(1) from tenant_info where tenant_id = ?";
private static final String SQL_FIND_CONFIG_INFO_BY_IDS = "SELECT ID,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE ";
private static final String SQL_DELETE_CONFIG_INFO_BY_IDS = "DELETE FROM config_info WHERE ";
/** /**
* @author klw * @author klw
* @Description: constant variables * @Description: constant variables
@ -500,7 +505,7 @@ public class PersistService {
public Boolean doInTransaction(TransactionStatus status) { public Boolean doInTransaction(TransactionStatus status) {
try { try {
long configId = addConfigInfoAtomic(srcIp, srcUser, configInfo, time, configAdvanceInfo); long configId = addConfigInfoAtomic(srcIp, srcUser, configInfo, time, configAdvanceInfo);
String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
addConfiTagsRelationAtomic(configId, configTags, configInfo.getDataId(), configInfo.getGroup(), addConfiTagsRelationAtomic(configId, configTags, configInfo.getDataId(), configInfo.getGroup(),
configInfo.getTenant()); configInfo.getTenant());
insertConfigHistoryAtomic(0, configInfo, srcIp, srcUser, time, "I"); insertConfigHistoryAtomic(0, configInfo, srcIp, srcUser, time, "I");
@ -587,7 +592,7 @@ public class PersistService {
configInfo.setAppName(appNameTmp); configInfo.setAppName(appNameTmp);
} }
updateConfigInfoAtomic(configInfo, srcIp, srcUser, time, configAdvanceInfo); updateConfigInfoAtomic(configInfo, srcIp, srcUser, time, configAdvanceInfo);
String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
if (configTags != null) { if (configTags != null) {
// 删除所有tag然后再重新创建 // 删除所有tag然后再重新创建
removeTagByIdAtomic(oldConfigInfo.getId()); removeTagByIdAtomic(oldConfigInfo.getId());
@ -746,6 +751,42 @@ public class PersistService {
}); });
} }
/**
* @author klw
* @Description: delete config info by ids
* @Date 2019/7/5 16:45
* @Param [ids, srcIp, srcUser]
* @return List<ConfigInfo> deleted configInfos
*/
public List<ConfigInfo> removeConfigInfoByIds(final List<Long> ids, final String srcIp, final String srcUser) {
if(CollectionUtils.isEmpty(ids)){
return null;
}
ids.removeAll(Collections.singleton(null));
return tjt.execute(new TransactionCallback<List<ConfigInfo>>() {
final Timestamp time = new Timestamp(System.currentTimeMillis());
@Override
public List<ConfigInfo> doInTransaction(TransactionStatus status) {
try {
String idsStr = Joiner.on(",").join(ids);
List<ConfigInfo> configInfoList = findConfigInfosByIds(idsStr);
if (!CollectionUtils.isEmpty(configInfoList)) {
removeConfigInfoByIdsAtomic(idsStr);
for(ConfigInfo configInfo : configInfoList){
removeTagByIdAtomic(configInfo.getId());
insertConfigHistoryAtomic(configInfo.getId(), configInfo, srcIp, srcUser, time, "D");
}
}
return configInfoList;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
});
}
/** /**
* 删除beta配置信息, 物理删除 * 删除beta配置信息, 物理删除
*/ */
@ -791,7 +832,7 @@ public class PersistService {
try { try {
try { try {
String dbContent = jt.queryForObject(select, new Object[] {dataId, group, tenantTmp, datumId}, String dbContent = jt.queryForObject(select, new Object[]{dataId, group, tenantTmp, datumId},
String.class); String.class);
if (dbContent != null && dbContent.equals(content)) { if (dbContent != null && dbContent.equals(content)) {
@ -890,7 +931,7 @@ public class PersistService {
String sql = "delete from his_config_info where gmt_modified < ? limit ?"; String sql = "delete from his_config_info where gmt_modified < ? limit ?";
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
try { try {
helper.updateLimit(jt, sql, new Object[] {startTime, limitSize}); helper.updateLimit(jt, sql, new Object[]{startTime, limitSize});
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -902,7 +943,7 @@ public class PersistService {
*/ */
public int findConfigHistoryCountByTime(final Timestamp startTime) { public int findConfigHistoryCountByTime(final Timestamp startTime) {
String sql = "SELECT COUNT(*) FROM his_config_info WHERE gmt_modified < ?"; String sql = "SELECT COUNT(*) FROM his_config_info WHERE gmt_modified < ?";
Integer result = jt.queryForObject(sql, Integer.class, new Object[] {startTime}); Integer result = jt.queryForObject(sql, Integer.class, new Object[]{startTime});
if (result == null) { if (result == null) {
throw new IllegalArgumentException("configInfoBetaCount error"); throw new IllegalArgumentException("configInfoBetaCount error");
} }
@ -1010,7 +1051,7 @@ public class PersistService {
String sql = "SELECT DISTINCT data_id, group_id FROM config_info"; String sql = "SELECT DISTINCT data_id, group_id FROM config_info";
try { try {
return jt.query(sql, new Object[] {}, CONFIG_INFO_ROW_MAPPER); return jt.query(sql, new Object[]{}, CONFIG_INFO_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
return Collections.emptyList(); return Collections.emptyList();
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -1031,7 +1072,7 @@ public class PersistService {
return this.jt.queryForObject( return this.jt.queryForObject(
"SELECT ID,data_id,group_id,tenant_id,app_name,content,beta_ips FROM config_info_beta WHERE data_id=?" "SELECT ID,data_id,group_id,tenant_id,app_name,content,beta_ips FROM config_info_beta WHERE data_id=?"
+ " AND group_id=? AND tenant_id=?", + " AND group_id=? AND tenant_id=?",
new Object[] {dataId, group, tenantTmp}, CONFIG_INFO4BETA_ROW_MAPPER); new Object[]{dataId, group, tenantTmp}, CONFIG_INFO4BETA_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null } catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null
return null; return null;
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -1051,7 +1092,7 @@ public class PersistService {
return this.jt.queryForObject( return this.jt.queryForObject(
"SELECT ID,data_id,group_id,tenant_id,tag_id,app_name,content FROM config_info_tag WHERE data_id=? " "SELECT ID,data_id,group_id,tenant_id,tag_id,app_name,content FROM config_info_tag WHERE data_id=? "
+ "AND group_id=? AND tenant_id=? AND tag_id=?", + "AND group_id=? AND tenant_id=? AND tag_id=?",
new Object[] {dataId, group, tenantTmp, tagTmp}, CONFIG_INFO4TAG_ROW_MAPPER); new Object[]{dataId, group, tenantTmp, tagTmp}, CONFIG_INFO4TAG_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null } catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null
return null; return null;
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -1070,7 +1111,7 @@ public class PersistService {
return this.jt.queryForObject( return this.jt.queryForObject(
"SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE data_id=? AND " "SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE data_id=? AND "
+ "group_id=? AND tenant_id=? AND app_name=?", + "group_id=? AND tenant_id=? AND app_name=?",
new Object[] {dataId, group, tenantTmp, appName}, CONFIG_INFO_ROW_MAPPER); new Object[]{dataId, group, tenantTmp, appName}, CONFIG_INFO_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null } catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null
return null; return null;
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -1085,8 +1126,8 @@ public class PersistService {
public ConfigInfo findConfigInfoAdvanceInfo(final String dataId, final String group, final String tenant, public ConfigInfo findConfigInfoAdvanceInfo(final String dataId, final String group, final String tenant,
final Map<String, Object> configAdvanceInfo) { final Map<String, Object> configAdvanceInfo) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
final String appName = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("appName"); final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
final String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
List<String> paramList = new ArrayList<String>(); List<String> paramList = new ArrayList<String>();
paramList.add(dataId); paramList.add(dataId);
paramList.add(group); paramList.add(group);
@ -1141,7 +1182,7 @@ public class PersistService {
.queryForObject( .queryForObject(
"SELECT ID,data_id,group_id,content FROM config_info WHERE data_id=? AND group_id=? AND " "SELECT ID,data_id,group_id,content FROM config_info WHERE data_id=? AND group_id=? AND "
+ "tenant_id=?", + "tenant_id=?",
new Object[] {dataId, group, StringUtils.EMPTY}, new Object[]{dataId, group, StringUtils.EMPTY},
CONFIG_INFO_BASE_ROW_MAPPER); CONFIG_INFO_BASE_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null } catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null
return null; return null;
@ -1162,7 +1203,7 @@ public class PersistService {
return this.jt return this.jt
.queryForObject( .queryForObject(
"SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE ID=?", "SELECT ID,data_id,group_id,tenant_id,app_name,content FROM config_info WHERE ID=?",
new Object[] {id}, CONFIG_INFO_ROW_MAPPER); new Object[]{id}, CONFIG_INFO_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在 } catch (EmptyResultDataAccessException e) { // 表明数据不存在
return null; return null;
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -1187,7 +1228,7 @@ public class PersistService {
return helper.fetchPage(this.jt, "select count(*) from config_info where data_id=? and tenant_id=?", return helper.fetchPage(this.jt, "select count(*) from config_info where data_id=? and tenant_id=?",
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where data_id=? and " "select ID,data_id,group_id,tenant_id,app_name,content from config_info where data_id=? and "
+ "tenant_id=?", + "tenant_id=?",
new Object[] {dataId, tenantTmp}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); new Object[]{dataId, tenantTmp}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -1211,7 +1252,7 @@ public class PersistService {
"select count(*) from config_info where data_id=? and tenant_id=? and app_name=?", "select count(*) from config_info where data_id=? and tenant_id=? and app_name=?",
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where data_id=? and " "select ID,data_id,group_id,tenant_id,app_name,content from config_info where data_id=? and "
+ "tenant_id=? and app_name=?", + "tenant_id=? and app_name=?",
new Object[] {dataId, tenantTmp, appName}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); new Object[]{dataId, tenantTmp, appName}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -1223,8 +1264,8 @@ public class PersistService {
final Map<String, Object> configAdvanceInfo) { final Map<String, Object> configAdvanceInfo) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
final String appName = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("appName"); final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
final String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
StringBuilder sqlCount = new StringBuilder("select count(*) from config_info where data_id=? and tenant_id=? "); StringBuilder sqlCount = new StringBuilder("select count(*) from config_info where data_id=? and tenant_id=? ");
StringBuilder sql = new StringBuilder( StringBuilder sql = new StringBuilder(
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where data_id=? and tenant_id=? "); "select ID,data_id,group_id,tenant_id,app_name,content from config_info where data_id=? and tenant_id=? ");
@ -1281,8 +1322,8 @@ public class PersistService {
final String tenant, final Map<String, Object> configAdvanceInfo) { final String tenant, final Map<String, Object> configAdvanceInfo) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
final String appName = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("appName"); final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
final String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
String sqlCount = "select count(*) from config_info"; String sqlCount = "select count(*) from config_info";
String sql = "select ID,data_id,group_id,tenant_id,app_name,content from config_info"; String sql = "select ID,data_id,group_id,tenant_id,app_name,content from config_info";
StringBuilder where = new StringBuilder(" where "); StringBuilder where = new StringBuilder(" where ");
@ -1360,7 +1401,7 @@ public class PersistService {
this.jt, this.jt,
"select count(*) from config_info where data_id=? and tenant_id=?", "select count(*) from config_info where data_id=? and tenant_id=?",
"select ID,data_id,group_id,content from config_info where data_id=? and tenant_id=?", "select ID,data_id,group_id,content from config_info where data_id=? and tenant_id=?",
new Object[] {dataId, StringUtils.EMPTY}, pageNo, pageSize, new Object[]{dataId, StringUtils.EMPTY}, pageNo, pageSize,
CONFIG_INFO_BASE_ROW_MAPPER); CONFIG_INFO_BASE_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -1384,7 +1425,7 @@ public class PersistService {
return helper.fetchPage(this.jt, "select count(*) from config_info where group_id=? and tenant_id=?", return helper.fetchPage(this.jt, "select count(*) from config_info where group_id=? and tenant_id=?",
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where group_id=? and " "select ID,data_id,group_id,tenant_id,app_name,content from config_info where group_id=? and "
+ "tenant_id=?", + "tenant_id=?",
new Object[] {group, tenantTmp}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); new Object[]{group, tenantTmp}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -1409,7 +1450,7 @@ public class PersistService {
"select count(*) from config_info where group_id=? and tenant_id=? and app_name =?", "select count(*) from config_info where group_id=? and tenant_id=? and app_name =?",
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where group_id=? and " "select ID,data_id,group_id,tenant_id,app_name,content from config_info where group_id=? and "
+ "tenant_id=? and app_name =?", + "tenant_id=? and app_name =?",
new Object[] {group, tenantTmp, appName}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); new Object[]{group, tenantTmp, appName}, pageNo, pageSize, CONFIG_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -1422,8 +1463,8 @@ public class PersistService {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
final String appName = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("appName"); final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
final String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
StringBuilder sqlCount = new StringBuilder( StringBuilder sqlCount = new StringBuilder(
"select count(*) from config_info where group_id=? and tenant_id=? "); "select count(*) from config_info where group_id=? and tenant_id=? ");
StringBuilder sql = new StringBuilder( StringBuilder sql = new StringBuilder(
@ -1491,7 +1532,7 @@ public class PersistService {
return helper.fetchPage(this.jt, "select count(*) from config_info where tenant_id like ? and app_name=?", return helper.fetchPage(this.jt, "select count(*) from config_info where tenant_id like ? and app_name=?",
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where tenant_id like ? and " "select ID,data_id,group_id,tenant_id,app_name,content from config_info where tenant_id like ? and "
+ "app_name=?", + "app_name=?",
new Object[] {generateLikeArgument(tenantTmp), appName}, pageNo, pageSize, new Object[]{generateLikeArgument(tenantTmp), appName}, pageNo, pageSize,
CONFIG_INFO_ROW_MAPPER); CONFIG_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -1504,8 +1545,8 @@ public class PersistService {
final Map<String, Object> configAdvanceInfo) { final Map<String, Object> configAdvanceInfo) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
final String appName = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("appName"); final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
final String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
StringBuilder sqlCount = new StringBuilder("select count(*) from config_info where tenant_id like ? "); StringBuilder sqlCount = new StringBuilder("select count(*) from config_info where tenant_id like ? ");
StringBuilder sql = new StringBuilder( StringBuilder sql = new StringBuilder(
"select ID,data_id,group_id,tenant_id,app_name,content from config_info where tenant_id like ? "); "select ID,data_id,group_id,tenant_id,app_name,content from config_info where tenant_id like ? ");
@ -1574,7 +1615,7 @@ public class PersistService {
this.jt, this.jt,
"select count(*) from config_info where group_id=? and tenant_id=?", "select count(*) from config_info where group_id=? and tenant_id=?",
"select ID,data_id,group_id,content from config_info where group_id=? and tenant_id=?", "select ID,data_id,group_id,content from config_info where group_id=? and tenant_id=?",
new Object[] {group, StringUtils.EMPTY}, pageNo, pageSize, new Object[]{group, StringUtils.EMPTY}, pageNo, pageSize,
CONFIG_INFO_BASE_ROW_MAPPER); CONFIG_INFO_BASE_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -1645,7 +1686,7 @@ public class PersistService {
public int aggrConfigInfoCount(String dataId, String group, String tenant) { public int aggrConfigInfoCount(String dataId, String group, String tenant) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
String sql = " SELECT COUNT(ID) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ?"; String sql = " SELECT COUNT(ID) FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND tenant_id = ?";
Integer result = jt.queryForObject(sql, Integer.class, new Object[] {dataId, group, tenantTmp}); Integer result = jt.queryForObject(sql, Integer.class, new Object[]{dataId, group, tenantTmp});
if (result == null) { if (result == null) {
throw new IllegalArgumentException("aggrConfigInfoCount error"); throw new IllegalArgumentException("aggrConfigInfoCount error");
} }
@ -1712,7 +1753,7 @@ public class PersistService {
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
try { try {
return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows,
new Object[] {generateLikeArgument(tenantTmp), (pageNo - 1) * pageSize, pageSize}, new Object[]{generateLikeArgument(tenantTmp), (pageNo - 1) * pageSize, pageSize},
pageNo, pageSize, CONFIG_INFO_ROW_MAPPER); pageNo, pageSize, CONFIG_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -1754,7 +1795,7 @@ public class PersistService {
try { try {
List<ConfigKey> result = jt.query(select, List<ConfigKey> result = jt.query(select,
new Object[] {generateLikeArgument(tenantTmp), (pageNo - 1) * pageSize, pageSize}, new Object[]{generateLikeArgument(tenantTmp), (pageNo - 1) * pageSize, pageSize},
// new Object[0], // new Object[0],
CONFIG_KEY_ROW_MAPPER); CONFIG_KEY_ROW_MAPPER);
@ -1790,7 +1831,7 @@ public class PersistService {
PaginationHelper<ConfigInfoBase> helper = new PaginationHelper<ConfigInfoBase>(); PaginationHelper<ConfigInfoBase> helper = new PaginationHelper<ConfigInfoBase>();
try { try {
return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[] { return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[]{
(pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_BASE_ROW_MAPPER); (pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_BASE_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -1907,7 +1948,7 @@ public class PersistService {
+ "order by id asc limit ?,?"; + "order by id asc limit ?,?";
PaginationHelper<ConfigInfoWrapper> helper = new PaginationHelper<ConfigInfoWrapper>(); PaginationHelper<ConfigInfoWrapper> helper = new PaginationHelper<ConfigInfoWrapper>();
try { try {
return helper.fetchPageLimit(jt, select, new Object[] {lastMaxId, 0, pageSize}, 1, pageSize, return helper.fetchPageLimit(jt, select, new Object[]{lastMaxId, 0, pageSize}, 1, pageSize,
CONFIG_INFO_WRAPPER_ROW_MAPPER); CONFIG_INFO_WRAPPER_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -1926,7 +1967,7 @@ public class PersistService {
+ " WHERE g.id = t.id "; + " WHERE g.id = t.id ";
PaginationHelper<ConfigInfoBetaWrapper> helper = new PaginationHelper<ConfigInfoBetaWrapper>(); PaginationHelper<ConfigInfoBetaWrapper> helper = new PaginationHelper<ConfigInfoBetaWrapper>();
try { try {
return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[] { return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[]{
(pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER); (pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_BETA_WRAPPER_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -1946,7 +1987,7 @@ public class PersistService {
+ " WHERE g.id = t.id "; + " WHERE g.id = t.id ";
PaginationHelper<ConfigInfoTagWrapper> helper = new PaginationHelper<ConfigInfoTagWrapper>(); PaginationHelper<ConfigInfoTagWrapper> helper = new PaginationHelper<ConfigInfoTagWrapper>();
try { try {
return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[] { return helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[]{
(pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER); (pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -2073,9 +2114,9 @@ public class PersistService {
final String group, final String tenant, final String group, final String tenant,
final Map<String, Object> configAdvanceInfo) { final Map<String, Object> configAdvanceInfo) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
final String appName = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("appName"); final String appName = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("appName");
final String content = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("content"); final String content = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("content");
final String configTags = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("config_tags"); final String configTags = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("config_tags");
PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>(); PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
String sqlCountRows = "select count(*) from config_info"; String sqlCountRows = "select count(*) from config_info";
String sqlFetchRows = "select ID,data_id,group_id,tenant_id,app_name,content from config_info"; String sqlFetchRows = "select ID,data_id,group_id,tenant_id,app_name,content from config_info";
@ -2319,7 +2360,7 @@ public class PersistService {
+ "AND group_id=? AND tenant_id=? AND datum_id=?"; + "AND group_id=? AND tenant_id=? AND datum_id=?";
try { try {
return this.jt.queryForObject(sql, new Object[] {dataId, group, tenantTmp, datumId}, return this.jt.queryForObject(sql, new Object[]{dataId, group, tenantTmp, datumId},
CONFIG_INFO_AGGR_ROW_MAPPER); CONFIG_INFO_AGGR_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
// 是EmptyResultDataAccessException, 表明数据不存在, 返回null // 是EmptyResultDataAccessException, 表明数据不存在, 返回null
@ -2343,7 +2384,7 @@ public class PersistService {
+ "group_id=? AND tenant_id=? ORDER BY datum_id"; + "group_id=? AND tenant_id=? ORDER BY datum_id";
try { try {
return this.jt.query(sql, new Object[] {dataId, group, tenantTmp}, return this.jt.query(sql, new Object[]{dataId, group, tenantTmp},
CONFIG_INFO_AGGR_ROW_MAPPER); CONFIG_INFO_AGGR_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -2366,8 +2407,8 @@ public class PersistService {
+ "group_id=? and tenant_id=? order by datum_id limit ?,?"; + "group_id=? and tenant_id=? order by datum_id limit ?,?";
PaginationHelper<ConfigInfoAggr> helper = new PaginationHelper<ConfigInfoAggr>(); PaginationHelper<ConfigInfoAggr> helper = new PaginationHelper<ConfigInfoAggr>();
try { try {
return helper.fetchPageLimit(jt, sqlCountRows, new Object[] {dataId, group, tenantTmp}, sqlFetchRows, return helper.fetchPageLimit(jt, sqlCountRows, new Object[]{dataId, group, tenantTmp}, sqlFetchRows,
new Object[] {dataId, group, tenantTmp, (pageNo - 1) * pageSize, pageSize}, new Object[]{dataId, group, tenantTmp, (pageNo - 1) * pageSize, pageSize},
pageNo, pageSize, CONFIG_INFO_AGGR_ROW_MAPPER); pageNo, pageSize, CONFIG_INFO_AGGR_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -2495,7 +2536,7 @@ public class PersistService {
String sql = "SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr"; String sql = "SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr";
try { try {
return this.jt.query(sql, new Object[] {}, return this.jt.query(sql, new Object[]{},
CONFIG_INFO_CHANGED_ROW_MAPPER); CONFIG_INFO_CHANGED_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -2521,7 +2562,7 @@ public class PersistService {
String sql = "SELECT datum_id FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND content = ? "; String sql = "SELECT datum_id FROM config_info_aggr WHERE data_id = ? AND group_id = ? AND content = ? ";
try { try {
return this.jt.queryForList(sql, new Object[] {dataId, groupId, return this.jt.queryForList(sql, new Object[]{dataId, groupId,
content}, String.class); content}, String.class);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
return null; return null;
@ -2540,7 +2581,7 @@ public class PersistService {
.queryForList( .queryForList(
"SELECT data_id, group_id, tenant_id, app_name, content, gmt_modified FROM config_info WHERE " "SELECT data_id, group_id, tenant_id, app_name, content, gmt_modified FROM config_info WHERE "
+ "gmt_modified >=? AND gmt_modified <= ?", + "gmt_modified >=? AND gmt_modified <= ?",
new Object[] {startTime, endTime}); new Object[]{startTime, endTime});
return convertChangeConfig(list); return convertChangeConfig(list);
} catch (DataAccessException e) { } catch (DataAccessException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -2615,7 +2656,7 @@ public class PersistService {
.queryForList( .queryForList(
"SELECT DISTINCT data_id, group_id, tenant_id FROM his_config_info WHERE op_type = 'D' AND " "SELECT DISTINCT data_id, group_id, tenant_id FROM his_config_info WHERE op_type = 'D' AND "
+ "gmt_modified >=? AND gmt_modified <= ?", + "gmt_modified >=? AND gmt_modified <= ?",
new Object[] {startTime, endTime}); new Object[]{startTime, endTime});
return convertDeletedConfig(list); return convertDeletedConfig(list);
} catch (DataAccessException e) { } catch (DataAccessException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
@ -2641,11 +2682,11 @@ public class PersistService {
final String tenantTmp = StringUtils.isBlank(configInfo.getTenant()) ? StringUtils.EMPTY final String tenantTmp = StringUtils.isBlank(configInfo.getTenant()) ? StringUtils.EMPTY
: configInfo.getTenant(); : configInfo.getTenant();
final String desc = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("desc"); final String desc = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("desc");
final String use = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("use"); final String use = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("use");
final String effect = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("effect"); final String effect = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("effect");
final String type = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("type"); final String type = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("type");
final String schema = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("schema"); final String schema = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("schema");
final String md5Tmp = MD5.getInstance().getMD5String(configInfo.getContent()); final String md5Tmp = MD5.getInstance().getMD5String(configInfo.getContent());
@ -2740,7 +2781,7 @@ public class PersistService {
public List<String> getConfigTagsByTenant(String tenant) { public List<String> getConfigTagsByTenant(String tenant) {
String sql = "SELECT tag_name FROM config_tags_relation WHERE tenant_id = ? "; String sql = "SELECT tag_name FROM config_tags_relation WHERE tenant_id = ? ";
try { try {
return jt.queryForList(sql, new Object[] {tenant}, String.class); return jt.queryForList(sql, new Object[]{tenant}, String.class);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
return null; return null;
} catch (IncorrectResultSizeDataAccessException e) { } catch (IncorrectResultSizeDataAccessException e) {
@ -2754,7 +2795,7 @@ public class PersistService {
public List<String> selectTagByConfig(String dataId, String group, String tenant) { public List<String> selectTagByConfig(String dataId, String group, String tenant) {
String sql = "SELECT tag_name FROM config_tags_relation WHERE data_id=? AND group_id=? AND tenant_id = ? "; String sql = "SELECT tag_name FROM config_tags_relation WHERE data_id=? AND group_id=? AND tenant_id = ? ";
try { try {
return jt.queryForList(sql, new Object[] {dataId, group, tenant}, String.class); return jt.queryForList(sql, new Object[]{dataId, group, tenant}, String.class);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
return null; return null;
} catch (IncorrectResultSizeDataAccessException e) { } catch (IncorrectResultSizeDataAccessException e) {
@ -2787,6 +2828,37 @@ public class PersistService {
} }
} }
/**
* @author klw
* @Description: Delete configuration; database atomic operation, minimum SQL action, no business encapsulation
* @Date 2019/7/5 16:39
* @Param [id]
* @return void
*/
private void removeConfigInfoByIdsAtomic(final String ids) {
if(StringUtils.isBlank(ids)){
return;
}
StringBuilder sql = new StringBuilder(SQL_DELETE_CONFIG_INFO_BY_IDS);
sql.append("id in (");
List<Long> paramList = new ArrayList<>();
String[] tagArr = ids.split(",");
for (int i = 0; i < tagArr.length; i++) {
if (i != 0) {
sql.append(", ");
}
sql.append("?");
paramList.add(Long.valueOf(tagArr[i]));
}
sql.append(") ");
try {
jt.update(sql.toString(), paramList.toArray());
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
/** /**
* 删除配置数据库原子操作最小sql动作无业务封装 * 删除配置数据库原子操作最小sql动作无业务封装
* *
@ -2826,11 +2898,11 @@ public class PersistService {
String appNameTmp = StringUtils.isBlank(configInfo.getAppName()) ? StringUtils.EMPTY : configInfo.getAppName(); String appNameTmp = StringUtils.isBlank(configInfo.getAppName()) ? StringUtils.EMPTY : configInfo.getAppName();
String tenantTmp = StringUtils.isBlank(configInfo.getTenant()) ? StringUtils.EMPTY : configInfo.getTenant(); String tenantTmp = StringUtils.isBlank(configInfo.getTenant()) ? StringUtils.EMPTY : configInfo.getTenant();
final String md5Tmp = MD5.getInstance().getMD5String(configInfo.getContent()); final String md5Tmp = MD5.getInstance().getMD5String(configInfo.getContent());
String desc = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("desc"); String desc = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("desc");
String use = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("use"); String use = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("use");
String effect = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("effect"); String effect = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("effect");
String type = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("type"); String type = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("type");
String schema = configAdvanceInfo == null ? null : (String)configAdvanceInfo.get("schema"); String schema = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("schema");
try { try {
jt.update( jt.update(
@ -2856,7 +2928,40 @@ public class PersistService {
try { try {
return this.jt.queryForObject( return this.jt.queryForObject(
"SELECT ID,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?", "SELECT ID,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?",
new Object[] {dataId, group, tenantTmp}, CONFIG_INFO_ROW_MAPPER); new Object[]{dataId, group, tenantTmp}, CONFIG_INFO_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null
return null;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
/**
* @author klw
* @Description: find ConfigInfo by ids
* @Date 2019/7/5 16:37
* @Param [ids]
* @return java.util.List<com.alibaba.nacos.config.server.model.ConfigInfo>
*/
public List<ConfigInfo> findConfigInfosByIds(final String ids) {
if(StringUtils.isBlank(ids)){
return null;
}
StringBuilder sql = new StringBuilder(SQL_FIND_CONFIG_INFO_BY_IDS);
sql.append("id in (");
List<Long> paramList = new ArrayList<>();
String[] tagArr = ids.split(",");
for (int i = 0; i < tagArr.length; i++) {
if (i != 0) {
sql.append(", ");
}
sql.append("?");
paramList.add(Long.valueOf(tagArr[i]));
}
sql.append(") ");
try {
return this.jt.query(sql.toString(), paramList.toArray(), CONFIG_INFO_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null } catch (EmptyResultDataAccessException e) { // 表明数据不存在, 返回null
return null; return null;
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -2879,7 +2984,7 @@ public class PersistService {
List<String> configTagList = this.selectTagByConfig(dataId, group, tenant); List<String> configTagList = this.selectTagByConfig(dataId, group, tenant);
ConfigAdvanceInfo configAdvance = this.jt.queryForObject( ConfigAdvanceInfo configAdvance = this.jt.queryForObject(
"SELECT gmt_create,gmt_modified,src_user,src_ip,c_desc,c_use,effect,type,c_schema FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?", "SELECT gmt_create,gmt_modified,src_user,src_ip,c_desc,c_use,effect,type,c_schema FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?",
new Object[] {dataId, group, tenantTmp}, CONFIG_ADVANCE_INFO_ROW_MAPPER); new Object[]{dataId, group, tenantTmp}, CONFIG_ADVANCE_INFO_ROW_MAPPER);
if (configTagList != null && !configTagList.isEmpty()) { if (configTagList != null && !configTagList.isEmpty()) {
StringBuilder configTagsTmp = new StringBuilder(); StringBuilder configTagsTmp = new StringBuilder();
for (String configTag : configTagList) { for (String configTag : configTagList) {
@ -2914,7 +3019,7 @@ public class PersistService {
List<String> configTagList = this.selectTagByConfig(dataId, group, tenant); List<String> configTagList = this.selectTagByConfig(dataId, group, tenant);
ConfigAllInfo configAdvance = this.jt.queryForObject( ConfigAllInfo configAdvance = this.jt.queryForObject(
"SELECT ID,data_id,group_id,tenant_id,app_name,content,md5,gmt_create,gmt_modified,src_user,src_ip,c_desc,c_use,effect,type,c_schema FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?", "SELECT ID,data_id,group_id,tenant_id,app_name,content,md5,gmt_create,gmt_modified,src_user,src_ip,c_desc,c_use,effect,type,c_schema FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?",
new Object[] {dataId, group, tenantTmp}, CONFIG_ALL_INFO_ROW_MAPPER); new Object[]{dataId, group, tenantTmp}, CONFIG_ALL_INFO_ROW_MAPPER);
if (configTagList != null && !configTagList.isEmpty()) { if (configTagList != null && !configTagList.isEmpty()) {
StringBuilder configTagsTmp = new StringBuilder(); StringBuilder configTagsTmp = new StringBuilder();
for (String configTag : configTagList) { for (String configTag : configTagList) {
@ -2982,11 +3087,11 @@ public class PersistService {
Page<ConfigHistoryInfo> page = null; Page<ConfigHistoryInfo> page = null;
try { try {
page = helper.fetchPage(this.jt, sqlCountRows, sqlFetchRows, new Object[] {dataId, group, tenantTmp}, page = helper.fetchPage(this.jt, sqlCountRows, sqlFetchRows, new Object[]{dataId, group, tenantTmp},
pageNo, pageNo,
pageSize, HISTORY_LIST_ROW_MAPPER); pageSize, HISTORY_LIST_ROW_MAPPER);
} catch (DataAccessException e) { } catch (DataAccessException e) {
fatalLog.error("[list-config-history] error, dataId:{}, group:{}", new Object[] {dataId, group}, e); fatalLog.error("[list-config-history] error, dataId:{}, group:{}", new Object[]{dataId, group}, e);
throw e; throw e;
} }
return page; return page;
@ -3038,11 +3143,11 @@ public class PersistService {
String sqlFetchRows String sqlFetchRows
= "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create,gmt_modified FROM his_config_info WHERE nid = ?"; = "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,gmt_create,gmt_modified FROM his_config_info WHERE nid = ?";
try { try {
ConfigHistoryInfo historyInfo = jt.queryForObject(sqlFetchRows, new Object[] {nid}, ConfigHistoryInfo historyInfo = jt.queryForObject(sqlFetchRows, new Object[]{nid},
HISTORY_DETAIL_ROW_MAPPER); HISTORY_DETAIL_ROW_MAPPER);
return historyInfo; return historyInfo;
} catch (DataAccessException e) { } catch (DataAccessException e) {
fatalLog.error("[list-config-history] error, nid:{}", new Object[] {nid}, e); fatalLog.error("[list-config-history] error, nid:{}", new Object[]{nid}, e);
throw e; throw e;
} }
} }
@ -3090,7 +3195,7 @@ public class PersistService {
public List<TenantInfo> findTenantByKp(String kp) { public List<TenantInfo> findTenantByKp(String kp) {
String sql = "SELECT tenant_id,tenant_name,tenant_desc FROM tenant_info WHERE kp=?"; String sql = "SELECT tenant_id,tenant_name,tenant_desc FROM tenant_info WHERE kp=?";
try { try {
return this.jt.query(sql, new Object[] {kp}, TENANT_INFO_ROW_MAPPER); return this.jt.query(sql, new Object[]{kp}, TENANT_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -3105,7 +3210,7 @@ public class PersistService {
public TenantInfo findTenantByKp(String kp, String tenantId) { public TenantInfo findTenantByKp(String kp, String tenantId) {
String sql = "SELECT tenant_id,tenant_name,tenant_desc FROM tenant_info WHERE kp=? AND tenant_id=?"; String sql = "SELECT tenant_id,tenant_name,tenant_desc FROM tenant_info WHERE kp=? AND tenant_id=?";
try { try {
return this.jt.queryForObject(sql, new Object[] {kp, tenantId}, TENANT_INFO_ROW_MAPPER); return this.jt.queryForObject(sql, new Object[]{kp, tenantId}, TENANT_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -3129,7 +3234,7 @@ public class PersistService {
public User findUserByUsername(String username) { public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? "; String sql = "SELECT username,password FROM users WHERE username=? ";
try { try {
return this.jt.queryForObject(sql, new Object[] {username}, USER_ROW_MAPPER); return this.jt.queryForObject(sql, new Object[]{username}, USER_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
throw e; throw e;
@ -3141,13 +3246,27 @@ public class PersistService {
} }
} }
/**
* 更新用户密码
*/
public void updateUserPassword(String username, String password) {
try {
jt.update(
"UPDATE users SET password = ? WHERE username=?",
password, username);
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
private List<ConfigInfo> convertDeletedConfig(List<Map<String, Object>> list) { private List<ConfigInfo> convertDeletedConfig(List<Map<String, Object>> list) {
List<ConfigInfo> configs = new ArrayList<ConfigInfo>(); List<ConfigInfo> configs = new ArrayList<ConfigInfo>();
for (Map<String, Object> map : list) { for (Map<String, Object> map : list) {
String dataId = (String)map.get("data_id"); String dataId = (String) map.get("data_id");
String group = (String)map.get("group_id"); String group = (String) map.get("group_id");
String tenant = (String)map.get("tenant_id"); String tenant = (String) map.get("tenant_id");
ConfigInfo config = new ConfigInfo(); ConfigInfo config = new ConfigInfo();
config.setDataId(dataId); config.setDataId(dataId);
config.setGroup(group); config.setGroup(group);
@ -3161,11 +3280,11 @@ public class PersistService {
List<Map<String, Object>> list) { List<Map<String, Object>> list) {
List<ConfigInfoWrapper> configs = new ArrayList<ConfigInfoWrapper>(); List<ConfigInfoWrapper> configs = new ArrayList<ConfigInfoWrapper>();
for (Map<String, Object> map : list) { for (Map<String, Object> map : list) {
String dataId = (String)map.get("data_id"); String dataId = (String) map.get("data_id");
String group = (String)map.get("group_id"); String group = (String) map.get("group_id");
String tenant = (String)map.get("tenant_id"); String tenant = (String) map.get("tenant_id");
String content = (String)map.get("content"); String content = (String) map.get("content");
long mTime = ((Timestamp)map.get("gmt_modified")).getTime(); long mTime = ((Timestamp) map.get("gmt_modified")).getTime();
ConfigInfoWrapper config = new ConfigInfoWrapper(); ConfigInfoWrapper config = new ConfigInfoWrapper();
config.setDataId(dataId); config.setDataId(dataId);
config.setGroup(group); config.setGroup(group);
@ -3185,7 +3304,7 @@ public class PersistService {
public List<ConfigInfoWrapper> listAllGroupKeyMd5() { public List<ConfigInfoWrapper> listAllGroupKeyMd5() {
final int pageSize = 10000; final int pageSize = 10000;
int totalCount = configInfoCount(); int totalCount = configInfoCount();
int pageCount = (int)Math.ceil(totalCount * 1.0 / pageSize); int pageCount = (int) Math.ceil(totalCount * 1.0 / pageSize);
List<ConfigInfoWrapper> allConfigInfo = new ArrayList<ConfigInfoWrapper>(); List<ConfigInfoWrapper> allConfigInfo = new ArrayList<ConfigInfoWrapper>();
for (int pageNo = 1; pageNo <= pageCount; pageNo++) { for (int pageNo = 1; pageNo <= pageCount; pageNo++) {
List<ConfigInfoWrapper> configInfoList = listGroupKeyMd5ByPage(pageNo, pageSize); List<ConfigInfoWrapper> configInfoList = listGroupKeyMd5ByPage(pageNo, pageSize);
@ -3200,7 +3319,7 @@ public class PersistService {
= " SELECT t.id,data_id,group_id,tenant_id,app_name,md5,gmt_modified FROM ( SELECT id FROM config_info ORDER BY id LIMIT ?,? ) g, config_info t WHERE g.id = t.id"; = " SELECT t.id,data_id,group_id,tenant_id,app_name,md5,gmt_modified FROM ( SELECT id FROM config_info ORDER BY id LIMIT ?,? ) g, config_info t WHERE g.id = t.id";
PaginationHelper<ConfigInfoWrapper> helper = new PaginationHelper<ConfigInfoWrapper>(); PaginationHelper<ConfigInfoWrapper> helper = new PaginationHelper<ConfigInfoWrapper>();
try { try {
Page<ConfigInfoWrapper> page = helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[] { Page<ConfigInfoWrapper> page = helper.fetchPageLimit(jt, sqlCountRows, sqlFetchRows, new Object[]{
(pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_WRAPPER_ROW_MAPPER); (pageNo - 1) * pageSize, pageSize}, pageNo, pageSize, CONFIG_INFO_WRAPPER_ROW_MAPPER);
return page.getPageItems(); return page.getPageItems();
@ -3213,7 +3332,9 @@ public class PersistService {
private String generateLikeArgument(String s) { private String generateLikeArgument(String s) {
String fuzzySearchSign = "\\*"; String fuzzySearchSign = "\\*";
String sqlLikePercentSign = "%"; String sqlLikePercentSign = "%";
if (s.contains(PATTERN_STR)) { return s.replaceAll(fuzzySearchSign, sqlLikePercentSign); } else { if (s.contains(PATTERN_STR)) {
return s.replaceAll(fuzzySearchSign, sqlLikePercentSign);
} else {
return s; return s;
} }
} }
@ -3224,7 +3345,7 @@ public class PersistService {
return this.jt return this.jt
.queryForObject( .queryForObject(
"SELECT ID,data_id,group_id,tenant_id,app_name,content,gmt_modified,md5 FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?", "SELECT ID,data_id,group_id,tenant_id,app_name,content,gmt_modified,md5 FROM config_info WHERE data_id=? AND group_id=? AND tenant_id=?",
new Object[] {dataId, group, tenantTmp}, CONFIG_INFO_WRAPPER_ROW_MAPPER); new Object[]{dataId, group, tenantTmp}, CONFIG_INFO_WRAPPER_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) { } catch (EmptyResultDataAccessException e) {
return null; return null;
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
@ -3247,7 +3368,7 @@ public class PersistService {
defaultLog.info("[start completeMd5]"); defaultLog.info("[start completeMd5]");
int perPageSize = 1000; int perPageSize = 1000;
int rowCount = configInfoCount(); int rowCount = configInfoCount();
int pageCount = (int)Math.ceil(rowCount * 1.0 / perPageSize); int pageCount = (int) Math.ceil(rowCount * 1.0 / perPageSize);
int actualRowCount = 0; int actualRowCount = 0;
for (int pageNo = 1; pageNo <= pageCount; pageNo++) { for (int pageNo = 1; pageNo <= pageCount; pageNo++) {
Page<PersistService.ConfigInfoWrapper> page = findAllConfigInfoForDumpAll( Page<PersistService.ConfigInfoWrapper> page = findAllConfigInfoForDumpAll(
@ -3265,7 +3386,7 @@ public class PersistService {
} catch (Exception e) { } catch (Exception e) {
LogUtil.defaultLog LogUtil.defaultLog
.error("[completeMd5-error] datId:{} group:{} lastModified:{}", .error("[completeMd5-error] datId:{} group:{} lastModified:{}",
new Object[] { new Object[]{
cf.getDataId(), cf.getDataId(),
cf.getGroup(), cf.getGroup(),
new Timestamp(cf new Timestamp(cf
@ -3278,7 +3399,7 @@ public class PersistService {
new Timestamp(cf.getLastModified())); new Timestamp(cf.getLastModified()));
} catch (Exception e) { } catch (Exception e) {
LogUtil.defaultLog.error("[completeMd5-error] datId:{} group:{} lastModified:{}", LogUtil.defaultLog.error("[completeMd5-error] datId:{} group:{} lastModified:{}",
new Object[] {cf.getDataId(), cf.getGroup(), new Object[]{cf.getDataId(), cf.getGroup(),
new Timestamp(cf.getLastModified())}); new Timestamp(cf.getLastModified())});
} }
} }
@ -3299,11 +3420,11 @@ public class PersistService {
* @return Collection of ConfigInfo objects * @return Collection of ConfigInfo objects
*/ */
public List<ConfigInfo> findAllConfigInfo4Export(final String dataId, final String group, final String tenant, public List<ConfigInfo> findAllConfigInfo4Export(final String dataId, final String group, final String tenant,
final String appName, final List<Long> ids) { final String appName, final List<Long> ids) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
StringBuilder where = new StringBuilder(" where "); StringBuilder where = new StringBuilder(" where ");
List<Object> paramList = new ArrayList<>(); List<Object> paramList = new ArrayList<>();
if(!CollectionUtils.isEmpty(ids)){ if (!CollectionUtils.isEmpty(ids)) {
where.append(" id in ("); where.append(" id in (");
for (int i = 0; i < ids.size(); i++) { for (int i = 0; i < ids.size(); i++) {
if (i != 0) { if (i != 0) {
@ -3367,9 +3488,9 @@ public class PersistService {
String type = null; String type = null;
if (configInfo.getDataId().contains(SPOT)) { if (configInfo.getDataId().contains(SPOT)) {
String extName = configInfo.getDataId().substring(configInfo.getDataId().lastIndexOf(SPOT) + 1).toLowerCase(); String extName = configInfo.getDataId().substring(configInfo.getDataId().lastIndexOf(SPOT) + 1).toLowerCase();
try{ try {
type = FileTypeEnum.valueOf(extName).getFileType(); type = FileTypeEnum.valueOf(extName).getFileType();
}catch (Exception ex){ } catch (Exception ex) {
type = FileTypeEnum.TEXT.getFileType(); type = FileTypeEnum.TEXT.getFileType();
} }
} }

View File

@ -15,20 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.monitor.MetricsMonitor; import com.alibaba.nacos.config.server.monitor.MetricsMonitor;
import com.alibaba.nacos.config.server.service.notify.NotifyService; import com.alibaba.nacos.config.server.service.notify.NotifyService;
@ -37,7 +23,6 @@ import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import com.alibaba.nacos.config.server.utils.RunningConfigUtils;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
@ -54,11 +39,18 @@ import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
import static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP; import static com.alibaba.nacos.core.utils.SystemUtils.*;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.readClusterConf;
/** /**
* Serverlist service * Serverlist service
@ -169,7 +161,8 @@ public class ServerListService implements ApplicationListener<WebServerInitializ
/** /**
* serverList has changed * serverList has changed
*/ */
static public class ServerlistChangeEvent implements EventDispatcher.Event {} static public class ServerlistChangeEvent implements EventDispatcher.Event {
}
private void updateIfChanged(List<String> newList) { private void updateIfChanged(List<String> newList) {
if (newList.isEmpty()) { if (newList.isEmpty()) {

View File

@ -16,15 +16,12 @@
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
/** /**

View File

@ -15,6 +15,7 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import ch.qos.logback.classic.Level;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,46 +29,74 @@ public class LogUtil {
/** /**
* 默认的日志 * 默认的日志
*/ */
static public final Logger defaultLog = LoggerFactory.getLogger("com.alibaba.nacos.config.startLog"); public static final Logger defaultLog = LoggerFactory.getLogger("com.alibaba.nacos.config.startLog");
/** /**
* 致命错误需要告警 * 致命错误需要告警
*/ */
static public final Logger fatalLog = LoggerFactory public static final Logger fatalLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.fatal"); .getLogger("com.alibaba.nacos.config.fatal");
/** /**
* 客户端GET方法获取数据的日志 * 客户端GET方法获取数据的日志
*/ */
static public final Logger pullLog = LoggerFactory public static final Logger pullLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.pullLog"); .getLogger("com.alibaba.nacos.config.pullLog");
static public final Logger pullCheckLog = LoggerFactory public static final Logger pullCheckLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.pullCheckLog"); .getLogger("com.alibaba.nacos.config.pullCheckLog");
/** /**
* 从DB dump数据的日志 * 从DB dump数据的日志
*/ */
static public final Logger dumpLog = LoggerFactory public static final Logger dumpLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.dumpLog"); .getLogger("com.alibaba.nacos.config.dumpLog");
static public final Logger memoryLog = LoggerFactory public static final Logger memoryLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.monitorLog"); .getLogger("com.alibaba.nacos.config.monitorLog");
static public final Logger clientLog = LoggerFactory public static final Logger clientLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.clientLog"); .getLogger("com.alibaba.nacos.config.clientLog");
static public final Logger sdkLog = LoggerFactory public static final Logger traceLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.sdkLog");
static public final Logger traceLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.traceLog"); .getLogger("com.alibaba.nacos.config.traceLog");
static public final Logger aclLog = LoggerFactory public static final Logger notifyLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.aclLog");
static public final Logger notifyLog = LoggerFactory
.getLogger("com.alibaba.nacos.config.notifyLog"); .getLogger("com.alibaba.nacos.config.notifyLog");
static public final Logger appCollectorLog = LoggerFactory public static void setLogLevel(String logName, String level) {
.getLogger("com.alibaba.nacos.config.appCollectorLog");
switch (logName) {
case "config-server":
((ch.qos.logback.classic.Logger) defaultLog).setLevel(Level.valueOf(level));
break;
case "config-fatal":
((ch.qos.logback.classic.Logger) fatalLog).setLevel(Level.valueOf(level));
break;
case "config-pull":
((ch.qos.logback.classic.Logger) pullLog).setLevel(Level.valueOf(level));
break;
case "config-pull-check":
((ch.qos.logback.classic.Logger) pullCheckLog).setLevel(Level.valueOf(level));
break;
case "config-dump":
((ch.qos.logback.classic.Logger) dumpLog).setLevel(Level.valueOf(level));
break;
case "config-memory":
((ch.qos.logback.classic.Logger) memoryLog).setLevel(Level.valueOf(level));
break;
case "config-client-request":
((ch.qos.logback.classic.Logger) clientLog).setLevel(Level.valueOf(level));
break;
case "config-trace":
((ch.qos.logback.classic.Logger) traceLog).setLevel(Level.valueOf(level));
break;
case "config-notify":
((ch.qos.logback.classic.Logger) notifyLog).setLevel(Level.valueOf(level));
break;
default:
break;
}
}
} }

View File

@ -24,7 +24,6 @@ import org.springframework.test.context.web.WebAppConfiguration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;

View File

@ -15,16 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import com.alibaba.nacos.config.server.utils.SimpleReadWriteLock; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration

View File

@ -15,6 +15,8 @@
*/ */
package com.alibaba.nacos.config.server.utils.event; package com.alibaba.nacos.config.server.utils.event;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
import org.junit.After; import org.junit.After;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
@ -22,10 +24,6 @@ import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;

View File

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
</parent> </parent>
<artifactId>nacos-console</artifactId> <artifactId>nacos-console</artifactId>
<!--<packaging>war</packaging>--> <!--<packaging>war</packaging>-->
@ -93,13 +93,6 @@
<exclude>static/console-fe/.vscode/**</exclude> <exclude>static/console-fe/.vscode/**</exclude>
</excludes> </excludes>
</resource> </resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>nacos-version.txt</include>
</includes>
</resource>
</resources> </resources>
</build> </build>

View File

@ -17,15 +17,19 @@ package com.alibaba.nacos.console.controller;
import com.alibaba.nacos.console.config.WebSecurityConfig; import com.alibaba.nacos.console.config.WebSecurityConfig;
import com.alibaba.nacos.config.server.model.RestResult; import com.alibaba.nacos.config.server.model.RestResult;
import com.alibaba.nacos.console.security.CustomUserDetailsServiceImpl;
import com.alibaba.nacos.console.utils.JwtTokenUtils; import com.alibaba.nacos.console.utils.JwtTokenUtils;
import com.alibaba.nacos.console.utils.PasswordEncoderUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -42,6 +46,8 @@ public class AuthController {
private JwtTokenUtils jwtTokenUtils; private JwtTokenUtils jwtTokenUtils;
@Autowired @Autowired
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsServiceImpl userDetailsService;
/** /**
* Whether the Nacos is in broken states or not, and cannot recover except by being restarted * Whether the Nacos is in broken states or not, and cannot recover except by being restarted
@ -78,4 +84,33 @@ public class AuthController {
return rr; return rr;
} }
} }
@ResponseBody
@RequestMapping(value = "password", method = RequestMethod.PUT)
public RestResult<String> updatePassword(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "oldPassword", required = true) String oldPassword,
@RequestParam(value = "newPassword", required = true) String newPassword) throws Exception {
RestResult<String> rr = new RestResult<String>();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = ((UserDetails) principal).getUsername();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
String password = userDetails.getPassword();
// TODO: throw out more fine grained exceptions
try {
if (PasswordEncoderUtil.matches(oldPassword, password)) {
userDetailsService.updateUserPassword(username, PasswordEncoderUtil.encode(newPassword));
rr.setCode(200);
rr.setMessage("Update password success");
} else {
rr.setCode(401);
rr.setMessage("Old password is invalid");
}
} catch (Exception e) {
rr.setCode(500);
rr.setMessage("Update userpassword failed");
}
return rr;
}
} }

View File

@ -43,4 +43,8 @@ public class CustomUserDetailsServiceImpl implements UserDetailsService {
} }
return new CustomUserDetails(user); return new CustomUserDetails(user);
} }
public void updateUserPassword(String username, String password) throws Exception {
persistService.updateUserPassword(username, password);
}
} }

View File

@ -27,4 +27,12 @@ public class PasswordEncoderUtil {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(new BCryptPasswordEncoder().encode("nacos")); System.out.println(new BCryptPasswordEncoder().encode("nacos"));
} }
public static Boolean matches(String raw, String encoded) {
return new BCryptPasswordEncoder().matches(raw, encoded);
}
public static String encode(String raw) {
return new BCryptPasswordEncoder().encode(raw);
}
} }

View File

@ -23,8 +23,8 @@ cssLoader.use.push({
loader: '@alifd/next-theme-loader', loader: '@alifd/next-theme-loader',
options: { options: {
modifyVars: { modifyVars: {
'$icon-font-path':'"/console-fe/public/icons/icon-font"', '$icon-font-path':'"/nacos/console-fe/public/icons/icon-font"',
'$font-custom-path': '"/console-fe/public/fonts/"' '$font-custom-path': '"/nacos/console-fe/public/fonts/"'
} }
} }
}) })

View File

@ -619,6 +619,10 @@ const request = (function(_global) {
// 跳转至login页 // 跳转至login页
// TODO: react-router 重写改造成本比较高这里先hack // TODO: react-router 重写改造成本比较高这里先hack
const url = window.location.href; const url = window.location.href;
// TODO: 后端返回细致的错误码如果原始密码不对 不应该直接跳到登陆页
if (url.includes('password')) {
return;
}
const base_url = url.split('#')[0]; const base_url = url.split('#')[0];
window.location = `${base_url}#/login`; window.location = `${base_url}#/login`;
} }

View File

@ -30,6 +30,7 @@ import { LANGUAGE_KEY, REDUX_DEVTOOLS } from './constants';
import Login from './pages/Login'; import Login from './pages/Login';
import Namespace from './pages/NameSpace'; import Namespace from './pages/NameSpace';
import Password from './pages/Password';
import Newconfig from './pages/ConfigurationManagement/NewConfig'; import Newconfig from './pages/ConfigurationManagement/NewConfig';
import Configsync from './pages/ConfigurationManagement/ConfigSync'; import Configsync from './pages/ConfigurationManagement/ConfigSync';
import Configdetail from './pages/ConfigurationManagement/ConfigDetail'; import Configdetail from './pages/ConfigurationManagement/ConfigDetail';
@ -74,6 +75,7 @@ const MENU = [
{ path: '/', exact: true, render: () => <Redirect to="/welcome" /> }, { path: '/', exact: true, render: () => <Redirect to="/welcome" /> },
{ path: '/welcome', component: Welcome }, { path: '/welcome', component: Welcome },
{ path: '/namespace', component: Namespace }, { path: '/namespace', component: Namespace },
{ path: '/password', component: Password },
{ path: '/newconfig', component: Newconfig }, { path: '/newconfig', component: Newconfig },
{ path: '/configsync', component: Configsync }, { path: '/configsync', component: Configsync },
{ path: '/configdetail', component: Configdetail }, { path: '/configdetail', component: Configdetail },

View File

@ -49,6 +49,10 @@ class Header extends React.Component {
this.props.history.push('/login'); this.props.history.push('/login');
}; };
changePassword = () => {
this.props.history.push('/password');
};
getUsername = () => { getUsername = () => {
const token = window.localStorage.getItem('token'); const token = window.localStorage.getItem('token');
if (token) { if (token) {
@ -94,6 +98,7 @@ class Header extends React.Component {
<Dropdown trigger={<div className="logout">{this.getUsername()}</div>}> <Dropdown trigger={<div className="logout">{this.getUsername()}</div>}>
<Menu> <Menu>
<Menu.Item onClick={this.logout}>{locale.logout}</Menu.Item> <Menu.Item onClick={this.logout}>{locale.logout}</Menu.Item>
<Menu.Item onClick={this.changePassword}>{locale.changePassword}</Menu.Item>
</Menu> </Menu>
</Dropdown> </Dropdown>
)} )}

View File

@ -341,9 +341,6 @@ class MainLayout extends React.Component {
}); });
return; return;
} }
this.setState({
noChild: !!nowNavObj.dontUseChild,
});
const { parentServiceName } = nowNavObj; const { parentServiceName } = nowNavObj;
const parentNav = this.oneLevelNavArr[parentServiceName]; const parentNav = this.oneLevelNavArr[parentServiceName];
@ -391,7 +388,11 @@ class MainLayout extends React.Component {
refreshNav() { refreshNav() {
const { navList } = this.state; const { navList } = this.state;
const { location, history, functionMode } = this.props; const { location, history, functionMode } = this.props;
const [configUrl, serviceUrl, clusterUrl] = ['/configurationManagement', '/serviceManagement', '/clusterManagement']; const [configUrl, serviceUrl, clusterUrl] = [
'/configurationManagement',
'/serviceManagement',
'/clusterManagement',
];
this.setState( this.setState(
{ {
navList: navList.map(item => { navList: navList.map(item => {

View File

@ -19,6 +19,7 @@ const I18N_CONF = {
community: 'COMMUNITY', community: 'COMMUNITY',
languageSwitchButton: '中', languageSwitchButton: '中',
logout: 'logout', logout: 'logout',
changePassword: 'modify password',
passwordRequired: 'password should not be empty', passwordRequired: 'password should not be empty',
usernameRequired: 'username should not be empty', usernameRequired: 'username should not be empty',
}, },
@ -50,6 +51,19 @@ const I18N_CONF = {
clusterManagementVirtual: 'ClusterManagement', clusterManagementVirtual: 'ClusterManagement',
clusterManagement: 'Cluster Node List', clusterManagement: 'Cluster Node List',
}, },
Password: {
passwordNotConsistent: 'The passwords are not consistent',
passwordRequired: 'password should not be empty',
pleaseInputOldPassword: 'Please input original password',
pleaseInputNewPassword: 'Please input new password',
pleaseInputNewPasswordAgain: 'Please input new password again',
oldPassword: 'Original password',
newPassword: 'New password',
checkPassword: 'Check password',
changePassword: 'modify password',
invalidPassword: 'Invalid original password',
modifyPasswordFailed: 'Modify password failed',
},
NameSpace: { NameSpace: {
namespace: 'Namespaces', namespace: 'Namespaces',
prompt: 'Notice', prompt: 'Notice',
@ -78,6 +92,7 @@ const I18N_CONF = {
serviceList: 'Service List', serviceList: 'Service List',
serviceName: 'Service Name', serviceName: 'Service Name',
serviceNamePlaceholder: 'Enter Service Name', serviceNamePlaceholder: 'Enter Service Name',
hiddenEmptyService: 'Hidden Empty Service',
query: 'Search', query: 'Search',
pubNoData: 'No results found.', pubNoData: 'No results found.',
columnServiceName: 'Service Name', columnServiceName: 'Service Name',
@ -291,12 +306,17 @@ const I18N_CONF = {
target: 'Target:', target: 'Target:',
selectNamespace: 'Select Namespace', selectNamespace: 'Select Namespace',
selectedEntry: '| Selected Entry', selectedEntry: '| Selected Entry',
cloneSelectedAlertTitle: 'Clone config',
cloneSelectedAlertContent: 'please select the configuration to clone',
delSelectedAlertTitle: 'Delete config',
delSelectedAlertContent: 'please select the configuration to delete',
delSuccessMsg: 'delete successful',
}, },
NewConfig: { NewConfig: {
newListingMain: 'Create Configuration', newListingMain: 'Create Configuration',
newListing: 'Create Configuration', newListing: 'Create Configuration',
publishFailed: 'Publish failed. Make sure parameters are entered correctly.', publishFailed: 'Publish failed. Make sure parameters are entered correctly.',
doNotEnte: 'Illegal characters not allowed', doNotEnter: 'Illegal characters not allowed',
newConfig: 'Data ID cannot be empty.', newConfig: 'Data ID cannot be empty.',
dataIdIsNotEmpty: 'Data ID cannot exceed 255 characters in length', dataIdIsNotEmpty: 'Data ID cannot exceed 255 characters in length',
groupPlaceholder: 'Enter your group name', groupPlaceholder: 'Enter your group name',

View File

@ -19,6 +19,7 @@ const I18N_CONF = {
community: '社区', community: '社区',
languageSwitchButton: 'En', languageSwitchButton: 'En',
logout: '登出', logout: '登出',
changePassword: '修改密码',
}, },
Login: { Login: {
login: '登录', login: '登录',
@ -50,6 +51,19 @@ const I18N_CONF = {
clusterManagementVirtual: '集群管理', clusterManagementVirtual: '集群管理',
clusterManagement: '节点列表', clusterManagement: '节点列表',
}, },
Password: {
passwordNotConsistent: '两次输入密码不一致',
passwordRequired: '密码不能为空',
pleaseInputOldPassword: '请输入原始密码',
pleaseInputNewPassword: '请输入新密码',
pleaseInputNewPasswordAgain: '请再次输入新密码',
oldPassword: '原始密码',
newPassword: '新密码',
checkPassword: '再次输入',
changePassword: '修改密码',
invalidPassword: '原始密码错误',
modifyPasswordFailed: '修改密码失败',
},
NameSpace: { NameSpace: {
namespace: '命名空间', namespace: '命名空间',
prompt: '提示', prompt: '提示',
@ -78,6 +92,7 @@ const I18N_CONF = {
serviceList: '服务列表', serviceList: '服务列表',
serviceName: '服务名称', serviceName: '服务名称',
serviceNamePlaceholder: '请输入服务名称', serviceNamePlaceholder: '请输入服务名称',
hiddenEmptyService: '隐藏空服务',
query: '查询', query: '查询',
pubNoData: '没有数据', pubNoData: '没有数据',
columnServiceName: '服务名', columnServiceName: '服务名',
@ -289,12 +304,17 @@ const I18N_CONF = {
target: '目标空间', target: '目标空间',
selectNamespace: '请选择命名空间', selectNamespace: '请选择命名空间',
selectedEntry: '| 选中的条目', selectedEntry: '| 选中的条目',
cloneSelectedAlertTitle: '配置克隆',
cloneSelectedAlertContent: '请选择要克隆的配置',
delSelectedAlertTitle: '配置删除',
delSelectedAlertContent: '请选择要删除的配置',
delSuccessMsg: '删除成功',
}, },
NewConfig: { NewConfig: {
newListingMain: '新建配置', newListingMain: '新建配置',
newListing: '新建配置', newListing: '新建配置',
publishFailed: '发布失败请检查参数是否正确', publishFailed: '发布失败请检查参数是否正确',
doNotEnte: 'Illegal characters not allowed', doNotEnter: '不允许非法字符',
newConfig: 'Data ID 不能为空', newConfig: 'Data ID 不能为空',
dataIdIsNotEmpty: 'Data ID 长度不能超过255字符', dataIdIsNotEmpty: 'Data ID 长度不能超过255字符',
groupPlaceholder: '请输入Group名称', groupPlaceholder: '请输入Group名称',

View File

@ -242,6 +242,22 @@ module.exports = {
useRouter: false, useRouter: false,
id: 'namespace', id: 'namespace',
}, },
{
enable: true,
isExtend: false,
name: '修改密码',
title: '修改密码',
isVirtual: false,
projectName: 'nacos',
serviceName: 'password',
link: 'password',
hasFusion: true,
template: '',
dontUseChild: true,
registerName: 'com.alibaba.nacos.page.password',
useRouter: false,
id: 'password',
},
{ {
enable: false, enable: false,
isExtend: true, isExtend: true,

View File

@ -262,12 +262,14 @@ class ConfigEditor extends React.Component {
stopBeta() { stopBeta() {
const { locale } = this.props; const { locale } = this.props;
const { dataId, group } = this.state.form; const { dataId, group } = this.state.form;
const tenant = getParams('namespace');
return request return request
.delete('v1/cs/configs', { .delete('v1/cs/configs', {
params: { params: {
beta: true, beta: true,
dataId, dataId,
group, group,
tenant,
}, },
}) })
.then(res => { .then(res => {

View File

@ -697,6 +697,52 @@ class ConfigurationManagement extends React.Component {
} }
} }
multipleSelectionDeletion() {
const { locale = {} } = this.props;
const self = this;
if (configsTableSelected.size === 0) {
Dialog.alert({
title: locale.delSelectedAlertTitle,
content: locale.delSelectedAlertContent,
});
} else {
let toShowDatas = [];
configsTableSelected.forEach((value, key, map) => {
let item = {};
item.dataId = value.dataId;
item.group = value.group;
toShowDatas.push(item);
});
Dialog.confirm({
title: locale.removeConfiguration,
content: (
<div style={{ marginTop: '-20px' }}>
<h3>{locale.sureDelete}</h3>
<Table dataSource={toShowDatas}>
<Table.Column title="Data Id" dataIndex="dataId" />
<Table.Column title="Group" dataIndex="group" />
</Table>
</div>
),
onOk: () => {
let idsStr = '';
configsTableSelected.forEach((value, key, map) => {
idsStr = `${idsStr + key},`;
});
const url = `v1/cs/configs?delType=ids&ids=${idsStr}`;
request({
url,
type: 'delete',
success(res) {
Message.success(locale.delSuccessMsg);
self.getData();
},
});
},
});
}
}
cloneSelectedDataConfirm() { cloneSelectedDataConfirm() {
const { locale = {} } = this.props; const { locale = {} } = this.props;
const self = this; const self = this;
@ -704,8 +750,8 @@ class ConfigurationManagement extends React.Component {
self.field.setValue('cloneTargetSpace', undefined); self.field.setValue('cloneTargetSpace', undefined);
if (configsTableSelected.size === 0) { if (configsTableSelected.size === 0) {
Dialog.alert({ Dialog.alert({
title: locale.exportSelectedAlertTitle, title: locale.cloneSelectedAlertTitle,
content: locale.exportSelectedAlertContent, content: locale.cloneSelectedAlertContent,
}); });
return; return;
} }
@ -1258,7 +1304,16 @@ class ConfigurationManagement extends React.Component {
<div style={{ float: 'left' }}> <div style={{ float: 'left' }}>
<Button <Button
type={'primary'} type={'primary'}
style={{ marginLeft: 60, marginRight: 10 }} warning
style={{ marginRight: 10 }}
onClick={this.multipleSelectionDeletion.bind(this)}
data-spm-click={'gostr=/aliyun;locaid=configsDelete'}
>
{locale.deleteAction}
</Button>
<Button
type={'primary'}
style={{ marginRight: 10 }}
onClick={this.exportSelectedData.bind(this)} onClick={this.exportSelectedData.bind(this)}
data-spm-click={'gostr=/aliyun;locaid=configsExport'} data-spm-click={'gostr=/aliyun;locaid=configsExport'}
> >

View File

@ -365,10 +365,10 @@ class NewConfig extends React.Component {
validateChart(rule, value, callback) { validateChart(rule, value, callback) {
const { locale = {} } = this.props; const { locale = {} } = this.props;
const chartReg = /[@#\$%\^&\*]+/g; const chartReg = /[@#\$%\^&\*\s]+/g;
if (chartReg.test(value)) { if (chartReg.test(value)) {
callback(locale.doNotEnte); callback(locale.doNotEnter);
} else { } else {
callback(); callback();
} }

View File

@ -0,0 +1,178 @@
/*
* 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.
*/
import React from 'react';
import PropTypes from 'prop-types';
import RegionGroup from 'components/RegionGroup';
import { ConfigProvider, Input, Field, Form, Message } from '@alifd/next';
import { getParams, setParams, request } from '../../globalLib';
import './index.scss';
const FormItem = Form.Item;
@ConfigProvider.config
class Password extends React.Component {
static displayName = 'Password';
static propTypes = {
locale: PropTypes.object,
};
constructor(props) {
super(props);
this.field = new Field(this);
this.state = {};
}
componentDidMount() {}
validatePassword(rule, value, callback) {
const { locale = {} } = this.props;
if (this.field.getValue('newPassword') !== this.field.getValue('confirmNewPassword')) {
callback(locale.passwordNotConsistent);
} else {
callback();
}
}
handleSubmit = () => {
const { locale = {} } = this.props;
this.field.validate((errors, values) => {
if (errors) {
return;
}
request({
type: 'post',
url: 'v1/auth/login',
data: values,
success: ({ code, data }) => {
if (code === 200) {
// TODO: 封装一个方法存储读取token
localStorage.setItem('token', data);
// TODO: 使用react router
this.props.history.push('/');
}
if (code === 401) {
Message.error({
content: locale.invalidUsernameOrPassword,
});
}
},
error: () => {
Message.error({
content: locale.invalidUsernameOrPassword,
});
},
});
});
};
changePassword() {
const { locale = {} } = this.props;
this.field.validate((errors, values) => {
if (errors) {
return;
}
request({
type: 'put',
url: 'v1/auth/password',
data: values,
success: ({ code, data }) => {
if (code === 200) {
window.localStorage.clear();
this.props.history.push('/login');
}
if (code === 401) {
Message.error({
content: locale.invalidPassword,
});
}
},
error: () => {
Message.error({
content: locale.invalidPassword,
});
},
});
});
}
render() {
const { locale = {} } = this.props;
const formItemLayout = {
labelCol: { fixedSpan: 6 },
wrapperCol: { span: 18 },
};
return (
<div style={{ padding: 10 }}>
<RegionGroup left={locale.changePassword} />
<Form style={{ width: '300px' }} field={this.field}>
<FormItem label={locale.oldPassword} required {...formItemLayout}>
<Input
htmlType="password"
placeholder={locale.pleaseInputOldPassword}
{...this.field.init('oldPassword', {
rules: [
{
required: true,
message: locale.passwordRequired,
},
],
})}
disabled={this.state.type === 0}
/>
</FormItem>
<FormItem label={locale.newPassword} required {...formItemLayout}>
<Input
htmlType="password"
placeholder={locale.pleaseInputNewPassword}
{...this.field.init('newPassword', {
rules: [
{
required: true,
message: locale.passwordRequired,
},
],
})}
disabled={this.state.type === 0}
/>
</FormItem>
<FormItem label={locale.checkPassword} required {...formItemLayout}>
<Input
htmlType="password"
placeholder={locale.pleaseInputNewPasswordAgain}
{...this.field.init('confirmNewPassword', {
rules: [
{
required: true,
message: locale.passwordRequired,
},
{ validator: this.validatePassword.bind(this) },
],
})}
disabled={this.state.type === 0}
/>
</FormItem>
<FormItem label=" " {...formItemLayout}>
<Form.Submit type="primary" onClick={this.changePassword.bind(this)}>
{locale.changePassword}
</Form.Submit>
</FormItem>
</Form>
</div>
);
}
}
export default Password;

View File

@ -0,0 +1,16 @@
/*
* 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.
*/
import Password from './Password';
export default Password;

View File

@ -0,0 +1,12 @@
/*
* 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.
*/

View File

@ -25,6 +25,7 @@ import {
Dialog, Dialog,
Message, Message,
ConfigProvider, ConfigProvider,
Switch,
} from '@alifd/next'; } from '@alifd/next';
import { request } from '../../../globalLib'; import { request } from '../../../globalLib';
import RegionGroup from '../../../components/RegionGroup'; import RegionGroup from '../../../components/RegionGroup';
@ -57,6 +58,7 @@ class ServiceList extends React.Component {
currentPage: 1, currentPage: 1,
keyword: '', keyword: '',
dataSource: [], dataSource: [],
hasIpCount: !(localStorage.getItem('hasIpCount') === 'false'),
}; };
this.field = new Field(this); this.field = new Field(this);
} }
@ -71,15 +73,14 @@ class ServiceList extends React.Component {
openEditServiceDialog() { openEditServiceDialog() {
try { try {
this.editServiceDialog.current.getInstance() this.editServiceDialog.current.getInstance().show(this.state.service);
.show(this.state.service); } catch (error) {}
} catch (error) {
}
} }
queryServiceList() { queryServiceList() {
const { currentPage, pageSize, keyword, withInstances = false } = this.state; const { currentPage, pageSize, keyword, withInstances = false, hasIpCount } = this.state;
const parameter = [ const parameter = [
`hasIpCount=${hasIpCount}`,
`withInstances=${withInstances}`, `withInstances=${withInstances}`,
`pageNo=${currentPage}`, `pageNo=${currentPage}`,
`pageSize=${pageSize}`, `pageSize=${pageSize}`,
@ -119,8 +120,7 @@ class ServiceList extends React.Component {
* *
*/ */
showSampleCode(record) { showSampleCode(record) {
this.showcode.current.getInstance() this.showcode.current.getInstance().openDialog(record);
.openDialog(record);
} }
deleteService(service) { deleteService(service) {
@ -157,7 +157,6 @@ class ServiceList extends React.Component {
rowColor = row => ({ className: !row.healthyInstanceCount ? 'row-bg-red' : '' }); rowColor = row => ({ className: !row.healthyInstanceCount ? 'row-bg-red' : '' });
render() { render() {
const { locale = {} } = this.props; const { locale = {} } = this.props;
const { const {
@ -165,6 +164,7 @@ class ServiceList extends React.Component {
serviceList, serviceList,
serviceName, serviceName,
serviceNamePlaceholder, serviceNamePlaceholder,
hiddenEmptyService,
query, query,
create, create,
operation, operation,
@ -172,7 +172,7 @@ class ServiceList extends React.Component {
sampleCode, sampleCode,
deleteAction, deleteAction,
} = locale; } = locale;
const { keyword, nowNamespaceName, nowNamespaceId } = this.state; const { keyword, nowNamespaceName, nowNamespaceId, hasIpCount } = this.state;
const { init, getValue } = this.field; const { init, getValue } = this.field;
this.init = init; this.init = init;
this.getValue = getValue; this.getValue = getValue;
@ -221,6 +221,17 @@ class ServiceList extends React.Component {
} }
/> />
</FormItem> </FormItem>
<Form.Item label={`${hiddenEmptyService}:`}>
<Switch
checked={hasIpCount}
onChange={hasIpCount =>
this.setState({ hasIpCount, currentPage: 1 }, () => {
localStorage.setItem('hasIpCount', hasIpCount);
this.queryServiceList();
})
}
/>
</Form.Item>
<FormItem label=""> <FormItem label="">
<Button <Button
type="primary" type="primary"
@ -266,8 +277,9 @@ class ServiceList extends React.Component {
<a <a
onClick={() => onClick={() =>
this.props.history.push( this.props.history.push(
`/serviceDetail?name=${record.name}&groupName=${record.groupName}`, `/serviceDetail?name=${record.name}&groupName=${record.groupName}`
)} )
}
style={{ marginRight: 5 }} style={{ marginRight: 5 }}
> >
{detail} {detail}
@ -277,10 +289,7 @@ class ServiceList extends React.Component {
{sampleCode} {sampleCode}
</a> </a>
<span style={{ marginRight: 5 }}>|</span> <span style={{ marginRight: 5 }}>|</span>
<a <a onClick={() => this.deleteService(record)} style={{ marginRight: 5 }}>
onClick={() => this.deleteService(record)}
style={{ marginRight: 5 }}
>
{deleteAction} {deleteAction}
</a> </a>
</div> </div>
@ -290,10 +299,11 @@ class ServiceList extends React.Component {
</Col> </Col>
</Row> </Row>
{this.state.total > this.state.pageSize && ( {this.state.total > this.state.pageSize && (
<div style={{ <div
marginTop: 10, style={{
textAlign: 'right', marginTop: 10,
}} textAlign: 'right',
}}
> >
<Pagination <Pagination
current={this.state.currentPage} current={this.state.currentPage}

View File

@ -26,4 +26,8 @@
color: #000; color: #000;
margin-right: 8px; margin-right: 8px;
} }
.next-switch-off {
background-color: #f2f3f7;
border-color: #c4c6cf;
}
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

View File

@ -16,6 +16,10 @@
package com.alibaba.nacos.core.utils; package com.alibaba.nacos.core.utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.InetAddress; import java.net.InetAddress;
@ -27,10 +31,6 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.alibaba.nacos.core.utils.Constants.*; import static com.alibaba.nacos.core.utils.Constants.*;
/** /**
@ -108,7 +108,7 @@ public class InetUtils {
try { try {
int lowest = Integer.MAX_VALUE; int lowest = Integer.MAX_VALUE;
for (Enumeration<NetworkInterface> nics = NetworkInterface for (Enumeration<NetworkInterface> nics = NetworkInterface
.getNetworkInterfaces(); nics.hasMoreElements();) { .getNetworkInterfaces(); nics.hasMoreElements(); ) {
NetworkInterface ifc = nics.nextElement(); NetworkInterface ifc = nics.nextElement();
if (ifc.isUp()) { if (ifc.isUp()) {
log.info("Testing interface: " + ifc.getDisplayName()); log.info("Testing interface: " + ifc.getDisplayName());
@ -133,8 +133,7 @@ public class InetUtils {
} }
} }
} }
} } catch (IOException ex) {
catch (IOException ex) {
log.error("Cannot get first non-loopback address", ex); log.error("Cannot get first non-loopback address", ex);
} }
@ -144,8 +143,7 @@ public class InetUtils {
try { try {
return InetAddress.getLocalHost(); return InetAddress.getLocalHost();
} } catch (UnknownHostException e) {
catch (UnknownHostException e) {
log.warn("Unable to retrieve localhost"); log.warn("Unable to retrieve localhost");
} }

View File

@ -11,7 +11,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${nacos.home}/logs/cmdb-main.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${nacos.home}/logs/cmdb-main.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize> <maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>7GB</totalSizeCap> <totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -34,8 +34,8 @@
<append>true</append> <append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-server.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-server.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>7GB</totalSizeCap> <totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -59,7 +59,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-raft.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-raft.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -77,14 +77,14 @@
</appender> </appender>
<appender name="naming-ephemeral" <appender name="naming-distro"
class="ch.qos.logback.core.rolling.RollingFileAppender"> class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-ephemeral.log</file> <file>${LOG_HOME}/naming-distro.log</file>
<append>true</append> <append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-ephemeral.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-distro.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -94,11 +94,11 @@
</encoder> </encoder>
</appender> </appender>
<appender name="async-naming-ephemeral" class="ch.qos.logback.classic.AsyncAppender"> <appender name="async-naming-distro" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold> <discardingThreshold>0</discardingThreshold>
<queueSize>1024</queueSize> <queueSize>1024</queueSize>
<neverBlock>true</neverBlock> <neverBlock>true</neverBlock>
<appender-ref ref="naming-ephemeral"/> <appender-ref ref="naming-distro"/>
</appender> </appender>
<appender name="naming-event" <appender name="naming-event"
@ -108,7 +108,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-event.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-event.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -132,7 +132,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-push.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-push.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -148,7 +148,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-rt.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-rt.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -165,7 +165,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-performance.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/naming-performance.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -175,109 +175,6 @@
</encoder> </encoder>
</appender> </appender>
<appender name="naming-router"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-router.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-router.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date|%msg%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="naming-cache"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-cache.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-cache.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date|%msg%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="naming-device"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-device.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-device.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date|%msg%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="naming-tag"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-tag.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-tag.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date %level %msg%n%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="naming-tenant"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-tenant.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-tenant.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date %level %msg%n%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="naming-debug"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/naming-debug.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/naming-debug.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date %level %msg%n%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!--config module logback config--> <!--config module logback config-->
<appender name="dumpFile" <appender name="dumpFile"
class="ch.qos.logback.core.rolling.RollingFileAppender"> class="ch.qos.logback.core.rolling.RollingFileAppender">
@ -286,7 +183,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-dump.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-dump.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize> <maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>7GB</totalSizeCap> <totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -302,7 +199,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-pull.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-pull.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>20MB</maxFileSize> <maxFileSize>20MB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>128MB</totalSizeCap> <totalSizeCap>128MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -318,7 +215,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-fatal.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-fatal.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>20MB</maxFileSize> <maxFileSize>20MB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>128MB</totalSizeCap> <totalSizeCap>128MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -334,7 +231,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-memory.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-memory.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>20MB</maxFileSize> <maxFileSize>20MB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>128MB</totalSizeCap> <totalSizeCap>128MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -350,7 +247,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-pull-check.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-pull-check.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -360,23 +257,6 @@
</encoder> </encoder>
</appender> </appender>
<appender name="aclLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/config-acl.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-acl.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>512MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date %level %msg%n%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="clientLog" <appender name="clientLog"
class="ch.qos.logback.core.rolling.RollingFileAppender"> class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/config-client-request.log</file> <file>${LOG_HOME}/config-client-request.log</file>
@ -384,7 +264,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-client-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-client-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize> <maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>7GB</totalSizeCap> <totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -394,23 +274,6 @@
</encoder> </encoder>
</appender> </appender>
<appender name="sdkLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/config-sdk-request.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-sdk-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date|%msg%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="traceLog" <appender name="traceLog"
class="ch.qos.logback.core.rolling.RollingFileAppender"> class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/config-trace.log</file> <file>${LOG_HOME}/config-trace.log</file>
@ -418,7 +281,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-trace.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-trace.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize> <maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>7GB</totalSizeCap> <totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -435,7 +298,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-notify.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-notify.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>1GB</maxFileSize> <maxFileSize>1GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>3GB</totalSizeCap> <totalSizeCap>3GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -445,23 +308,6 @@
</encoder> </encoder>
</appender> </appender>
<appender name="appCollectorLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/config-app.log</file>
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-app.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>20MB</maxFileSize>
<MaxHistory>15</MaxHistory>
<totalSizeCap>128MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy>
<encoder>
<Pattern>%date %level %msg%n%n</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="startLog" <appender name="startLog"
class="ch.qos.logback.core.rolling.RollingFileAppender"> class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/config-server.log</file> <file>${LOG_HOME}/config-server.log</file>
@ -469,7 +315,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/config-server.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/config-server.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>50MB</maxFileSize> <maxFileSize>50MB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>512MB</totalSizeCap> <totalSizeCap>512MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -486,7 +332,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/nacos.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/nacos.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>50MB</maxFileSize> <maxFileSize>50MB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>512MB</totalSizeCap> <totalSizeCap>512MB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -503,7 +349,7 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_HOME}/nacos-address.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <fileNamePattern>${LOG_HOME}/nacos-address.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxFileSize>2GB</maxFileSize> <maxFileSize>2GB</maxFileSize>
<MaxHistory>15</MaxHistory> <MaxHistory>7</MaxHistory>
<totalSizeCap>7GB</totalSizeCap> <totalSizeCap>7GB</totalSizeCap>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <cleanHistoryOnStart>true</cleanHistoryOnStart>
</rollingPolicy> </rollingPolicy>
@ -531,9 +377,9 @@
<level value="INFO"/> <level value="INFO"/>
<appender-ref ref="async-naming-raft"/> <appender-ref ref="async-naming-raft"/>
</logger> </logger>
<logger name="com.alibaba.nacos.naming.ephemeral" additivity="false"> <logger name="com.alibaba.nacos.naming.distro" additivity="false">
<level value="DEBUG"/> <level value="INFO"/>
<appender-ref ref="async-naming-ephemeral"/> <appender-ref ref="async-naming-distro"/>
</logger> </logger>
<logger name="com.alibaba.nacos.naming.event" additivity="false"> <logger name="com.alibaba.nacos.naming.event" additivity="false">
<level value="INFO"/> <level value="INFO"/>
@ -551,22 +397,6 @@
<level value="INFO"/> <level value="INFO"/>
<appender-ref ref="naming-performance"/> <appender-ref ref="naming-performance"/>
</logger> </logger>
<logger name="com.alibaba.nacos.naming.router" additivity="false">
<level value="INFO"/>
<appender-ref ref="naming-router"/>
</logger>
<logger name="com.alibaba.nacos.naming.cache" additivity="false">
<level value="INFO"/>
<appender-ref ref="naming-cache"/>
</logger>
<logger name="com.alibaba.nacos.naming.tenant" additivity="false">
<level value="INFO"/>
<appender-ref ref="naming-tenant"/>
</logger>
<logger name="com.alibaba.nacos.naming.debug" additivity="false">
<level value="INFO"/>
<appender-ref ref="naming-debug"/>
</logger>
<logger name="com.alibaba.nacos.config.dumpLog" additivity="false"> <logger name="com.alibaba.nacos.config.dumpLog" additivity="false">
<level value="INFO"/> <level value="INFO"/>
@ -589,21 +419,11 @@
<appender-ref ref="memoryFile"/> <appender-ref ref="memoryFile"/>
</logger> </logger>
<logger name="com.alibaba.nacos.config.aclLog" additivity="false">
<level value="INFO"/>
<appender-ref ref="aclLog"/>
</logger>
<logger name="com.alibaba.nacos.config.clientLog" additivity="false"> <logger name="com.alibaba.nacos.config.clientLog" additivity="false">
<level value="info"/> <level value="info"/>
<appender-ref ref="clientLog"/> <appender-ref ref="clientLog"/>
</logger> </logger>
<logger name="com.alibaba.nacos.config.sdkLog" additivity="false">
<level value="INFO"/>
<appender-ref ref="sdkLog"/>
</logger>
<logger name="com.alibaba.nacos.config.notifyLog" additivity="false"> <logger name="com.alibaba.nacos.config.notifyLog" additivity="false">
<level value="INFO"/> <level value="INFO"/>
<appender-ref ref="notifyLog"/> <appender-ref ref="notifyLog"/>
@ -614,11 +434,6 @@
<appender-ref ref="traceLog"/> <appender-ref ref="traceLog"/>
</logger> </logger>
<logger name="com.alibaba.nacos.config.appCollectorLog" additivity="false">
<level value="INFO"/>
<appender-ref ref="appCollectorLog"/>
</logger>
<logger name="com.alibaba.nacos.config.startLog" additivity="false"> <logger name="com.alibaba.nacos.config.startLog" additivity="false">
<level value="INFO"/> <level value="INFO"/>
<appender-ref ref="startLog"/> <appender-ref ref="startLog"/>

View File

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

View File

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

View File

@ -23,31 +23,27 @@ import junit.framework.TestSuite;
* Unit test for simple App. * Unit test for simple App.
*/ */
public class AppTest public class AppTest
extends TestCase extends TestCase {
{
/** /**
* Create the test case * Create the test case
* *
* @param testName name of the test case * @param testName name of the test case
*/ */
public AppTest( String testName ) public AppTest(String testName) {
{ super(testName);
super( testName );
} }
/** /**
* @return the suite of tests being tested * @return the suite of tests being tested
*/ */
public static Test suite() public static Test suite() {
{ return new TestSuite(AppTest.class);
return new TestSuite( AppTest.class );
} }
/** /**
* Rigourous Test :-) * Rigourous Test :-)
*/ */
public void testApp() public void testApp() {
{ assertTrue(true);
assertTrue( true );
} }
} }

View File

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

View File

@ -25,7 +25,8 @@ public class AuthInfo {
private String appKey; private String appKey;
public AuthInfo() {} public AuthInfo() {
}
public AuthInfo(String operator, String appKey) { public AuthInfo(String operator, String appKey) {
this.operator = operator; this.operator = operator;
@ -36,8 +37,8 @@ public class AuthInfo {
try { try {
String[] byteStrs = auth.split(","); String[] byteStrs = auth.split(",");
byte[] bytes = new byte[byteStrs.length]; byte[] bytes = new byte[byteStrs.length];
for(int i = 0; i < byteStrs.length; i++) { for (int i = 0; i < byteStrs.length; i++) {
bytes[i] = (byte)(~(Short.parseShort(byteStrs[i]))); bytes[i] = (byte) (~(Short.parseShort(byteStrs[i])));
} }
String contentStr = new String(bytes, encoding); String contentStr = new String(bytes, encoding);

View File

@ -54,6 +54,8 @@ public class ServerListManager {
private Map<String, List<Server>> distroConfig = new ConcurrentHashMap<>(); private Map<String, List<Server>> distroConfig = new ConcurrentHashMap<>();
private Map<String, Long> distroBeats = new ConcurrentHashMap<>(16);
private Set<String> liveSites = new HashSet<>(); private Set<String> liveSites = new HashSet<>();
private final static String LOCALHOST_SITE = UtilsAndCommons.UNKNOWN_SITE; private final static String LOCALHOST_SITE = UtilsAndCommons.UNKNOWN_SITE;
@ -93,15 +95,15 @@ public class ServerListManager {
Loggers.SRV_LOG.warn("failed to get config: " + CLUSTER_CONF_FILE_PATH, e); Loggers.SRV_LOG.warn("failed to get config: " + CLUSTER_CONF_FILE_PATH, e);
} }
if (Loggers.DEBUG_LOG.isDebugEnabled()) { if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("SERVER-LIST from cluster.conf: {}", result); Loggers.SRV_LOG.debug("SERVER-LIST from cluster.conf: {}", result);
} }
//use system env //use system env
if (CollectionUtils.isEmpty(serverList)) { if (CollectionUtils.isEmpty(serverList)) {
serverList = SystemUtils.getIPsBySystemEnv(UtilsAndCommons.SELF_SERVICE_CLUSTER_ENV); serverList = SystemUtils.getIPsBySystemEnv(UtilsAndCommons.SELF_SERVICE_CLUSTER_ENV);
if (Loggers.DEBUG_LOG.isDebugEnabled()) { if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("SERVER-LIST from system variable: {}", result); Loggers.SRV_LOG.debug("SERVER-LIST from system variable: {}", result);
} }
} }
@ -196,11 +198,17 @@ public class ServerListManager {
throw new IllegalArgumentException("server: " + server.getKey() + " is not in serverlist"); throw new IllegalArgumentException("server: " + server.getKey() + " is not in serverlist");
} }
Long lastBeat = distroBeats.get(server.getKey());
long now = System.currentTimeMillis();
if (null != lastBeat) {
server.setAlive(now - lastBeat < switchDomain.getDistroServerExpiredMillis());
}
distroBeats.put(server.getKey(), now);
Date date = new Date(Long.parseLong(params[2])); Date date = new Date(Long.parseLong(params[2]));
server.setLastRefTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); server.setLastRefTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
server.setWeight(params.length == 4 ? Integer.parseInt(params[3]) : 1); server.setWeight(params.length == 4 ? Integer.parseInt(params[3]) : 1);
server.setAlive(System.currentTimeMillis() - server.getLastRefTime() < switchDomain.getDistroServerExpiredMillis());
List<Server> list = distroConfig.get(server.getSite()); List<Server> list = distroConfig.get(server.getSite());
if (list == null || list.size() <= 0) { if (list == null || list.size() <= 0) {
list = new ArrayList<>(); list = new ArrayList<>();
@ -230,65 +238,6 @@ public class ServerListManager {
distroConfig.put(server.getSite(), tmpServerList); distroConfig.put(server.getSite(), tmpServerList);
} }
liveSites.addAll(distroConfig.keySet()); liveSites.addAll(distroConfig.keySet());
List<Server> servers = distroConfig.get(LOCALHOST_SITE);
if (CollectionUtils.isEmpty(servers)) {
return;
}
//local site servers
List<String> allLocalSiteSrvs = new ArrayList<>();
for (Server server : servers) {
if (server.getKey().endsWith(":0")) {
continue;
}
server.setAdWeight(switchDomain.getAdWeight(server.getKey()) == null ? 0 : switchDomain.getAdWeight(server.getKey()));
for (int i = 0; i < server.getWeight() + server.getAdWeight(); i++) {
if (!allLocalSiteSrvs.contains(server.getKey())) {
allLocalSiteSrvs.add(server.getKey());
}
if (server.isAlive() && !newHealthyList.contains(server)) {
newHealthyList.add(server);
}
}
}
Collections.sort(newHealthyList);
float curRatio = (float) newHealthyList.size() / allLocalSiteSrvs.size();
if (autoDisabledHealthCheck
&& curRatio > switchDomain.getDistroThreshold()
&& System.currentTimeMillis() - lastHealthServerMillis > STABLE_PERIOD) {
Loggers.SRV_LOG.info("[NACOS-DISTRO] distro threshold restored and " +
"stable now, enable health check. current ratio: {}", curRatio);
switchDomain.setHealthCheckEnabled(true);
// we must set this variable, otherwise it will conflict with user's action
autoDisabledHealthCheck = false;
}
if (!CollectionUtils.isEqualCollection(healthyServers, newHealthyList)) {
// for every change disable healthy check for some while
if (switchDomain.isHealthCheckEnabled()) {
Loggers.SRV_LOG.info("[NACOS-DISTRO] healthy server list changed, " +
"disable health check for {} ms from now on, old: {}, new: {}", STABLE_PERIOD,
healthyServers, newHealthyList);
switchDomain.setHealthCheckEnabled(false);
autoDisabledHealthCheck = true;
lastHealthServerMillis = System.currentTimeMillis();
}
healthyServers = newHealthyList;
notifyListeners();
}
} }
public void clean() { public void clean() {
@ -310,29 +259,14 @@ public class ServerListManager {
} }
private void cleanInvalidServers() { private void cleanInvalidServers() {
for (Map.Entry<String, List<Server>> entry : distroConfig.entrySet()) { for (Map.Entry<String, List<Server>> entry : distroConfig.entrySet()) {
List<Server> tmpServers = null; List<Server> currentServers = entry.getValue();
List<Server> currentServerList = entry.getValue(); if (null == currentServers) {
distroConfig.remove(entry.getKey());
for (Server server : entry.getValue()) { continue;
if (!server.isAlive()) {
tmpServers = new ArrayList<>();
for (Server server1 : currentServerList) {
String serverKey1 = server1.getKey() + "_" + server1.getSite();
String serverKey = server.getKey() + "_" + server.getSite();
if (!serverKey.equals(serverKey1) && !tmpServers.contains(server1)) {
tmpServers.add(server1);
}
}
}
}
if (tmpServers != null) {
distroConfig.put(entry.getKey(), tmpServers);
} }
currentServers.removeIf(server -> !server.isAlive());
} }
} }
@ -397,11 +331,7 @@ public class ServerListManager {
return; return;
} }
for (String key : distroConfig.keySet()) { checkDistroHeartbeat();
for (Server server : distroConfig.get(key)) {
server.setAlive(System.currentTimeMillis() - server.getLastRefTime() < switchDomain.getDistroServerExpiredMillis());
}
}
int weight = Runtime.getRuntime().availableProcessors() / 2; int weight = Runtime.getRuntime().availableProcessors() / 2;
if (weight <= 0) { if (weight <= 0) {
@ -442,4 +372,79 @@ public class ServerListManager {
} }
} }
private void checkDistroHeartbeat() {
Loggers.SRV_LOG.debug("check distro heartbeat.");
List<Server> servers = distroConfig.get(LOCALHOST_SITE);
if (CollectionUtils.isEmpty(servers)) {
return;
}
List<Server> newHealthyList = new ArrayList<>(servers.size());
long now = System.currentTimeMillis();
for (Server s: servers) {
Long lastBeat = distroBeats.get(s.getKey());
if (null == lastBeat) {
continue;
}
s.setAlive(now - lastBeat < switchDomain.getDistroServerExpiredMillis());
}
//local site servers
List<String> allLocalSiteSrvs = new ArrayList<>();
for (Server server : servers) {
if (server.getKey().endsWith(":0")) {
continue;
}
server.setAdWeight(switchDomain.getAdWeight(server.getKey()) == null ? 0 : switchDomain.getAdWeight(server.getKey()));
for (int i = 0; i < server.getWeight() + server.getAdWeight(); i++) {
if (!allLocalSiteSrvs.contains(server.getKey())) {
allLocalSiteSrvs.add(server.getKey());
}
if (server.isAlive() && !newHealthyList.contains(server)) {
newHealthyList.add(server);
}
}
}
Collections.sort(newHealthyList);
float curRatio = (float) newHealthyList.size() / allLocalSiteSrvs.size();
if (autoDisabledHealthCheck
&& curRatio > switchDomain.getDistroThreshold()
&& System.currentTimeMillis() - lastHealthServerMillis > STABLE_PERIOD) {
Loggers.SRV_LOG.info("[NACOS-DISTRO] distro threshold restored and " +
"stable now, enable health check. current ratio: {}", curRatio);
switchDomain.setHealthCheckEnabled(true);
// we must set this variable, otherwise it will conflict with user's action
autoDisabledHealthCheck = false;
}
if (!CollectionUtils.isEqualCollection(healthyServers, newHealthyList)) {
// for every change disable healthy check for some while
if (switchDomain.isHealthCheckEnabled()) {
Loggers.SRV_LOG.info("[NACOS-DISTRO] healthy server list changed, " +
"disable health check for {} ms from now on, old: {}, new: {}", STABLE_PERIOD,
healthyServers, newHealthyList);
switchDomain.setHealthCheckEnabled(false);
autoDisabledHealthCheck = true;
lastHealthServerMillis = System.currentTimeMillis();
}
healthyServers = newHealthyList;
notifyListeners();
}
}
} }

View File

@ -23,13 +23,10 @@ import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.pojo.Record; import com.alibaba.nacos.naming.pojo.Record;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.apache.commons.lang3.CharEncoding.UTF_8;
/** /**
* Use FastJSON to serialize data * Use FastJSON to serialize data
* *

View File

@ -75,8 +75,8 @@ public class DataSyncer {
String key = iterator.next(); String key = iterator.next();
if (StringUtils.isNotBlank(taskMap.putIfAbsent(buildKey(key, task.getTargetServer()), key))) { if (StringUtils.isNotBlank(taskMap.putIfAbsent(buildKey(key, task.getTargetServer()), key))) {
// associated key already exist: // associated key already exist:
if (Loggers.EPHEMERAL.isDebugEnabled()) { if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("sync already in process, key: {}", key); Loggers.DISTRO.debug("sync already in process, key: {}", key);
} }
iterator.remove(); iterator.remove();
} }
@ -100,8 +100,8 @@ public class DataSyncer {
List<String> keys = task.getKeys(); List<String> keys = task.getKeys();
if (Loggers.EPHEMERAL.isDebugEnabled()) { if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("sync keys: {}", keys); Loggers.DISTRO.debug("sync keys: {}", keys);
} }
Map<String, Datum> datumMap = dataStore.batchGet(keys); Map<String, Datum> datumMap = dataStore.batchGet(keys);
@ -133,7 +133,7 @@ public class DataSyncer {
} }
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("sync data failed.", e); Loggers.DISTRO.error("sync data failed.", e);
} }
} }
}, delay); }, delay);
@ -164,8 +164,8 @@ public class DataSyncer {
try { try {
if (Loggers.EPHEMERAL.isDebugEnabled()) { if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("server list is: {}", getServers()); Loggers.DISTRO.debug("server list is: {}", getServers());
} }
// send local timestamps to other servers: // send local timestamps to other servers:
@ -182,8 +182,8 @@ public class DataSyncer {
return; return;
} }
if (Loggers.EPHEMERAL.isDebugEnabled()) { if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("sync checksums: {}", keyChecksums); Loggers.DISTRO.debug("sync checksums: {}", keyChecksums);
} }
for (Server member : getServers()) { for (Server member : getServers()) {
@ -193,7 +193,7 @@ public class DataSyncer {
NamingProxy.syncCheckSums(keyChecksums, member.getKey()); NamingProxy.syncCheckSums(keyChecksums, member.getKey());
} }
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("timed sync task failed.", e); Loggers.DISTRO.error("timed sync task failed.", e);
} }
} }
} }

View File

@ -104,14 +104,14 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
private Map<String, String> syncChecksumTasks = new ConcurrentHashMap<>(16); private Map<String, String> syncChecksumTasks = new ConcurrentHashMap<>(16);
@PostConstruct @PostConstruct
public void init() throws Exception { public void init() {
GlobalExecutor.submit(new Runnable() { GlobalExecutor.submit(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
load(); load();
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("load data failed.", e); Loggers.DISTRO.error("load data failed.", e);
} }
} }
}); });
@ -127,15 +127,15 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
// size = 1 means only myself in the list, we need at least one another server alive: // size = 1 means only myself in the list, we need at least one another server alive:
while (serverListManager.getHealthyServers().size() <= 1) { while (serverListManager.getHealthyServers().size() <= 1) {
Thread.sleep(1000L); Thread.sleep(1000L);
Loggers.EPHEMERAL.info("waiting server list init..."); Loggers.DISTRO.info("waiting server list init...");
} }
for (Server server : serverListManager.getHealthyServers()) { for (Server server : serverListManager.getHealthyServers()) {
if (NetUtils.localServer().equals(server.getKey())) { if (NetUtils.localServer().equals(server.getKey())) {
continue; continue;
} }
if (Loggers.EPHEMERAL.isDebugEnabled()) { if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("sync from " + server); Loggers.DISTRO.debug("sync from " + server);
} }
// try sync data from remote server: // try sync data from remote server:
if (syncAllDataFromRemote(server)) { if (syncAllDataFromRemote(server)) {
@ -154,6 +154,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
@Override @Override
public void remove(String key) throws NacosException { public void remove(String key) throws NacosException {
onRemove(key); onRemove(key);
listeners.remove(key);
} }
@Override @Override
@ -186,8 +187,6 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
return; return;
} }
listeners.remove(key);
notifier.addTask(key, ApplyAction.DELETE); notifier.addTask(key, ApplyAction.DELETE);
} }
@ -195,7 +194,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
if (syncChecksumTasks.containsKey(server)) { if (syncChecksumTasks.containsKey(server)) {
// Already in process of this server: // Already in process of this server:
Loggers.EPHEMERAL.warn("sync checksum task already in process with {}", server); Loggers.DISTRO.warn("sync checksum task already in process with {}", server);
return; return;
} }
@ -208,7 +207,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
for (Map.Entry<String, String> entry : checksumMap.entrySet()) { for (Map.Entry<String, String> entry : checksumMap.entrySet()) {
if (distroMapper.responsible(KeyBuilder.getServiceName(entry.getKey()))) { if (distroMapper.responsible(KeyBuilder.getServiceName(entry.getKey()))) {
// this key should not be sent from remote server: // this key should not be sent from remote server:
Loggers.EPHEMERAL.error("receive responsible key timestamp of " + entry.getKey() + " from " + server); Loggers.DISTRO.error("receive responsible key timestamp of " + entry.getKey() + " from " + server);
// abort the procedure: // abort the procedure:
return; return;
} }
@ -230,7 +229,9 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
} }
} }
Loggers.EPHEMERAL.info("to remove keys: {}, to update keys: {}, source: {}", toRemoveKeys, toUpdateKeys, server); if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.DISTRO.info("to remove keys: {}, to update keys: {}, source: {}", toRemoveKeys, toUpdateKeys, server);
}
for (String key : toRemoveKeys) { for (String key : toRemoveKeys) {
onRemove(key); onRemove(key);
@ -244,7 +245,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
byte[] result = NamingProxy.getData(toUpdateKeys, server); byte[] result = NamingProxy.getData(toUpdateKeys, server);
processData(result); processData(result);
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("get data from " + server + " failed!", e); Loggers.DISTRO.error("get data from " + server + " failed!", e);
} }
} finally { } finally {
// Remove this 'in process' flag: // Remove this 'in process' flag:
@ -260,7 +261,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
processData(data); processData(data);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("sync full data from " + server + " failed!", e); Loggers.DISTRO.error("sync full data from " + server + " failed!", e);
return false; return false;
} }
} }
@ -278,7 +279,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
// pretty sure the service not exist: // pretty sure the service not exist:
if (switchDomain.isDefaultInstanceEphemeral()) { if (switchDomain.isDefaultInstanceEphemeral()) {
// create empty service // create empty service
Loggers.EPHEMERAL.info("creating service {}", entry.getKey()); Loggers.DISTRO.info("creating service {}", entry.getKey());
Service service = new Service(); Service service = new Service();
String serviceName = KeyBuilder.getServiceName(entry.getKey()); String serviceName = KeyBuilder.getServiceName(entry.getKey());
String namespaceId = KeyBuilder.getNamespace(entry.getKey()); String namespaceId = KeyBuilder.getNamespace(entry.getKey());
@ -298,7 +299,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
if (!listeners.containsKey(entry.getKey())) { if (!listeners.containsKey(entry.getKey())) {
// Should not happen: // Should not happen:
Loggers.EPHEMERAL.warn("listener of {} not found.", entry.getKey()); Loggers.DISTRO.warn("listener of {} not found.", entry.getKey());
continue; continue;
} }
@ -307,7 +308,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
listener.onChange(entry.getKey(), entry.getValue().value); listener.onChange(entry.getKey(), entry.getValue().value);
} }
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("[NACOS-DISTRO] error while execute listener of key: {}", entry.getKey(), e); Loggers.DISTRO.error("[NACOS-DISTRO] error while execute listener of key: {}", entry.getKey(), e);
continue; continue;
} }
@ -322,6 +323,11 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
if (!listeners.containsKey(key)) { if (!listeners.containsKey(key)) {
listeners.put(key, new CopyOnWriteArrayList<>()); listeners.put(key, new CopyOnWriteArrayList<>());
} }
if (listeners.get(key).contains(listener)) {
return;
}
listeners.get(key).add(listener); listeners.get(key).add(listener);
} }
@ -370,7 +376,7 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
@Override @Override
public void run() { public void run() {
Loggers.EPHEMERAL.info("distro notifier started"); Loggers.DISTRO.info("distro notifier started");
while (true) { while (true) {
try { try {
@ -407,16 +413,16 @@ public class DistroConsistencyServiceImpl implements EphemeralConsistencyService
continue; continue;
} }
} catch (Throwable e) { } catch (Throwable e) {
Loggers.EPHEMERAL.error("[NACOS-DISTRO] error while notifying listener of key: {}", datumKey, e); Loggers.DISTRO.error("[NACOS-DISTRO] error while notifying listener of key: {}", datumKey, e);
} }
} }
if (Loggers.EPHEMERAL.isDebugEnabled()) { if (Loggers.DISTRO.isDebugEnabled()) {
Loggers.EPHEMERAL.debug("[NACOS-DISTRO] datum change notified, key: {}, listener count: {}, action: {}", Loggers.DISTRO.debug("[NACOS-DISTRO] datum change notified, key: {}, listener count: {}, action: {}",
datumKey, count, action.name()); datumKey, count, action.name());
} }
} catch (Throwable e) { } catch (Throwable e) {
Loggers.EPHEMERAL.error("[NACOS-DISTRO] Error while handling notifying task", e); Loggers.DISTRO.error("[NACOS-DISTRO] Error while handling notifying task", e);
} }
} }
} }

View File

@ -94,8 +94,8 @@ public class TaskDispatcher {
String key = queue.poll(partitionConfig.getTaskDispatchPeriod(), String key = queue.poll(partitionConfig.getTaskDispatchPeriod(),
TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS);
if (Loggers.EPHEMERAL.isDebugEnabled() && StringUtils.isNotBlank(key)) { if (Loggers.DISTRO.isDebugEnabled() && StringUtils.isNotBlank(key)) {
Loggers.EPHEMERAL.debug("got key: {}", key); Loggers.DISTRO.debug("got key: {}", key);
} }
if (dataSyncer.getServers() == null || dataSyncer.getServers().isEmpty()) { if (dataSyncer.getServers() == null || dataSyncer.getServers().isEmpty()) {
@ -124,8 +124,8 @@ public class TaskDispatcher {
syncTask.setKeys(keys); syncTask.setKeys(keys);
syncTask.setTargetServer(member.getKey()); syncTask.setTargetServer(member.getKey());
if (Loggers.EPHEMERAL.isDebugEnabled() && StringUtils.isNotBlank(key)) { if (Loggers.DISTRO.isDebugEnabled() && StringUtils.isNotBlank(key)) {
Loggers.EPHEMERAL.debug("add sync task: {}", JSON.toJSONString(syncTask)); Loggers.DISTRO.debug("add sync task: {}", JSON.toJSONString(syncTask));
} }
dataSyncer.submit(syncTask, 0); dataSyncer.submit(syncTask, 0);
@ -135,7 +135,7 @@ public class TaskDispatcher {
} }
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.error("dispatch sync task failed.", e); Loggers.DISTRO.error("dispatch sync task failed.", e);
} }
} }
} }

View File

@ -485,7 +485,9 @@ public class RaftCore {
return; return;
} }
Loggers.RAFT.info("[RAFT] send beat with {} keys.", datums.size()); if (Loggers.RAFT.isDebugEnabled()) {
Loggers.RAFT.debug("[RAFT] send beat with {} keys.", datums.size());
}
local.resetLeaderDue(); local.resetLeaderDue();
@ -513,8 +515,6 @@ public class RaftCore {
array.add(element); array.add(element);
} }
} else {
Loggers.RAFT.info("[RAFT] send beat only.");
} }
packet.put("datums", array); packet.put("datums", array);
@ -531,13 +531,18 @@ public class RaftCore {
byte[] compressedBytes = out.toByteArray(); byte[] compressedBytes = out.toByteArray();
String compressedContent = new String(compressedBytes, StandardCharsets.UTF_8); String compressedContent = new String(compressedBytes, StandardCharsets.UTF_8);
Loggers.RAFT.info("raw beat data size: {}, size of compressed data: {}",
content.length(), compressedContent.length()); if (Loggers.RAFT.isDebugEnabled()) {
Loggers.RAFT.debug("raw beat data size: {}, size of compressed data: {}",
content.length(), compressedContent.length());
}
for (final String server : peers.allServersWithoutMySelf()) { for (final String server : peers.allServersWithoutMySelf()) {
try { try {
final String url = buildURL(server, API_BEAT); final String url = buildURL(server, API_BEAT);
Loggers.RAFT.info("send beat to server " + server); if (Loggers.RAFT.isDebugEnabled()) {
Loggers.RAFT.debug("send beat to server " + server);
}
HttpClient.asyncHttpPostLarge(url, null, compressedBytes, new AsyncCompletionHandler<Integer>() { HttpClient.asyncHttpPostLarge(url, null, compressedBytes, new AsyncCompletionHandler<Integer>() {
@Override @Override
public Integer onCompleted(Response response) throws Exception { public Integer onCompleted(Response response) throws Exception {
@ -549,7 +554,9 @@ public class RaftCore {
} }
peers.update(JSON.parseObject(response.getResponseBody(), RaftPeer.class)); peers.update(JSON.parseObject(response.getResponseBody(), RaftPeer.class));
Loggers.RAFT.info("receive beat response from: {}", url); if (Loggers.RAFT.isDebugEnabled()) {
Loggers.RAFT.debug("receive beat response from: {}", url);
}
return 0; return 0;
} }
@ -615,8 +622,10 @@ public class RaftCore {
List<String> batch = new ArrayList<>(); List<String> batch = new ArrayList<>();
if (!switchDomain.isSendBeatOnly()) { if (!switchDomain.isSendBeatOnly()) {
int processedCount = 0; int processedCount = 0;
Loggers.RAFT.info("[RAFT] received beat with {} keys, RaftCore.datums' size is {}, remote server: {}, term: {}, local term: {}", if (Loggers.RAFT.isDebugEnabled()) {
beatDatums.size(), datums.size(), remote.ip, remote.term, local.term); Loggers.RAFT.debug("[RAFT] received beat with {} keys, RaftCore.datums' size is {}, remote server: {}, term: {}, local term: {}",
beatDatums.size(), datums.size(), remote.ip, remote.term, local.term);
}
for (Object object : beatDatums) { for (Object object : beatDatums) {
processedCount = processedCount + 1; processedCount = processedCount + 1;

View File

@ -177,7 +177,8 @@ public class RaftStore {
instancesDatum.key = key; instancesDatum.key = key;
instancesDatum.value = new Instances(); instancesDatum.value = new Instances();
instancesDatum.value.setInstanceList(JSON.parseObject(jsonObject.getString("value"), instancesDatum.value.setInstanceList(JSON.parseObject(jsonObject.getString("value"),
new TypeReference<List<Instance>>(){})); new TypeReference<List<Instance>>() {
}));
if (!instancesDatum.value.getInstanceList().isEmpty()) { if (!instancesDatum.value.getInstanceList().isEmpty()) {
for (Instance instance : instancesDatum.value.getInstanceList()) { for (Instance instance : instancesDatum.value.getInstanceList()) {
instance.setEphemeral(false); instance.setEphemeral(false);

View File

@ -153,7 +153,7 @@ public class CatalogController {
String keyword = WebUtils.optional(request, "keyword", StringUtils.EMPTY); String keyword = WebUtils.optional(request, "keyword", StringUtils.EMPTY);
List<Service> serviceList = new ArrayList<>(8); List<Service> serviceList = new ArrayList<>(8);
serviceManager.getPagedService(namespaceId, pageNo, pageSize, keyword, StringUtils.EMPTY, serviceList); serviceManager.getPagedService(namespaceId, pageNo, pageSize, keyword, StringUtils.EMPTY, serviceList, false);
for (Service service : serviceList) { for (Service service : serviceList) {
ServiceDetailInfo serviceDetailInfo = new ServiceDetailInfo(); ServiceDetailInfo serviceDetailInfo = new ServiceDetailInfo();
@ -259,9 +259,10 @@ public class CatalogController {
int pageSize = Integer.parseInt(WebUtils.required(request, "pageSize")); int pageSize = Integer.parseInt(WebUtils.required(request, "pageSize"));
String keyword = WebUtils.optional(request, "keyword", StringUtils.EMPTY); String keyword = WebUtils.optional(request, "keyword", StringUtils.EMPTY);
String containedInstance = WebUtils.optional(request, "instance", StringUtils.EMPTY); String containedInstance = WebUtils.optional(request, "instance", StringUtils.EMPTY);
boolean hasIpCount = Boolean.parseBoolean(WebUtils.optional(request, "hasIpCount", "false"));
List<Service> services = new ArrayList<>(); List<Service> services = new ArrayList<>();
int total = serviceManager.getPagedService(namespaceId, page - 1, pageSize, keyword, containedInstance, services); int total = serviceManager.getPagedService(namespaceId, page - 1, pageSize, keyword, containedInstance, services, hasIpCount);
if (CollectionUtils.isEmpty(services)) { if (CollectionUtils.isEmpty(services)) {
result.put("serviceList", Collections.emptyList()); result.put("serviceList", Collections.emptyList());

View File

@ -74,7 +74,7 @@ public class DistroController {
String entity = IOUtils.toString(request.getInputStream(), "UTF-8"); String entity = IOUtils.toString(request.getInputStream(), "UTF-8");
if (StringUtils.isBlank(entity)) { if (StringUtils.isBlank(entity)) {
Loggers.EPHEMERAL.error("[onSync] receive empty entity!"); Loggers.DISTRO.error("[onSync] receive empty entity!");
throw new NacosException(NacosException.INVALID_PARAM, "receive empty entity!"); throw new NacosException(NacosException.INVALID_PARAM, "receive empty entity!");
} }

View File

@ -234,8 +234,8 @@ public class InstanceController {
String clusterName = clientBeat.getCluster(); String clusterName = clientBeat.getCluster();
if (Loggers.DEBUG_LOG.isDebugEnabled()) { if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("[CLIENT-BEAT] full arguments: beat: {}, serviceName: {}", clientBeat, serviceName); Loggers.SRV_LOG.debug("[CLIENT-BEAT] full arguments: beat: {}, serviceName: {}", clientBeat, serviceName);
} }
Instance instance = serviceManager.getInstance(namespaceId, serviceName, clientBeat.getCluster(), clientBeat.getIp(), Instance instance = serviceManager.getInstance(namespaceId, serviceName, clientBeat.getCluster(), clientBeat.getIp(),
@ -372,10 +372,11 @@ public class InstanceController {
Service service = serviceManager.getService(namespaceId, serviceName); Service service = serviceManager.getService(namespaceId, serviceName);
if (service == null) { if (service == null) {
if (Loggers.DEBUG_LOG.isDebugEnabled()) { if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("no instance to serve for service: " + serviceName); Loggers.SRV_LOG.debug("no instance to serve for service: " + serviceName);
} }
result.put("name", serviceName); result.put("name", serviceName);
result.put("clusters", clusters);
result.put("hosts", new JSONArray()); result.put("hosts", new JSONArray());
return result; return result;
} }
@ -412,8 +413,8 @@ public class InstanceController {
if (CollectionUtils.isEmpty(srvedIPs)) { if (CollectionUtils.isEmpty(srvedIPs)) {
if (Loggers.DEBUG_LOG.isDebugEnabled()) { if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("no instance to serve for service: " + serviceName); Loggers.SRV_LOG.debug("no instance to serve for service: " + serviceName);
} }
if (clientInfo.type == ClientInfo.ClientType.JAVA && if (clientInfo.type == ClientInfo.ClientType.JAVA &&

View File

@ -29,10 +29,7 @@ import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeerSet;
import com.alibaba.nacos.naming.core.DistroMapper; import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.*;
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.pojo.ClusterStateView; import com.alibaba.nacos.naming.pojo.ClusterStateView;
import com.alibaba.nacos.naming.push.PushService; import com.alibaba.nacos.naming.push.PushService;
import com.alibaba.nacos.naming.web.NeedAuth; import com.alibaba.nacos.naming.web.NeedAuth;
@ -55,7 +52,7 @@ import java.util.List;
* @author nkorange * @author nkorange
*/ */
@RestController @RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/operator") @RequestMapping({UtilsAndCommons.NACOS_NAMING_CONTEXT + "/operator", UtilsAndCommons.NACOS_NAMING_CONTEXT + "/ops"})
public class OperatorController { public class OperatorController {
@Autowired @Autowired
@ -224,6 +221,14 @@ public class OperatorController {
return "ok"; return "ok";
} }
@RequestMapping(value = "/log", method = RequestMethod.PUT)
public String setLogLevel(HttpServletRequest request) {
String logName = WebUtils.required(request, "logName");
String logLevel = WebUtils.required(request, "logLevel");
Loggers.setLogLevel(logName, logLevel);
return "ok";
}
@RequestMapping(value = "/cluster/states", method = RequestMethod.GET) @RequestMapping(value = "/cluster/states", method = RequestMethod.GET)
public Object listStates(HttpServletRequest request) { public Object listStates(HttpServletRequest request) {

View File

@ -36,6 +36,7 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -45,6 +46,7 @@ import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/** /**
* Core manager storing all services in Nacos * Core manager storing all services in Nacos
@ -143,12 +145,11 @@ public class ServiceManager implements RecordListener<Service> {
if (oldDom != null) { if (oldDom != null) {
oldDom.update(service); oldDom.update(service);
// re-listen to handle the situation when the underlying listener is removed:
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), true), oldDom);
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), false), oldDom);
} else { } else {
putService(service); putServiceAndInit(service);
service.init();
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), true), service);
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), false), service);
Loggers.SRV_LOG.info("[NEW-SERVICE] {}", service.toJSON());
} }
} catch (Throwable e) { } catch (Throwable e) {
Loggers.SRV_LOG.error("[NACOS-SERVICE] error while processing service update", e); Loggers.SRV_LOG.error("[NACOS-SERVICE] error while processing service update", e);
@ -283,27 +284,35 @@ public class ServiceManager implements RecordListener<Service> {
return; return;
} }
boolean changed = false;
List<Instance> instances = service.allIPs(); List<Instance> instances = service.allIPs();
for (Instance instance : instances) { for (Instance instance : instances) {
Boolean valid = Boolean.parseBoolean(ipsMap.get(instance.toIPAddr())); boolean valid = Boolean.parseBoolean(ipsMap.get(instance.toIPAddr()));
if (valid != instance.isHealthy()) { if (valid != instance.isHealthy()) {
changed = true;
instance.setHealthy(valid); instance.setHealthy(valid);
Loggers.EVT_LOG.info("{} {SYNC} IP-{} : {}@{}", Loggers.EVT_LOG.info("{} {SYNC} IP-{} : {}@{}{}",
serviceName, (instance.isHealthy() ? "ENABLED" : "DISABLED"), serviceName, (instance.isHealthy() ? "ENABLED" : "DISABLED"),
instance.getIp(), instance.getPort(), instance.getClusterName()); instance.getIp(), instance.getPort(), instance.getClusterName());
} }
} }
pushService.serviceChanged(service); if (changed) {
pushService.serviceChanged(service);
}
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
List<Instance> allIps = service.allIPs(); List<Instance> allIps = service.allIPs();
for (Instance instance : allIps) { for (Instance instance : allIps) {
stringBuilder.append(instance.toIPAddr()).append("_").append(instance.isHealthy()).append(","); stringBuilder.append(instance.toIPAddr()).append("_").append(instance.isHealthy()).append(",");
} }
Loggers.EVT_LOG.info("[IP-UPDATED] namespace: {}, service: {}, ips: {}", if (changed && Loggers.EVT_LOG.isDebugEnabled()) {
service.getNamespaceId(), service.getName(), stringBuilder.toString()); Loggers.EVT_LOG.debug("[HEALTH-STATUS-UPDATED] namespace: {}, service: {}, ips: {}",
service.getNamespaceId(), service.getName(), stringBuilder.toString());
}
} }
@ -409,16 +418,37 @@ public class ServiceManager implements RecordListener<Service> {
} }
service.validate(); service.validate();
if (local) { if (local) {
putService(service); putServiceAndInit(service);
service.init();
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), true), service);
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), false), service);
} else { } else {
addOrReplaceService(service); addOrReplaceService(service);
} }
} }
} }
public void putServiceIfAbsent(Service service, boolean local, Cluster cluster) throws NacosException {
final String namespaceId = service.getNamespaceId();
final String serviceName = service.getName();
if (getService(namespaceId, serviceName) != null) {
return;
}
Loggers.SRV_LOG.info("creating empty service {}:{}", namespaceId, serviceName);
// now validate the service. if failed, exception will be thrown
service.setLastModifiedMillis(System.currentTimeMillis());
service.recalculateChecksum();
if (cluster != null) {
cluster.setService(service);
service.getClusterMap().put(cluster.getName(), cluster);
}
service.validate();
if (local) {
putServiceAndInit(service);
} else {
addOrReplaceService(service);
}
}
/** /**
* Register an instance to a service in AP mode. * Register an instance to a service in AP mode.
* <p> * <p>
@ -474,11 +504,14 @@ public class ServiceManager implements RecordListener<Service> {
} }
public void removeInstance(String namespaceId, String serviceName, boolean ephemeral, Instance... ips) throws NacosException { public void removeInstance(String namespaceId, String serviceName, boolean ephemeral, Instance... ips) throws NacosException {
Service service = getService(namespaceId, serviceName);
removeInstance(namespaceId, serviceName, ephemeral, service, ips);
}
public void removeInstance(String namespaceId, String serviceName, boolean ephemeral, Service service, Instance... ips) throws NacosException {
String key = KeyBuilder.buildInstanceListKey(namespaceId, serviceName, ephemeral); String key = KeyBuilder.buildInstanceListKey(namespaceId, serviceName, ephemeral);
Service service = getService(namespaceId, serviceName);
List<Instance> instanceList = substractIpAddresses(service, ephemeral, ips); List<Instance> instanceList = substractIpAddresses(service, ephemeral, ips);
Instances instances = new Instances(); Instances instances = new Instances();
@ -598,6 +631,15 @@ public class ServiceManager implements RecordListener<Service> {
serviceMap.get(service.getNamespaceId()).put(service.getName(), service); serviceMap.get(service.getNamespaceId()).put(service.getName(), service);
} }
private void putServiceAndInit(Service service) throws NacosException {
putService(service);
service.init();
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), true), service);
consistencyService.listen(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), false), service);
Loggers.SRV_LOG.info("[NEW-SERVICE] {}", service.toJSON());
}
public List<Service> searchServices(String namespaceId, String regex) { public List<Service> searchServices(String namespaceId, String regex) {
List<Service> result = new ArrayList<>(); List<Service> result = new ArrayList<>();
for (Map.Entry<String, Service> entry : chooseServiceMap(namespaceId).entrySet()) { for (Map.Entry<String, Service> entry : chooseServiceMap(namespaceId).entrySet()) {
@ -633,7 +675,7 @@ public class ServiceManager implements RecordListener<Service> {
return serviceMap.get(namespaceId); return serviceMap.get(namespaceId);
} }
public int getPagedService(String namespaceId, int startPage, int pageSize, String keyword, String containedInstance, List<Service> serviceList) { public int getPagedService(String namespaceId, int startPage, int pageSize, String keyword, String containedInstance, List<Service> serviceList, boolean hasIpCount) {
List<Service> matchList; List<Service> matchList;
@ -647,6 +689,10 @@ public class ServiceManager implements RecordListener<Service> {
matchList = new ArrayList<>(chooseServiceMap(namespaceId).values()); matchList = new ArrayList<>(chooseServiceMap(namespaceId).values());
} }
if (!CollectionUtils.isEmpty(matchList) && hasIpCount) {
matchList = matchList.stream().filter(s -> !CollectionUtils.isEmpty(s.allIPs())).collect(Collectors.toList());
}
if (StringUtils.isNotBlank(containedInstance)) { if (StringUtils.isNotBlank(containedInstance)) {
boolean contained; boolean contained;

View File

@ -22,6 +22,7 @@ import com.alibaba.nacos.naming.boot.SpringContext;
import com.alibaba.nacos.naming.core.DistroMapper; import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.Instance; import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service; import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.healthcheck.events.InstanceHeartbeatTimeoutEvent;
import com.alibaba.nacos.naming.misc.*; import com.alibaba.nacos.naming.misc.*;
import com.alibaba.nacos.naming.push.PushService; import com.alibaba.nacos.naming.push.PushService;
import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncCompletionHandler;
@ -82,6 +83,7 @@ public class ClientBeatCheckTask implements Runnable {
instance.getIp(), instance.getPort(), instance.getClusterName(), service.getName(), instance.getIp(), instance.getPort(), instance.getClusterName(), service.getName(),
UtilsAndCommons.LOCALHOST_SITE, instance.getInstanceHeartBeatTimeOut(), instance.getLastBeat()); UtilsAndCommons.LOCALHOST_SITE, instance.getInstanceHeartBeatTimeOut(), instance.getLastBeat());
getPushService().serviceChanged(service); getPushService().serviceChanged(service);
SpringContext.getAppContext().publishEvent(new InstanceHeartbeatTimeoutEvent(this, instance));
} }
} }
} }

View File

@ -88,8 +88,8 @@ public class HealthCheckCommon {
} }
Map<String, String> params = new HashMap<>(10); Map<String, String> params = new HashMap<>(10);
params.put("result", JSON.toJSONString(list)); params.put("result", JSON.toJSONString(list));
if (Loggers.DEBUG_LOG.isDebugEnabled()) { if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("[HEALTH-SYNC] server: {}, healthCheckResults: {}", Loggers.SRV_LOG.debug("[HEALTH-SYNC] server: {}, healthCheckResults: {}",
server, JSON.toJSONString(list)); server, JSON.toJSONString(list));
} }

View File

@ -94,10 +94,13 @@ public class HealthCheckTask implements Runnable {
this.setCheckRTLastLast(this.getCheckRTLast()); this.setCheckRTLastLast(this.getCheckRTLast());
Cluster cluster = this.getCluster(); Cluster cluster = this.getCluster();
Loggers.CHECK_RT.info("{}:{}@{}->normalized: {}, worst: {}, best: {}, last: {}, diff: {}",
cluster.getService().getName(), cluster.getName(), cluster.getHealthChecker().getType(), if (Loggers.CHECK_RT.isDebugEnabled()) {
this.getCheckRTNormalized(), this.getCheckRTWorst(), this.getCheckRTBest(), Loggers.CHECK_RT.debug("{}:{}@{}->normalized: {}, worst: {}, best: {}, last: {}, diff: {}",
this.getCheckRTLast(), diff); cluster.getService().getName(), cluster.getName(), cluster.getHealthChecker().getType(),
this.getCheckRTNormalized(), this.getCheckRTWorst(), this.getCheckRTBest(),
this.getCheckRTLast(), diff);
}
} }
} }
} }

View File

@ -0,0 +1,41 @@
/*
* Copyright (C) 2019 the original author or authors.
*
* 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.healthcheck.events;
import com.alibaba.nacos.naming.core.Instance;
import org.springframework.context.ApplicationEvent;
/**
* @author pbting
* @date 2019-05-28 8:29 PM
*/
public class InstanceHeartbeatTimeoutEvent extends ApplicationEvent {
private Instance instance;
public InstanceHeartbeatTimeoutEvent(Object source, Instance instance) {
super(source);
this.instance = instance;
}
public void setInstance(Instance instance) {
this.instance = instance;
}
public Instance getInstance() {
return instance;
}
}

View File

@ -15,6 +15,7 @@
*/ */
package com.alibaba.nacos.naming.misc; package com.alibaba.nacos.naming.misc;
import ch.qos.logback.classic.Level;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,9 +34,37 @@ public class Loggers {
public static final Logger RAFT = LoggerFactory.getLogger("com.alibaba.nacos.naming.raft"); public static final Logger RAFT = LoggerFactory.getLogger("com.alibaba.nacos.naming.raft");
public static final Logger EPHEMERAL = LoggerFactory.getLogger("com.alibaba.nacos.naming.ephemeral"); public static final Logger DISTRO = LoggerFactory.getLogger("com.alibaba.nacos.naming.distro");
public static final Logger PERFORMANCE_LOG = LoggerFactory.getLogger("com.alibaba.nacos.naming.performance"); public static final Logger PERFORMANCE_LOG = LoggerFactory.getLogger("com.alibaba.nacos.naming.performance");
public static final Logger DEBUG_LOG = LoggerFactory.getLogger("com.alibaba.nacos.naming.debug"); public static void setLogLevel(String logName, String level) {
switch (logName) {
case "naming-push":
((ch.qos.logback.classic.Logger) PUSH).setLevel(Level.valueOf(level));
break;
case "naming-rt":
((ch.qos.logback.classic.Logger) CHECK_RT).setLevel(Level.valueOf(level));
break;
case "naming-server":
((ch.qos.logback.classic.Logger) SRV_LOG).setLevel(Level.valueOf(level));
break;
case "naming-event":
((ch.qos.logback.classic.Logger) EVT_LOG).setLevel(Level.valueOf(level));
break;
case "naming-raft":
((ch.qos.logback.classic.Logger) RAFT).setLevel(Level.valueOf(level));
break;
case "naming-distro":
((ch.qos.logback.classic.Logger) DISTRO).setLevel(Level.valueOf(level));
break;
case "naming-performance":
((ch.qos.logback.classic.Logger) PERFORMANCE_LOG).setLevel(Level.valueOf(level));
break;
default:
break;
}
}
} }

View File

@ -54,7 +54,7 @@ public class NamingProxy {
@Override @Override
public Object onCompleted(Response response) throws Exception { public Object onCompleted(Response response) throws Exception {
if (HttpURLConnection.HTTP_OK != response.getStatusCode()) { if (HttpURLConnection.HTTP_OK != response.getStatusCode()) {
Loggers.EPHEMERAL.error("failed to req API: {}, code: {}, msg: {}", Loggers.DISTRO.error("failed to req API: {}, code: {}, msg: {}",
"http://" + server + RunningConfig.getContextPath() + "http://" + server + RunningConfig.getContextPath() +
UtilsAndCommons.NACOS_NAMING_CONTEXT + TIMESTAMP_SYNC_URL, UtilsAndCommons.NACOS_NAMING_CONTEXT + TIMESTAMP_SYNC_URL,
response.getStatusCode(), response.getResponseBody()); response.getStatusCode(), response.getResponseBody());
@ -64,13 +64,13 @@ public class NamingProxy {
@Override @Override
public void onThrowable(Throwable t) { public void onThrowable(Throwable t) {
Loggers.EPHEMERAL.error("failed to req API:" + "http://" + server Loggers.DISTRO.error("failed to req API:" + "http://" + server
+ RunningConfig.getContextPath() + RunningConfig.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + TIMESTAMP_SYNC_URL, t); + UtilsAndCommons.NACOS_NAMING_CONTEXT + TIMESTAMP_SYNC_URL, t);
} }
}); });
} catch (Exception e) { } catch (Exception e) {
Loggers.EPHEMERAL.warn("NamingProxy", e); Loggers.DISTRO.warn("NamingProxy", e);
} }
} }

View File

@ -79,7 +79,9 @@ public class ServiceStatusSynchronizer implements Synchronizer {
String result; String result;
try { try {
Loggers.SRV_LOG.info("[STATUS-SYNCHRONIZE] sync service status from: {}, service: {}", serverIP, key); if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG.debug("[STATUS-SYNCHRONIZE] sync service status from: {}, service: {}", serverIP, key);
}
result = NamingProxy.reqAPI(RunningConfig.getContextPath() result = NamingProxy.reqAPI(RunningConfig.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/" + "statuses", params, serverIP); + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/instance/" + "statuses", params, serverIP);
} catch (Exception e) { } catch (Exception e) {

View File

@ -21,6 +21,7 @@ import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker; import com.alibaba.nacos.api.naming.pojo.AbstractHealthChecker;
import com.alibaba.nacos.common.util.VersionUtils;
import com.alibaba.nacos.naming.exception.NacosException; import com.alibaba.nacos.naming.exception.NacosException;
import com.alibaba.nacos.naming.healthcheck.JsonAdapter; import com.alibaba.nacos.naming.healthcheck.JsonAdapter;
import com.alibaba.nacos.naming.selector.Selector; import com.alibaba.nacos.naming.selector.Selector;
@ -70,7 +71,7 @@ public class UtilsAndCommons {
public static final String NACOS_SERVER_HEADER = "Nacos-Server"; public static final String NACOS_SERVER_HEADER = "Nacos-Server";
public static final String NACOS_VERSION = "1.0.1"; public static final String NACOS_VERSION = VersionUtils.VERSION;
public static final String SUPER_TOKEN = "xy"; public static final String SUPER_TOKEN = "xy";

View File

@ -19,7 +19,6 @@ import com.alibaba.nacos.naming.consistency.persistent.raft.RaftCore;
import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer; import com.alibaba.nacos.naming.consistency.persistent.raft.RaftPeer;
import com.alibaba.nacos.naming.core.ServiceManager; import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.push.PushService; import com.alibaba.nacos.naming.push.PushService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
@ -42,9 +41,6 @@ public class PerformanceLoggerThread {
@Autowired @Autowired
private ServiceManager serviceManager; private ServiceManager serviceManager;
@Autowired
private SwitchDomain switchDomain;
@Autowired @Autowired
private PushService pushService; private PushService pushService;
@ -62,34 +58,15 @@ public class PerformanceLoggerThread {
}); });
private static final long PERIOD = 5 * 60; private static final long PERIOD = 5 * 60;
private static final long HEALTH_CHECK_PERIOD = 5 * 60;
@PostConstruct @PostConstruct
public void init() { public void init() {
start(); start();
} }
private void freshHealthCheckSwitch() {
Loggers.SRV_LOG.info("[HEALTH-CHECK] health check is {}", switchDomain.isHealthCheckEnabled());
}
class HealthCheckSwitchTask implements Runnable {
@Override
public void run() {
try {
freshHealthCheckSwitch();
} catch (Exception ignore) {
}
}
}
private void start() { private void start() {
PerformanceLogTask task = new PerformanceLogTask(); PerformanceLogTask task = new PerformanceLogTask();
executor.scheduleWithFixedDelay(task, 30, PERIOD, TimeUnit.SECONDS); executor.scheduleWithFixedDelay(task, 30, PERIOD, TimeUnit.SECONDS);
executor.scheduleWithFixedDelay(new HealthCheckSwitchTask(), 30, HEALTH_CHECK_PERIOD, TimeUnit.SECONDS);
} }
@Scheduled(cron = "0 0 0 * * ?") @Scheduled(cron = "0 0 0 * * ?")

View File

@ -275,7 +275,9 @@ public class PushService implements ApplicationContextAware, ApplicationListener
size += clientConcurrentMap.size(); size += clientConcurrentMap.size();
} }
Loggers.PUSH.info("[NACOS-PUSH] clientMap size: {}", size); if (Loggers.PUSH.isDebugEnabled()) {
Loggers.PUSH.debug("[NACOS-PUSH] clientMap size: {}", size);
}
} }

View File

@ -15,10 +15,12 @@
*/ */
package com.alibaba.nacos.naming.web; package com.alibaba.nacos.naming.web;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.acl.AuthChecker; import com.alibaba.nacos.naming.acl.AuthChecker;
import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.*; import javax.servlet.*;
@ -34,6 +36,8 @@ import java.security.AccessControlException;
*/ */
public class AuthFilter implements Filter { public class AuthFilter implements Filter {
private static final String[] NAMESPACE_FORBIDDEN_STRINGS = new String[]{"..", "/"};
@Autowired @Autowired
private AuthChecker authChecker; private AuthChecker authChecker;
@ -64,11 +68,16 @@ public class AuthFilter implements Filter {
} }
if (method.isAnnotationPresent(NeedAuth.class) && !switchDomain.isEnableAuthentication()) { if (method.isAnnotationPresent(NeedAuth.class) && !switchDomain.isEnableAuthentication()) {
// leave it empty.
}
if (path.contains(UtilsAndCommons.NACOS_NAMING_RAFT_CONTEXT)) { // Check namespace:
authChecker.doRaftAuth(req); String namespaceId = req.getParameter(CommonParams.NAMESPACE_ID);
} else {
authChecker.doAuth(req.getParameterMap(), req); if (StringUtils.isNotBlank(namespaceId)) {
if (namespaceId.contains(NAMESPACE_FORBIDDEN_STRINGS[0]) || namespaceId.contains(NAMESPACE_FORBIDDEN_STRINGS[1])) {
throw new IllegalArgumentException("forbidden namespace: " + namespaceId);
} }
} }
@ -78,9 +87,12 @@ public class AuthFilter implements Filter {
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "no such api"); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "no such api");
return; return;
} catch (IllegalArgumentException e) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, UtilsAndCommons.getAllExceptionMsg(e));
return;
} catch (Exception e) { } catch (Exception e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Server failed," + UtilsAndCommons.getAllExceptionMsg(e)); "Server failed," + UtilsAndCommons.getAllExceptionMsg(e));
return; return;
} }
filterChain.doFilter(req, resp); filterChain.doFilter(req, resp);

View File

@ -52,7 +52,7 @@ public class NamingConfig {
FilterRegistrationBean<AuthFilter> registration = new FilterRegistrationBean<>(); FilterRegistrationBean<AuthFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(authFilter()); registration.setFilter(authFilter());
registration.addUrlPatterns("/api/*", "/raft/*"); registration.addUrlPatterns("/v1/ns/*");
registration.setName("authFilter"); registration.setName("authFilter");
registration.setOrder(5); registration.setOrder(5);

View File

@ -1,8 +1,9 @@
package com.alibaba.nacos.naming.healthcheck; package com.alibaba.nacos.naming.healthcheck;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.alibaba.nacos.core.utils.SystemUtils; import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.*; import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.misc.GlobalConfig; import com.alibaba.nacos.naming.misc.GlobalConfig;
import com.alibaba.nacos.naming.push.PushService; import com.alibaba.nacos.naming.push.PushService;
import org.junit.Assert; import org.junit.Assert;
@ -13,10 +14,7 @@ import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import java.util.ArrayList; import java.util.ArrayList;

16
pom.xml
View File

@ -21,7 +21,7 @@
<inceptionYear>2018</inceptionYear> <inceptionYear>2018</inceptionYear>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>Alibaba NACOS ${project.version}</name> <name>Alibaba NACOS ${project.version}</name>
@ -523,7 +523,7 @@
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.47</version> <version>1.2.58</version>
</dependency> </dependency>
<!-- javax libs--> <!-- javax libs-->
@ -733,5 +733,17 @@
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<distributionManagement>
<snapshotRepository>
<!-- 这里的ID一定要在maven setting文件中存在于server下的ID -->
<id>sona</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>sona</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project> </project>

View File

@ -17,7 +17,7 @@
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>1.1.0</version> <version>1.1.3</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -23,31 +23,27 @@ import junit.framework.TestSuite;
* Unit test for simple App. * Unit test for simple App.
*/ */
public class AppTest public class AppTest
extends TestCase extends TestCase {
{
/** /**
* Create the test case * Create the test case
* *
* @param testName name of the test case * @param testName name of the test case
*/ */
public AppTest( String testName ) public AppTest(String testName) {
{ super(testName);
super( testName );
} }
/** /**
* @return the suite of tests being tested * @return the suite of tests being tested
*/ */
public static Test suite() public static Test suite() {
{ return new TestSuite(AppTest.class);
return new TestSuite( AppTest.class );
} }
/** /**
* Rigourous Test :-) * Rigourous Test :-)
*/ */
public void testApp() public void testApp() {
{ assertTrue(true);
assertTrue( true );
} }
} }

View File

@ -16,23 +16,11 @@
package com.alibaba.nacos.test.config; package com.alibaba.nacos.test.config;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.config.server.Config; import com.alibaba.nacos.config.server.Config;
import com.alibaba.nacos.naming.misc.HttpClient.HttpResult;
import com.alibaba.nacos.test.naming.NamingBase;
import com.alibaba.nacos.test.naming.Params; import com.alibaba.nacos.test.naming.Params;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -43,9 +31,8 @@ import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity.HeadersBuilder; import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;

View File

@ -232,6 +232,32 @@ public class RestAPI_ITCase {
namingServiceDelete(serviceName); namingServiceDelete(serviceName);
} }
@Test
public void testInvalidNamespace() {
String serviceName = NamingBase.randomDomainName();
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.appendParam("namespaceId", "..invalid-namespace")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is4xxClientError());
response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",
Params.newParams()
.appendParam("serviceName", serviceName)
.appendParam("protectThreshold", "0.6")
.appendParam("namespaceId", "/invalid-namespace")
.done(),
String.class,
HttpMethod.POST);
Assert.assertTrue(response.getStatusCode().is4xxClientError());
}
private void namingServiceDelete(String serviceName) { private void namingServiceDelete(String serviceName) {
//delete service //delete service
ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service",