[#3241]Reformat the nacos-config module by new code style. (#3243)

This commit is contained in:
Hu Zongtang 2020-07-03 16:51:08 +08:00 committed by GitHub
parent aa020e0b81
commit 31670f124c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
160 changed files with 6293 additions and 6136 deletions

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server;
import org.springframework.boot.SpringApplication;
@ -25,12 +26,9 @@ import org.springframework.scheduling.annotation.EnableScheduling;
* @author Nacos
*/
@EnableScheduling
@SpringBootApplication(scanBasePackages = {
"com.alibaba.nacos.config.server",
"com.alibaba.nacos.core"
})
@SpringBootApplication(scanBasePackages = {"com.alibaba.nacos.config.server", "com.alibaba.nacos.core"})
public class Config {
public static void main(String[] args) {
SpringApplication.run(Config.class, args);
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.aspect;
import com.alibaba.nacos.config.server.constant.Constants;
@ -42,29 +43,30 @@ import java.nio.charset.Charset;
*/
@Aspect
public class CapacityManagementAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(CapacityManagementAspect.class);
private static final String SYNC_UPDATE_CONFIG_ALL
= "execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) && args"
+ "(request,response,dataId,group,content,appName,srcUser,tenant,tag,..)";
private static final String DELETE_CONFIG
= "execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..)) && args"
+ "(request,response,dataId,group,tenant,..)";
private static final String SYNC_UPDATE_CONFIG_ALL =
"execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) && args"
+ "(request,response,dataId,group,content,appName,srcUser,tenant,tag,..)";
private static final String DELETE_CONFIG =
"execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..)) && args"
+ "(request,response,dataId,group,tenant,..)";
@Autowired
private CapacityService capacityService;
@Autowired
private PersistService persistService;
/**
* 更新也需要判断content内容是否超过大小限制
*/
@Around(SYNC_UPDATE_CONFIG_ALL)
public Object aroundSyncUpdateConfigAll(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String content,
String appName, String srcUser, String tenant, String tag)
throws Throwable {
HttpServletResponse response, String dataId, String group, String content, String appName, String srcUser,
String tenant, String tag) throws Throwable {
if (!PropertyUtil.isManageCapacity()) {
return pjp.proceed();
}
@ -83,14 +85,14 @@ public class CapacityManagementAspect {
}
return pjp.proceed();
}
/**
* 更新操作开启容量管理的限制检验功能会检验"content的大小"是否超过限制
*
* @throws Throwable "实际操作"抛出的异常
*/
private Object do4Update(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response,
String dataId, String group, String tenant, String content) throws Throwable {
String dataId, String group, String tenant, String content) throws Throwable {
if (!PropertyUtil.isCapacityLimitCheck()) {
return pjp.proceed();
}
@ -105,15 +107,14 @@ public class CapacityManagementAspect {
}
return pjp.proceed();
}
/**
* 写入操作1. 无论是否开启容量管理的限制检验功能都会计数usage 2.开启容量管理的限制检验功能会检验"限额""content的大小"
*
* @throws Throwable "实际操作"抛出的异常
*/
private Object do4Insert(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String group, String tenant, String content)
throws Throwable {
private Object do4Insert(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response,
String group, String tenant, String content) throws Throwable {
LOGGER.info("[capacityManagement] do4Insert");
CounterMode counterMode = CounterMode.INCREMENT;
boolean hasTenant = hasTenant(tenant);
@ -129,22 +130,22 @@ public class CapacityManagementAspect {
}
return getResult(pjp, response, group, tenant, counterMode, hasTenant);
}
private Object response4Limit(HttpServletRequest request, HttpServletResponse response, LimitType limitType) {
response.setStatus(limitType.status);
return String.valueOf(limitType.status);
}
private boolean hasTenant(String tenant) {
return StringUtils.isNotBlank(tenant);
}
/**
* 无论是否开启容量管理的限制检验功能删除时候计数模块中容量信息表中的usage都得减一
*/
@Around(DELETE_CONFIG)
public Object aroundDeleteConfig(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response,
String dataId, String group, String tenant) throws Throwable {
String dataId, String group, String tenant) throws Throwable {
if (!PropertyUtil.isManageCapacity()) {
return pjp.proceed();
}
@ -155,13 +156,12 @@ public class CapacityManagementAspect {
}
return do4Delete(pjp, response, group, tenant, configInfo);
}
/**
* @throws Throwable "实际操作"抛出的异常
*/
private Object do4Delete(ProceedingJoinPoint pjp, HttpServletResponse response, String group, String tenant,
ConfigInfo configInfo)
throws Throwable {
ConfigInfo configInfo) throws Throwable {
boolean hasTenant = hasTenant(tenant);
if (configInfo == null) {
// "configInfo == null"有2种可能
@ -178,7 +178,7 @@ public class CapacityManagementAspect {
insertOrUpdateUsage(group, tenant, counterMode, hasTenant);
return getResult(pjp, response, group, tenant, counterMode, hasTenant);
}
private void correctUsage(String group, String tenant, boolean hasTenant) {
try {
if (hasTenant) {
@ -192,9 +192,9 @@ public class CapacityManagementAspect {
LOGGER.error("[capacityManagement] correctUsage ", e);
}
}
private Object getResult(ProceedingJoinPoint pjp, HttpServletResponse response, String group, String tenant,
CounterMode counterMode, boolean hasTenant) throws Throwable {
CounterMode counterMode, boolean hasTenant) throws Throwable {
try {
// 执行实际操作
Object result = pjp.proceed();
@ -202,13 +202,13 @@ public class CapacityManagementAspect {
doResult(counterMode, response, group, tenant, result, hasTenant);
return result;
} catch (Throwable throwable) {
LOGGER.warn("[capacityManagement] inner operation throw exception, rollback, group: {}, tenant: {}",
group, tenant, throwable);
LOGGER.warn("[capacityManagement] inner operation throw exception, rollback, group: {}, tenant: {}", group,
tenant, throwable);
rollback(counterMode, group, tenant, hasTenant);
throw throwable;
}
}
/**
* usage计数器服务无论容量管理的限制检验功能是否开启都会进行计数
*/
@ -224,9 +224,9 @@ public class CapacityManagementAspect {
LOGGER.error("[capacityManagement] insertOrUpdateUsage ", e);
}
}
private LimitType getLimitType(CounterMode counterMode, String group, String tenant, String content, boolean
hasTenant) {
private LimitType getLimitType(CounterMode counterMode, String group, String tenant, String content,
boolean hasTenant) {
try {
boolean clusterLimited = !capacityService.insertAndUpdateClusterUsage(counterMode, false);
if (clusterLimited) {
@ -237,8 +237,7 @@ public class CapacityManagementAspect {
return null;
}
int currentSize = getCurrentSize(content);
LimitType limitType = getGroupOrTenantLimitType(counterMode, group, tenant, currentSize,
hasTenant);
LimitType limitType = getGroupOrTenantLimitType(counterMode, group, tenant, currentSize, hasTenant);
if (limitType != null) {
rollbackClusterUsage(counterMode);
return limitType;
@ -248,7 +247,7 @@ public class CapacityManagementAspect {
}
return null;
}
/**
* 编码字节数
*/
@ -260,9 +259,9 @@ public class CapacityManagementAspect {
}
return 0;
}
private LimitType getGroupOrTenantLimitType(CounterMode counterMode, String group, String tenant,
int currentSize, boolean hasTenant) {
private LimitType getGroupOrTenantLimitType(CounterMode counterMode, String group, String tenant, int currentSize,
boolean hasTenant) {
if (group == null) {
return null;
}
@ -282,7 +281,7 @@ public class CapacityManagementAspect {
}
return LimitType.OVER_GROUP_QUOTA;
}
private boolean isUpdateSuccess(CounterMode counterMode, String group, String tenant, boolean hasTenant) {
boolean updateSuccess;
if (hasTenant) {
@ -298,7 +297,7 @@ public class CapacityManagementAspect {
}
return updateSuccess;
}
private void insertCapacity(String group, String tenant, boolean hasTenant) {
if (hasTenant) {
capacityService.initTenantCapacity(tenant);
@ -306,7 +305,7 @@ public class CapacityManagementAspect {
capacityService.initGroupCapacity(group);
}
}
private Capacity getCapacity(String group, String tenant, boolean hasTenant) {
Capacity capacity;
if (hasTenant) {
@ -316,9 +315,9 @@ public class CapacityManagementAspect {
}
return capacity;
}
private boolean isSizeLimited(String group, String tenant, int currentSize, boolean hasTenant, boolean isAggr,
Capacity capacity) {
Capacity capacity) {
int defaultMaxSize = getDefaultMaxSize(isAggr);
if (capacity != null) {
Integer maxSize = getMaxSize(isAggr, capacity);
@ -332,61 +331,60 @@ public class CapacityManagementAspect {
// 不已经存在容量信息记录使用"默认maxSize限制值"进行比较
return isOverSize(group, tenant, currentSize, defaultMaxSize, hasTenant);
}
private Integer getMaxSize(boolean isAggr, Capacity capacity) {
if (isAggr) {
return capacity.getMaxAggrSize();
}
return capacity.getMaxSize();
}
private int getDefaultMaxSize(boolean isAggr) {
if (isAggr) {
return PropertyUtil.getDefaultMaxAggrSize();
}
return PropertyUtil.getDefaultMaxSize();
}
private boolean isOverSize(String group, String tenant, int currentSize, int maxSize, boolean hasTenant) {
if (currentSize > maxSize) {
if (hasTenant) {
LOGGER.warn(
"[capacityManagement] tenant content is over maxSize, tenant: {}, maxSize: {}, currentSize: {}",
tenant, maxSize, currentSize);
"[capacityManagement] tenant content is over maxSize, tenant: {}, maxSize: {}, currentSize: {}",
tenant, maxSize, currentSize);
} else {
LOGGER.warn(
"[capacityManagement] group content is over maxSize, group: {}, maxSize: {}, currentSize: {}",
group, maxSize, currentSize);
"[capacityManagement] group content is over maxSize, group: {}, maxSize: {}, currentSize: {}",
group, maxSize, currentSize);
}
return true;
}
return false;
}
private void doResult(CounterMode counterMode, HttpServletResponse response, String group,
String tenant, Object result, boolean hasTenant) {
private void doResult(CounterMode counterMode, HttpServletResponse response, String group, String tenant,
Object result, boolean hasTenant) {
try {
if (!isSuccess(response, result)) {
LOGGER.warn(
"[capacityManagement] inner operation is fail, rollback, counterMode: {}, group: {}, tenant: {}",
counterMode, group, tenant);
"[capacityManagement] inner operation is fail, rollback, counterMode: {}, group: {}, tenant: {}",
counterMode, group, tenant);
rollback(counterMode, group, tenant, hasTenant);
}
} catch (Exception e) {
LOGGER.error("[capacityManagement] doResult ", e);
}
}
private boolean isSuccess(HttpServletResponse response, Object result) {
int status = response.getStatus();
if (status == HttpServletResponse.SC_OK) {
return true;
}
LOGGER.warn("[capacityManagement] response status is not 200, status: {}, result: {}", status,
result);
LOGGER.warn("[capacityManagement] response status is not 200, status: {}, result: {}", status, result);
return false;
}
private void rollback(CounterMode counterMode, String group, String tenant, boolean hasTenant) {
try {
rollbackClusterUsage(counterMode);
@ -399,7 +397,7 @@ public class CapacityManagementAspect {
LOGGER.error("[capacityManagement] rollback ", e);
}
}
private void rollbackClusterUsage(CounterMode counterMode) {
try {
if (!capacityService.updateClusterUsage(counterMode.reverse())) {
@ -409,7 +407,7 @@ public class CapacityManagementAspect {
LOGGER.error("[capacityManagement] rollback ", e);
}
}
/**
* limit tyep
*
@ -423,9 +421,11 @@ public class CapacityManagementAspect {
OVER_GROUP_QUOTA("超过该Group配置个数上限", 429),
OVER_TENANT_QUOTA("超过该租户配置个数上限", 429),
OVER_MAX_SIZE("超过配置的内容大小上限", 429);
public final String description;
public final int status;
LimitType(String description, int status) {
this.description = description;
this.status = status;

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.aspect;
import com.alibaba.nacos.common.utils.MD5Utils;
@ -38,67 +39,66 @@ import javax.servlet.http.HttpServletResponse;
@Aspect
@Component
public class RequestLogAspect {
/**
* publish config
*/
private static final String CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG
= "execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) && args"
+ "(request,response,dataId,group,tenant,content,..)";
private static final String CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG =
"execution(* com.alibaba.nacos.config.server.controller.ConfigController.publishConfig(..)) && args"
+ "(request,response,dataId,group,tenant,content,..)";
/**
* get config
*/
private static final String CLIENT_INTERFACE_GET_CONFIG
= "execution(* com.alibaba.nacos.config.server.controller.ConfigController.getConfig(..)) && args(request,"
+ "response,dataId,group,tenant,..)";
private static final String CLIENT_INTERFACE_GET_CONFIG =
"execution(* com.alibaba.nacos.config.server.controller.ConfigController.getConfig(..)) && args(request,"
+ "response,dataId,group,tenant,..)";
/**
* remove config
*/
private static final String CLIENT_INTERFACE_REMOVE_ALL_CONFIG
= "execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..)) && args(request,"
+ "response,dataId,group,tenant,..)";
private static final String CLIENT_INTERFACE_REMOVE_ALL_CONFIG =
"execution(* com.alibaba.nacos.config.server.controller.ConfigController.deleteConfig(..)) && args(request,"
+ "response,dataId,group,tenant,..)";
/**
* publishSingle
*/
@Around(CLIENT_INTERFACE_PUBLISH_SINGLE_CONFIG)
public Object interfacePublishSingle(ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String tenant,
String content) throws Throwable {
HttpServletResponse response, String dataId, String group, String tenant, String content) throws Throwable {
final String md5 = content == null ? null : MD5Utils.md5Hex(content, Constants.ENCODE);
MetricsMonitor.getPublishMonitor().incrementAndGet();
return logClientRequest("publish", pjp, request, response, dataId, group, tenant, md5);
}
/**
* removeAll
*/
@Around(CLIENT_INTERFACE_REMOVE_ALL_CONFIG)
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 {
return logClientRequest("remove", pjp, request, response, dataId, group, tenant, null);
}
/**
* getConfig
*/
@Around(CLIENT_INTERFACE_GET_CONFIG)
public Object interfaceGetConfig(ProceedingJoinPoint pjp, HttpServletRequest request, HttpServletResponse response,
String dataId, String group, String tenant) throws Throwable {
String dataId, String group, String tenant) throws Throwable {
final String groupKey = GroupKey2.getKey(dataId, group, tenant);
final String md5 = ConfigCacheService.getContentMd5(groupKey);
MetricsMonitor.getConfigMonitor().incrementAndGet();
return logClientRequest("get", pjp, request, response, dataId, group, tenant, md5);
}
/**
* client api request log rt | status | requestIp | opType | dataId | group | datumId | md5
*/
private Object logClientRequest(String requestType, ProceedingJoinPoint pjp, HttpServletRequest request,
HttpServletResponse response, String dataId, String group, String tenant,
String md5) throws Throwable {
HttpServletResponse response, String dataId, String group, String tenant, String md5) throws Throwable {
final String requestIp = RequestUtil.getRemoteIp(request);
String appName = request.getHeader(RequestUtil.CLIENT_APPNAME_HEADER);
final long st = System.currentTimeMillis();
@ -106,9 +106,10 @@ public class RequestLogAspect {
final long rt = System.currentTimeMillis() - st;
// rt | status | requestIp | opType | dataId | group | datumId | md5 |
// appName
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}|{}|{}|{}", rt, retVal, requestIp, requestType, dataId, group, tenant,
md5, appName);
LogUtil.clientLog
.info("{}|{}|{}|{}|{}|{}|{}|{}|{}", rt, retVal, requestIp, requestType, dataId, group, tenant, md5,
appName);
return retVal;
}
}

View File

@ -13,11 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.core.auth.Resource;
import com.alibaba.nacos.core.auth.ResourceParser;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
/**
@ -27,36 +30,30 @@ import org.apache.commons.lang3.StringUtils;
* @since 1.2.0
*/
public class ConfigResourceParser implements ResourceParser {
private static final String AUTH_CONFIG_PREFIX = "config/";
@Override
public String parseName(Object request) {
HttpServletRequest req = (HttpServletRequest) request;
String namespaceId = req.getParameter("tenant");
String groupName = req.getParameter("group");
String dataId = req.getParameter("dataId");
StringBuilder sb = new StringBuilder();
if (StringUtils.isNotBlank(namespaceId)) {
sb.append(namespaceId);
}
sb.append(Resource.SPLITTER);
if (StringUtils.isBlank(dataId)) {
sb.append("*")
.append(Resource.SPLITTER)
.append(AUTH_CONFIG_PREFIX)
.append("*");
sb.append("*").append(Resource.SPLITTER).append(AUTH_CONFIG_PREFIX).append("*");
} else {
sb.append(groupName)
.append(Resource.SPLITTER)
.append(AUTH_CONFIG_PREFIX)
.append(dataId);
sb.append(groupName).append(Resource.SPLITTER).append(AUTH_CONFIG_PREFIX).append(dataId);
}
return sb.toString();
}
}

View File

@ -39,48 +39,47 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class EmbeddedPermissionPersistServiceImpl implements PermissionPersistService {
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private EmbeddedStoragePersistServiceImpl persistService;
public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) {
PaginationHelper<PermissionInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from permissions where ";
String sqlFetchRows
= "select role,resource,action from permissions where ";
String where = " role='" + role + "' ";
if (StringUtils.isBlank(role)) {
where = " 1=1 ";
}
Page<PermissionInfo> pageInfo = helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
public void addPermission(String role, String resource, String action) {
String sql = "INSERT into permissions (role, resource, action) VALUES (?, ?, ?)";
EmbeddedStorageContextUtils.addSqlContext(sql, role, resource, action);
databaseOperate.blockUpdate();
}
public void deletePermission(String role, String resource, String action) {
String sql = "DELETE from permissions WHERE role=? and resource=? and action=?";
EmbeddedStorageContextUtils.addSqlContext(sql, role, resource, action);
databaseOperate.blockUpdate();
}
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private EmbeddedStoragePersistServiceImpl persistService;
public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) {
PaginationHelper<PermissionInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from permissions where ";
String sqlFetchRows = "select role,resource,action from permissions where ";
String where = " role='" + role + "' ";
if (StringUtils.isBlank(role)) {
where = " 1=1 ";
}
Page<PermissionInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
public void addPermission(String role, String resource, String action) {
String sql = "INSERT into permissions (role, resource, action) VALUES (?, ?, ?)";
EmbeddedStorageContextUtils.addSqlContext(sql, role, resource, action);
databaseOperate.blockUpdate();
}
public void deletePermission(String role, String resource, String action) {
String sql = "DELETE from permissions WHERE role=? and resource=? and action=?";
EmbeddedStorageContextUtils.addSqlContext(sql, role, resource, action);
databaseOperate.blockUpdate();
}
}

View File

@ -39,85 +39,82 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class EmbeddedRolePersistServiceImpl implements RolePersistService {
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private EmbeddedStoragePersistServiceImpl persistService;
public Page<RoleInfo> getRoles(int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from (select distinct role from roles) roles where ";
String sqlFetchRows
= "select role,username from roles where ";
String where = " 1=1 ";
Page<RoleInfo> pageInfo = helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
public Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from roles where ";
String sqlFetchRows
= "select role,username from roles where ";
String where = " username='" + username + "' ";
if (StringUtils.isBlank(username)) {
where = " 1=1 ";
}
return helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
}
public void addRole(String role, String userName) {
String sql = "INSERT into roles (role, username) VALUES (?, ?)";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, role, userName);
databaseOperate.update(EmbeddedStorageContextUtils.getCurrentSqlContext());
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void deleteRole(String role) {
String sql = "DELETE from roles WHERE role=?";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, role);
databaseOperate.update(EmbeddedStorageContextUtils.getCurrentSqlContext());
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void deleteRole(String role, String username) {
String sql = "DELETE from roles WHERE role=? and username=?";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, role, username);
databaseOperate.update(EmbeddedStorageContextUtils.getCurrentSqlContext());
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private EmbeddedStoragePersistServiceImpl persistService;
public Page<RoleInfo> getRoles(int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from (select distinct role from roles) roles where ";
String sqlFetchRows = "select role,username from roles where ";
String where = " 1=1 ";
Page<RoleInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
public Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from roles where ";
String sqlFetchRows = "select role,username from roles where ";
String where = " username='" + username + "' ";
if (StringUtils.isBlank(username)) {
where = " 1=1 ";
}
return helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
}
public void addRole(String role, String userName) {
String sql = "INSERT into roles (role, username) VALUES (?, ?)";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, role, userName);
databaseOperate.update(EmbeddedStorageContextUtils.getCurrentSqlContext());
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void deleteRole(String role) {
String sql = "DELETE from roles WHERE role=?";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, role);
databaseOperate.update(EmbeddedStorageContextUtils.getCurrentSqlContext());
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void deleteRole(String role, String username) {
String sql = "DELETE from roles WHERE role=? and username=?";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, role, username);
databaseOperate.update(EmbeddedStorageContextUtils.getCurrentSqlContext());
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
}

View File

@ -39,69 +39,67 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
@Conditional(value = ConditionOnEmbeddedStorage.class)
@Component
public class EmbeddedUserPersistServiceImpl implements UserPersistService {
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private EmbeddedStoragePersistServiceImpl persistService;
public void createUser(String username, String password) {
String sql = "INSERT into users (username, password, enabled) VALUES (?, ?, ?)";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, username, password, true);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void deleteUser(String username) {
String sql = "DELETE from users WHERE username=?";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, username);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void updateUserPassword(String username, String password) {
try {
EmbeddedStorageContextUtils.addSqlContext(
"UPDATE users SET password = ? WHERE username=?",
password, username);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? ";
return databaseOperate.queryOne(sql, new Object[]{username}, USER_ROW_MAPPER);
}
public Page<User> getUsers(int pageNo, int pageSize) {
PaginationHelper<User> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from users where ";
String sqlFetchRows
= "select username,password from users where ";
String where = " 1=1 ";
Page<User> pageInfo = helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, USER_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
@Autowired
private DatabaseOperate databaseOperate;
@Autowired
private EmbeddedStoragePersistServiceImpl persistService;
public void createUser(String username, String password) {
String sql = "INSERT into users (username, password, enabled) VALUES (?, ?, ?)";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, username, password, true);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void deleteUser(String username) {
String sql = "DELETE from users WHERE username=?";
try {
EmbeddedStorageContextUtils.addSqlContext(sql, username);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public void updateUserPassword(String username, String password) {
try {
EmbeddedStorageContextUtils
.addSqlContext("UPDATE users SET password = ? WHERE username=?", password, username);
databaseOperate.blockUpdate();
} finally {
EmbeddedStorageContextUtils.cleanAllContext();
}
}
public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? ";
return databaseOperate.queryOne(sql, new Object[] {username}, USER_ROW_MAPPER);
}
public Page<User> getUsers(int pageNo, int pageSize) {
PaginationHelper<User> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from users where ";
String sqlFetchRows = "select username,password from users where ";
String where = " 1=1 ";
Page<User> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, USER_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
}
}

View File

@ -39,70 +39,69 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalPermissionPersistServiceImpl implements PermissionPersistService {
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;
@PostConstruct
protected void init() {
jt = persistService.getJdbcTemplate();
}
public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) {
PaginationHelper<PermissionInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from permissions where ";
String sqlFetchRows
= "select role,resource,action from permissions where ";
String where = " role='" + role + "' ";
if (StringUtils.isBlank(role)) {
where = " 1=1 ";
}
try {
Page<PermissionInfo> pageInfo = helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo==null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void addPermission(String role, String resource, String action) {
String sql = "INSERT into permissions (role, resource, action) VALUES (?, ?, ?)";
try {
jt.update(sql, role, resource, action);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deletePermission(String role, String resource, String action) {
String sql = "DELETE from permissions WHERE role=? and resource=? and action=?";
try {
jt.update(sql, role, resource, action);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;
@PostConstruct
protected void init() {
jt = persistService.getJdbcTemplate();
}
public Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize) {
PaginationHelper<PermissionInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from permissions where ";
String sqlFetchRows = "select role,resource,action from permissions where ";
String where = " role='" + role + "' ";
if (StringUtils.isBlank(role)) {
where = " 1=1 ";
}
try {
Page<PermissionInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void addPermission(String role, String resource, String action) {
String sql = "INSERT into permissions (role, resource, action) VALUES (?, ?, ?)";
try {
jt.update(sql, role, resource, action);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deletePermission(String role, String resource, String action) {
String sql = "DELETE from permissions WHERE role=? and resource=? and action=?";
try {
jt.update(sql, role, resource, action);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
}

View File

@ -42,109 +42,107 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalRolePersistServiceImpl implements RolePersistService {
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;
@PostConstruct
protected void init() {
jt = persistService.getJdbcTemplate();
}
public Page<RoleInfo> getRoles(int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from (select distinct role from roles) roles where ";
String sqlFetchRows
= "select role,username from roles where ";
String where = " 1=1 ";
try {
Page<RoleInfo> pageInfo = helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from roles where ";
String sqlFetchRows
= "select role,username from roles where ";
String where = " username='" + username + "' ";
if (StringUtils.isBlank(username)) {
where = " 1=1 ";
}
try {
return helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void addRole(String role, String userName) {
String sql = "INSERT into roles (role, username) VALUES (?, ?)";
try {
jt.update(sql, role, userName);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deleteRole(String role) {
String sql = "DELETE from roles WHERE role=?";
try {
jt.update(sql, role);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deleteRole(String role, String username) {
String sql = "DELETE from roles WHERE role=? and username=?";
try {
jt.update(sql, role, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
private static final class RoleInfoRowMapper implements RowMapper<RoleInfo> {
@Override
public RoleInfo mapRow(ResultSet rs, int rowNum)
throws SQLException {
RoleInfo roleInfo = new RoleInfo();
roleInfo.setRole(rs.getString("role"));
roleInfo.setUsername(rs.getString("username"));
return roleInfo;
}
}
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;
@PostConstruct
protected void init() {
jt = persistService.getJdbcTemplate();
}
public Page<RoleInfo> getRoles(int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from (select distinct role from roles) roles where ";
String sqlFetchRows = "select role,username from roles where ";
String where = " 1=1 ";
try {
Page<RoleInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize) {
PaginationHelper<RoleInfo> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from roles where ";
String sqlFetchRows = "select role,username from roles where ";
String where = " username='" + username + "' ";
if (StringUtils.isBlank(username)) {
where = " 1=1 ";
}
try {
return helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void addRole(String role, String userName) {
String sql = "INSERT into roles (role, username) VALUES (?, ?)";
try {
jt.update(sql, role, userName);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deleteRole(String role) {
String sql = "DELETE from roles WHERE role=?";
try {
jt.update(sql, role);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deleteRole(String role, String username) {
String sql = "DELETE from roles WHERE role=? and username=?";
try {
jt.update(sql, role, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
private static final class RoleInfoRowMapper implements RowMapper<RoleInfo> {
@Override
public RoleInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
RoleInfo roleInfo = new RoleInfo();
roleInfo.setRole(rs.getString("role"));
roleInfo.setUsername(rs.getString("username"));
return roleInfo;
}
}
}

View File

@ -40,89 +40,86 @@ import static com.alibaba.nacos.config.server.service.repository.RowMapperManage
@Conditional(value = ConditionOnExternalStorage.class)
@Component
public class ExternalUserPersistServiceImpl implements UserPersistService {
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;
@PostConstruct
protected void init() {
jt = persistService.getJdbcTemplate();
}
public void createUser(String username, String password) {
String sql = "INSERT into users (username, password, enabled) VALUES (?, ?, ?)";
try {
jt.update(sql, username, password, true);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deleteUser(String username) {
String sql = "DELETE from users WHERE username=?";
try {
jt.update(sql, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void updateUserPassword(String username, String password) {
try {
jt.update(
"UPDATE users SET password = ? WHERE username=?",
password, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? ";
try {
return this.jt.queryForObject(sql, new Object[]{username}, USER_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
} catch (EmptyResultDataAccessException e) {
return null;
} catch (Exception e) {
LogUtil.fatalLog.error("[db-other-error]" + e.getMessage(), e);
throw new RuntimeException(e);
}
}
public Page<User> getUsers(int pageNo, int pageSize) {
PaginationHelper<User> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from users where ";
String sqlFetchRows
= "select username,password from users where ";
String where = " 1=1 ";
try {
Page<User> pageInfo = helper.fetchPage(sqlCountRows
+ where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, USER_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
@Autowired
private ExternalStoragePersistServiceImpl persistService;
private JdbcTemplate jt;
@PostConstruct
protected void init() {
jt = persistService.getJdbcTemplate();
}
public void createUser(String username, String password) {
String sql = "INSERT into users (username, password, enabled) VALUES (?, ?, ?)";
try {
jt.update(sql, username, password, true);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void deleteUser(String username) {
String sql = "DELETE from users WHERE username=?";
try {
jt.update(sql, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public void updateUserPassword(String username, String password) {
try {
jt.update("UPDATE users SET password = ? WHERE username=?", password, username);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
public User findUserByUsername(String username) {
String sql = "SELECT username,password FROM users WHERE username=? ";
try {
return this.jt.queryForObject(sql, new Object[] {username}, USER_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
} catch (EmptyResultDataAccessException e) {
return null;
} catch (Exception e) {
LogUtil.fatalLog.error("[db-other-error]" + e.getMessage(), e);
throw new RuntimeException(e);
}
}
public Page<User> getUsers(int pageNo, int pageSize) {
PaginationHelper<User> helper = persistService.createPaginationHelper();
String sqlCountRows = "select count(*) from users where ";
String sqlFetchRows = "select username,password from users where ";
String where = " 1=1 ";
try {
Page<User> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, USER_ROW_MAPPER);
if (pageInfo == null) {
pageInfo = new Page<>();
pageInfo.setTotalCount(0);
pageInfo.setPageItems(new ArrayList<>());
}
return pageInfo;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.fatalLog.error("[db-error] " + e.toString(), e);
throw e;
}
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.auth;
import java.io.Serializable;
@ -22,43 +23,44 @@ import java.io.Serializable;
* @since 1.2.0
*/
public class PermissionInfo implements Serializable {
private static final long serialVersionUID = 388813573388837395L;
/**
* Role name
*/
private String role;
/**
* Resource
*/
private String resource;
/**
* Action on resource
*/
private String action;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.model.Page;
@ -25,11 +26,11 @@ import com.alibaba.nacos.config.server.model.Page;
*/
@SuppressWarnings("PMD.AbstractMethodOrInterfaceMethodMustUseJavadocRule")
public interface PermissionPersistService {
Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize);
void addPermission(String role, String resource, String action);
void deletePermission(String role, String resource, String action);
Page<PermissionInfo> getPermissions(String role, int pageNo, int pageSize);
void addPermission(String role, String resource, String action);
void deletePermission(String role, String resource, String action);
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.auth;
import java.io.Serializable;
@ -24,34 +25,31 @@ import java.io.Serializable;
* @since 1.2.0
*/
public class RoleInfo implements Serializable {
private static final long serialVersionUID = 5946986388047856568L;
private String role;
private String username;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "RoleInfo{" +
"role='" + role + '\'' +
", username='" + username + '\'' +
'}';
return "RoleInfo{" + "role='" + role + '\'' + ", username='" + username + '\'' + '}';
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.model.Page;
@ -25,15 +26,15 @@ import com.alibaba.nacos.config.server.model.Page;
*/
@SuppressWarnings("PMD.AbstractMethodOrInterfaceMethodMustUseJavadocRule")
public interface RolePersistService {
Page<RoleInfo> getRoles(int pageNo, int pageSize);
Page<RoleInfo> getRolesByUserName(String username, int pageNo, int pageSize);
void addRole(String role, String userName);
void deleteRole(String role);
void deleteRole(String role, String username);
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.model.Page;
@ -26,15 +27,15 @@ import com.alibaba.nacos.config.server.model.User;
*/
@SuppressWarnings("PMD.AbstractMethodOrInterfaceMethodMustUseJavadocRule")
public interface UserPersistService {
void createUser(String username, String password);
void deleteUser(String username);
void updateUserPassword(String username, String password);
User findUserByUsername(String username);
Page<User> getUsers(int pageNo, int pageSize);
}

View File

@ -28,7 +28,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConditionDistributedEmbedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode();

View File

@ -25,9 +25,9 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConditionOnEmbeddedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return PropertyUtil.isEmbeddedStorage();
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return PropertyUtil.isEmbeddedStorage();
}
}

View File

@ -25,10 +25,10 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConditionOnExternalStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !PropertyUtil.isEmbeddedStorage();
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return !PropertyUtil.isEmbeddedStorage();
}
}

View File

@ -28,7 +28,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConditionStandaloneEmbedStorage implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return PropertyUtil.isEmbeddedStorage() && ApplicationUtils.getStandaloneMode();

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.configuration;
import com.alibaba.nacos.config.server.filter.NacosWebFilter;
@ -30,37 +31,37 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration
public class NacosConfigConfiguration {
@Bean
public FilterRegistrationBean nacosWebFilterRegistration() {
FilterRegistrationBean<NacosWebFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(nacosWebFilter());
registration.addUrlPatterns("/v1/cs/*");
registration.setName("nacosWebFilter");
registration.setOrder(1);
return registration;
}
@Bean
public NacosWebFilter nacosWebFilter() {
return new NacosWebFilter();
}
@Conditional(ConditionDistributedEmbedStorage.class)
@Bean
public FilterRegistrationBean transferToLeaderRegistration() {
FilterRegistrationBean<CurcuitFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(transferToLeader());
registration.addUrlPatterns("/v1/cs/*");
registration.setName("curcuitFilter");
registration.setOrder(6);
return registration;
}
@Conditional(ConditionDistributedEmbedStorage.class)
@Bean
public CurcuitFilter transferToLeader() {
return new CurcuitFilter();
}
@Bean
public FilterRegistrationBean nacosWebFilterRegistration() {
FilterRegistrationBean<NacosWebFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(nacosWebFilter());
registration.addUrlPatterns("/v1/cs/*");
registration.setName("nacosWebFilter");
registration.setOrder(1);
return registration;
}
@Bean
public NacosWebFilter nacosWebFilter() {
return new NacosWebFilter();
}
@Conditional(ConditionDistributedEmbedStorage.class)
@Bean
public FilterRegistrationBean transferToLeaderRegistration() {
FilterRegistrationBean<CurcuitFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(transferToLeader());
registration.addUrlPatterns("/v1/cs/*");
registration.setName("curcuitFilter");
registration.setOrder(6);
return registration;
}
@Conditional(ConditionDistributedEmbedStorage.class)
@Bean
public CurcuitFilter transferToLeader() {
return new CurcuitFilter();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.constant;
import com.alibaba.nacos.config.server.model.event.ConfigDumpEvent;
@ -23,171 +24,243 @@ import com.alibaba.nacos.config.server.model.event.ConfigDumpEvent;
* @author Nacos
*/
public class Constants {
public static final String CLIENT_VERSION_HEADER = "Client-Version";
public static final String CLIENT_VERSION = "3.0.0";
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
/**
* server端配置文件基目录
*/
public static final String BASE_DIR = "config-data";
/**
* server端配置文件备份目录
*/
public static final String CONFIG_BAK_DIR = System.getProperty("user.home", "/home/admin") + "/nacos/bak_data";
public static final String APPNAME = "AppName";
public static final String UNKNOWN_APP = "UnknownApp";
public static final String DEFAULT_DOMAINNAME = "commonconfig.config-host.taobao.com";
public static final String DAILY_DOMAINNAME = "commonconfig.taobao.net";
public static final String NULL = "";
public static final String DATAID = "dataId";
public static final String GROUP = "group";
public static final String LAST_MODIFIED = "Last-Modified";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String PROBE_MODIFY_REQUEST = "Listening-Configs";
public static final String PROBE_MODIFY_RESPONSE = "Probe-Modify-Response";
public static final String PROBE_MODIFY_RESPONSE_NEW = "Probe-Modify-Response-New";
public static final String USE_ZIP = "true";
public static final String CONTENT_MD5 = "Content-MD5";
public static final String CONFIG_VERSION = "Config-Version";
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String SPACING_INTERVAL = "client-spacing-interval";
/**
*
*/
public static final int ASYNC_UPDATE_ADDRESS_INTERVAL = 300;
/**
*
*/
public static final int POLLING_INTERVAL_TIME = 15;
/**
* 毫秒
*/
public static final int ONCE_TIMEOUT = 2000;
/**
* 毫秒
*/
public static final int CONN_TIMEOUT = 2000;
/**
* 毫秒
*/
public static final int SO_TIMEOUT = 60000;
/**
* 毫秒
*/
public static final int RECV_WAIT_TIMEOUT = ONCE_TIMEOUT * 5;
public static final String BASE_PATH = "/v1/cs";
public static final String OPS_CONTROLLER_PATH = BASE_PATH + "/ops";
public static final String CAPACITY_CONTROLLER_PATH = BASE_PATH + "/capacity";
public static final String COMMUNICATION_CONTROLLER_PATH = BASE_PATH + "/communication";
public static final String CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs";
public static final String HEALTH_CONTROLLER_PATH = BASE_PATH + "/health";
public static final String HISTORY_CONTROLLER_PATH = BASE_PATH + "/history";
public static final String LISTENER_CONTROLLER_PATH = BASE_PATH + "/listener";
public static final String NAMESPACE_CONTROLLER_PATH = BASE_PATH + "/namespaces";
public static final String ENCODE = "UTF-8";
public static final String MAP_FILE = "map-file.js";
public static final int FLOW_CONTROL_THRESHOLD = 20;
public static final int FLOW_CONTROL_SLOT = 10;
public static final int FLOW_CONTROL_INTERVAL = 1000;
public static final String LINE_SEPARATOR = Character.toString((char) 1);
public static final String WORD_SEPARATOR = Character.toString((char) 2);
public static final String NACOS_LINE_SEPARATOR = "\r\n";
/**
* 从网络获取数据的总时间, 当超过此时间, 不再从网络获取数据, 单位ms
*/
public static final long TOTALTIME_FROM_SERVER = 10000;
/**
* 从网络获取数据的总时间的失效时间, 单位ms
*/
public static final long TOTALTIME_INVALID_THRESHOLD = 60000;
/**
* 发生异常
*/
public static final int BATCH_OP_ERROR = -1;
/**
* 批量操作时, 单条数据的状态码
*/
public static final String BATCH_OP_ERROR_IO_MSG = "get config dump error";
public static final String BATCH_OP_ERROR_CONFLICT_MSG = "config get conflicts";
/**
* 查询成功, 数据存在
*/
public static final int BATCH_QUERY_EXISTS = 1;
public static final String BATCH_QUERY_EXISTS_MSG = "config exits";
/**
* 查询成功, 数据不存在
*/
public static final int BATCH_QUERY_NONEXISTS = 2;
public static final String BATCH_QUERY_NONEEXISTS_MSG = "config not exits";
/**
* 新增成功
*/
public static final int BATCH_ADD_SUCCESS = 3;
/**
* 更新成功
*/
public static final int BATCH_UPDATE_SUCCESS = 4;
public static final int MAX_UPDATE_FAIL_COUNT = 5;
public static final int MAX_UPDATEALL_FAIL_COUNT = 5;
public static final int MAX_REMOVE_FAIL_COUNT = 5;
public static final int MAX_REMOVEALL_FAIL_COUNT = 5;
public static final int MAX_NOTIFY_COUNT = 5;
public static final int MAX_ADDACK_COUNT = 5;
/**
* 数据的初始版本号
*/
public static final int FIRST_VERSION = 1;
/**
* 数据被删除的标识版本号
*/
public static final int POISON_VERSION = -1;
/**
* 写磁盘文件时, 临时版本号
*/
public static final int TEMP_VERSION = 0;
/**
* 获取数据的顺序容灾文件-> 服务器 -> 本地缓存
*/
public static final int GETCONFIG_LOCAL_SERVER_SNAPSHOT = 1;
/**
* 获取数据的顺序容灾文件-> 本地缓存 -> 服务器
*/
public static final int GETCONFIG_LOCAL_SNAPSHOT_SERVER = 2;
public static final String CLIENT_APPNAME_HEADER = "Client-AppName";
public static final String CLIENT_REQUEST_TS_HEADER = "Client-RequestTS";
public static final String CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken";
/**
* client, sdk请求server服务的身份
*/
public static final String REQUEST_IDENTITY = "Request-Identity";
/**
* 转发给Leader节点
*/
public static final String FORWARD_LEADER = "Forward-Leader";
/**
* 鉴权结果信息
*/
public static final String ACL_RESPONSE = "ACL-Response";
public static final int ATOMIC_MAX_SIZE = 1000;
public static final String CONFIG_MODEL_RAFT_GROUP = "nacos_config";
public static int DATA_IN_BODY_VERSION = 204;
/**
* Configure the dump event name
*/
public static final String EXTEND_INFO_CONFIG_DUMP_EVENT = ConfigDumpEvent.class.getName();
/**
* Configure the dump event-list name
*/
public static final String EXTEND_INFOS_CONFIG_DUMP_EVENT = ConfigDumpEvent.class.getName() + "@@many";
/**
* Specifies that reads wait without timeout
*/

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.constant;
/**
@ -30,7 +31,7 @@ public enum CounterMode {
* 减少
*/
DECREMENT;
public CounterMode reverse() {
if (INCREMENT == this) {
return DECREMENT;

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.common.model.RestResult;
@ -35,20 +36,19 @@ import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping(Constants.CAPACITY_CONTROLLER_PATH)
public class CapacityController {
private static final Logger LOGGER = LoggerFactory.getLogger(CapacityController.class);
private final CapacityService capacityService;
@Autowired
public CapacityController(CapacityService capacityService) {
this.capacityService = capacityService;
}
@GetMapping
public RestResult<Capacity> getCapacity(HttpServletResponse response,
@RequestParam(required = false) String group,
@RequestParam(required = false) String tenant) {
public RestResult<Capacity> getCapacity(HttpServletResponse response, @RequestParam(required = false) String group,
@RequestParam(required = false) String tenant) {
if (group == null && tenant == null) {
RestResult<Capacity> restResult = new RestResult<Capacity>();
response.setStatus(400);
@ -84,18 +84,15 @@ public class CapacityController {
}
return restResult;
}
/**
* 修改Group或租户的容量容量信息还没有初始化的则初始化记录
*/
@PostMapping
public RestResult<Boolean> updateCapacity(HttpServletResponse response,
@RequestParam(required = false) String group,
@RequestParam(required = false) String tenant,
@RequestParam(required = false) Integer quota,
@RequestParam(required = false) Integer maxSize,
@RequestParam(required = false) Integer maxAggrCount,
@RequestParam(required = false) Integer maxAggrSize) {
@RequestParam(required = false) String group, @RequestParam(required = false) String tenant,
@RequestParam(required = false) Integer quota, @RequestParam(required = false) Integer maxSize,
@RequestParam(required = false) Integer maxAggrCount, @RequestParam(required = false) Integer maxAggrSize) {
if (StringUtils.isBlank(group) && StringUtils.isBlank(tenant)) {
capacityService.initAllCapacity();
RestResult<Boolean> restResult = new RestResult<Boolean>();
@ -125,8 +122,8 @@ public class CapacityController {
return restResult;
}
try {
boolean insertOrUpdateResult = capacityService.insertOrUpdateCapacity(group, tenant, quota, maxSize,
maxAggrCount, maxAggrSize);
boolean insertOrUpdateResult = capacityService
.insertOrUpdateCapacity(group, tenant, quota, maxSize, maxAggrCount, maxAggrSize);
if (insertOrUpdateResult) {
setSuccessResult(response, restResult);
restResult.setMessage(String.format("成功更新%s为%s的容量信息配置", targetFieldName, targetFieldValue));
@ -142,13 +139,13 @@ public class CapacityController {
return restResult;
}
}
private void setFailResult(HttpServletResponse response, RestResult<Boolean> restResult, int statusCode) {
response.setStatus(statusCode);
restResult.setCode(statusCode);
restResult.setData(false);
}
private void setSuccessResult(HttpServletResponse response, RestResult<Boolean> restResult) {
response.setStatus(200);
restResult.setCode(200);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.config.server.constant.Constants;
@ -40,28 +41,27 @@ import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping(Constants.COMMUNICATION_CONTROLLER_PATH)
public class CommunicationController {
private final DumpService dumpService;
private final LongPollingService longPollingService;
private String trueStr = "true";
@Autowired
public CommunicationController(DumpService dumpService, LongPollingService longPollingService) {
this.dumpService = dumpService;
this.longPollingService = longPollingService;
}
/**
* 通知配置信息改变
*/
@GetMapping("/dataChange")
public Boolean notifyConfigInfo(HttpServletRequest request,
@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY)
String tenant,
@RequestParam(value = "tag", required = false) String tag) {
public Boolean notifyConfigInfo(HttpServletRequest request, @RequestParam("dataId") String dataId,
@RequestParam("group") String group,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,
@RequestParam(value = "tag", required = false) String tag) {
dataId = dataId.trim();
group = group.trim();
String lastModified = request.getHeader(NotifyService.NOTIFY_HEADER_LAST_MODIFIED);
@ -75,26 +75,23 @@ public class CommunicationController {
}
return true;
}
/**
* 在本台机器上获得订阅改配置的客户端信息
*/
@GetMapping("/configWatchers")
public SampleResult getSubClientConfig(@RequestParam("dataId") String dataId,
@RequestParam("group") String group,
@RequestParam(value = "tenant", required = false) String tenant,
ModelMap modelMap) {
public SampleResult getSubClientConfig(@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "tenant", required = false) String tenant, ModelMap modelMap) {
group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group;
return longPollingService.getCollectSubscribleInfo(dataId, group, tenant);
}
/**
* 在本台机器上获得客户端监听的配置列表
*/
@GetMapping("/watcherConfigs")
public SampleResult getSubClientConfigByIp(HttpServletRequest request,
HttpServletResponse response, @RequestParam("ip") String ip,
ModelMap modelMap) {
public SampleResult getSubClientConfigByIp(HttpServletRequest request, HttpServletResponse response,
@RequestParam("ip") String ip, ModelMap modelMap) {
return longPollingService.getCollectSubscribleInfoByIp(ip);
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.config.server.constant.Constants;
@ -51,43 +52,42 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
*/
@Service
public class ConfigServletInner {
@Autowired
private LongPollingService longPollingService;
@Autowired
private PersistService persistService;
private static final int TRY_GET_LOCK_TIMES = 9;
private static final int START_LONG_POLLING_VERSION_NUM = 204;
/**
* 轮询接口
*/
public String doPollingConfig(HttpServletRequest request, HttpServletResponse response,
Map<String, String> clientMd5Map, int probeRequestSize)
throws IOException {
Map<String, String> clientMd5Map, int probeRequestSize) throws IOException {
// 长轮询
if (LongPollingService.isSupportLongPolling(request)) {
longPollingService.addLongPollingClient(request, response, clientMd5Map, probeRequestSize);
return HttpServletResponse.SC_OK + "";
}
// else 兼容短轮询逻辑
List<String> changedGroups = MD5Util.compareMd5(request, response, clientMd5Map);
// 兼容短轮询result
String oldResult = MD5Util.compareMd5OldResult(changedGroups);
String newResult = MD5Util.compareMd5ResultString(changedGroups);
String version = request.getHeader(Constants.CLIENT_VERSION_HEADER);
if (version == null) {
version = "2.0.0";
}
int versionNum = Protocol.getVersionNumber(version);
/**
* 2.0.4版本以前, 返回值放入header中
*/
@ -97,9 +97,9 @@ public class ConfigServletInner {
} else {
request.setAttribute("content", newResult);
}
Loggers.AUTH.info("new content:" + newResult);
// 禁用缓存
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
@ -107,17 +107,17 @@ public class ConfigServletInner {
response.setStatus(HttpServletResponse.SC_OK);
return HttpServletResponse.SC_OK + "";
}
/**
* 同步配置获取接口
*/
public String doGetConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group,
String tenant, String tag, String clientIp) throws IOException, ServletException {
String tenant, String tag, String clientIp) throws IOException, ServletException {
final String groupKey = GroupKey2.getKey(dataId, group, tenant);
String autoTag = request.getHeader("Vipserver-Tag");
String requestIpApp = RequestUtil.getAppName(request);
int lockResult = tryConfigReadLock(groupKey);
final String requestIp = RequestUtil.getRemoteIp(request);
boolean isBeta = false;
if (lockResult > 0) {
@ -163,9 +163,9 @@ public class ConfigServletInner {
} else {
file = DiskUtil.targetTagFile(dataId, group, tenant, autoTag);
}
response.setHeader("Vipserver-Tag",
URLEncoder.encode(autoTag, StandardCharsets.UTF_8.displayName()));
URLEncoder.encode(autoTag, StandardCharsets.UTF_8.displayName()));
} else {
md5 = cacheItem.getMd5();
lastModified = cacheItem.getLastModifiedTs();
@ -178,12 +178,12 @@ public class ConfigServletInner {
// FIXME CacheItem
// 不存在了无法简单的计算推送delayed这里简单的记做-1
ConfigTraceService.logPullEvent(dataId, group, tenant, requestIpApp, -1,
ConfigTraceService.PULL_EVENT_NOTFOUND, -1, requestIp);
ConfigTraceService.PULL_EVENT_NOTFOUND, -1, requestIp);
// pullLog.info("[client-get] clientIp={}, {},
// no data",
// new Object[]{clientIp, groupKey});
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().println("config data not exist");
return HttpServletResponse.SC_NOT_FOUND + "";
@ -210,20 +210,19 @@ public class ConfigServletInner {
// FIXME CacheItem
// 不存在了无法简单的计算推送delayed这里简单的记做-1
ConfigTraceService.logPullEvent(dataId, group, tenant, requestIpApp, -1,
ConfigTraceService.PULL_EVENT_NOTFOUND,
-1, requestIp);
ConfigTraceService.PULL_EVENT_NOTFOUND, -1, requestIp);
// pullLog.info("[client-get] clientIp={}, {},
// no data",
// new Object[]{clientIp, groupKey});
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().println("config data not exist");
return HttpServletResponse.SC_NOT_FOUND + "";
}
}
}
response.setHeader(Constants.CONTENT_MD5, md5);
/**
* 禁用缓存
@ -237,27 +236,26 @@ public class ConfigServletInner {
fis = new FileInputStream(file);
response.setDateHeader("Last-Modified", file.lastModified());
}
if (PropertyUtil.isDirectRead()) {
out = response.getWriter();
out.print(configInfoBase.getContent());
out.flush();
out.close();
} else {
fis.getChannel().transferTo(0L, fis.getChannel().size(),
Channels.newChannel(response.getOutputStream()));
fis.getChannel()
.transferTo(0L, fis.getChannel().size(), Channels.newChannel(response.getOutputStream()));
}
LogUtil.pullCheckLog.warn("{}|{}|{}|{}", groupKey, requestIp, md5, TimeUtils.getCurrentTimeStr());
final long delayed = System.currentTimeMillis() - lastModified;
// TODO distinguish pull-get && push-get
// 否则无法直接把delayed作为推送延时的依据因为主动get请求的delayed值都很大
ConfigTraceService.logPullEvent(dataId, group, tenant, requestIpApp, lastModified,
ConfigTraceService.PULL_EVENT_OK, delayed,
requestIp);
ConfigTraceService.PULL_EVENT_OK, delayed, requestIp);
} finally {
releaseConfigReadLock(groupKey);
if (null != fis) {
@ -265,32 +263,33 @@ public class ConfigServletInner {
}
}
} else if (lockResult == 0) {
// FIXME CacheItem 不存在了无法简单的计算推送delayed这里简单的记做-1
ConfigTraceService.logPullEvent(dataId, group, tenant, requestIpApp, -1,
ConfigTraceService.PULL_EVENT_NOTFOUND, -1, requestIp);
ConfigTraceService
.logPullEvent(dataId, group, tenant, requestIpApp, -1, ConfigTraceService.PULL_EVENT_NOTFOUND, -1,
requestIp);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().println("config data not exist");
return HttpServletResponse.SC_NOT_FOUND + "";
} else {
pullLog.info("[client-get] clientIp={}, {}, get data during dump", clientIp, groupKey);
response.setStatus(HttpServletResponse.SC_CONFLICT);
response.getWriter().println("requested file is being modified, please try later.");
return HttpServletResponse.SC_CONFLICT + "";
}
return HttpServletResponse.SC_OK + "";
}
private static void releaseConfigReadLock(String groupKey) {
ConfigCacheService.releaseReadLock(groupKey);
}
private static int tryConfigReadLock(String groupKey) {
/**
* 默认加锁失败
@ -307,7 +306,7 @@ public class ConfigServletInner {
if (0 == lockResult) {
break;
}
/**
* success
*/
@ -324,19 +323,19 @@ public class ConfigServletInner {
}
}
}
return lockResult;
}
private static boolean isUseTag(CacheItem cacheItem, String tag) {
if (cacheItem != null && cacheItem.tagMd5 != null && cacheItem.tagMd5.size() > 0) {
return StringUtils.isNotBlank(tag) && cacheItem.tagMd5.containsKey(tag);
}
return false;
}
private static boolean fileNotExist(File file) {
return file == null || !file.exists();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.config.server.constant.Constants;
@ -35,45 +36,45 @@ import javax.annotation.PostConstruct;
@RestController
@RequestMapping(Constants.HEALTH_CONTROLLER_PATH)
public class HealthController {
private DataSourceService dataSourceService;
private String heathUpStr = "UP";
private String heathDownStr = "DOWN";
private String heathWarnStr = "WARN";
@Autowired
private ServerMemberManager memberManager;
@PostConstruct
public void init() {
dataSourceService = DynamicDataSource.getInstance().getDataSource();
}
@GetMapping
public String getHealth() {
// TODO UP DOWN WARN
StringBuilder sb = new StringBuilder();
String dbStatus = dataSourceService.getHealth();
if (dbStatus.contains(heathUpStr) && memberManager.isInIpList()) {
sb.append(heathUpStr);
}
else if (dbStatus.contains(heathWarnStr) && memberManager.isInIpList()) {
sb.append("WARN:");
sb.append("slave db (").append(dbStatus.split(":")[1]).append(") down. ");
}
else {
sb.append("DOWN:");
if (dbStatus.contains(heathDownStr)) {
sb.append("master db (").append(dbStatus.split(":")[1])
.append(") down. ");
}
if (!memberManager.isInIpList()) {
sb.append("server ip ").append(InetUtils.getSelfIp())
.append(" is not in the serverList of address server. ");
}
}
return sb.toString();
}
private DataSourceService dataSourceService;
private String heathUpStr = "UP";
private String heathDownStr = "DOWN";
private String heathWarnStr = "WARN";
@Autowired
private ServerMemberManager memberManager;
@PostConstruct
public void init() {
dataSourceService = DynamicDataSource.getInstance().getDataSource();
}
@GetMapping
public String getHealth() {
// TODO UP DOWN WARN
StringBuilder sb = new StringBuilder();
String dbStatus = dataSourceService.getHealth();
if (dbStatus.contains(heathUpStr) && memberManager.isInIpList()) {
sb.append(heathUpStr);
} else if (dbStatus.contains(heathWarnStr) && memberManager.isInIpList()) {
sb.append("WARN:");
sb.append("slave db (").append(dbStatus.split(":")[1]).append(") down. ");
} else {
sb.append("DOWN:");
if (dbStatus.contains(heathDownStr)) {
sb.append("master db (").append(dbStatus.split(":")[1]).append(") down. ");
}
if (!memberManager.isInIpList()) {
sb.append("server ip ").append(InetUtils.getSelfIp())
.append(" is not in the serverList of address server. ");
}
}
return sb.toString();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.config.server.constant.Constants;
@ -38,35 +39,33 @@ import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping(Constants.HISTORY_CONTROLLER_PATH)
public class HistoryController {
@Autowired
protected PersistService persistService;
@GetMapping(params = "search=accurate")
public Page<ConfigHistoryInfo> listConfigHistory(@RequestParam("dataId") String dataId, //
@RequestParam("group") String group, //
@RequestParam(value = "tenant", required = false,
defaultValue = StringUtils.EMPTY) String tenant,
@RequestParam(value = "appName", required = false) String appName,
@RequestParam(value = "pageNo", required = false) Integer pageNo,
//
@RequestParam(value = "pageSize", required = false)
Integer pageSize, //
ModelMap modelMap) {
@RequestParam("group") String group, //
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) String tenant,
@RequestParam(value = "appName", required = false) String appName,
@RequestParam(value = "pageNo", required = false) Integer pageNo,
//
@RequestParam(value = "pageSize", required = false) Integer pageSize, //
ModelMap modelMap) {
pageNo = null == pageNo ? 1 : pageNo;
pageSize = null == pageSize ? 100 : pageSize;
pageSize = Math.min(500,pageSize);
pageSize = Math.min(500, pageSize);
// configInfoBase没有appName字段
return persistService.findConfigHistory(dataId, group, tenant, pageNo, pageSize);
}
/**
* 查看配置历史信息详情
*/
@GetMapping
public ConfigHistoryInfo getConfigHistoryInfo(HttpServletRequest request, HttpServletResponse response,
@RequestParam("nid") Long nid, ModelMap modelMap) {
@RequestParam("nid") Long nid, ModelMap modelMap) {
return persistService.detailConfigHistory(nid);
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.config.server.constant.Constants;
@ -39,25 +40,23 @@ import java.util.Map;
@RestController
@RequestMapping(Constants.LISTENER_CONTROLLER_PATH)
public class ListenerController {
private final ConfigSubService configSubService;
@Autowired
public ListenerController(ConfigSubService configSubService) {
this.configSubService = configSubService;
}
/**
* 获取客户端订阅配置信息
*/
@GetMapping
public GroupkeyListenserStatus getAllSubClientConfigByIp(@RequestParam("ip") String ip,
@RequestParam(value = "all", required = false) boolean all,
@RequestParam(value = "tenant", required = false)
String tenant,
@RequestParam(value = "sampleTime", required = false,
defaultValue = "1") int sampleTime, ModelMap modelMap)
throws Exception {
@RequestParam(value = "all", required = false) boolean all,
@RequestParam(value = "tenant", required = false) String tenant,
@RequestParam(value = "sampleTime", required = false, defaultValue = "1") int sampleTime, ModelMap modelMap)
throws Exception {
SampleResult collectSampleResult = configSubService.getCollectSampleResultByIp(ip, sampleTime);
GroupkeyListenserStatus gls = new GroupkeyListenserStatus();
gls.setCollectStatus(200);
@ -83,9 +82,9 @@ public class ListenerController {
}
gls.setLisentersGroupkeyStatus(configMd5Status);
}
return gls;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.controller.parameters;
/**
@ -22,33 +23,33 @@ package com.alibaba.nacos.config.server.controller.parameters;
* @date 2019/12/13 16:10
*/
public class SameNamespaceCloneConfigBean {
private Long cfgId;
private String dataId;
private String group;
public Long getCfgId() {
return cfgId;
}
public void setCfgId(Long cfgId) {
this.cfgId = cfgId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.enums;
/**
@ -22,74 +23,74 @@ package com.alibaba.nacos.config.server.enums;
* @date 2019/7/1 10:21
*/
public enum FileTypeEnum {
/**
* @author klw
* @Description: yaml file
*/
YML("yaml"),
/**
* @author klw
* @Description: yaml file
*/
YAML("yaml"),
/**
* @author klw
* @Description: text file
*/
TXT("text"),
/**
* @author klw
* @Description: text file
*/
TEXT("text"),
/**
* @author klw
* @Description: json file
*/
JSON("json"),
/**
* @author klw
* @Description: xml file
*/
XML("xml"),
/**
* @author klw
* @Description: html file
*/
HTM("html"),
/**
* @author klw
* @Description: html file
*/
HTML("html"),
/**
* @author klw
* @Description: properties file
*/
PROPERTIES("properties");
/**
* @author klw
* @Description: file type corresponding to file extension
*/
private String fileType;
FileTypeEnum(String fileType) {
this.fileType = fileType;
}
public String getFileType() {
return this.fileType;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.exception;
import com.alibaba.nacos.api.exception.NacosException;
@ -32,7 +33,7 @@ import java.io.IOException;
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* For IllegalArgumentException, we are returning void with status code as 400, so our error-page will be used in
* this case.
@ -44,7 +45,7 @@ public class GlobalExceptionHandler {
MetricsMonitor.getIllegalArgumentException().increment();
return ResponseEntity.status(400).body(ExceptionUtil.getAllExceptionMsg(ex));
}
/**
* For NacosException
*
@ -55,7 +56,7 @@ public class GlobalExceptionHandler {
MetricsMonitor.getNacosException().increment();
return ResponseEntity.status(ex.getErrCode()).body(ExceptionUtil.getAllExceptionMsg(ex));
}
/**
* For DataAccessException
*
@ -66,5 +67,5 @@ public class GlobalExceptionHandler {
MetricsMonitor.getDbException().increment();
return ResponseEntity.status(500).body(ExceptionUtil.getAllExceptionMsg(ex));
}
}

View File

@ -23,27 +23,27 @@ import org.springframework.dao.DataAccessException;
*/
@SuppressWarnings("all")
public class NJdbcException extends DataAccessException {
private String originExceptionName;
public NJdbcException(String msg) {
super(msg);
}
public NJdbcException(String msg, String originExceptionName) {
super(msg);
this.originExceptionName = originExceptionName;
}
public NJdbcException(String msg, Throwable cause, String originExceptionName) {
super(msg, cause);
this.originExceptionName = originExceptionName;
}
public NJdbcException(String msg, Throwable cause) {
super(msg, cause);
}
public NJdbcException(Throwable cause) {
super("", cause);
}

View File

@ -20,23 +20,24 @@ package com.alibaba.nacos.config.server.exception;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class NacosConfigException extends RuntimeException {
public NacosConfigException() {
}
public NacosConfigException(String message) {
super(message);
}
public NacosConfigException(String message, Throwable cause) {
super(message, cause);
}
public NacosConfigException(Throwable cause) {
super(cause);
}
public NacosConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
public NacosConfigException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -44,106 +44,101 @@ import java.security.AccessControlException;
import java.util.List;
/**
* If the embedded distributed storage is enabled, all requests are routed to the Leader
* node for processing, and the maximum number of forwards for a single request cannot
* exceed three
* If the embedded distributed storage is enabled, all requests are routed to the Leader node for processing, and the
* maximum number of forwards for a single request cannot exceed three
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class CurcuitFilter implements Filter {
private volatile boolean isDowngrading = false;
private volatile boolean isOpenService = false;
@Autowired
private ServerMemberManager memberManager;
@Autowired
private CPProtocol protocol;
@Autowired
private ControllerMethodsCache controllerMethodsCache;
@PostConstruct
protected void init() {
listenerSelfInCluster();
registerSubscribe();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (!isOpenService) {
resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"In the node initialization, unable to process any requests at this time");
return;
}
try {
// If an unrecoverable exception occurs on this node, the write request operation shall not be processed
// This is a very important warning message !!!
if (isDowngrading) {
resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"Unable to process the request at this time: System triggered degradation");
return;
}
chain.doFilter(req, response);
}
catch (AccessControlException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,
"access denied: " + ExceptionUtil.getAllExceptionMsg(e));
}
catch (Throwable e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Server failed," + e.toString());
}
}
@Override
public void destroy() {
}
private void listenerSelfInCluster() {
protocol.protocolMetaData().subscribe(Constants.CONFIG_MODEL_RAFT_GROUP,
MetadataKey.RAFT_GROUP_MEMBER, (o, arg) -> {
final List<String> peers = (List<String>) arg;
final Member self = memberManager.getSelf();
final String raftAddress = self.getIp() + ":" + self
.getExtendVal(MemberMetaDataConstants.RAFT_PORT);
// Only when you are in the cluster and the current Leader is
// elected can you provide external services
isOpenService = peers.contains(raftAddress);
});
}
private void registerSubscribe() {
NotifyCenter.registerSubscribe(new SmartSubscribe() {
@Override
public void onEvent(Event event) {
// @JustForTest
// This event only happens in the case of unit tests
if (event instanceof RaftDBErrorRecoverEvent) {
isDowngrading = false;
return;
}
if (event instanceof RaftDBErrorEvent) {
isDowngrading = true;
}
}
@Override
public boolean canNotify(Event event) {
return (event instanceof RaftDBErrorEvent)
|| (event instanceof RaftDBErrorRecoverEvent);
}
});
}
private volatile boolean isDowngrading = false;
private volatile boolean isOpenService = false;
@Autowired
private ServerMemberManager memberManager;
@Autowired
private CPProtocol protocol;
@Autowired
private ControllerMethodsCache controllerMethodsCache;
@PostConstruct
protected void init() {
listenerSelfInCluster();
registerSubscribe();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (!isOpenService) {
resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"In the node initialization, unable to process any requests at this time");
return;
}
try {
// If an unrecoverable exception occurs on this node, the write request operation shall not be processed
// This is a very important warning message !!!
if (isDowngrading) {
resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"Unable to process the request at this time: System triggered degradation");
return;
}
chain.doFilter(req, response);
} catch (AccessControlException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN, "access denied: " + ExceptionUtil.getAllExceptionMsg(e));
} catch (Throwable e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server failed," + e.toString());
}
}
@Override
public void destroy() {
}
private void listenerSelfInCluster() {
protocol.protocolMetaData()
.subscribe(Constants.CONFIG_MODEL_RAFT_GROUP, MetadataKey.RAFT_GROUP_MEMBER, (o, arg) -> {
final List<String> peers = (List<String>) arg;
final Member self = memberManager.getSelf();
final String raftAddress =
self.getIp() + ":" + self.getExtendVal(MemberMetaDataConstants.RAFT_PORT);
// Only when you are in the cluster and the current Leader is
// elected can you provide external services
isOpenService = peers.contains(raftAddress);
});
}
private void registerSubscribe() {
NotifyCenter.registerSubscribe(new SmartSubscribe() {
@Override
public void onEvent(Event event) {
// @JustForTest
// This event only happens in the case of unit tests
if (event instanceof RaftDBErrorRecoverEvent) {
isDowngrading = false;
return;
}
if (event instanceof RaftDBErrorEvent) {
isDowngrading = true;
}
}
@Override
public boolean canNotify(Event event) {
return (event instanceof RaftDBErrorEvent) || (event instanceof RaftDBErrorRecoverEvent);
}
});
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.filter;
import com.alibaba.nacos.config.server.constant.Constants;
@ -34,13 +35,13 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
* @author Nacos
*/
public class NacosWebFilter implements Filter {
static private String webRootPath;
static public String rootPath() {
return webRootPath;
}
/**
* 方便测试
*
@ -49,19 +50,19 @@ public class NacosWebFilter implements Filter {
static public void setWebRootPath(String path) {
webRootPath = path;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
ServletContext ctx = filterConfig.getServletContext();
setWebRootPath(ctx.getRealPath("/"));
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
throws IOException, ServletException {
request.setCharacterEncoding(Constants.ENCODE);
response.setContentType("application/json;charset=" + Constants.ENCODE);
try {
chain.doFilter(request, response);
} catch (IOException | ServletException ioe) {
@ -69,9 +70,9 @@ public class NacosWebFilter implements Filter {
throw ioe;
}
}
@Override
public void destroy() {
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.manager;
/**
@ -21,39 +22,40 @@ package com.alibaba.nacos.config.server.manager;
* @author huali
*/
public abstract class AbstractTask {
/**
* 一个任务两次处理的间隔单位是毫秒
*/
private long taskInterval;
/**
* 任务上次被处理的时间用毫秒表示
*/
private long lastProcessTime;
/**
* merge task
*
* @param task task
*/
public abstract void merge(AbstractTask task);
public void setTaskInterval(long interval) {
this.taskInterval = interval;
}
public long getTaskInterval() {
return this.taskInterval;
}
public void setLastProcessTime(long lastProcessTime) {
this.lastProcessTime = lastProcessTime;
}
public long getLastProcessTime() {
return this.lastProcessTime;
}
/**
* TaskManager 判断当前是否需要处理这个Task子类可以Override这个函数实现自己的逻辑
*
@ -62,5 +64,5 @@ public abstract class AbstractTask {
public boolean shouldProcess() {
return (System.currentTimeMillis() - this.lastProcessTime >= this.taskInterval);
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.manager;
import com.alibaba.nacos.config.server.constant.Constants;
@ -36,25 +37,24 @@ import java.util.concurrent.locks.ReentrantLock;
* @author huali
*/
public final class TaskManager implements TaskManagerMBean {
private static final Logger log = LogUtil.defaultLog;
private final ConcurrentHashMap<String, AbstractTask> tasks = new ConcurrentHashMap<String, AbstractTask>();
private final ConcurrentHashMap<String, TaskProcessor> taskProcessors =
new ConcurrentHashMap<String, TaskProcessor>();
private final ConcurrentHashMap<String, TaskProcessor> taskProcessors = new ConcurrentHashMap<String, TaskProcessor>();
private TaskProcessor defaultTaskProcessor;
Thread processingThread;
private final AtomicBoolean closed = new AtomicBoolean(true);
private String name;
class ProcessRunnable implements Runnable {
@Override
public void run() {
while (!TaskManager.this.closed.get()) {
@ -65,27 +65,27 @@ public final class TaskManager implements TaskManagerMBean {
LogUtil.dumpLog.error("execute dump process has error : {}", e);
}
}
}
}
ReentrantLock lock = new ReentrantLock();
Condition notEmpty = this.lock.newCondition();
public TaskManager() {
this(null);
}
public AbstractTask getTask(String type) {
return this.tasks.get(type);
}
public TaskProcessor getTaskProcessor(String type) {
return this.taskProcessors.get(type);
}
@SuppressWarnings("PMD.AvoidManuallyCreateThreadRule")
public TaskManager(String name) {
this.name = name;
@ -98,16 +98,16 @@ public final class TaskManager implements TaskManagerMBean {
this.closed.set(false);
this.processingThread.start();
}
public int size() {
return tasks.size();
}
public void close() {
this.closed.set(true);
this.processingThread.interrupt();
}
public void await() throws InterruptedException {
this.lock.lock();
try {
@ -118,7 +118,7 @@ public final class TaskManager implements TaskManagerMBean {
this.lock.unlock();
}
}
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
this.lock.lock();
boolean isawait = false;
@ -131,15 +131,15 @@ public final class TaskManager implements TaskManagerMBean {
this.lock.unlock();
}
}
public void addProcessor(String type, TaskProcessor taskProcessor) {
this.taskProcessors.put(type, taskProcessor);
}
public void removeProcessor(String type) {
this.taskProcessors.remove(type);
}
public void removeTask(String type) {
this.lock.lock();
try {
@ -149,7 +149,7 @@ public final class TaskManager implements TaskManagerMBean {
this.lock.unlock();
}
}
/**
* 将任务加入到任务Map中
*
@ -168,7 +168,7 @@ public final class TaskManager implements TaskManagerMBean {
this.lock.unlock();
}
}
/**
*
*/
@ -191,7 +191,7 @@ public final class TaskManager implements TaskManagerMBean {
} finally {
this.lock.unlock();
}
if (null != task) {
// 获取任务处理器
TaskProcessor processor = this.taskProcessors.get(entry.getKey());
@ -210,14 +210,14 @@ public final class TaskManager implements TaskManagerMBean {
if (!result) {
// 任务处理失败设置最后处理时间
task.setLastProcessTime(System.currentTimeMillis());
// 将任务重新加入到任务Map中
this.addTask(entry.getKey(), task);
}
}
}
}
if (tasks.isEmpty()) {
this.lock.lock();
try {
@ -227,11 +227,11 @@ public final class TaskManager implements TaskManagerMBean {
}
}
}
public boolean isEmpty() {
return tasks.isEmpty();
}
public TaskProcessor getDefaultTaskProcessor() {
this.lock.lock();
try {
@ -240,7 +240,7 @@ public final class TaskManager implements TaskManagerMBean {
this.lock.unlock();
}
}
public void setDefaultTaskProcessor(TaskProcessor defaultTaskProcessor) {
this.lock.lock();
try {
@ -249,7 +249,7 @@ public final class TaskManager implements TaskManagerMBean {
this.lock.unlock();
}
}
@Override
public String getTaskInfos() {
StringBuilder sb = new StringBuilder();
@ -263,10 +263,10 @@ public final class TaskManager implements TaskManagerMBean {
}
sb.append(Constants.NACOS_LINE_SEPARATOR);
}
return sb.toString();
}
public void init() {
try {
ObjectName oName = new ObjectName(this.name + ":type=" + TaskManager.class.getSimpleName());

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.manager;
/**
@ -22,12 +23,12 @@ package com.alibaba.nacos.config.server.manager;
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public interface TaskManagerMBean {
/**
* get task info
*
* @return info
*/
String getTaskInfos();
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.manager;
/**
@ -21,6 +22,7 @@ package com.alibaba.nacos.config.server.manager;
* @author Nacos
*/
public interface TaskProcessor {
/**
* process task
*

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -25,23 +26,25 @@ import java.util.List;
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class ACLInfo implements Serializable {
private static final long serialVersionUID = 1383026926036269457L;
private Boolean isOpen;
private List<String> ips;
public List<String> getIps() {
return ips;
}
public void setIps(List<String> ips) {
this.ips = ips;
}
public Boolean getIsOpen() {
return isOpen;
}
public void setIsOpen(Boolean isOpen) {
this.isOpen = isOpen;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import com.alibaba.nacos.config.server.constant.Constants;
@ -28,109 +29,118 @@ import java.util.Map;
* @author Nacos
*/
public class CacheItem {
public CacheItem(String groupKey) {
this.groupKey = DataIdGroupIdCache.getSingleton(groupKey);
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public long getLastModifiedTs() {
return lastModifiedTs;
}
public void setLastModifiedTs(long lastModifiedTs) {
this.lastModifiedTs = lastModifiedTs;
}
public boolean isBeta() {
return isBeta;
}
public void setBeta(boolean isBeta) {
this.isBeta = isBeta;
}
public String getMd54Beta() {
return md54Beta;
}
public void setMd54Beta(String md54Beta) {
this.md54Beta = md54Beta;
}
public List<String> getIps4Beta() {
return ips4Beta;
}
public void setIps4Beta(List<String> ips4Beta) {
this.ips4Beta = ips4Beta;
}
public long getLastModifiedTs4Beta() {
return lastModifiedTs4Beta;
}
public void setLastModifiedTs4Beta(long lastModifiedTs4Beta) {
this.lastModifiedTs4Beta = lastModifiedTs4Beta;
}
public SimpleReadWriteLock getRwLock() {
return rwLock;
}
public void setRwLock(SimpleReadWriteLock rwLock) {
this.rwLock = rwLock;
}
public String getGroupKey() {
return groupKey;
}
public Map<String, String> getTagMd5() {
return tagMd5;
}
public Map<String, Long> getTagLastModifiedTs() {
return tagLastModifiedTs;
}
public void setTagMd5(Map<String, String> tagMd5) {
this.tagMd5 = tagMd5;
}
public void setTagLastModifiedTs(Map<String, Long> tagLastModifiedTs) {
this.tagLastModifiedTs = tagLastModifiedTs;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
final String groupKey;
public volatile String md5 = Constants.NULL;
public volatile long lastModifiedTs;
/**
* use for beta
*/
public volatile boolean isBeta = false;
public volatile String md54Beta = Constants.NULL;
public volatile List<String> ips4Beta;
public volatile long lastModifiedTs4Beta;
public volatile Map<String, String> tagMd5;
public volatile Map<String, Long> tagLastModifiedTs;
public SimpleReadWriteLock rwLock = new SimpleReadWriteLock();
public String type;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,96 +24,107 @@ import java.io.Serializable;
* @author Nacos
*/
public class ConfigAdvanceInfo implements Serializable {
static final long serialVersionUID = -1L;
private long createTime;
private long modifyTime;
private String createUser;
private String createIp;
private String desc;
private String use;
private String effect;
private String type;
private String schema;
private String configTags;
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getModifyTime() {
return modifyTime;
}
public void setModifyTime(long modifyTime) {
this.modifyTime = modifyTime;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getCreateIp() {
return createIp;
}
public void setCreateIp(String createIp) {
this.createIp = createIp;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
public String getEffect() {
return effect;
}
public void setEffect(String effect) {
this.effect = effect;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getConfigTags() {
return configTags;
}
public void setConfigTags(String configTags) {
this.configTags = configTags;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -21,111 +22,120 @@ package com.alibaba.nacos.config.server.model;
* @author Nacos
*/
public class ConfigAllInfo extends ConfigInfo {
/**
*
*/
private static final long serialVersionUID = 296578467953931353L;
private long createTime;
private long modifyTime;
private String createUser;
private String createIp;
private String desc;
private String use;
private String effect;
private String type;
private String schema;
private String configTags;
public ConfigAllInfo() {
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getModifyTime() {
return modifyTime;
}
public void setModifyTime(long modifyTime) {
this.modifyTime = modifyTime;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getCreateIp() {
return createIp;
}
public void setCreateIp(String createIp) {
this.createIp = createIp;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
public String getEffect() {
return effect;
}
public void setEffect(String effect) {
this.effect = effect;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getConfigTags() {
return configTags;
}
public void setConfigTags(String configTags) {
this.configTags = configTags;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@ -27,138 +28,147 @@ import java.sql.Timestamp;
* @author Nacos
*/
public class ConfigHistoryInfo implements Serializable {
private static final long serialVersionUID = -7827521105376245603L;
/**
* id, nid, data_id, group_id, content, md5, gmt_create, gmt_modified, 配置创建时间配置变更时间 src_user, src_ip, (变更操作者)
* op_type变更操作类型
*/
@JsonSerialize(using = ToStringSerializer.class)
private long id;
/**
* 上次改动历史的id
*/
private long lastId = -1;
private String dataId;
private String group;
private String tenant;
private String appName;
private String md5;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getLastId() {
return lastId;
}
public void setLastId(long lastId) {
this.lastId = lastId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSrcIp() {
return srcIp;
}
public void setSrcIp(String srcIp) {
this.srcIp = srcIp;
}
public String getSrcUser() {
return srcUser;
}
public void setSrcUser(String srcUser) {
this.srcUser = srcUser;
}
public String getOpType() {
return opType;
}
public void setOpType(String opType) {
this.opType = opType;
}
public Timestamp getCreatedTime() {
return new Timestamp(createdTime.getTime());
}
public void setCreatedTime(Timestamp createdTime) {
this.createdTime = new Timestamp(createdTime.getTime());
}
public Timestamp getLastModifiedTime() {
return new Timestamp(lastModifiedTime.getTime());
}
public void setLastModifiedTime(Timestamp lastModifiedTime) {
this.lastModifiedTime = new Timestamp(lastModifiedTime.getTime());
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
private String content;
private String srcIp;
private String srcUser;
/**
* 操作类型, 包括插入更新删除
*/
private String opType;
private Timestamp createdTime;
private Timestamp lastModifiedTime;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -22,72 +23,73 @@ package com.alibaba.nacos.config.server.model;
* @date 2010-5-4
*/
public class ConfigInfo extends ConfigInfoBase {
static final long serialVersionUID = -1L;
private String tenant;
private String appName;
private String type;
public ConfigInfo() {
}
public ConfigInfo(String dataId, String group, String content) {
super(dataId, group, content);
}
public ConfigInfo(String dataId, String group, String appName, String content) {
super(dataId, group, content);
this.appName = appName;
}
public ConfigInfo(String dataId, String group, String tenant, String appName, String content) {
super(dataId, group, content);
this.tenant = tenant;
this.appName = appName;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public String toString() {
return "ConfigInfo{" + "id=" + getId() + ", dataId='" + getDataId() + '\'' + ", group='" + getGroup() + '\''
+ ", tenant='" + tenant + '\'' + ", appName='" + appName + '\'' + ", content='" + getContent() + '\''
+ ", md5='" + getMd5() + '\'' + '}';
+ ", tenant='" + tenant + '\'' + ", appName='" + appName + '\'' + ", content='" + getContent() + '\''
+ ", md5='" + getMd5() + '\'' + '}';
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -21,35 +22,35 @@ package com.alibaba.nacos.config.server.model;
* @author Nacos
*/
public class ConfigInfo4Beta extends ConfigInfo {
/**
*
*/
private static final long serialVersionUID = 296578467953931353L;
private String betaIps;
public ConfigInfo4Beta() {
}
public ConfigInfo4Beta(String dataId, String group, String appName, String content, String betaIps) {
super(dataId, group, appName, content);
this.betaIps = betaIps;
}
public String getBetaIps() {
return betaIps;
}
public void setBetaIps(String betaIps) {
this.betaIps = betaIps;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -21,38 +22,38 @@ package com.alibaba.nacos.config.server.model;
* @author Nacos
*/
public class ConfigInfo4Tag extends ConfigInfo {
/**
*
*/
private static final long serialVersionUID = 296578467953931353L;
private String tag;
public ConfigInfo4Tag() {
}
public ConfigInfo4Tag(String dataId, String group, String tag, String appName, String content) {
super(dataId, group, appName, content);
this.tag = tag;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@ -26,25 +27,31 @@ import java.io.Serializable;
* @author leiwen.zh
*/
public class ConfigInfoAggr implements Serializable {
private static final long serialVersionUID = -3845825581059306364L;
@JsonSerialize(using = ToStringSerializer.class)
private long id;
private String dataId;
private String group;
private String datumId;
private String tenant;
private String appName;
private String content;
public ConfigInfoAggr(String dataId, String group, String datumId, String content) {
this.dataId = dataId;
this.group = group;
this.datumId = datumId;
this.content = content;
}
public ConfigInfoAggr(String dataId, String group, String datumId, String appName, String content) {
this.dataId = dataId;
this.group = group;
@ -52,51 +59,51 @@ public class ConfigInfoAggr implements Serializable {
this.appName = appName;
this.content = content;
}
public ConfigInfoAggr() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDatumId() {
return datumId;
}
public void setDatumId(String datumId) {
this.datumId = datumId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public int hashCode() {
final int prime = 31;
@ -107,7 +114,7 @@ public class ConfigInfoAggr implements Serializable {
result = prime * result + ((group == null) ? 0 : group.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
@ -119,7 +126,7 @@ public class ConfigInfoAggr implements Serializable {
if (getClass() != obj.getClass()) {
return false;
}
ConfigInfoAggr other = (ConfigInfoAggr)obj;
ConfigInfoAggr other = (ConfigInfoAggr) obj;
if (content == null) {
if (other.content != null) {
return false;
@ -150,27 +157,27 @@ public class ConfigInfoAggr implements Serializable {
}
return true;
}
@Override
public String toString() {
return "ConfigInfoAggr [dataId=" + dataId + ", group=" + group + ", datumId=" + datumId + ", content="
+ content + "]";
return "ConfigInfoAggr [dataId=" + dataId + ", group=" + group + ", datumId=" + datumId + ", content=" + content
+ "]";
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import com.alibaba.nacos.common.utils.MD5Utils;
@ -29,22 +30,27 @@ import java.io.Serializable;
* @author Nacos
*/
public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase> {
static final long serialVersionUID = -1L;
/**
* 不能增加字段
*/
@JsonSerialize(using = ToStringSerializer.class)
private long id;
private String dataId;
private String group;
private String content;
private String md5;
public ConfigInfoBase() {
}
public ConfigInfoBase(String dataId, String group, String content) {
this.dataId = dataId;
this.group = group;
@ -53,51 +59,51 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
this.md5 = MD5Utils.md5Hex(this.content, Constants.ENCODE);
}
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public void dump(PrintWriter writer) {
writer.write(this.content);
}
@Override
public int compareTo(ConfigInfoBase o) {
if (o == null) {
@ -119,7 +125,7 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
}
}
}
if (this.group == null) {
if (o.getGroup() == null) {
return 0;
@ -136,7 +142,7 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
}
}
}
if (this.content == null) {
if (o.getContent() == null) {
return 0;
@ -155,7 +161,7 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
}
return 0;
}
@Override
public int hashCode() {
final int prime = 31;
@ -166,7 +172,7 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
result = prime * result + ((md5 == null) ? 0 : md5.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
@ -178,7 +184,7 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
if (getClass() != obj.getClass()) {
return false;
}
ConfigInfoBase other = (ConfigInfoBase)obj;
ConfigInfoBase other = (ConfigInfoBase) obj;
if (content == null) {
if (other.content != null) {
return false;
@ -209,11 +215,10 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
}
return true;
}
@Override
public String toString() {
return "ConfigInfoBase{" + "id=" + id + ", dataId='" + dataId + '\''
+ ", group='" + group + '\'' + ", content='" + content + '\''
+ ", md5='" + md5 + '\'' + '}';
return "ConfigInfoBase{" + "id=" + id + ", dataId='" + dataId + '\'' + ", group='" + group + '\''
+ ", content='" + content + '\'' + ", md5='" + md5 + '\'' + '}';
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -21,61 +22,61 @@ package com.alibaba.nacos.config.server.model;
* @author Nacos
*/
public class ConfigInfoBaseEx extends ConfigInfoBase {
private static final long serialVersionUID = -1L;
//不能增加字段
/**
* 批量查询时, 单条数据的状态码, 具体的状态码在Constants.java中
*/
private int status;
/**
* 批量查询时, 单条数据的信息
*/
private String message;
public ConfigInfoBaseEx() {
super();
}
public ConfigInfoBaseEx(String dataId, String group, String content) {
super(dataId, group, content);
}
public ConfigInfoBaseEx(String dataId, String group, String content,
int status, String message) {
public ConfigInfoBaseEx(String dataId, String group, String content, int status, String message) {
super(dataId, group, content);
this.status = status;
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return "ConfigInfoBaseEx [status=" + status + ", message=" + message
+ ", dataId=" + getDataId() + ", group()=" + getGroup()
+ ", content()=" + getContent() + "]";
return "ConfigInfoBaseEx [status=" + status + ", message=" + message + ", dataId=" + getDataId() + ", group()="
+ getGroup() + ", content()=" + getContent() + "]";
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);

View File

@ -20,26 +20,27 @@ package com.alibaba.nacos.config.server.model;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConfigInfoBetaWrapper extends ConfigInfo4Beta {
private static final long serialVersionUID = 4511997359365712505L;
private long lastModified;
public ConfigInfoBetaWrapper() {
}
public long getLastModified() {
return lastModified;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,38 +24,41 @@ import java.io.Serializable;
* @author leiwen.zh
*/
public class ConfigInfoChanged implements Serializable {
private static final long serialVersionUID = -1819539062100125171L;
private String dataId;
private String group;
private String tenant;
public ConfigInfoChanged(String dataId, String group, String tenant) {
this.dataId = dataId;
this.group = group;
this.setTenant(tenant);
}
public ConfigInfoChanged() {
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
@Override
public int hashCode() {
final int prime = 31;
@ -63,7 +67,7 @@ public class ConfigInfoChanged implements Serializable {
result = prime * result + ((group == null) ? 0 : group.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
@ -75,7 +79,7 @@ public class ConfigInfoChanged implements Serializable {
if (getClass() != obj.getClass()) {
return false;
}
ConfigInfoChanged other = (ConfigInfoChanged)obj;
ConfigInfoChanged other = (ConfigInfoChanged) obj;
if (dataId == null) {
if (other.dataId != null) {
return false;
@ -92,18 +96,18 @@ public class ConfigInfoChanged implements Serializable {
}
return true;
}
@Override
public String toString() {
return "ConfigInfoChanged [dataId=" + dataId + ", group=" + group + "]";
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -21,64 +22,63 @@ package com.alibaba.nacos.config.server.model;
* @author leiwen.zh
*/
public class ConfigInfoEx extends ConfigInfo {
private static final long serialVersionUID = -1L;
/**
* 批量查询时, 单条数据的状态码, 具体的状态码在Constants.java中
*/
private int status;
/**
* 批量查询时, 单条数据的信息
*/
private String message;
public ConfigInfoEx() {
super();
}
public ConfigInfoEx(String dataId, String group, String content) {
super(dataId, group, content);
}
public ConfigInfoEx(String dataId, String group, String content, int status, String message) {
super(dataId, group, content);
this.status = status;
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public String toString() {
return "ConfigInfoEx [status=" + status + ", message=" + message
+ ", dataId=" + getDataId() + ", group=" + getGroup()
+ ", appName=" + getAppName() + ", content=" + getContent()
+ "]";
return "ConfigInfoEx [status=" + status + ", message=" + message + ", dataId=" + getDataId() + ", group="
+ getGroup() + ", appName=" + getAppName() + ", content=" + getContent() + "]";
}
}

View File

@ -20,26 +20,27 @@ package com.alibaba.nacos.config.server.model;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConfigInfoTagWrapper extends ConfigInfo4Tag {
private static final long serialVersionUID = 4511997359365712505L;
private long lastModified;
public ConfigInfoTagWrapper() {
}
public long getLastModified() {
return lastModified;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -21,26 +22,27 @@ package com.alibaba.nacos.config.server.model;
* @author Nacos
*/
public class ConfigInfoWrapper extends ConfigInfo {
private static final long serialVersionUID = 4511997359365712505L;
private long lastModified;
public ConfigInfoWrapper() {
}
public long getLastModified() {
return lastModified;
}
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,47 +24,49 @@ import java.io.Serializable;
* @author Nacos
*/
public class ConfigKey implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1748953484511867580L;
private String appName;
private String dataId;
private String group;
public ConfigKey() {
}
public ConfigKey(String appName, String dataId, String group) {
this.appName = appName;
this.dataId = dataId;
this.group = group;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@ -26,57 +27,61 @@ import java.io.Serializable;
* @author Nacos
*/
public class GroupInfo implements Serializable {
static final long serialVersionUID = -1L;
@JsonSerialize(using = ToStringSerializer.class)
private long id;
private String address;
private String group;
private String dataId;
public GroupInfo() {
}
public GroupInfo(String address, String dataId, String group) {
super();
this.address = address;
this.group = group;
this.dataId = dataId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
@Override
public int hashCode() {
final int prime = 31;
@ -86,7 +91,7 @@ public class GroupInfo implements Serializable {
result = prime * result + ((group == null) ? 0 : group.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
@ -98,7 +103,7 @@ public class GroupInfo implements Serializable {
if (getClass() != obj.getClass()) {
return false;
}
GroupInfo other = (GroupInfo)obj;
GroupInfo other = (GroupInfo) obj;
if (address == null) {
if (other.address != null) {
return false;
@ -122,5 +127,5 @@ public class GroupInfo implements Serializable {
}
return true;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -24,30 +25,29 @@ import java.util.Map;
* @author Nacos
*/
public class GroupkeyListenserStatus implements Serializable {
/**
* 随机数
*/
private static final long serialVersionUID = -2094829323598842474L;
private int collectStatus;
private Map<String, String> lisentersGroupkeyStatus;
public int getCollectStatus() {
return collectStatus;
}
public void setCollectStatus(int collectStatus) {
this.collectStatus = collectStatus;
}
public Map<String, String> getLisentersGroupkeyStatus() {
return lisentersGroupkeyStatus;
}
public void setLisentersGroupkeyStatus(
Map<String, String> lisentersGroupkeyStatus) {
public void setLisentersGroupkeyStatus(Map<String, String> lisentersGroupkeyStatus) {
this.lisentersGroupkeyStatus = lisentersGroupkeyStatus;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,20 +24,29 @@ import java.io.Serializable;
* @author Nacos
*/
public class HistoryContext implements Serializable {
private static final long serialVersionUID = -8400843549603420766L;
public String serverId;
public String dataId;
public String group;
public String tenant;
private String appName;
public boolean success;
public int statusCode;
public String statusMsg;
public Page<ConfigHistoryInfo> configs;
public HistoryContext(String serverId, String dataId, String group, int statusCode, String statusMsg,
Page<ConfigHistoryInfo> configs) {
Page<ConfigHistoryInfo> configs) {
this.serverId = serverId;
this.dataId = dataId;
this.group = group;
@ -45,80 +55,80 @@ public class HistoryContext implements Serializable {
this.configs = configs;
this.success = 200 == statusCode;
}
public HistoryContext() {
}
public String getServerId() {
return serverId;
}
public void setServerId(String serverId) {
this.serverId = serverId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getStatusMsg() {
return statusMsg;
}
public void setStatusMsg(String statusMsg) {
this.statusMsg = statusMsg;
}
public Page<ConfigHistoryInfo> getConfigs() {
return configs;
}
public void setConfigs(Page<ConfigHistoryInfo> configs) {
this.configs = configs;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -27,52 +28,57 @@ import java.util.List;
* @date 2010-5-6
*/
public class Page<E> implements Serializable {
static final long serialVersionUID = -1L;
/**
* 总记录数
*/
private int totalCount;
/**
* 页数
*/
private int pageNumber;
/**
* 总页数
*/
private int pagesAvailable;
/**
* 该页内容
*/
private List<E> pageItems = new ArrayList<E>();
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public void setPagesAvailable(int pagesAvailable) {
this.pagesAvailable = pagesAvailable;
}
public void setPageItems(List<E> pageItems) {
this.pageItems = pageItems;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageNumber() {
return pageNumber;
}
public int getPagesAvailable() {
return pagesAvailable;
}
public List<E> getPageItems() {
return pageItems;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -24,69 +25,74 @@ import java.io.Serializable;
* @author Nacos
*/
public class RestPageResult<T> implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8048577763828650575L;
private int code;
private String message;
private int total;
private int pageSize;
private int currentPage;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
/**
@ -22,20 +23,20 @@ package com.alibaba.nacos.config.server.model;
* @date 2019/5/21 10:55
*/
public enum SameConfigPolicy {
/**
* @Description: abort import on duplicate
*/
ABORT,
/**
* @Description: skipping on duplicate
*/
SKIP,
/**
* @Description: overwrite on duplicate
*/
OVERWRITE
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -24,21 +25,20 @@ import java.util.Map;
* @author Nacos
*/
public class SampleResult implements Serializable {
/**
* 随机数
*/
private static final long serialVersionUID = 2587823382317389453L;
private Map<String, String> lisentersGroupkeyStatus;
public Map<String, String> getLisentersGroupkeyStatus() {
return lisentersGroupkeyStatus;
}
public void setLisentersGroupkeyStatus(
Map<String, String> lisentersGroupkeyStatus) {
public void setLisentersGroupkeyStatus(Map<String, String> lisentersGroupkeyStatus) {
this.lisentersGroupkeyStatus = lisentersGroupkeyStatus;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -24,52 +25,57 @@ import java.sql.Timestamp;
* @author Nacos
*/
public class SubInfo implements Serializable {
private static final long serialVersionUID = -3900485932969066685L;
private String appName;
private String dataId;
private String group;
private String localIp;
private Timestamp date;
public String getAppName() {
return appName;
}
public String getDataId() {
return dataId;
}
public String getGroup() {
return group;
}
public Timestamp getDate() {
return new Timestamp(date.getTime());
}
public void setAppName(String appName) {
this.appName = appName;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public void setGroup(String group) {
this.group = group;
}
public void setDate(Timestamp date) {
this.date = new Timestamp(date.getTime());
}
public String getLocalIp() {
return localIp;
}
public void setLocalIp(String localIp) {
this.localIp = localIp;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,61 +24,66 @@ import java.io.Serializable;
* @author Nacos
*/
public class SubscriberStatus implements Serializable {
private static final long serialVersionUID = 1065466896062351086L;
String groupKey;
String md5;
Long lastTime;
Boolean status;
String serverIp;
public SubscriberStatus() {
}
public SubscriberStatus(String groupKey, Boolean status, String md5, Long lastTime) {
this.groupKey = groupKey;
this.md5 = md5;
this.lastTime = lastTime;
this.status = status;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public Long getLastTime() {
return lastTime;
}
public void setLastTime(Long lastTime) {
this.lastTime = lastTime;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getGroupKey() {
return groupKey;
}
public void setGroupKey(String groupKey) {
this.groupKey = groupKey;
}
public String getServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,34 +24,37 @@ import java.io.Serializable;
* @author Nacos
*/
public class TenantInfo implements Serializable {
private static final long serialVersionUID = -1498218072016383809L;
private String tenantId;
private String tenantName;
private String tenantDesc;
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantName() {
return tenantName;
}
public void setTenantName(String tenantName) {
this.tenantName = tenantName;
}
public String getTenantDesc() {
return tenantDesc;
}
public void setTenantDesc(String tenantDesc) {
this.tenantDesc = tenantDesc;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model;
import java.io.Serializable;
@ -23,23 +24,25 @@ import java.io.Serializable;
* @author wfnuser
*/
public class User implements Serializable {
private static final long serialVersionUID = 3371769277802700069L;
private String username;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.app;
import com.alibaba.nacos.core.utils.InetUtils;
@ -23,89 +24,88 @@ import com.alibaba.nacos.core.utils.InetUtils;
* @author Nacos
*/
public class ApplicationInfo {
private static final long LOCK_EXPIRE_DURATION = 30 * 1000L;
private static final long RECENTLY_DURATION = 24 * 60 * 60 * 1000L;
private String appName;
private boolean isDynamicCollectDisabled = false;
private long lastSubscribeInfoCollectedTime = 0L;
private String subInfoCollectLockOwner = null;
private long subInfoCollectLockExpireTime = 0L;
public ApplicationInfo(String appName) {
this.appName = appName;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public boolean isDynamicCollectDisabled() {
return isDynamicCollectDisabled;
}
public void setDynamicCollectDisabled(boolean isDynamicCollectDisabled) {
this.isDynamicCollectDisabled = isDynamicCollectDisabled;
}
public long getLastSubscribeInfoCollectedTime() {
return lastSubscribeInfoCollectedTime;
}
public void setLastSubscribeInfoCollectedTime(
long lastSubscribeInfoCollectedTime) {
public void setLastSubscribeInfoCollectedTime(long lastSubscribeInfoCollectedTime) {
this.lastSubscribeInfoCollectedTime = lastSubscribeInfoCollectedTime;
}
public String getSubInfoCollectLockOwner() {
return subInfoCollectLockOwner;
}
public void setSubInfoCollectLockOwner(String subInfoCollectLockOwner) {
this.subInfoCollectLockOwner = subInfoCollectLockOwner;
}
public long getSubInfoCollectLockExpireTime() {
return subInfoCollectLockExpireTime;
}
public void setSubInfoCollectLockExpireTime(
long subInfoCollectLockExpireTime) {
public void setSubInfoCollectLockExpireTime(long subInfoCollectLockExpireTime) {
this.subInfoCollectLockExpireTime = subInfoCollectLockExpireTime;
}
public boolean isSubInfoRecentlyCollected() {
if (System.currentTimeMillis() - this.lastSubscribeInfoCollectedTime < RECENTLY_DURATION) {
return true;
}
return false;
}
public boolean canCurrentServerOwnTheLock() {
boolean currentOwnerIsMe = subInfoCollectLockOwner == null || InetUtils.getSelfIp()
.equals(subInfoCollectLockOwner);
boolean currentOwnerIsMe =
subInfoCollectLockOwner == null || InetUtils.getSelfIp().equals(subInfoCollectLockOwner);
if (currentOwnerIsMe) {
return true;
}
if (System.currentTimeMillis() - this.subInfoCollectLockExpireTime > LOCK_EXPIRE_DURATION) {
return true;
}
return false;
}
public String currentServer() {
return InetUtils.getSelfIp();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.app;
/**
@ -21,29 +22,30 @@ package com.alibaba.nacos.config.server.model.app;
* @author Nacos
*/
public class ApplicationPublishRecord {
private String appName;
private GroupKey configInfo;
public ApplicationPublishRecord(String appName, String dataId, String groupId) {
this.appName = appName;
this.configInfo = new GroupKey(dataId, groupId);
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public GroupKey getConfigInfo() {
return configInfo;
}
public void setConfigInfo(GroupKey configInfo) {
this.configInfo = configInfo;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.app;
import com.alibaba.nacos.config.server.utils.GroupKey2;
@ -23,46 +24,47 @@ import com.alibaba.nacos.config.server.utils.GroupKey2;
* @author Nacos
*/
public class GroupKey extends GroupKey2 {
private String dataId;
private String group;
public GroupKey(String dataId, String group) {
this.dataId = dataId;
this.group = group;
}
public GroupKey(String groupKeyString) {
String[] groupKeys = parseKey(groupKeyString);
this.dataId = groupKeys[0];
this.group = groupKeys[1];
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
@Override
public String toString() {
return dataId + "+" + group;
}
public String getGroupkeyString() {
return getKey(dataId, group);
}
//TODO : equal as we use Set
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.app;
/**
@ -21,141 +22,142 @@ package com.alibaba.nacos.config.server.model.app;
* @author Nacos
*/
public class MonitorInfo {
/**
* 可使用内存.
*/
private long totalMemory;
/**
* 剩余内存.
*/
private long freeMemory;
/**
* 最大可使用内存.
*/
private volatile long maxMemory;
/**
* cpu使用率.
*/
private double cpuRatio;
/**
* 系统负载.
*/
private double load;
/**
* ygc次数
*/
private int ygc;
/**
* ygc时间
*/
private double ygct;
/**
* fgc次数
*/
private int fgc;
/**
* fgc时间
*/
private double fgct;
/**
* gc时间
*/
private double gct;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(int cpuRatio) {
this.cpuRatio = cpuRatio;
}
public double getLoad() {
return load;
}
public void setLoad(int load) {
this.load = load;
}
public int getYgc() {
return ygc;
}
public void setYgc(int ygc) {
this.ygc = ygc;
}
public double getYgct() {
return ygct;
}
public void setYgct(int ygct) {
this.ygct = ygct;
}
public int getFgc() {
return fgc;
}
public void setFgc(int fgc) {
this.fgc = fgc;
}
public double getFgct() {
return fgct;
}
public void setFgct(int fgct) {
this.fgct = fgct;
}
public double getGct() {
return gct;
}
public void setGct(int gct) {
this.gct = gct;
}
@Override
public String toString() {
return "MonitorInfo{" +
"totalMemory=" + totalMemory +
", freeMemory=" + freeMemory +
", maxMemory=" + maxMemory +
", cpuRatio=" + cpuRatio +
", load=" + load +
", ygc=" + ygc +
", ygct=" + ygct +
", fgc=" + fgc +
", fgct=" + fgct +
", gct=" + gct +
'}';
return "MonitorInfo{" + "totalMemory=" + totalMemory + ", freeMemory=" + freeMemory + ", maxMemory=" + maxMemory
+ ", cpuRatio=" + cpuRatio + ", load=" + load + ", ygc=" + ygc + ", ygct=" + ygct + ", fgc=" + fgc
+ ", fgct=" + fgct + ", gct=" + gct + '}';
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.capacity;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@ -28,90 +29,97 @@ import java.sql.Timestamp;
* @date 2018/3/13
*/
public class Capacity implements Serializable {
private static final long serialVersionUID = 77343194329627468L;
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private Integer quota;
private Integer usage;
private Integer maxSize;
private Integer maxAggrCount;
private Integer maxAggrSize;
private Timestamp gmtCreate;
private Timestamp gmtModified;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getQuota() {
return quota;
}
public void setQuota(Integer quota) {
this.quota = quota;
}
public Integer getUsage() {
return usage;
}
public void setUsage(Integer usage) {
this.usage = usage;
}
public Integer getMaxSize() {
return maxSize;
}
public void setMaxSize(Integer maxSize) {
this.maxSize = maxSize;
}
public Integer getMaxAggrCount() {
return maxAggrCount;
}
public void setMaxAggrCount(Integer maxAggrCount) {
this.maxAggrCount = maxAggrCount;
}
public Integer getMaxAggrSize() {
return maxAggrSize;
}
public void setMaxAggrSize(Integer maxAggrSize) {
this.maxAggrSize = maxAggrSize;
}
public Timestamp getGmtCreate() {
if (gmtCreate == null) {
return null;
}
return new Timestamp(gmtCreate.getTime());
}
public void setGmtCreate(Timestamp gmtCreate) {
if (gmtCreate == null) {
this.gmtCreate = null;
} else {
this.gmtCreate = new Timestamp(gmtCreate.getTime());
}
}
public Timestamp getGmtModified() {
if (gmtModified == null) {
return null;
}
return new Timestamp(gmtModified.getTime());
}
public void setGmtModified(Timestamp gmtModified) {
if (gmtModified == null) {
this.gmtModified = null;

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.capacity;
/**
@ -22,14 +23,15 @@ package com.alibaba.nacos.config.server.model.capacity;
* @date 2018/3/13
*/
public class GroupCapacity extends Capacity {
private static final long serialVersionUID = 5888791286289014878L;
private String group;
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.capacity;
/**
@ -22,14 +23,15 @@ package com.alibaba.nacos.config.server.model.capacity;
* @date 2018/3/13
*/
public class TenantCapacity extends Capacity {
private static final long serialVersionUID = -1238179608935781384L;
private String tenant;
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.event;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
@ -24,18 +25,23 @@ import org.apache.commons.lang3.StringUtils;
* @author Nacos
*/
public class ConfigDataChangeEvent implements Event {
final public boolean isBeta;
final public String dataId;
final public String group;
final public String tenant;
final public String tag;
final public long lastModifiedTs;
public ConfigDataChangeEvent(String dataId, String group, long gmtModified) {
this(false, dataId, group, gmtModified);
}
public ConfigDataChangeEvent(boolean isBeta, String dataId, String group, String tenant, long gmtModified) {
if (null == dataId || null == group) {
throw new IllegalArgumentException("dataId is null or group is null");
@ -47,13 +53,13 @@ public class ConfigDataChangeEvent implements Event {
this.tag = null;
this.lastModifiedTs = gmtModified;
}
public ConfigDataChangeEvent(boolean isBeta, String dataId, String group, long gmtModified) {
this(isBeta, dataId, group, StringUtils.EMPTY, gmtModified);
}
public ConfigDataChangeEvent(boolean isBeta, String dataId, String group, String tenant, String tag,
long gmtModified) {
long gmtModified) {
if (null == dataId || null == group) {
throw new IllegalArgumentException("dataId is null or group is null");
}
@ -64,5 +70,5 @@ public class ConfigDataChangeEvent implements Event {
this.tag = tag;
this.lastModifiedTs = gmtModified;
}
}

View File

@ -22,198 +22,219 @@ import com.alibaba.nacos.core.notify.Event;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConfigDumpEvent implements Event {
private static final long serialVersionUID = -8776888606458370294L;
private boolean remove;
private String namespaceId;
private String dataId;
private String group;
private boolean isBeta;
private String tag;
private String content;
private String betaIps;
private String handleIp;
private String type;
private long lastModifiedTs;
public boolean isRemove() {
return remove;
}
public void setRemove(boolean remove) {
this.remove = remove;
}
public String getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(String namespaceId) {
this.namespaceId = namespaceId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public boolean isBeta() {
return isBeta;
}
public void setBeta(boolean beta) {
isBeta = beta;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getBetaIps() {
return betaIps;
}
public void setBetaIps(String betaIps) {
this.betaIps = betaIps;
}
public String getHandleIp() {
return handleIp;
}
public void setHandleIp(String handleIp) {
this.handleIp = handleIp;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public long getLastModifiedTs() {
return lastModifiedTs;
}
public void setLastModifiedTs(long lastModifiedTs) {
this.lastModifiedTs = lastModifiedTs;
}
public static ConfigDumpEventBuilder builder() {
return new ConfigDumpEventBuilder();
}
public static final class ConfigDumpEventBuilder {
private boolean remove;
private String namespaceId;
private String dataId;
private String group;
private boolean isBeta;
private String tag;
private String content;
private String betaIps;
private String handleIp;
private String type;
private long lastModifiedTs;
private ConfigDumpEventBuilder() {
}
public ConfigDumpEventBuilder remove(boolean remove) {
this.remove = remove;
return this;
}
public ConfigDumpEventBuilder namespaceId(String namespaceId) {
this.namespaceId = namespaceId;
return this;
}
public ConfigDumpEventBuilder dataId(String dataId) {
this.dataId = dataId;
return this;
}
public ConfigDumpEventBuilder group(String group) {
this.group = group;
return this;
}
public ConfigDumpEventBuilder isBeta(boolean isBeta) {
this.isBeta = isBeta;
return this;
}
public ConfigDumpEventBuilder tag(String tag) {
this.tag = tag;
return this;
}
public ConfigDumpEventBuilder content(String content) {
this.content = content;
return this;
}
public ConfigDumpEventBuilder betaIps(String betaIps) {
this.betaIps = betaIps;
return this;
}
public ConfigDumpEventBuilder handleIp(String handleIp) {
this.handleIp = handleIp;
return this;
}
public ConfigDumpEventBuilder type(String type) {
this.type = type;
return this;
}
public ConfigDumpEventBuilder lastModifiedTs(long lastModifiedTs) {
this.lastModifiedTs = lastModifiedTs;
return this;
}
public ConfigDumpEvent build() {
ConfigDumpEvent configDumpEvent = new ConfigDumpEvent();
configDumpEvent.setRemove(remove);
configDumpEvent.setNamespaceId(namespaceId);
configDumpEvent.setDataId(dataId);
configDumpEvent.setGroup(group);
configDumpEvent.setTag(tag);
configDumpEvent.setContent(content);
configDumpEvent.setBetaIps(betaIps);
configDumpEvent.setHandleIp(handleIp);
configDumpEvent.setType(type);
configDumpEvent.setLastModifiedTs(lastModifiedTs);
configDumpEvent.isBeta = this.isBeta;
return configDumpEvent;
}
}
private static final long serialVersionUID = -8776888606458370294L;
private boolean remove;
private String namespaceId;
private String dataId;
private String group;
private boolean isBeta;
private String tag;
private String content;
private String betaIps;
private String handleIp;
private String type;
private long lastModifiedTs;
public boolean isRemove() {
return remove;
}
public void setRemove(boolean remove) {
this.remove = remove;
}
public String getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(String namespaceId) {
this.namespaceId = namespaceId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public boolean isBeta() {
return isBeta;
}
public void setBeta(boolean beta) {
isBeta = beta;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getBetaIps() {
return betaIps;
}
public void setBetaIps(String betaIps) {
this.betaIps = betaIps;
}
public String getHandleIp() {
return handleIp;
}
public void setHandleIp(String handleIp) {
this.handleIp = handleIp;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public long getLastModifiedTs() {
return lastModifiedTs;
}
public void setLastModifiedTs(long lastModifiedTs) {
this.lastModifiedTs = lastModifiedTs;
}
public static ConfigDumpEventBuilder builder() {
return new ConfigDumpEventBuilder();
}
public static final class ConfigDumpEventBuilder {
private boolean remove;
private String namespaceId;
private String dataId;
private String group;
private boolean isBeta;
private String tag;
private String content;
private String betaIps;
private String handleIp;
private String type;
private long lastModifiedTs;
private ConfigDumpEventBuilder() {
}
public ConfigDumpEventBuilder remove(boolean remove) {
this.remove = remove;
return this;
}
public ConfigDumpEventBuilder namespaceId(String namespaceId) {
this.namespaceId = namespaceId;
return this;
}
public ConfigDumpEventBuilder dataId(String dataId) {
this.dataId = dataId;
return this;
}
public ConfigDumpEventBuilder group(String group) {
this.group = group;
return this;
}
public ConfigDumpEventBuilder isBeta(boolean isBeta) {
this.isBeta = isBeta;
return this;
}
public ConfigDumpEventBuilder tag(String tag) {
this.tag = tag;
return this;
}
public ConfigDumpEventBuilder content(String content) {
this.content = content;
return this;
}
public ConfigDumpEventBuilder betaIps(String betaIps) {
this.betaIps = betaIps;
return this;
}
public ConfigDumpEventBuilder handleIp(String handleIp) {
this.handleIp = handleIp;
return this;
}
public ConfigDumpEventBuilder type(String type) {
this.type = type;
return this;
}
public ConfigDumpEventBuilder lastModifiedTs(long lastModifiedTs) {
this.lastModifiedTs = lastModifiedTs;
return this;
}
public ConfigDumpEvent build() {
ConfigDumpEvent configDumpEvent = new ConfigDumpEvent();
configDumpEvent.setRemove(remove);
configDumpEvent.setNamespaceId(namespaceId);
configDumpEvent.setDataId(dataId);
configDumpEvent.setGroup(group);
configDumpEvent.setTag(tag);
configDumpEvent.setContent(content);
configDumpEvent.setBetaIps(betaIps);
configDumpEvent.setHandleIp(handleIp);
configDumpEvent.setType(type);
configDumpEvent.setLastModifiedTs(lastModifiedTs);
configDumpEvent.isBeta = this.isBeta;
return configDumpEvent;
}
}
}

View File

@ -22,9 +22,9 @@ import com.alibaba.nacos.core.notify.SlowEvent;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class DerbyLoadEvent implements SlowEvent {
public static final DerbyLoadEvent INSTANCE = new DerbyLoadEvent();
private static final long serialVersionUID = 875401667921565121L;
public static final DerbyLoadEvent INSTANCE = new DerbyLoadEvent();
private static final long serialVersionUID = 875401667921565121L;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.event;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
@ -25,25 +26,29 @@ import java.util.List;
* @author Nacos
*/
public class LocalDataChangeEvent implements Event {
final public String groupKey;
final public boolean isBeta;
final public List<String> betaIps;
final public String tag;
public LocalDataChangeEvent(String groupKey) {
this.groupKey = groupKey;
this.isBeta = false;
this.betaIps = null;
this.tag = null;
}
public LocalDataChangeEvent(String groupKey, boolean isBeta, List<String> betaIps) {
this.groupKey = groupKey;
this.isBeta = isBeta;
this.betaIps = betaIps;
this.tag = null;
}
public LocalDataChangeEvent(String groupKey, boolean isBeta, List<String> betaIps, String tag) {
this.groupKey = groupKey;
this.isBeta = isBeta;

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.model.event;
import com.alibaba.nacos.core.notify.SlowEvent;
@ -22,19 +23,19 @@ import com.alibaba.nacos.core.notify.SlowEvent;
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class RaftDBErrorEvent implements SlowEvent {
private static final long serialVersionUID = 101591819161802336L;
private Throwable ex;
public RaftDBErrorEvent() {
}
public RaftDBErrorEvent(Throwable ex) {
this.ex = ex;
}
public Throwable getEx() {
return ex;
}
private static final long serialVersionUID = 101591819161802336L;
private Throwable ex;
public RaftDBErrorEvent() {
}
public RaftDBErrorEvent(Throwable ex) {
this.ex = ex;
}
public Throwable getEx() {
return ex;
}
}

View File

@ -20,7 +20,6 @@ import com.alibaba.nacos.common.JustForTest;
import com.alibaba.nacos.core.notify.Event;
/**
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.monitor;
import com.alibaba.nacos.config.server.service.ClientTrackService;
@ -35,23 +36,22 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
*/
@Service
public class MemoryMonitor {
@Autowired
public MemoryMonitor(AsyncNotifyService notifySingleService) {
ConfigExecutor.scheduleWithFixedDelay(new PrintMemoryTask(), DELAY_SECONDS,
DELAY_SECONDS, TimeUnit.SECONDS);
ConfigExecutor.scheduleWithFixedDelay(new PrintGetConfigResponeTask(), DELAY_SECONDS,
DELAY_SECONDS, TimeUnit.SECONDS);
ConfigExecutor.scheduleWithFixedDelay(new PrintMemoryTask(), DELAY_SECONDS, DELAY_SECONDS, TimeUnit.SECONDS);
ConfigExecutor.scheduleWithFixedDelay(new PrintGetConfigResponeTask(), DELAY_SECONDS, DELAY_SECONDS,
TimeUnit.SECONDS);
ConfigExecutor.scheduleWithFixedDelay(new NotifyTaskQueueMonitorTask(notifySingleService), DELAY_SECONDS,
DELAY_SECONDS, TimeUnit.SECONDS);
DELAY_SECONDS, TimeUnit.SECONDS);
}
private static final long DELAY_SECONDS = 10;
@Scheduled(cron = "0 0 0 * * ?")
public void clear() {
MetricsMonitor.getConfigMonitor().set(0);
@ -60,6 +60,7 @@ public class MemoryMonitor {
}
class PrintGetConfigResponeTask implements Runnable {
@Override
public void run() {
memoryLog.info(ResponseMonitor.getStringForPrint());
@ -67,28 +68,29 @@ class PrintGetConfigResponeTask implements Runnable {
}
class PrintMemoryTask implements Runnable {
@Override
public void run() {
int groupCount = ConfigCacheService.groupCount();
int subClientCount = ClientTrackService.subscribeClientCount();
long subCount = ClientTrackService.subscriberCount();
memoryLog.info("groupCount={}, subscriberClientCount={}, subscriberCount={}", groupCount, subClientCount,
subCount);
subCount);
MetricsMonitor.getConfigCountMonitor().set(groupCount);
}
}
class NotifyTaskQueueMonitorTask implements Runnable {
final private AsyncNotifyService notifySingleService;
NotifyTaskQueueMonitorTask(AsyncNotifyService notifySingleService) {
this.notifySingleService = notifySingleService;
}
@Override
public void run() {
int size = ((ScheduledThreadPoolExecutor)notifySingleService.getExecutor()).getQueue().size();
int size = ((ScheduledThreadPoolExecutor) notifySingleService.getExecutor()).getQueue().size();
memoryLog.info("toNotifyTaskSize={}", size);
MetricsMonitor.getNotifyTaskMonitor().set(size);
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.monitor;
import io.micrometer.core.instrument.*;
@ -27,98 +28,98 @@ import java.util.concurrent.atomic.AtomicInteger;
* @author Nacos
*/
public class MetricsMonitor {
private static AtomicInteger getConfig = new AtomicInteger();
private static AtomicInteger publish = new AtomicInteger();
private static AtomicInteger longPolling = new AtomicInteger();
private static AtomicInteger configCount = new AtomicInteger();
private static AtomicInteger notifyTask = new AtomicInteger();
private static AtomicInteger dumpTask = new AtomicInteger();
static {
List<Tag> tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "getConfig"));
Metrics.gauge("nacos_monitor", tags, getConfig);
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "publish"));
Metrics.gauge("nacos_monitor", tags, publish);
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "longPolling"));
Metrics.gauge("nacos_monitor", tags, longPolling);
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "configCount"));
Metrics.gauge("nacos_monitor", tags, configCount);
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "notifyTask"));
Metrics.gauge("nacos_monitor", tags, notifyTask);
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "dumpTask"));
Metrics.gauge("nacos_monitor", tags, dumpTask);
}
public static AtomicInteger getConfigMonitor() {
return getConfig;
}
public static AtomicInteger getPublishMonitor() {
return publish;
}
public static AtomicInteger getLongPollingMonitor() {
return longPolling;
}
public static AtomicInteger getConfigCountMonitor() {
return configCount;
}
public static AtomicInteger getNotifyTaskMonitor() {
return notifyTask;
}
public static AtomicInteger getDumpTaskMonitor() {
return dumpTask;
}
public static Timer getNotifyRtTimer() {
return Metrics.timer("nacos_timer",
"module", "config", "name", "notifyRt");
return Metrics.timer("nacos_timer", "module", "config", "name", "notifyRt");
}
public static Counter getIllegalArgumentException() {
return Metrics.counter("nacos_exception",
"module", "config", "name", "illegalArgument");
return Metrics.counter("nacos_exception", "module", "config", "name", "illegalArgument");
}
public static Counter getNacosException() {
return Metrics.counter("nacos_exception",
"module", "config", "name", "nacos");
return Metrics.counter("nacos_exception", "module", "config", "name", "nacos");
}
public static Counter getDbException() {
return Metrics.counter("nacos_exception",
"module", "config", "name", "db");
return Metrics.counter("nacos_exception", "module", "config", "name", "db");
}
public static Counter getConfigNotifyException() {
return Metrics.counter("nacos_exception",
"module", "config", "name", "configNotify");
return Metrics.counter("nacos_exception", "module", "config", "name", "configNotify");
}
public static Counter getUnhealthException() {
return Metrics.counter("nacos_exception",
"module", "config", "name", "unhealth");
return Metrics.counter("nacos_exception", "module", "config", "name", "unhealth");
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.monitor;
import java.text.DecimalFormat;
@ -24,26 +25,35 @@ import java.util.concurrent.atomic.AtomicLong;
* @author Nacos
*/
public class ResponseMonitor {
private static AtomicLong[] getConfigCountDetail = new AtomicLong[8];
private static AtomicLong getConfigCount = new AtomicLong();
private static final int MS_50 = 50;
private static final int MS_100 = 100;
private static final int MS_200 = 200;
private static final int MS_500 = 500;
private static final int MS_1000 = 1000;
private static final int MS_2000 = 2000;
private static final int MS_3000 = 3000;
static {
refresh();
}
public static void refresh() {
for (int i = 0; i < getConfigCountDetail.length; i++) {
getConfigCountDetail[i] = new AtomicLong();
}
}
public static void addConfigTime(long time) {
getConfigCount.incrementAndGet();
if (time < MS_50) {
@ -64,24 +74,24 @@ public class ResponseMonitor {
getConfigCountDetail[7].incrementAndGet();
}
}
public static String getStringForPrint() {
DecimalFormat df = new DecimalFormat("##.0");
StringBuilder s = new StringBuilder("getConfig monitor:\r\n");
s.append("0-50ms:" + df.format(getConfigCountDetail[0].getAndSet(0) * 100 / getConfigCount.get())).append(
"%\r\n");
s.append("100-200ms:" + df.format(getConfigCountDetail[2].getAndSet(0) * 100 / getConfigCount.get())).append(
"%\r\n");
s.append("200-500ms:" + df.format(getConfigCountDetail[3].getAndSet(0) * 100 / getConfigCount.get())).append(
"%\r\n");
s.append("500-1000ms:" + df.format(getConfigCountDetail[4].getAndSet(0) * 100 / getConfigCount.get())).append(
"%\r\n");
s.append("1000-2000ms:" + df.format(getConfigCountDetail[5].getAndSet(0) * 100 / getConfigCount.get())).append(
"%\r\n");
s.append("2000-3000ms:" + df.format(getConfigCountDetail[6].getAndSet(0) * 100 / getConfigCount.get())).append(
"%\r\n");
s.append("0-50ms:" + df.format(getConfigCountDetail[0].getAndSet(0) * 100 / getConfigCount.get()))
.append("%\r\n");
s.append("100-200ms:" + df.format(getConfigCountDetail[2].getAndSet(0) * 100 / getConfigCount.get()))
.append("%\r\n");
s.append("200-500ms:" + df.format(getConfigCountDetail[3].getAndSet(0) * 100 / getConfigCount.get()))
.append("%\r\n");
s.append("500-1000ms:" + df.format(getConfigCountDetail[4].getAndSet(0) * 100 / getConfigCount.get()))
.append("%\r\n");
s.append("1000-2000ms:" + df.format(getConfigCountDetail[5].getAndSet(0) * 100 / getConfigCount.get()))
.append("%\r\n");
s.append("2000-3000ms:" + df.format(getConfigCountDetail[6].getAndSet(0) * 100 / getConfigCount.get()))
.append("%\r\n");
s.append("3000以上ms:" + df.format(getConfigCountDetail[7].getAndSet(0) * 100 / getConfigCount.getAndSet(0)))
.append("%\r\n");
.append("%\r\n");
return s.toString();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.result;
import com.alibaba.nacos.common.model.RestResult;
@ -27,28 +28,28 @@ import org.springframework.util.Assert;
* @date 2019/6/28 14:47
*/
public class ResultBuilder {
public static <T extends Object> RestResult<T> buildResult(IResultCode resultCode, T resultData){
public static <T extends Object> RestResult<T> buildResult(IResultCode resultCode, T resultData) {
Assert.notNull(resultCode, "the resultCode can not be null");
RestResult<T> rr = new RestResult<>(resultCode.getCode(), resultCode.getCodeMsg(), resultData);
return rr;
}
public static <T extends Object> RestResult<T> buildSuccessResult(T resultData){
public static <T extends Object> RestResult<T> buildSuccessResult(T resultData) {
return buildResult(ResultCodeEnum.SUCCESS, resultData);
}
public static <T extends Object> RestResult<T> buildSuccessResult(String successMsg, T resultData){
public static <T extends Object> RestResult<T> buildSuccessResult(String successMsg, T resultData) {
RestResult<T> rr = buildResult(ResultCodeEnum.SUCCESS, resultData);
rr.setMessage(successMsg);
return rr;
}
public static <T extends Object> RestResult<T> buildSuccessResult(){
public static <T extends Object> RestResult<T> buildSuccessResult() {
return buildResult(ResultCodeEnum.SUCCESS, null);
}
public static <T extends Object> RestResult<T> buildSuccessResult(String successMsg){
public static <T extends Object> RestResult<T> buildSuccessResult(String successMsg) {
RestResult<T> rr = buildResult(ResultCodeEnum.SUCCESS, null);
rr.setMessage(successMsg);
return rr;

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.result.code;
import com.alibaba.nacos.config.server.result.core.IResultCode;
@ -24,45 +25,44 @@ import com.alibaba.nacos.config.server.result.core.IResultCode;
* @date 2019/6/28 14:43
*/
public enum ResultCodeEnum implements IResultCode {
/**
* common code
**/
SUCCESS(200, "处理成功"),
ERROR(500, "服务器内部错误"),
/**
* config use 100001 ~ 100999
**/
NAMESPACE_NOT_EXIST(100001, "目标 namespace 不存在"),
METADATA_ILLEGAL(100002, "导入的元数据非法"),
DATA_VALIDATION_FAILED(100003, "未读取到合法数据"),
PARSING_DATA_FAILED(100004, "解析数据失败"),
DATA_EMPTY(100005, "导入的文件数据为空"),
NO_SELECTED_CONFIG(100006, "没有选择任何配制"),
;
private int code;
private String msg;
ResultCodeEnum(int code, String codeMsg) {
this.code = code;
this.msg = codeMsg;
}
@Override
public int getCode() {
return code;
}
@Override
public String getCodeMsg() {
return msg;

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.result.core;
/**
@ -22,24 +23,24 @@ package com.alibaba.nacos.config.server.result.core;
* @date 2019/6/28 14:44
*/
public interface IResultCode {
/**
* get the result code
*
* @return java.lang.String
* @author klw
* @Date 2019/6/28 14:56
* @Param []
* @return java.lang.String
*/
int getCode();
/**
* get the result code's message
*
* @return java.lang.String
* @author klw
* @Date 2019/6/28 14:56
* @Param []
* @return java.lang.String
*/
String getCodeMsg();
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.common.utils.IoUtils;
@ -37,17 +38,17 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
*/
@Service
public class AggrWhitelist {
public static final String AGGRIDS_METADATA = "com.alibaba.nacos.metadata.aggrIDs";
/**
* 判断指定的dataId是否在聚合dataId白名单
*/
public static boolean isAggrDataId(String dataId) {
public static boolean isAggrDataId(String dataId) {
if (null == dataId) {
throw new IllegalArgumentException("dataId is null");
}
for (Pattern pattern : AGGR_DATAID_WHITELIST.get()) {
if (pattern.matcher(dataId).matches()) {
return true;
@ -55,17 +56,17 @@ public class AggrWhitelist {
}
return false;
}
/**
* 传入内容重新加载聚合白名单
*/
public static void load(String content) {
public static void load(String content) {
if (StringUtils.isBlank(content)) {
fatalLog.error("aggr dataId whitelist is blank.");
return;
}
defaultLog.warn("[aggr-dataIds] {}", content);
try {
List<String> lines = IoUtils.readLines(new StringReader(content));
compile(lines);
@ -73,10 +74,10 @@ public class AggrWhitelist {
defaultLog.error("failed to load aggr whitelist, " + ioe.toString(), ioe);
}
}
static void compile(List<String> whitelist) {
List<Pattern> list = new ArrayList<Pattern>(whitelist.size());
for (String line : whitelist) {
if (!StringUtils.isBlank(line)) {
String regex = RegexParser.regexFormat(line.trim());
@ -85,13 +86,13 @@ public class AggrWhitelist {
}
AGGR_DATAID_WHITELIST.set(list);
}
public static List<Pattern> getWhiteList() {
return AGGR_DATAID_WHITELIST.get();
}
// =======================
static final AtomicReference<List<Pattern>> AGGR_DATAID_WHITELIST = new AtomicReference<List<Pattern>>(
new ArrayList<Pattern>());
new ArrayList<Pattern>());
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.model.ACLInfo;
@ -33,7 +34,7 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
*/
@Service
public class ClientIpWhiteList {
/**
* 判断指定的ip在白名单中
*/
@ -47,7 +48,7 @@ public class ClientIpWhiteList {
}
return false;
}
/**
* whether start client ip whitelist
*
@ -56,7 +57,7 @@ public class ClientIpWhiteList {
static public boolean isEnableWhitelist() {
return isOpen;
}
/**
* 传入内容重新加载客户端ip白名单
*/
@ -69,20 +70,20 @@ public class ClientIpWhiteList {
}
defaultLog.warn("[clientIpWhiteList] {}", content);
try {
ACLInfo acl = (ACLInfo)JSONUtils.deserializeObject(content, ACLInfo.class);
ACLInfo acl = (ACLInfo) JSONUtils.deserializeObject(content, ACLInfo.class);
isOpen = acl.getIsOpen();
CLIENT_IP_WHITELIST.set(acl.getIps());
} catch (Exception ioe) {
defaultLog.error(
"failed to load clientIpWhiteList, " + ioe.toString(), ioe);
defaultLog.error("failed to load clientIpWhiteList, " + ioe.toString(), ioe);
}
}
// =======================
static public final String CLIENT_IP_WHITELIST_METADATA = "com.alibaba.nacos.metadata.clientIpWhitelist";
static final AtomicReference<List<String>> CLIENT_IP_WHITELIST = new AtomicReference<List<String>>(
new ArrayList<String>());
new ArrayList<String>());
static Boolean isOpen = false;
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.model.SubscriberStatus;
@ -28,6 +29,7 @@ import java.util.concurrent.ConcurrentMap;
* @author Nacos
*/
public class ClientTrackService {
/**
* 跟踪客户端md5.
*/
@ -36,29 +38,29 @@ public class ClientTrackService {
record.lastTime = System.currentTimeMillis();
record.groupKey2md5Map.putAll(clientMd5Map);
}
static public void trackClientMd5(String ip, Map<String, String> clientMd5Map,
Map<String, Long> clientlastPollingTSMap) {
Map<String, Long> clientlastPollingTSMap) {
ClientRecord record = getClientRecord(ip);
record.lastTime = System.currentTimeMillis();
record.groupKey2md5Map.putAll(clientMd5Map);
record.groupKey2pollingTsMap.putAll(clientlastPollingTSMap);
}
static public void trackClientMd5(String ip, String groupKey, String clientMd5) {
ClientRecord record = getClientRecord(ip);
record.lastTime = System.currentTimeMillis();
record.groupKey2md5Map.put(groupKey, clientMd5);
record.groupKey2pollingTsMap.put(groupKey, record.lastTime);
}
/**
* 返回订阅者客户端个数
*/
static public int subscribeClientCount() {
return clientRecords.size();
}
/**
* 返回所有订阅者个数
*/
@ -69,49 +71,49 @@ public class ClientTrackService {
}
return count;
}
/**
* groupkey -> SubscriberStatus
*/
static public Map<String, SubscriberStatus> listSubStatus(String ip) {
Map<String, SubscriberStatus> status = new HashMap<String, SubscriberStatus>(100);
ClientRecord record = getClientRecord(ip);
if (record == null) {
return status;
}
for (Map.Entry<String, String> entry : record.groupKey2md5Map.entrySet()) {
String groupKey = entry.getKey();
String clientMd5 = entry.getValue();
long lastPollingTs = record.groupKey2pollingTsMap.get(groupKey);
boolean isUpdate = ConfigCacheService.isUptodate(groupKey, clientMd5);
status.put(groupKey, new SubscriberStatus(groupKey, isUpdate, clientMd5, lastPollingTs));
}
return status;
}
/**
* ip -> SubscriberStatus
*/
static public Map<String, SubscriberStatus> listSubsByGroup(String groupKey) {
Map<String, SubscriberStatus> subs = new HashMap<String, SubscriberStatus>(100);
for (ClientRecord clientRec : clientRecords.values()) {
String clientMd5 = clientRec.groupKey2md5Map.get(groupKey);
Long lastPollingTs = clientRec.groupKey2pollingTsMap.get(groupKey);
if (null != clientMd5 && lastPollingTs != null) {
Boolean isUpdate = ConfigCacheService.isUptodate(groupKey, clientMd5);
subs.put(clientRec.ip, new SubscriberStatus(groupKey, isUpdate, clientMd5, lastPollingTs));
}
}
return subs;
}
/**
* 指定订阅者IP查找数据是否最新 groupKey -> isUptodate
*/
@ -125,13 +127,13 @@ public class ClientTrackService {
}
return result;
}
/**
* 指定groupKey查找所有订阅者以及数据是否最新 IP -> isUptodate
*/
static public Map<String, Boolean> listSubscriberByGroup(String groupKey) {
Map<String, Boolean> subs = new HashMap<String, Boolean>(100);
for (ClientRecord clientRec : clientRecords.values()) {
String clientMd5 = clientRec.groupKey2md5Map.get(groupKey);
if (null != clientMd5) {
@ -141,7 +143,7 @@ public class ClientTrackService {
}
return subs;
}
/**
* 找到指定clientIp对应的记录
*/
@ -153,11 +155,11 @@ public class ClientTrackService {
clientRecords.putIfAbsent(clientIp, new ClientRecord(clientIp));
return clientRecords.get(clientIp);
}
static public void refreshClientRecord() {
clientRecords = new ConcurrentHashMap<String, ClientRecord>(50);
}
/**
* 所有客户端记录遍历 >> 新增/删除
*/
@ -168,11 +170,15 @@ public class ClientTrackService {
* 保存客户端拉数据的记录
*/
class ClientRecord {
final String ip;
volatile long lastTime;
final ConcurrentMap<String, String> groupKey2md5Map;
final ConcurrentMap<String, Long> groupKey2pollingTsMap;
ClientRecord(String clientIp) {
ip = clientIp;
groupKey2md5Map = new ConcurrentHashMap<String, String>(20, 0.75f, 1);

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.common.utils.MD5Utils;
@ -44,41 +45,41 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.*;
* @author Nacos
*/
public class ConfigCacheService {
@Autowired
private static PersistService persistService;
static public int groupCount() {
return CACHE.size();
}
static public boolean hasGroupKey(String groupKey) {
return CACHE.containsKey(groupKey);
}
/**
* 保存配置文件并缓存md5.
*/
static public boolean dump(String dataId, String group, String tenant, String content, long lastModifiedTs, String type) {
static public boolean dump(String dataId, String group, String tenant, String content, long lastModifiedTs,
String type) {
String groupKey = GroupKey2.getKey(dataId, group, tenant);
CacheItem ci = makeSure(groupKey);
ci.setType(type);
final int lockResult = tryWriteLock(groupKey);
assert (lockResult != 0);
if (lockResult < 0) {
dumpLog.warn("[dump-error] write lock failed. {}", groupKey);
return false;
}
try {
final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
if (md5.equals(ConfigCacheService.getContentMd5(groupKey))) {
dumpLog.warn(
"[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}",
groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey), lastModifiedTs);
dumpLog.warn("[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey),
lastModifiedTs);
} else if (!PropertyUtil.isDirectRead()) {
DiskUtil.saveToDisk(dataId, group, tenant, content);
}
@ -88,8 +89,8 @@ public class ConfigCacheService {
dumpLog.error("[dump-exception] save disk error. " + groupKey + ", " + ioe.toString(), ioe);
if (ioe.getMessage() != null) {
String errMsg = ioe.getMessage();
if (NO_SPACE_CN.equals(errMsg) || NO_SPACE_EN.equals(errMsg) || errMsg.contains(DISK_QUATA_CN)
|| errMsg.contains(DISK_QUATA_EN)) {
if (NO_SPACE_CN.equals(errMsg) || NO_SPACE_EN.equals(errMsg) || errMsg.contains(DISK_QUATA_CN) || errMsg
.contains(DISK_QUATA_EN)) {
// 磁盘写满保护代码
fatalLog.error("磁盘满自杀退出", ioe);
System.exit(0);
@ -100,108 +101,103 @@ public class ConfigCacheService {
releaseWriteLock(groupKey);
}
}
/**
* 保存配置文件并缓存md5.
*/
static public boolean dumpBeta(String dataId, String group, String tenant, String content, long lastModifiedTs,
String betaIps) {
String betaIps) {
final String groupKey = GroupKey2.getKey(dataId, group, tenant);
makeSure(groupKey);
final int lockResult = tryWriteLock(groupKey);
assert (lockResult != 0);
if (lockResult < 0) {
dumpLog.warn("[dump-beta-error] write lock failed. {}", groupKey);
return false;
}
try {
final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
if (md5.equals(ConfigCacheService.getContentBetaMd5(groupKey))) {
dumpLog.warn(
"[dump-beta-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}",
groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey), lastModifiedTs);
dumpLog.warn("[dump-beta-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey),
lastModifiedTs);
} else if (!PropertyUtil.isDirectRead()) {
DiskUtil.saveBetaToDisk(dataId, group, tenant, content);
}
String[] betaIpsArr = betaIps.split(",");
updateBetaMd5(groupKey, md5, Arrays.asList(betaIpsArr), lastModifiedTs);
return true;
} catch (IOException ioe) {
dumpLog.error("[dump-beta-exception] save disk error. " + groupKey + ", " + ioe.toString(),
ioe);
dumpLog.error("[dump-beta-exception] save disk error. " + groupKey + ", " + ioe.toString(), ioe);
return false;
} finally {
releaseWriteLock(groupKey);
}
}
/**
* 保存配置文件并缓存md5.
*/
static public boolean dumpTag(String dataId, String group, String tenant, String tag, String content,
long lastModifiedTs) {
long lastModifiedTs) {
final String groupKey = GroupKey2.getKey(dataId, group, tenant);
makeSure(groupKey);
final int lockResult = tryWriteLock(groupKey);
assert (lockResult != 0);
if (lockResult < 0) {
dumpLog.warn("[dump-tag-error] write lock failed. {}", groupKey);
return false;
}
try {
final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
if (md5.equals(ConfigCacheService.getContentTagMd5(groupKey, tag))) {
dumpLog.warn(
"[dump-tag-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}",
groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey), lastModifiedTs);
dumpLog.warn("[dump-tag-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey),
lastModifiedTs);
} else if (!PropertyUtil.isDirectRead()) {
DiskUtil.saveTagToDisk(dataId, group, tenant, tag, content);
}
updateTagMd5(groupKey, tag, md5, lastModifiedTs);
return true;
} catch (IOException ioe) {
dumpLog.error("[dump-tag-exception] save disk error. " + groupKey + ", " + ioe.toString(),
ioe);
dumpLog.error("[dump-tag-exception] save disk error. " + groupKey + ", " + ioe.toString(), ioe);
return false;
} finally {
releaseWriteLock(groupKey);
}
}
/**
* 保存配置文件并缓存md5.
*/
static public boolean dumpChange(String dataId, String group, String tenant, String content, long lastModifiedTs) {
final String groupKey = GroupKey2.getKey(dataId, group, tenant);
makeSure(groupKey);
final int lockResult = tryWriteLock(groupKey);
assert (lockResult != 0);
if (lockResult < 0) {
dumpLog.warn("[dump-error] write lock failed. {}", groupKey);
return false;
}
try {
final String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
if (!PropertyUtil.isDirectRead()) {
String loacalMd5 = DiskUtil.getLocalConfigMd5(dataId, group, tenant);
if (md5.equals(loacalMd5)) {
dumpLog.warn(
"[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}",
groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey), lastModifiedTs);
dumpLog.warn("[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", groupKey, md5, ConfigCacheService.getLastModifiedTs(groupKey),
lastModifiedTs);
} else {
DiskUtil.saveToDisk(dataId, group, tenant, content);
}
@ -209,26 +205,24 @@ public class ConfigCacheService {
updateMd5(groupKey, md5, lastModifiedTs);
return true;
} catch (IOException ioe) {
dumpLog.error("[dump-exception] save disk error. " + groupKey + ", " + ioe.toString(),
ioe);
dumpLog.error("[dump-exception] save disk error. " + groupKey + ", " + ioe.toString(), ioe);
return false;
} finally {
releaseWriteLock(groupKey);
}
}
static public void reloadConfig() {
String aggreds = null;
try {
if (PropertyUtil.isEmbeddedStorage()) {
ConfigInfoBase config = persistService.findConfigInfoBase(AggrWhitelist.AGGRIDS_METADATA,
"DEFAULT_GROUP");
ConfigInfoBase config = persistService
.findConfigInfoBase(AggrWhitelist.AGGRIDS_METADATA, "DEFAULT_GROUP");
if (config != null) {
aggreds = config.getContent();
}
} else {
aggreds = DiskUtil.getConfig(AggrWhitelist.AGGRIDS_METADATA,
"DEFAULT_GROUP", StringUtils.EMPTY);
aggreds = DiskUtil.getConfig(AggrWhitelist.AGGRIDS_METADATA, "DEFAULT_GROUP", StringUtils.EMPTY);
}
if (aggreds != null) {
AggrWhitelist.load(aggreds);
@ -236,38 +230,37 @@ public class ConfigCacheService {
} catch (IOException e) {
dumpLog.error("reload fail:" + AggrWhitelist.AGGRIDS_METADATA, e);
}
String clientIpWhitelist = null;
try {
if (PropertyUtil.isEmbeddedStorage()) {
ConfigInfoBase config = persistService.findConfigInfoBase(
ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP");
ConfigInfoBase config = persistService
.findConfigInfoBase(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP");
if (config != null) {
clientIpWhitelist = config.getContent();
}
} else {
clientIpWhitelist = DiskUtil.getConfig(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP",
StringUtils.EMPTY);
clientIpWhitelist = DiskUtil
.getConfig(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP", StringUtils.EMPTY);
}
if (clientIpWhitelist != null) {
ClientIpWhiteList.load(clientIpWhitelist);
}
} catch (IOException e) {
dumpLog.error("reload fail:"
+ ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, e);
dumpLog.error("reload fail:" + ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, e);
}
String switchContent = null;
try {
if (PropertyUtil.isEmbeddedStorage()) {
ConfigInfoBase config = persistService.findConfigInfoBase(SwitchService.SWITCH_META_DATAID,
"DEFAULT_GROUP");
ConfigInfoBase config = persistService
.findConfigInfoBase(SwitchService.SWITCH_META_DATAID, "DEFAULT_GROUP");
if (config != null) {
switchContent = config.getContent();
}
} else {
switchContent = DiskUtil.getConfig(
SwitchService.SWITCH_META_DATAID, "DEFAULT_GROUP", StringUtils.EMPTY);
switchContent = DiskUtil
.getConfig(SwitchService.SWITCH_META_DATAID, "DEFAULT_GROUP", StringUtils.EMPTY);
}
if (switchContent != null) {
SwitchService.load(switchContent);
@ -275,9 +268,9 @@ public class ConfigCacheService {
} catch (IOException e) {
dumpLog.error("reload fail:" + SwitchService.SWITCH_META_DATAID, e);
}
}
static public List<String> checkMd5() {
List<String> diffList = new ArrayList<String>();
long startTime = System.currentTimeMillis();
@ -290,21 +283,18 @@ public class ConfigCacheService {
try {
String loacalMd5 = DiskUtil.getLocalConfigMd5(dataId, group, tenant);
if (!entry.getValue().md5.equals(loacalMd5)) {
defaultLog.warn("[md5-different] dataId:{},group:{}",
dataId, group);
defaultLog.warn("[md5-different] dataId:{},group:{}", dataId, group);
diffList.add(groupKey);
}
} catch (IOException e) {
defaultLog.error("getLocalConfigMd5 fail,dataId:{},group:{}",
dataId, group);
defaultLog.error("getLocalConfigMd5 fail,dataId:{},group:{}", dataId, group);
}
}
long endTime = System.currentTimeMillis();
defaultLog.warn("checkMd5 cost:{}; diffCount:{}", endTime - startTime,
diffList.size());
defaultLog.warn("checkMd5 cost:{}; diffCount:{}", endTime - startTime, diffList.size());
return diffList;
}
/**
* 删除配置文件删除缓存
*/
@ -325,20 +315,20 @@ public class ConfigCacheService {
dumpLog.warn("[remove-error] write lock failed. {}", groupKey);
return false;
}
try {
if (!PropertyUtil.isDirectRead()) {
DiskUtil.removeConfigInfo(dataId, group, tenant);
}
CACHE.remove(groupKey);
EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey));
return true;
} finally {
releaseWriteLock(groupKey);
}
}
/**
* 删除配置文件删除缓存
*/
@ -359,7 +349,7 @@ public class ConfigCacheService {
dumpLog.warn("[remove-error] write lock failed. {}", groupKey);
return false;
}
try {
if (!PropertyUtil.isDirectRead()) {
DiskUtil.removeConfigInfo4Beta(dataId, group, tenant);
@ -373,7 +363,7 @@ public class ConfigCacheService {
releaseWriteLock(groupKey);
}
}
/**
* 删除配置文件删除缓存
*/
@ -394,12 +384,12 @@ public class ConfigCacheService {
dumpLog.warn("[remove-error] write lock failed. {}", groupKey);
return false;
}
try {
if (!PropertyUtil.isDirectRead()) {
DiskUtil.removeConfigInfo4Tag(dataId, group, tenant, tag);
}
CacheItem ci = CACHE.get(groupKey);
ci.tagMd5.remove(tag);
ci.tagLastModifiedTs.remove(tag);
@ -409,7 +399,7 @@ public class ConfigCacheService {
releaseWriteLock(groupKey);
}
}
public static void updateMd5(String groupKey, String md5, long lastModifiedTs) {
CacheItem cache = makeSure(groupKey);
if (cache.md5 == null || !cache.md5.equals(md5)) {
@ -418,7 +408,7 @@ public class ConfigCacheService {
EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey));
}
}
public static void updateBetaMd5(String groupKey, String md5, List<String> ips4Beta, long lastModifiedTs) {
CacheItem cache = makeSure(groupKey);
if (cache.md54Beta == null || !cache.md54Beta.equals(md5)) {
@ -429,7 +419,7 @@ public class ConfigCacheService {
EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey, true, ips4Beta));
}
}
public static void updateTagMd5(String groupKey, String tag, String md5, long lastModifiedTs) {
CacheItem cache = makeSure(groupKey);
if (cache.tagMd5 == null) {
@ -452,7 +442,7 @@ public class ConfigCacheService {
EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey, false, null, tag));
}
}
/**
* 返回cache的md5零长度字符串表示没有该数据
*/
@ -460,7 +450,7 @@ public class ConfigCacheService {
CacheItem item = CACHE.get(groupKey);
return (null != item) ? item.md5 : Constants.NULL;
}
/**
* 返回cache的md5零长度字符串表示没有该数据
*/
@ -468,7 +458,7 @@ public class ConfigCacheService {
CacheItem item = CACHE.get(groupKey);
return (null != item) ? item.md54Beta : Constants.NULL;
}
/**
* 返回cache的md5零长度字符串表示没有该数据
*/
@ -482,7 +472,7 @@ public class ConfigCacheService {
}
return item.tagMd5.get(tag);
}
/**
* 返回beta Ip列表
*/
@ -490,14 +480,14 @@ public class ConfigCacheService {
CacheItem item = CACHE.get(groupKey);
return (null != item) ? item.getIps4Beta() : Collections.<String>emptyList();
}
/**
* 返回cache
*/
static public CacheItem getContentCache(String groupKey) {
return CACHE.get(groupKey);
}
static public String getContentMd5(String groupKey, String ip, String tag) {
CacheItem item = CACHE.get(groupKey);
if (item != null && item.isBeta) {
@ -512,22 +502,22 @@ public class ConfigCacheService {
}
return (null != item) ? item.md5 : Constants.NULL;
}
static public long getLastModifiedTs(String groupKey) {
CacheItem item = CACHE.get(groupKey);
return (null != item) ? item.lastModifiedTs : 0L;
}
static public boolean isUptodate(String groupKey, String md5) {
String serverMd5 = ConfigCacheService.getContentMd5(groupKey);
return StringUtils.equals(md5, serverMd5);
}
static public boolean isUptodate(String groupKey, String md5, String ip, String tag) {
String serverMd5 = ConfigCacheService.getContentMd5(groupKey, ip, tag);
return StringUtils.equals(md5, serverMd5);
}
/**
* 给数据加读锁如果成功后面必须调用{@link #releaseReadLock(String)}失败则不需要
*
@ -542,14 +532,14 @@ public class ConfigCacheService {
}
return result;
}
static public void releaseReadLock(String groupKey) {
CacheItem item = CACHE.get(groupKey);
if (null != item) {
item.rwLock.releaseReadLock();
}
}
/**
* 给数据加写锁如果成功后面必须调用{@link #releaseWriteLock(String)}失败则不需要
*
@ -564,14 +554,14 @@ public class ConfigCacheService {
}
return result;
}
static void releaseWriteLock(String groupKey) {
CacheItem groupItem = CACHE.get(groupKey);
if (null != groupItem) {
groupItem.rwLock.releaseWriteLock();
}
}
static CacheItem makeSure(final String groupKey) {
CacheItem item = CACHE.get(groupKey);
if (null != item) {
@ -581,16 +571,20 @@ public class ConfigCacheService {
item = CACHE.putIfAbsent(groupKey, tmp);
return (null == item) ? tmp : item;
}
private final static String NO_SPACE_CN = "设备上没有空间";
private final static String NO_SPACE_EN = "No space left on device";
private final static String DISK_QUATA_CN = "超出磁盘限额";
private final static String DISK_QUATA_EN = "Disk quota exceeded";
static final Logger log = LoggerFactory.getLogger(ConfigCacheService.class);
/**
* groupKey -> cacheItem
*/
static private final ConcurrentHashMap<String, CacheItem> CACHE =
new ConcurrentHashMap<String, CacheItem>();
static private final ConcurrentHashMap<String, CacheItem> CACHE = new ConcurrentHashMap<String, CacheItem>();
}

View File

@ -25,12 +25,12 @@ import com.alibaba.nacos.core.utils.ApplicationUtils;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ConfigChangePublisher {
public static void notifyConfigChange(ConfigDataChangeEvent event) {
if (PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode()) {
return;
}
EventDispatcher.fireEvent(event);
}
public static void notifyConfigChange(ConfigDataChangeEvent event) {
if (PropertyUtil.isEmbeddedStorage() && !ApplicationUtils.getStandaloneMode()) {
return;
}
EventDispatcher.fireEvent(event);
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.common.utils.ThreadUtils;
@ -28,6 +29,7 @@ import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
@ -44,32 +46,31 @@ import java.util.concurrent.*;
*/
@Service
public class ConfigSubService {
private ScheduledExecutorService scheduler;
private ServerMemberManager memberManager;
@Autowired
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public ConfigSubService(ServerMemberManager memberManager) {
this.memberManager = memberManager;
scheduler = Executors.newScheduledThreadPool(
ThreadUtils.getSuitableThreadCount(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("com.alibaba.nacos.ConfigSubService");
return t;
}
});
scheduler = Executors.newScheduledThreadPool(ThreadUtils.getSuitableThreadCount(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("com.alibaba.nacos.ConfigSubService");
return t;
}
});
}
protected ConfigSubService() {
}
/**
* 获得调用的URL
*
@ -80,30 +81,26 @@ public class ConfigSubService {
private String getUrl(String ip, String relativePath) {
return "http://" + ip + ApplicationUtils.getContextPath() + relativePath;
}
private List<SampleResult> runCollectionJob(String url, Map<String, String> params,
CompletionService<SampleResult> completionService,
List<SampleResult> resultList) {
CompletionService<SampleResult> completionService, List<SampleResult> resultList) {
Collection<Member> ipList = memberManager.allMembers();
List<SampleResult> collectionResult = new ArrayList<SampleResult>(
ipList.size());
List<SampleResult> collectionResult = new ArrayList<SampleResult>(ipList.size());
// 提交查询任务
for (Member ip : ipList) {
try {
completionService.submit(new Job(ip.getAddress(), url, params));
} catch (Exception e) { // 发送请求失败
LogUtil.defaultLog
.warn("Get client info from {} with exception: {} during submit job",
ip, e.getMessage());
.warn("Get client info from {} with exception: {} during submit job", ip, e.getMessage());
}
}
// 获取结果并合并
SampleResult sampleResults = null;
for (Member member : ipList) {
try {
Future<SampleResult> f = completionService.poll(1000,
TimeUnit.MILLISECONDS);
Future<SampleResult> f = completionService.poll(1000, TimeUnit.MILLISECONDS);
try {
if (f != null) {
sampleResults = f.get(500, TimeUnit.MILLISECONDS);
@ -111,41 +108,33 @@ public class ConfigSubService {
collectionResult.add(sampleResults);
}
} else {
LogUtil.defaultLog
.warn("The task in ip: {} did not completed in 1000ms ",
member);
LogUtil.defaultLog.warn("The task in ip: {} did not completed in 1000ms ", member);
}
} catch (TimeoutException e) {
if (f != null) {
f.cancel(true);
}
LogUtil.defaultLog.warn(
"get task result with TimeoutException: {} ", e
.getMessage());
LogUtil.defaultLog.warn("get task result with TimeoutException: {} ", e.getMessage());
}
} catch (InterruptedException e) {
LogUtil.defaultLog.warn(
"get task result with InterruptedException: {} ", e
.getMessage());
LogUtil.defaultLog.warn("get task result with InterruptedException: {} ", e.getMessage());
} catch (ExecutionException e) {
LogUtil.defaultLog.warn(
"get task result with ExecutionException: {} ", e
.getMessage());
LogUtil.defaultLog.warn("get task result with ExecutionException: {} ", e.getMessage());
}
}
return collectionResult;
}
public SampleResult mergeSampleResult(SampleResult sampleCollectResult, List<SampleResult> sampleResults) {
SampleResult mergeResult = new SampleResult();
Map<String, String> lisentersGroupkeyStatus = null;
if (sampleCollectResult.getLisentersGroupkeyStatus() == null
|| sampleCollectResult.getLisentersGroupkeyStatus().isEmpty()) {
if (sampleCollectResult.getLisentersGroupkeyStatus() == null || sampleCollectResult.getLisentersGroupkeyStatus()
.isEmpty()) {
lisentersGroupkeyStatus = new HashMap<String, String>(10);
} else {
lisentersGroupkeyStatus = sampleCollectResult.getLisentersGroupkeyStatus();
}
for (SampleResult sampleResult : sampleResults) {
Map<String, String> lisentersGroupkeyStatusTmp = sampleResult.getLisentersGroupkeyStatus();
for (Map.Entry<String, String> entry : lisentersGroupkeyStatusTmp.entrySet()) {
@ -155,64 +144,62 @@ public class ConfigSubService {
mergeResult.setLisentersGroupkeyStatus(lisentersGroupkeyStatus);
return mergeResult;
}
/**
* 去每个Nacos Server节点查询订阅者的任务
*
* @author Nacos
*/
class Job implements Callable<SampleResult> {
private String ip;
private String url;
private Map<String, String> params;
public Job(String ip, String url, Map<String, String> params) {
this.ip = ip;
this.url = url;
this.params = params;
}
@Override
public SampleResult call() throws Exception {
try {
StringBuilder paramUrl = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
paramUrl.append("&").append(param.getKey()).append("=")
.append(URLEncoder.encode(param.getValue(), Constants.ENCODE));
.append(URLEncoder.encode(param.getValue(), Constants.ENCODE));
}
String urlAll = getUrl(ip, url) + "?" + paramUrl;
com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult result = NotifyService
.invokeURL(urlAll, null, Constants.ENCODE);
.invokeURL(urlAll, null, Constants.ENCODE);
/**
* http code 200
*/
if (result.code == HttpURLConnection.HTTP_OK) {
String json = result.content;
SampleResult resultObj = JSONUtils.deserializeObject(json,
new TypeReference<SampleResult>() {
});
SampleResult resultObj = JSONUtils.deserializeObject(json, new TypeReference<SampleResult>() {
});
return resultObj;
} else {
LogUtil.defaultLog.info(
"Can not get clientInfo from {} with {}", ip,
result.code);
LogUtil.defaultLog.info("Can not get clientInfo from {} with {}", ip, result.code);
return null;
}
} catch (Exception e) {
LogUtil.defaultLog.warn(
"Get client info from {} with exception: {}", ip, e
.getMessage());
LogUtil.defaultLog.warn("Get client info from {} with exception: {}", ip, e.getMessage());
return null;
}
}
}
public SampleResult getCollectSampleResult(String dataId, String group, String tenant, int sampleTime)
throws Exception {
throws Exception {
List<SampleResult> resultList = new ArrayList<SampleResult>();
String url = Constants.COMMUNICATION_CONTROLLER_PATH + "/configWatchers";
Map<String, String> params = new HashMap<String, String>(5);
@ -222,10 +209,10 @@ public class ConfigSubService {
params.put("tenant", tenant);
}
BlockingQueue<Future<SampleResult>> queue = new LinkedBlockingDeque<Future<SampleResult>>(
memberManager.getServerList().size());
memberManager.getServerList().size());
CompletionService<SampleResult> completionService = new ExecutorCompletionService<SampleResult>(scheduler,
queue);
queue);
SampleResult sampleCollectResult = new SampleResult();
for (int i = 0; i < sampleTime; i++) {
List<SampleResult> sampleResults = runCollectionJob(url, params, completionService, resultList);
@ -235,18 +222,17 @@ public class ConfigSubService {
}
return sampleCollectResult;
}
public SampleResult getCollectSampleResultByIp(String ip, int sampleTime)
throws Exception {
public SampleResult getCollectSampleResultByIp(String ip, int sampleTime) throws Exception {
List<SampleResult> resultList = new ArrayList<SampleResult>(10);
String url = Constants.COMMUNICATION_CONTROLLER_PATH + "/watcherConfigs";
Map<String, String> params = new HashMap<String, String>(50);
params.put("ip", ip);
BlockingQueue<Future<SampleResult>> queue = new LinkedBlockingDeque<Future<SampleResult>>(
memberManager.getServerList().size());
memberManager.getServerList().size());
CompletionService<SampleResult> completionService = new ExecutorCompletionService<SampleResult>(scheduler,
queue);
queue);
SampleResult sampleCollectResult = new SampleResult();
for (int i = 0; i < sampleTime; i++) {
List<SampleResult> sampleResults = runCollectionJob(url, params, completionService, resultList);
@ -256,5 +242,5 @@ public class ConfigSubService {
}
return sampleCollectResult;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.common.utils.CollectionUtils;
@ -45,44 +46,44 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
*/
@Service
public class LongPollingService extends AbstractEventListener {
private static final int FIXED_POLLING_INTERVAL_MS = 10000;
private static final int SAMPLE_PERIOD = 100;
private static final int SAMPLE_TIMES = 3;
private static final String TRUE_STR = "true";
private Map<String, Long> retainIps = new ConcurrentHashMap<String, Long>();
private static boolean isFixedPolling() {
return SwitchService.getSwitchBoolean(SwitchService.FIXED_POLLING, false);
}
private static int getFixedPollingInterval() {
return SwitchService.getSwitchInteger(SwitchService.FIXED_POLLING_INTERVAL, FIXED_POLLING_INTERVAL_MS);
}
public boolean isClientLongPolling(String clientIp) {
return getClientPollingRecord(clientIp) != null;
}
public Map<String, String> getClientSubConfigInfo(String clientIp) {
ClientLongPolling record = getClientPollingRecord(clientIp);
if (record == null) {
return Collections.<String, String>emptyMap();
}
return record.clientMd5Map;
}
public SampleResult getSubscribleInfo(String dataId, String group, String tenant) {
String groupKey = GroupKey.getKeyTenant(dataId, group, tenant);
SampleResult sampleResult = new SampleResult();
Map<String, String> lisentersGroupkeyStatus = new HashMap<String, String>(50);
for (ClientLongPolling clientLongPolling : allSubs) {
if (clientLongPolling.clientMd5Map.containsKey(groupKey)) {
lisentersGroupkeyStatus.put(clientLongPolling.ip, clientLongPolling.clientMd5Map.get(groupKey));
@ -91,11 +92,11 @@ public class LongPollingService extends AbstractEventListener {
sampleResult.setLisentersGroupkeyStatus(lisentersGroupkeyStatus);
return sampleResult;
}
public SampleResult getSubscribleInfoByIp(String clientIp) {
SampleResult sampleResult = new SampleResult();
Map<String, String> lisentersGroupkeyStatus = new HashMap<String, String>(50);
for (ClientLongPolling clientLongPolling : allSubs) {
if (clientLongPolling.ip.equals(clientIp)) {
// 一个ip可能有多个监听
@ -107,7 +108,7 @@ public class LongPollingService extends AbstractEventListener {
sampleResult.setLisentersGroupkeyStatus(lisentersGroupkeyStatus);
return sampleResult;
}
/**
* 聚合采样结果中的采样ip和监听配置的信息合并策略用后面的覆盖前面的是没有问题的
*
@ -126,15 +127,15 @@ public class LongPollingService extends AbstractEventListener {
mergeResult.setLisentersGroupkeyStatus(lisentersGroupkeyStatus);
return mergeResult;
}
public Map<String, Set<String>> collectApplicationSubscribeConfigInfos() {
if (allSubs == null || allSubs.isEmpty()) {
return null;
}
HashMap<String, Set<String>> app2Groupkeys = new HashMap<String, Set<String>>(50);
for (ClientLongPolling clientLongPolling : allSubs) {
if (StringUtils.isEmpty(clientLongPolling.appName) || "unknown".equalsIgnoreCase(
clientLongPolling.appName)) {
if (StringUtils.isEmpty(clientLongPolling.appName) || "unknown"
.equalsIgnoreCase(clientLongPolling.appName)) {
continue;
}
Set<String> appSubscribeConfigs = app2Groupkeys.get(clientLongPolling.appName);
@ -145,10 +146,10 @@ public class LongPollingService extends AbstractEventListener {
appSubscribeConfigs.addAll(clientSubscribeConfigs);
app2Groupkeys.put(clientLongPolling.appName, appSubscribeConfigs);
}
return app2Groupkeys;
}
public SampleResult getCollectSubscribleInfo(String dataId, String group, String tenant) {
List<SampleResult> sampleResultLst = new ArrayList<SampleResult>(50);
for (int i = 0; i < SAMPLE_TIMES; i++) {
@ -164,19 +165,19 @@ public class LongPollingService extends AbstractEventListener {
}
}
}
SampleResult sampleResult = mergeSampleResult(sampleResultLst);
return sampleResult;
}
public SampleResult getCollectSubscribleInfoByIp(String ip) {
SampleResult sampleResult = new SampleResult();
sampleResult.setLisentersGroupkeyStatus(new HashMap<String, String>(50));
for (int i = 0; i < SAMPLE_TIMES; i++) {
SampleResult sampleTmp = getSubscribleInfoByIp(ip);
if (sampleTmp != null) {
if (sampleTmp.getLisentersGroupkeyStatus() != null
&& !sampleResult.getLisentersGroupkeyStatus().equals(sampleTmp.getLisentersGroupkeyStatus())) {
if (sampleTmp.getLisentersGroupkeyStatus() != null && !sampleResult.getLisentersGroupkeyStatus()
.equals(sampleTmp.getLisentersGroupkeyStatus())) {
sampleResult.getLisentersGroupkeyStatus().putAll(sampleTmp.getLisentersGroupkeyStatus());
}
}
@ -190,26 +191,26 @@ public class LongPollingService extends AbstractEventListener {
}
return sampleResult;
}
private ClientLongPolling getClientPollingRecord(String clientIp) {
if (allSubs == null) {
return null;
}
for (ClientLongPolling clientLongPolling : allSubs) {
HttpServletRequest request = (HttpServletRequest) clientLongPolling.asyncContext.getRequest();
if (clientIp.equals(RequestUtil.getRemoteIp(request))) {
return clientLongPolling;
}
}
return null;
}
public void addLongPollingClient(HttpServletRequest req, HttpServletResponse rsp, Map<String, String> clientMd5Map,
int probeRequestSize) {
int probeRequestSize) {
String str = req.getHeader(LongPollingService.LONG_POLLING_HEADER);
String noHangUpFlag = req.getHeader(LongPollingService.LONG_POLLING_NO_HANG_UP_HEADER);
String appName = req.getHeader(RequestUtil.CLIENT_APPNAME_HEADER);
@ -227,14 +228,14 @@ public class LongPollingService extends AbstractEventListener {
List<String> changedGroups = MD5Util.compareMd5(req, rsp, clientMd5Map);
if (changedGroups.size() > 0) {
generateResponse(req, rsp, changedGroups);
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}|{}",
System.currentTimeMillis() - start, "instant", RequestUtil.getRemoteIp(req), "polling",
clientMd5Map.size(), probeRequestSize, changedGroups.size());
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}|{}", System.currentTimeMillis() - start, "instant",
RequestUtil.getRemoteIp(req), "polling", clientMd5Map.size(), probeRequestSize,
changedGroups.size());
return;
} else if (noHangUpFlag != null && noHangUpFlag.equalsIgnoreCase(TRUE_STR)) {
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}|{}", System.currentTimeMillis() - start, "nohangup",
RequestUtil.getRemoteIp(req), "polling", clientMd5Map.size(), probeRequestSize,
changedGroups.size());
RequestUtil.getRemoteIp(req), "polling", clientMd5Map.size(), probeRequestSize,
changedGroups.size());
return;
}
}
@ -243,38 +244,38 @@ public class LongPollingService extends AbstractEventListener {
final AsyncContext asyncContext = req.startAsync();
// AsyncContext.setTimeout()的超时时间不准所以只能自己控制
asyncContext.setTimeout(0L);
scheduler.execute(
new ClientLongPolling(asyncContext, clientMd5Map, ip, probeRequestSize, timeout, appName, tag));
new ClientLongPolling(asyncContext, clientMd5Map, ip, probeRequestSize, timeout, appName, tag));
}
@Override
public List<Class<? extends Event>> interest() {
List<Class<? extends Event>> eventTypes = new ArrayList<Class<? extends Event>>();
eventTypes.add(LocalDataChangeEvent.class);
return eventTypes;
}
@Override
public void onEvent(Event event) {
if (isFixedPolling()) {
// ignore
} else {
if (event instanceof LocalDataChangeEvent) {
LocalDataChangeEvent evt = (LocalDataChangeEvent)event;
LocalDataChangeEvent evt = (LocalDataChangeEvent) event;
scheduler.execute(new DataChangeTask(evt.groupKey, evt.isBeta, evt.betaIps));
}
}
}
static public boolean isSupportLongPolling(HttpServletRequest req) {
return null != req.getHeader(LONG_POLLING_HEADER);
}
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public LongPollingService() {
allSubs = new ConcurrentLinkedQueue<ClientLongPolling>();
scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
@ -286,22 +287,24 @@ public class LongPollingService extends AbstractEventListener {
});
scheduler.scheduleWithFixedDelay(new StatTask(), 0L, 10L, TimeUnit.SECONDS);
}
// =================
static public final String LONG_POLLING_HEADER = "Long-Pulling-Timeout";
static public final String LONG_POLLING_NO_HANG_UP_HEADER = "Long-Pulling-Timeout-No-Hangup";
final ScheduledExecutorService scheduler;
/**
* 长轮询订阅关系
*/
final Queue<ClientLongPolling> allSubs;
// =================
class DataChangeTask implements Runnable {
@Override
public void run() {
try {
@ -313,20 +316,19 @@ public class LongPollingService extends AbstractEventListener {
if (isBeta && !CollectionUtils.contains(betaIps, clientSub.ip)) {
continue;
}
// 如果tag发布且不在tag列表直接跳过
if (StringUtils.isNotBlank(tag) && !tag.equals(clientSub.tag)) {
continue;
}
getRetainIps().put(clientSub.ip, System.currentTimeMillis());
iter.remove(); // 删除订阅关系
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}|{}",
(System.currentTimeMillis() - changeTime),
"in-advance",
RequestUtil.getRemoteIp((HttpServletRequest)clientSub.asyncContext.getRequest()),
"polling",
clientSub.clientMd5Map.size(), clientSub.probeRequestSize, groupKey);
LogUtil.clientLog
.info("{}|{}|{}|{}|{}|{}|{}", (System.currentTimeMillis() - changeTime), "in-advance",
RequestUtil
.getRemoteIp((HttpServletRequest) clientSub.asyncContext.getRequest()),
"polling", clientSub.clientMd5Map.size(), clientSub.probeRequestSize, groupKey);
clientSub.sendResponse(Arrays.asList(groupKey));
}
}
@ -334,39 +336,44 @@ public class LongPollingService extends AbstractEventListener {
LogUtil.defaultLog.error("data change error: {}", ExceptionUtil.getStackTrace(t));
}
}
DataChangeTask(String groupKey, boolean isBeta, List<String> betaIps) {
this(groupKey, isBeta, betaIps, null);
}
DataChangeTask(String groupKey, boolean isBeta, List<String> betaIps, String tag) {
this.groupKey = groupKey;
this.isBeta = isBeta;
this.betaIps = betaIps;
this.tag = tag;
}
final String groupKey;
final long changeTime = System.currentTimeMillis();
final boolean isBeta;
final List<String> betaIps;
final String tag;
}
// =================
class StatTask implements Runnable {
@Override
public void run() {
memoryLog.info("[long-pulling] client count " + allSubs.size());
MetricsMonitor.getLongPollingMonitor().set(allSubs.size());
}
}
// =================
class ClientLongPolling implements Runnable {
@Override
public void run() {
asyncTimeoutFuture = scheduler.schedule(new Runnable() {
@ -378,40 +385,38 @@ public class LongPollingService extends AbstractEventListener {
* 删除订阅关系
*/
allSubs.remove(ClientLongPolling.this);
if (isFixedPolling()) {
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}",
(System.currentTimeMillis() - createTime),
"fix", RequestUtil.getRemoteIp((HttpServletRequest)asyncContext.getRequest()),
"polling",
clientMd5Map.size(), probeRequestSize);
List<String> changedGroups = MD5Util.compareMd5(
(HttpServletRequest)asyncContext.getRequest(),
(HttpServletResponse)asyncContext.getResponse(), clientMd5Map);
LogUtil.clientLog
.info("{}|{}|{}|{}|{}|{}", (System.currentTimeMillis() - createTime), "fix",
RequestUtil.getRemoteIp((HttpServletRequest) asyncContext.getRequest()),
"polling", clientMd5Map.size(), probeRequestSize);
List<String> changedGroups = MD5Util
.compareMd5((HttpServletRequest) asyncContext.getRequest(),
(HttpServletResponse) asyncContext.getResponse(), clientMd5Map);
if (changedGroups.size() > 0) {
sendResponse(changedGroups);
} else {
sendResponse(null);
}
} else {
LogUtil.clientLog.info("{}|{}|{}|{}|{}|{}",
(System.currentTimeMillis() - createTime),
"timeout", RequestUtil.getRemoteIp((HttpServletRequest)asyncContext.getRequest()),
"polling",
clientMd5Map.size(), probeRequestSize);
LogUtil.clientLog
.info("{}|{}|{}|{}|{}|{}", (System.currentTimeMillis() - createTime), "timeout",
RequestUtil.getRemoteIp((HttpServletRequest) asyncContext.getRequest()),
"polling", clientMd5Map.size(), probeRequestSize);
sendResponse(null);
}
} catch (Throwable t) {
LogUtil.defaultLog.error("long polling error:" + t.getMessage(), t.getCause());
}
}
}, timeoutTime, TimeUnit.MILLISECONDS);
allSubs.add(this);
}
void sendResponse(List<String> changedGroups) {
/**
* 取消超时任务
@ -421,7 +426,7 @@ public class LongPollingService extends AbstractEventListener {
}
generateResponse(changedGroups);
}
void generateResponse(List<String> changedGroups) {
if (null == changedGroups) {
/**
@ -430,12 +435,12 @@ public class LongPollingService extends AbstractEventListener {
asyncContext.complete();
return;
}
HttpServletResponse response = (HttpServletResponse)asyncContext.getResponse();
HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
try {
String respString = MD5Util.compareMd5ResultString(changedGroups);
// 禁用缓存
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
@ -448,9 +453,9 @@ public class LongPollingService extends AbstractEventListener {
asyncContext.complete();
}
}
ClientLongPolling(AsyncContext ac, Map<String, String> clientMd5Map, String ip, int probeRequestSize,
long timeoutTime, String appName, String tag) {
long timeoutTime, String appName, String tag) {
this.asyncContext = ac;
this.clientMd5Map = clientMd5Map;
this.probeRequestSize = probeRequestSize;
@ -460,34 +465,40 @@ public class LongPollingService extends AbstractEventListener {
this.appName = appName;
this.tag = tag;
}
// =================
final AsyncContext asyncContext;
final Map<String, String> clientMd5Map;
final long createTime;
final String ip;
final String appName;
final String tag;
final int probeRequestSize;
final long timeoutTime;
Future<?> asyncTimeoutFuture;
@Override
public String toString() {
return "ClientLongPolling{" + "clientMd5Map=" + clientMd5Map + ", createTime="
+ createTime + ", ip='" + ip + '\'' + ", appName='" + appName + '\''
+ ", tag='" + tag + '\'' + ", probeRequestSize=" + probeRequestSize
+ ", timeoutTime=" + timeoutTime + '}';
return "ClientLongPolling{" + "clientMd5Map=" + clientMd5Map + ", createTime=" + createTime + ", ip='" + ip
+ '\'' + ", appName='" + appName + '\'' + ", tag='" + tag + '\'' + ", probeRequestSize="
+ probeRequestSize + ", timeoutTime=" + timeoutTime + '}';
}
}
void generateResponse(HttpServletRequest request, HttpServletResponse response, List<String> changedGroups) {
if (null == changedGroups) {
return;
}
try {
String respString = MD5Util.compareMd5ResultString(changedGroups);
// 禁用缓存
@ -500,13 +511,13 @@ public class LongPollingService extends AbstractEventListener {
pullLog.error(se.toString(), se);
}
}
public Map<String, Long> getRetainIps() {
return retainIps;
}
public void setRetainIps(Map<String, Long> retainIps) {
this.retainIps = retainIps;
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.common.utils.IoUtils;
@ -35,17 +36,19 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
*/
@Service
public class SwitchService {
public static final String SWITCH_META_DATAID = "com.alibaba.nacos.meta.switch";
public static final String FIXED_POLLING = "isFixedPolling";
public static final String FIXED_POLLING_INTERVAL = "fixedPollingInertval";
public static final String FIXED_DELAY_TIME = "fixedDelayTime";
public static final String DISABLE_APP_COLLECTOR = "disableAppCollector";
private static volatile Map<String, String> switches = new HashMap<String, String>();
public static boolean getSwitchBoolean(String key, boolean defaultValue) {
boolean rtn = defaultValue;
try {
@ -57,7 +60,7 @@ public class SwitchService {
}
return rtn;
}
public static int getSwitchInteger(String key, int defaultValue) {
int rtn = defaultValue;
try {
@ -69,33 +72,33 @@ public class SwitchService {
}
return rtn;
}
public static String getSwitchString(String key, String defaultValue) {
String value = switches.get(key);
return StringUtils.isBlank(value) ? defaultValue : value;
}
public static void load(String config) {
if (StringUtils.isBlank(config)) {
fatalLog.error("switch config is blank.");
return;
}
fatalLog.warn("[switch-config] {}", config);
Map<String, String> map = new HashMap<String, String>(30);
try {
for (String line : IoUtils.readLines(new StringReader(config))) {
if (!StringUtils.isBlank(line) && !line.startsWith("#")) {
String[] array = line.split("=");
if (array == null || array.length != 2) {
LogUtil.fatalLog.error("corrupt switch record {}", line);
continue;
}
String key = array[0].trim();
String value = array[1].trim();
map.put(key, value);
}
switches = map;
@ -105,10 +108,10 @@ public class SwitchService {
LogUtil.fatalLog.warn("[reload-switches] error! {}", config);
}
}
public static String getSwitches() {
StringBuilder sb = new StringBuilder();
String split = "";
for (Map.Entry<String, String> entry : switches.entrySet()) {
String key = entry.getKey();
@ -119,8 +122,8 @@ public class SwitchService {
sb.append(value);
split = "; ";
}
return sb.toString();
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service.capacity;
import com.alibaba.nacos.config.server.constant.CounterMode;
@ -49,26 +50,30 @@ import java.util.concurrent.TimeUnit;
*/
@Service
public class CapacityService {
private static final Logger LOGGER = LoggerFactory.getLogger(CapacityService.class);
private static final Integer ZERO = 0;
private static final int INIT_PAGE_SIZE = 500;
@Autowired
private GroupCapacityPersistService groupCapacityPersistService;
@Autowired
private TenantCapacityPersistService tenantCapacityPersistService;
@Autowired
private PersistService persistService;
private ScheduledExecutorService scheduledExecutorService;
@PostConstruct
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public void init() {
// 每个Server都有修正usage的Job在跑幂等
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
"com.alibaba.nacos.CapacityManagement-%d").setDaemon(true).build();
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("com.alibaba.nacos.CapacityManagement-%d").setDaemon(true).build();
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
@ -77,34 +82,34 @@ public class CapacityService {
Stopwatch stopwatch = Stopwatch.createStarted();
correctUsage();
LOGGER.info("[capacityManagement] end correct usage, cost: {}s", stopwatch.elapsed(TimeUnit.SECONDS));
}
}, PropertyUtil.getCorrectUsageDelay(), PropertyUtil.getCorrectUsageDelay(), TimeUnit.SECONDS);
}
@PreDestroy
public void destroy() {
scheduledExecutorService.shutdown();
}
public void correctUsage() {
correctGroupUsage();
correctTenantUsage();
}
public void correctGroupUsage(String group) {
groupCapacityPersistService.correctUsage(group, TimeUtils.getCurrentTime());
}
public void correctTenantUsage(String tenant) {
tenantCapacityPersistService.correctUsage(tenant, TimeUtils.getCurrentTime());
}
public void initAllCapacity() {
initAllCapacity(false);
initAllCapacity(true);
}
private void initAllCapacity(boolean isTenant) {
int page = 1;
while (true) {
@ -134,7 +139,7 @@ public class CapacityService {
++page;
}
}
/**
* 修正Group容量信息中的使用值usage
*/
@ -142,8 +147,8 @@ public class CapacityService {
long lastId = 0;
int pageSize = 100;
while (true) {
List<GroupCapacity> groupCapacityList = groupCapacityPersistService.getCapacityList4CorrectUsage(lastId,
pageSize);
List<GroupCapacity> groupCapacityList = groupCapacityPersistService
.getCapacityList4CorrectUsage(lastId, pageSize);
if (groupCapacityList.isEmpty()) {
break;
}
@ -159,7 +164,7 @@ public class CapacityService {
}
}
}
/**
* 修正Tenant容量信息中的使用值usage
*/
@ -167,8 +172,8 @@ public class CapacityService {
long lastId = 0;
int pageSize = 100;
while (true) {
List<TenantCapacity> tenantCapacityList = tenantCapacityPersistService.getCapacityList4CorrectUsage(lastId,
pageSize);
List<TenantCapacity> tenantCapacityList = tenantCapacityPersistService
.getCapacityList4CorrectUsage(lastId, pageSize);
if (tenantCapacityList.isEmpty()) {
break;
}
@ -184,7 +189,7 @@ public class CapacityService {
}
}
}
/**
* 集群1. 如果容量信息不存在则初始化容量信息<br/> 2. 更新容量的使用量usage加一或减一
*
@ -197,15 +202,15 @@ public class CapacityService {
if (capacity == null) {
insertGroupCapacity(GroupCapacityPersistService.CLUSTER);
}
return updateGroupUsage(counterMode, GroupCapacityPersistService.CLUSTER,
PropertyUtil.getDefaultClusterQuota(), ignoreQuotaLimit);
return updateGroupUsage(counterMode, GroupCapacityPersistService.CLUSTER, PropertyUtil.getDefaultClusterQuota(),
ignoreQuotaLimit);
}
public boolean updateClusterUsage(CounterMode counterMode) {
return updateGroupUsage(counterMode, GroupCapacityPersistService.CLUSTER,
PropertyUtil.getDefaultClusterQuota(), false);
return updateGroupUsage(counterMode, GroupCapacityPersistService.CLUSTER, PropertyUtil.getDefaultClusterQuota(),
false);
}
/**
* 提供给关闭容量管理的限制检验功能时计数使用<br> Group1. 如果容量信息不存在则初始化容量信息<br/> 2. 更新容量的使用量usage加一或减一
*
@ -221,27 +226,27 @@ public class CapacityService {
}
return updateGroupUsage(counterMode, group, PropertyUtil.getDefaultGroupQuota(), ignoreQuotaLimit);
}
public GroupCapacity getGroupCapacity(String group) {
return groupCapacityPersistService.getGroupCapacity(group);
}
public boolean updateGroupUsage(CounterMode counterMode, String group) {
return updateGroupUsage(counterMode, group, PropertyUtil.getDefaultGroupQuota(), false);
}
/**
* 初始化该Group的容量信息如果到达限额将自动扩容以降低运维成本
*/
public boolean initGroupCapacity(String group) {
return initGroupCapacity(group, null, null, null, null);
}
/**
* 初始化该Group的容量信息如果到达限额将自动扩容以降低运维成本
*/
private boolean initGroupCapacity(String group, Integer quota, Integer maxSize, Integer maxAggrCount,
Integer maxAggrSize) {
Integer maxAggrSize) {
boolean insertSuccess = insertGroupCapacity(group, quota, maxSize, maxAggrCount, maxAggrSize);
if (quota != null) {
return insertSuccess;
@ -249,7 +254,7 @@ public class CapacityService {
autoExpansion(group, null);
return insertSuccess;
}
/**
* 自动扩容
*/
@ -263,33 +268,34 @@ public class CapacityService {
// 初始化的时候该Group/租户就已经到达限额自动扩容降低运维成本
int initialExpansionPercent = PropertyUtil.getInitialExpansionPercent();
if (initialExpansionPercent > 0) {
int finalQuota = (int)(usage + defaultQuota * (1.0 * initialExpansionPercent / 100));
int finalQuota = (int) (usage + defaultQuota * (1.0 * initialExpansionPercent / 100));
if (tenant != null) {
tenantCapacityPersistService.updateQuota(tenant, finalQuota);
LogUtil.defaultLog.warn("[capacityManagement] 初始化的时候该租户({})使用量({})就已经到达限额{},自动扩容到{}", tenant,
usage, defaultQuota, finalQuota);
LogUtil.defaultLog
.warn("[capacityManagement] 初始化的时候该租户({})使用量({})就已经到达限额{},自动扩容到{}", tenant, usage, defaultQuota,
finalQuota);
} else {
groupCapacityPersistService.updateQuota(group, finalQuota);
LogUtil.defaultLog.warn("[capacityManagement] 初始化的时候该Group{})使用量({})就已经到达限额{},自动扩容到{}", group,
usage, defaultQuota, finalQuota);
LogUtil.defaultLog.warn("[capacityManagement] 初始化的时候该Group{})使用量({})就已经到达限额{},自动扩容到{}", group, usage,
defaultQuota, finalQuota);
}
}
}
private int getDefaultQuota(boolean isTenant) {
if (isTenant) {
return PropertyUtil.getDefaultTenantQuota();
}
return PropertyUtil.getDefaultGroupQuota();
}
public Capacity getCapacity(String group, String tenant) {
if (tenant != null) {
return getTenantCapacity(tenant);
}
return getGroupCapacity(group);
}
public Capacity getCapacityWithDefault(String group, String tenant) {
Capacity capacity;
boolean isTenant = StringUtils.isNotBlank(tenant);
@ -327,7 +333,7 @@ public class CapacityService {
}
return capacity;
}
public boolean initCapacity(String group, String tenant) {
if (StringUtils.isNotBlank(tenant)) {
return initTenantCapacity(tenant);
@ -338,13 +344,13 @@ public class CapacityService {
// Group会自动扩容
return initGroupCapacity(group);
}
private boolean insertGroupCapacity(String group) {
return insertGroupCapacity(group, null, null, null, null);
}
private boolean insertGroupCapacity(String group, Integer quota, Integer maxSize, Integer maxAggrCount,
Integer maxAggrSize) {
Integer maxAggrSize) {
try {
final Timestamp now = TimeUtils.getCurrentTime();
GroupCapacity groupCapacity = new GroupCapacity();
@ -364,9 +370,9 @@ public class CapacityService {
}
return false;
}
private boolean updateGroupUsage(CounterMode counterMode, String group, int defaultQuota,
boolean ignoreQuotaLimit) {
boolean ignoreQuotaLimit) {
final Timestamp now = TimeUtils.getCurrentTime();
GroupCapacity groupCapacity = new GroupCapacity();
groupCapacity.setGroup(group);
@ -378,11 +384,11 @@ public class CapacityService {
}
// 先按默认值限额更新大部分情况下都是默认值默认值表里面的quota字段为0
return groupCapacityPersistService.incrementUsageWithDefaultQuotaLimit(groupCapacity)
|| groupCapacityPersistService.incrementUsageWithQuotaLimit(groupCapacity);
|| groupCapacityPersistService.incrementUsageWithQuotaLimit(groupCapacity);
}
return groupCapacityPersistService.decrementUsage(groupCapacity);
}
/**
* 提供给关闭容量管理的限制检验功能时计数使用<br/> 租户 1. 如果容量信息不存在则初始化容量信息<br/> 2. 更新容量的使用量usage加一或减一
*
@ -399,7 +405,7 @@ public class CapacityService {
}
return updateTenantUsage(counterMode, tenant, ignoreQuotaLimit);
}
private boolean updateTenantUsage(CounterMode counterMode, String tenant, boolean ignoreQuotaLimit) {
final Timestamp now = TimeUtils.getCurrentTime();
TenantCapacity tenantCapacity = new TenantCapacity();
@ -412,27 +418,27 @@ public class CapacityService {
}
// 先按默认值限额更新大部分情况下都是默认值默认值表里面的quota字段为0
return tenantCapacityPersistService.incrementUsageWithDefaultQuotaLimit(tenantCapacity)
|| tenantCapacityPersistService.incrementUsageWithQuotaLimit(tenantCapacity);
|| tenantCapacityPersistService.incrementUsageWithQuotaLimit(tenantCapacity);
}
return tenantCapacityPersistService.decrementUsage(tenantCapacity);
}
public boolean updateTenantUsage(CounterMode counterMode, String tenant) {
return updateTenantUsage(counterMode, tenant, false);
}
/**
* 初始化该租户的容量信息如果到达限额将自动扩容以降低运维成本
*/
public boolean initTenantCapacity(String tenant) {
return initTenantCapacity(tenant, null, null, null, null);
}
/**
* 初始化该租户的容量信息如果到达限额将自动扩容以降低运维成本
*/
public boolean initTenantCapacity(String tenant, Integer quota, Integer maxSize, Integer maxAggrCount,
Integer maxAggrSize) {
Integer maxAggrSize) {
boolean insertSuccess = insertTenantCapacity(tenant, quota, maxSize, maxAggrCount, maxAggrSize);
if (quota != null) {
return insertSuccess;
@ -440,13 +446,13 @@ public class CapacityService {
autoExpansion(null, tenant);
return insertSuccess;
}
private boolean insertTenantCapacity(String tenant) {
return insertTenantCapacity(tenant, null, null, null, null);
}
private boolean insertTenantCapacity(String tenant, Integer quota, Integer maxSize, Integer maxAggrCount,
Integer maxAggrSize) {
Integer maxAggrSize) {
try {
final Timestamp now = TimeUtils.getCurrentTime();
TenantCapacity tenantCapacity = new TenantCapacity();
@ -466,11 +472,11 @@ public class CapacityService {
}
return false;
}
public TenantCapacity getTenantCapacity(String tenant) {
return tenantCapacityPersistService.getTenantCapacity(tenant);
}
/**
* 提供给API接口使用<br/> 租户记录不存在则初始化存在则直接更新容量限额或者内容大小
*
@ -480,15 +486,14 @@ public class CapacityService {
* @param maxSize 配置内容content大小限制
* @return 是否操作成功
*/
public boolean insertOrUpdateCapacity(String group, String tenant, Integer quota, Integer maxSize, Integer
maxAggrCount, Integer maxAggrSize) {
public boolean insertOrUpdateCapacity(String group, String tenant, Integer quota, Integer maxSize,
Integer maxAggrCount, Integer maxAggrSize) {
if (StringUtils.isNotBlank(tenant)) {
Capacity capacity = tenantCapacityPersistService.getTenantCapacity(tenant);
if (capacity == null) {
return initTenantCapacity(tenant, quota, maxSize, maxAggrCount, maxAggrSize);
}
return tenantCapacityPersistService.updateTenantCapacity(tenant, quota, maxSize, maxAggrCount,
maxAggrSize);
return tenantCapacityPersistService.updateTenantCapacity(tenant, quota, maxSize, maxAggrCount, maxAggrSize);
}
Capacity capacity = groupCapacityPersistService.getGroupCapacity(group);
if (capacity == null) {

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service.capacity;
import com.alibaba.nacos.config.server.model.capacity.Capacity;
@ -43,22 +44,23 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
*/
@Service
public class GroupCapacityPersistService {
static final String CLUSTER = "";
private static final GroupCapacityRowMapper
GROUP_CAPACITY_ROW_MAPPER = new GroupCapacityRowMapper();
private static final GroupCapacityRowMapper GROUP_CAPACITY_ROW_MAPPER = new GroupCapacityRowMapper();
private JdbcTemplate jdbcTemplate;
private DataSourceService dataSourceService;
@PostConstruct
public void init() {
this.dataSourceService = DynamicDataSource.getInstance().getDataSource();
this.jdbcTemplate = dataSourceService.getJdbcTemplate();
}
private static final class GroupCapacityRowMapper implements
RowMapper<GroupCapacity> {
private static final class GroupCapacityRowMapper implements RowMapper<GroupCapacity> {
@Override
public GroupCapacity mapRow(ResultSet rs, int rowNum) throws SQLException {
GroupCapacity groupCapacity = new GroupCapacity();
@ -72,39 +74,36 @@ public class GroupCapacityPersistService {
return groupCapacity;
}
}
public GroupCapacity getGroupCapacity(String groupId) {
String sql
= "SELECT id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, group_id FROM group_capacity "
+ "WHERE group_id=?";
List<GroupCapacity> list = jdbcTemplate.query(sql, new Object[] {groupId},
GROUP_CAPACITY_ROW_MAPPER);
String sql =
"SELECT id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, group_id FROM group_capacity "
+ "WHERE group_id=?";
List<GroupCapacity> list = jdbcTemplate.query(sql, new Object[] {groupId}, GROUP_CAPACITY_ROW_MAPPER);
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
public Capacity getClusterCapacity() {
return getGroupCapacity(CLUSTER);
}
public boolean insertGroupCapacity(final GroupCapacity capacity) {
String sql;
if (CLUSTER.equals(capacity.getGroup())) {
sql
= "insert into group_capacity (group_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) select ?, ?, count(*), ?, ?, ?, ?, ? from config_info;";
sql = "insert into group_capacity (group_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) select ?, ?, count(*), ?, ?, ?, ?, ? from config_info;";
} else {
// 注意这里要加"tenant_id = ''"条件
sql =
"insert into group_capacity (group_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "
sql = "insert into group_capacity (group_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) select ?, ?, count(*), ?, ?, ?, ?, ? from config_info where "
+ "group_id=? and tenant_id = '';";
}
return insertGroupCapacity(sql, capacity);
}
public int getClusterUsage() {
Capacity clusterCapacity = getClusterCapacity();
if (clusterCapacity != null) {
@ -117,7 +116,7 @@ public class GroupCapacityPersistService {
}
return result.intValue();
}
private boolean insertGroupCapacity(final String sql, final GroupCapacity capacity) {
try {
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
@ -146,61 +145,57 @@ public class GroupCapacityPersistService {
throw e;
}
}
public boolean incrementUsageWithDefaultQuotaLimit(GroupCapacity groupCapacity) {
String sql =
"UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ? AND `usage` <"
+ " ? AND quota = 0";
"UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ? AND `usage` <"
+ " ? AND quota = 0";
try {
int affectRow = jdbcTemplate.update(sql,
groupCapacity.getGmtModified(), groupCapacity.getGroup(), groupCapacity.getQuota());
int affectRow = jdbcTemplate
.update(sql, groupCapacity.getGmtModified(), groupCapacity.getGroup(), groupCapacity.getQuota());
return affectRow == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean incrementUsageWithQuotaLimit(GroupCapacity groupCapacity) {
String sql
= "UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ? AND `usage` < "
+ "quota AND quota != 0";
String sql =
"UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ? AND `usage` < "
+ "quota AND quota != 0";
try {
return jdbcTemplate.update(sql,
groupCapacity.getGmtModified(), groupCapacity.getGroup()) == 1;
return jdbcTemplate.update(sql, groupCapacity.getGmtModified(), groupCapacity.getGroup()) == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean incrementUsage(GroupCapacity groupCapacity) {
String sql = "UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ?";
try {
int affectRow = jdbcTemplate.update(sql,
groupCapacity.getGmtModified(), groupCapacity.getGroup());
int affectRow = jdbcTemplate.update(sql, groupCapacity.getGmtModified(), groupCapacity.getGroup());
return affectRow == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean decrementUsage(GroupCapacity groupCapacity) {
String sql =
"UPDATE group_capacity SET `usage` = `usage` - 1, gmt_modified = ? WHERE group_id = ? AND `usage` > 0";
String sql = "UPDATE group_capacity SET `usage` = `usage` - 1, gmt_modified = ? WHERE group_id = ? AND `usage` > 0";
try {
return jdbcTemplate.update(sql,
groupCapacity.getGmtModified(), groupCapacity.getGroup()) == 1;
return jdbcTemplate.update(sql, groupCapacity.getGmtModified(), groupCapacity.getGroup()) == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean updateGroupCapacity(String group, Integer quota, Integer maxSize, Integer maxAggrCount,
Integer maxAggrSize) {
Integer maxAggrSize) {
List<Object> argList = Lists.newArrayList();
StringBuilder sql = new StringBuilder("update group_capacity set");
if (quota != null) {
@ -221,7 +216,7 @@ public class GroupCapacityPersistService {
}
sql.append(" gmt_modified = ?");
argList.add(TimeUtils.getCurrentTime());
sql.append(" where group_id = ?");
argList.add(group);
try {
@ -231,20 +226,20 @@ public class GroupCapacityPersistService {
throw e;
}
}
public boolean updateQuota(String group, Integer quota) {
return updateGroupCapacity(group, quota, null, null, null);
}
public boolean updateMaxSize(String group, Integer maxSize) {
return updateGroupCapacity(group, null, maxSize, null, null);
}
public boolean correctUsage(String group, Timestamp gmtModified) {
String sql;
if (CLUSTER.equals(group)) {
sql = "UPDATE group_capacity SET `usage` = (SELECT count(*) FROM config_info), gmt_modified = ? WHERE "
+ "group_id = ?";
+ "group_id = ?";
try {
return jdbcTemplate.update(sql, gmtModified, group) == 1;
} catch (CannotGetJdbcConnectionException e) {
@ -254,7 +249,7 @@ public class GroupCapacityPersistService {
} else {
// 注意这里要加"tenant_id = ''"条件
sql = "UPDATE group_capacity SET `usage` = (SELECT count(*) FROM config_info WHERE group_id=? AND "
+ "tenant_id = ''), gmt_modified = ? WHERE group_id = ?";
+ "tenant_id = ''), gmt_modified = ? WHERE group_id = ?";
try {
return jdbcTemplate.update(sql, group, gmtModified, group) == 1;
} catch (CannotGetJdbcConnectionException e) {
@ -263,7 +258,7 @@ public class GroupCapacityPersistService {
}
}
}
/**
* 获取GroupCapacity列表只有idgroupId有值
*
@ -273,34 +268,33 @@ public class GroupCapacityPersistService {
*/
public List<GroupCapacity> getCapacityList4CorrectUsage(long lastId, int pageSize) {
String sql = "SELECT id, group_id FROM group_capacity WHERE id>? LIMIT ?";
if (PropertyUtil.isEmbeddedStorage()) {
sql = "SELECT id, group_id FROM group_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY";
}
try {
return jdbcTemplate.query(sql, new Object[] {lastId, pageSize},
new RowMapper<GroupCapacity>() {
@Override
public GroupCapacity mapRow(ResultSet rs, int rowNum) throws SQLException {
GroupCapacity groupCapacity = new GroupCapacity();
groupCapacity.setId(rs.getLong("id"));
groupCapacity.setGroup(rs.getString("group_id"));
return groupCapacity;
}
});
return jdbcTemplate.query(sql, new Object[] {lastId, pageSize}, new RowMapper<GroupCapacity>() {
@Override
public GroupCapacity mapRow(ResultSet rs, int rowNum) throws SQLException {
GroupCapacity groupCapacity = new GroupCapacity();
groupCapacity.setId(rs.getLong("id"));
groupCapacity.setGroup(rs.getString("group_id"));
return groupCapacity;
}
});
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean deleteGroupCapacity(final String group) {
try {
PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(
"DELETE FROM group_capacity WHERE group_id = ?;");
PreparedStatement ps = connection
.prepareStatement("DELETE FROM group_capacity WHERE group_id = ?;");
ps.setString(1, group);
return ps;
}
@ -310,6 +304,6 @@ public class GroupCapacityPersistService {
fatalLog.error("[db-error]", e);
throw e;
}
}
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service.capacity;
import com.alibaba.nacos.config.server.model.capacity.TenantCapacity;
@ -42,21 +43,21 @@ import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
*/
@Service
public class TenantCapacityPersistService {
private static final TenantCapacityRowMapper
TENANT_CAPACITY_ROW_MAPPER = new TenantCapacityRowMapper();
private static final TenantCapacityRowMapper TENANT_CAPACITY_ROW_MAPPER = new TenantCapacityRowMapper();
private JdbcTemplate jdbcTemplate;
private DataSourceService dataSourceService;
@PostConstruct
public void init() {
this.dataSourceService = DynamicDataSource.getInstance().getDataSource();
this.jdbcTemplate = dataSourceService.getJdbcTemplate();
}
private static final class TenantCapacityRowMapper implements
RowMapper<TenantCapacity> {
private static final class TenantCapacityRowMapper implements RowMapper<TenantCapacity> {
@Override
public TenantCapacity mapRow(ResultSet rs, int rowNum) throws SQLException {
TenantCapacity tenantCapacity = new TenantCapacity();
@ -70,23 +71,22 @@ public class TenantCapacityPersistService {
return tenantCapacity;
}
}
public TenantCapacity getTenantCapacity(String tenantId) {
String sql
= "SELECT id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, tenant_id FROM tenant_capacity "
+ "WHERE tenant_id=?";
List<TenantCapacity> list = jdbcTemplate.query(sql, new Object[] {tenantId},
TENANT_CAPACITY_ROW_MAPPER);
String sql =
"SELECT id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, tenant_id FROM tenant_capacity "
+ "WHERE tenant_id=?";
List<TenantCapacity> list = jdbcTemplate.query(sql, new Object[] {tenantId}, TENANT_CAPACITY_ROW_MAPPER);
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
public boolean insertTenantCapacity(final TenantCapacity tenantCapacity) {
final String sql =
"INSERT INTO tenant_capacity (tenant_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;";
"INSERT INTO tenant_capacity (tenant_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "
+ "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info WHERE tenant_id=?;";
try {
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() {
@ -111,63 +111,59 @@ public class TenantCapacityPersistService {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean incrementUsageWithDefaultQuotaLimit(TenantCapacity tenantCapacity) {
String sql =
"UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE tenant_id = ? AND `usage` <"
+ " ? AND quota = 0";
"UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE tenant_id = ? AND `usage` <"
+ " ? AND quota = 0";
try {
int affectRow = jdbcTemplate.update(sql,
tenantCapacity.getGmtModified(), tenantCapacity.getTenant(), tenantCapacity.getQuota());
int affectRow = jdbcTemplate.update(sql, tenantCapacity.getGmtModified(), tenantCapacity.getTenant(),
tenantCapacity.getQuota());
return affectRow == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean incrementUsageWithQuotaLimit(TenantCapacity tenantCapacity) {
String sql
= "UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE tenant_id = ? AND `usage` < "
+ "quota AND quota != 0";
String sql =
"UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE tenant_id = ? AND `usage` < "
+ "quota AND quota != 0";
try {
return jdbcTemplate.update(sql,
tenantCapacity.getGmtModified(), tenantCapacity.getTenant()) == 1;
return jdbcTemplate.update(sql, tenantCapacity.getGmtModified(), tenantCapacity.getTenant()) == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean incrementUsage(TenantCapacity tenantCapacity) {
String sql = "UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE tenant_id = ?";
try {
int affectRow = jdbcTemplate.update(sql,
tenantCapacity.getGmtModified(), tenantCapacity.getTenant());
int affectRow = jdbcTemplate.update(sql, tenantCapacity.getGmtModified(), tenantCapacity.getTenant());
return affectRow == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean decrementUsage(TenantCapacity tenantCapacity) {
String sql =
"UPDATE tenant_capacity SET `usage` = `usage` - 1, gmt_modified = ? WHERE tenant_id = ? AND `usage` > 0";
String sql = "UPDATE tenant_capacity SET `usage` = `usage` - 1, gmt_modified = ? WHERE tenant_id = ? AND `usage` > 0";
try {
return jdbcTemplate.update(sql,
tenantCapacity.getGmtModified(), tenantCapacity.getTenant()) == 1;
return jdbcTemplate.update(sql, tenantCapacity.getGmtModified(), tenantCapacity.getTenant()) == 1;
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean updateTenantCapacity(String tenant, Integer quota, Integer maxSize, Integer maxAggrCount,
Integer maxAggrSize) {
Integer maxAggrSize) {
List<Object> argList = Lists.newArrayList();
StringBuilder sql = new StringBuilder("update tenant_capacity set");
if (quota != null) {
@ -188,7 +184,7 @@ public class TenantCapacityPersistService {
}
sql.append(" gmt_modified = ?");
argList.add(TimeUtils.getCurrentTime());
sql.append(" where tenant_id = ?");
argList.add(tenant);
try {
@ -198,14 +194,14 @@ public class TenantCapacityPersistService {
throw e;
}
}
public boolean updateQuota(String tenant, Integer quota) {
return updateTenantCapacity(tenant, quota, null, null, null);
}
public boolean correctUsage(String tenant, Timestamp gmtModified) {
String sql = "UPDATE tenant_capacity SET `usage` = (SELECT count(*) FROM config_info WHERE tenant_id = ?), "
+ "gmt_modified = ? WHERE tenant_id = ?";
+ "gmt_modified = ? WHERE tenant_id = ?";
try {
return jdbcTemplate.update(sql, tenant, gmtModified, tenant) == 1;
} catch (CannotGetJdbcConnectionException e) {
@ -213,7 +209,7 @@ public class TenantCapacityPersistService {
throw e;
}
}
/**
* 获取TenantCapacity列表只有idtenantId有值
*
@ -223,35 +219,34 @@ public class TenantCapacityPersistService {
*/
public List<TenantCapacity> getCapacityList4CorrectUsage(long lastId, int pageSize) {
String sql = "SELECT id, tenant_id FROM tenant_capacity WHERE id>? LIMIT ?";
if (PropertyUtil.isEmbeddedStorage()) {
sql = "SELECT id, tenant_id FROM tenant_capacity WHERE id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY";
}
try {
return jdbcTemplate.query(sql, new Object[] {lastId, pageSize},
new RowMapper<TenantCapacity>() {
@Override
public TenantCapacity mapRow(ResultSet rs, int rowNum) throws SQLException {
TenantCapacity tenantCapacity = new TenantCapacity();
tenantCapacity.setId(rs.getLong("id"));
tenantCapacity.setTenant(rs.getString("tenant_id"));
return tenantCapacity;
}
});
return jdbcTemplate.query(sql, new Object[] {lastId, pageSize}, new RowMapper<TenantCapacity>() {
@Override
public TenantCapacity mapRow(ResultSet rs, int rowNum) throws SQLException {
TenantCapacity tenantCapacity = new TenantCapacity();
tenantCapacity.setId(rs.getLong("id"));
tenantCapacity.setTenant(rs.getString("tenant_id"));
return tenantCapacity;
}
});
} catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error]", e);
throw e;
}
}
public boolean deleteTenantCapacity(final String tenant) {
try {
PreparedStatementCreator preparedStatementCreator = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(
"DELETE FROM tenant_capacity WHERE tenant_id = ?;");
PreparedStatement ps = connection
.prepareStatement("DELETE FROM tenant_capacity WHERE tenant_id = ?;");
ps.setString(1, tenant);
return ps;
}

View File

@ -13,9 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.service.datasource;
import java.io.IOException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;
@ -25,54 +27,54 @@ import org.springframework.transaction.support.TransactionTemplate;
* @author Nacos
*/
public interface DataSourceService {
/**
* Initialize the relevant resource information
*
* @throws Exception
*/
void init() throws Exception;
/**
* reload
*
* @throws IOException exception
*/
void reload() throws IOException;
/**
* check master db
*
* @return is master
*/
boolean checkMasterWritable();
/**
* get jdbc template
*
* @return JdbcTemplate
*/
JdbcTemplate getJdbcTemplate();
/**
* get transaction template
*
* @return TransactionTemplate
*/
TransactionTemplate getTransactionTemplate();
/**
* get current db url
*
* @return
*/
String getCurrentDBUrl();
/**
* get heath
*
* @return heath info
*/
String getHealth();
}

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