proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppClientCostTimeTotalStat.java
AppClientCostTimeTotalStat
getFromAppClientCostTimeStat
class AppClientCostTimeTotalStat { private long id; /** * 应用id */ private long appId; /** * 格式yyyyMMddHHmm00 */ private long collectTime; /** * 创建时间 */ private Date createTime; /** * 命令 */ private String command; /** * 调用总次数 */ private long totalCount; /** * 调用总耗时 */ private double totalCost; /** * 中位值 */ private int median; /** * 平均值 */ private double mean; /** * 90%最大值 */ private int ninetyPercentMax; /** * 99%最大值 */ private int ninetyNinePercentMax; /** * 100%最大值 */ private int hundredMax; /** * 实例ip */ private String maxInstanceHost; /** * 实例port */ private int maxInstancePort; /** * 实例id */ private long maxInstanceId; /** * 客户端 */ private String maxClientIp; public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public AppClientCostTimeTotalStat(long id, long appId, long collectTime, Date createTime, String command, long totalCount, double totalCost, int median, double mean, int ninetyPercentMax, int ninetyNinePercentMax, int hundredMax, String maxInstanceHost, int maxInstancePort, long maxInstanceId, String maxClientIp) { this.id = id; this.appId = appId; this.collectTime = collectTime; this.createTime = createTime; this.command = command; this.totalCount = totalCount; this.totalCost = totalCost; this.median = median; this.mean = mean; this.ninetyPercentMax = ninetyPercentMax; this.ninetyNinePercentMax = ninetyNinePercentMax; this.hundredMax = hundredMax; this.maxInstanceHost = maxInstanceHost; this.maxInstancePort = maxInstancePort; this.maxInstanceId = maxInstanceId; this.maxClientIp = maxClientIp; } public AppClientCostTimeTotalStat() { } public Long getTimeStamp() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); try { Date date = sdf.parse(String.valueOf(this.collectTime)); return date.getTime(); } catch (ParseException e) { return 0L; } } public static AppClientCostTimeTotalStat getFromAppClientCostTimeStat(AppClientCostTimeStat stat) {<FILL_FUNCTION_BODY>} }
AppClientCostTimeTotalStat appClientCostTimeTotalStat = new AppClientCostTimeTotalStat(); appClientCostTimeTotalStat.setAppId(stat.getAppId()); appClientCostTimeTotalStat.setCollectTime(stat.getCollectTime()); appClientCostTimeTotalStat.setCommand(stat.getCommand()); appClientCostTimeTotalStat.setCreateTime(stat.getCreateTime()); appClientCostTimeTotalStat.setMean(stat.getMean()); appClientCostTimeTotalStat.setMedian(stat.getMedian()); appClientCostTimeTotalStat.setHundredMax(stat.getHundredMax()); appClientCostTimeTotalStat.setNinetyPercentMax(stat.getNinetyPercentMax()); appClientCostTimeTotalStat.setNinetyNinePercentMax(stat.getNinetyNinePercentMax()); appClientCostTimeTotalStat.setMaxClientIp(stat.getClientIp()); appClientCostTimeTotalStat.setMaxInstanceHost(stat.getInstanceHost()); appClientCostTimeTotalStat.setMaxInstancePort(stat.getInstancePort()); appClientCostTimeTotalStat.setMaxInstanceId(stat.getInstanceId()); appClientCostTimeTotalStat.setMaxClientIp(stat.getClientIp()); //保留两位小数 DecimalFormat df = new DecimalFormat("#.00"); appClientCostTimeTotalStat.setTotalCost(NumberUtils.toDouble(df.format(stat.getMean() * stat.getCount()))); appClientCostTimeTotalStat.setTotalCount(stat.getCount()); return appClientCostTimeTotalStat;
965
427
1,392
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppClientExceptionStat.java
AppClientExceptionStat
getCollectTimeFormat
class AppClientExceptionStat { private long id; /** * 应用id */ private long appId; /** * 格式yyyyMMddHHmm00 */ private long collectTime; /** * 客户端ip */ private String clientIp; /** * 上报时间 */ private Date reportTime; /** * 创建时间 */ private Date createTime; /** * 异常类 */ private String exceptionClass; /** * 异常数 */ private Long exceptionCount; /** * 实例ip */ private String instanceHost; /** * 实例port */ private Integer instancePort; /** * 实例id */ private Integer instanceId; /** * 异常类型,参考ClientExceptionType.type */ private Integer type; public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public Date getReportTime() { return (Date) reportTime.clone(); } public void setReportTime(Date reportTime) { this.reportTime = (Date) reportTime.clone(); } public String getCollectTimeFormat(){<FILL_FUNCTION_BODY>} }
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); try { Date date = sdf.parse(String.valueOf(collectTime)); SimpleDateFormat newSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return newSdf.format(date); } catch (ParseException e) { return ""; }
473
110
583
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppCommandStats.java
AppCommandStats
compareTo
class AppCommandStats implements Comparable<AppCommandStats> { /** * 应用id */ private long appId; /** * 收集时间:格式yyyyMMddHHmm/yyyyMMdd/yyyyMMddHH */ private long collectTime; /** * 命令名称 */ private String commandName; /** * 命令执行次数 */ private long commandCount; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date modifyTime; @Override public int compareTo(AppCommandStats o) {<FILL_FUNCTION_BODY>} public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public Date getModifyTime() { return (Date) modifyTime.clone(); } public void setModifyTime(Date modifyTime) { this.modifyTime = (Date) modifyTime.clone(); } }
if (o.commandCount > this.commandCount) { return 1; } else if (o.commandCount < this.commandCount) { return -1; } return 0;
357
63
420
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppDailyData.java
AppDailyData
getValueSizeDistributeCountDesc
class AppDailyData { /** * 应用id */ private long appId; /** * 开始日期 */ private Date startDate; /** * 结束日期 */ private Date endDate; /** * 日期 */ private Date date; /** * bigkey次数 */ private long bigKeyTimes; /** * bigkey信息 */ private String bigKeyInfo; /** * 慢查询次数 */ private long slowLogCount; /** * 延迟事件个数 */ private long latencyCount; /** * 客户端异常个数 */ private long clientExceptionCount; /** * 累计命令调用次数 */ private long clientCmdCount; /** * 平均命令调用耗时 */ private double clientAvgCmdCost; /** * 累计连接异常事件次数 */ private long clientConnExpCount; /** * 平均连接异常事件耗时 */ private double clientAvgConnExpCost; /** * 累计命令超时事件次数 */ private long clientCmdExpCount; /** * 平均命令超时事件耗时 */ private double clientAvgCmdExpCost; /** * 每分钟最大客户端连接数 */ private long maxMinuteClientCount; /** * 每分钟平均客户端连接数 */ private long avgMinuteClientCount; /** * 每分钟最大命令数 */ private long maxMinuteCommandCount; /** * 每分钟平均命令数 */ private long avgMinuteCommandCount; /** * 平均命中率 */ private double avgHitRatio; /** * 每分钟最小命中率 */ private double minMinuteHitRatio; /** * 每分钟最大命中率 */ private double maxMinuteHitRatio; /** * 平均内存使用量 */ private long avgUsedMemory; /** * 最大内存使用量 */ private long maxUsedMemory; /** * 过期键个数 */ private long expiredKeysCount; /** * 剔除键个数 */ private long evictedKeysCount; /** * 每分钟平均网络input量 */ private double avgMinuteNetInputByte; /** * 每分钟最大网络input量 */ private double maxMinuteNetInputByte; /** * 每分钟平均网络output量 */ private double avgMinuteNetOutputByte; /** * 每分钟最大网络output量 */ private double maxMinuteNetOutputByte; /** * 键个数平均值 */ private long avgObjectSize; /** * 键个数最大值 */ private long maxObjectSize; /** * 值分布 */ private Map<String, Long> valueSizeDistributeCountMap; /** * 应用详情 */ private AppDetailVO appDetailVO; public String getValueSizeDistributeCountDesc() {<FILL_FUNCTION_BODY>} public String getValueSizeDistributeCountDescHtml() { return bigKeyInfo.replace("\n", "<br/>").replace(":", ":\t"); } }
if (MapUtils.isEmpty(valueSizeDistributeCountMap)) { return "无"; } StringBuffer desc = new StringBuffer(); for (Map.Entry<String, Long> entry : valueSizeDistributeCountMap.entrySet()) { desc.append(entry.getKey()).append(":").append(entry.getValue()).append("次<br/>"); } return desc.toString();
945
103
1,048
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppInstanceClientRelation.java
AppInstanceClientRelation
generateFromAppClientCostTimeStat
class AppInstanceClientRelation { /** * 应用id */ private long appId; /** * 客户端ip */ private String clientIp; /** * 节点ip */ private String instanceHost; /** * 节点端口 */ private int instancePort; /** * 节点端口 */ private long instanceId; /** * 日期 */ private Date day; public AppInstanceClientRelation(long appId, String clientIp, String instanceHost, int instancePort, long instanceId, Date day) { this.appId = appId; this.clientIp = clientIp; this.instanceHost = instanceHost; this.instancePort = instancePort; this.instanceId = instanceId; this.day = day; } public AppInstanceClientRelation() { } public static AppInstanceClientRelation generateFromAppClientCostTimeStat( AppClientCostTimeStat appClientCostTimeStat) {<FILL_FUNCTION_BODY>} public Date getDay() { return (Date) day.clone(); } public void setDay(Date day) { this.day = (Date) day.clone(); } }
if (appClientCostTimeStat == null) { return null; } else { return new AppInstanceClientRelation(appClientCostTimeStat.getAppId(), appClientCostTimeStat.getClientIp(), appClientCostTimeStat.getInstanceHost(), appClientCostTimeStat .getInstancePort(), appClientCostTimeStat.getInstanceId(), new Date( System.currentTimeMillis())); }
399
112
511
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppStats.java
AppStats
getHitPercent
class AppStats { /** * 应用id */ private long appId; /** * 收集时间:格式yyyyMMddHHmm/yyyyMMdd/yyyyMMddHH */ private long collectTime; /** * 命中数量 */ private long hits; /** * 未命中数量 */ private long misses; /** * 命令执行次数 */ private long commandCount; /** * 内存占用 */ private long usedMemory; /** * 物理内存占用 */ private long usedMemoryRss; /** * 过期key数量 */ private long expiredKeys; /** * 驱逐key数量 */ private long evictedKeys; /** * 网络输入字节 */ private long netInputByte; /** * 网络输出字节 */ private long netOutputByte; /** * 客户端连接数 */ private int connectedClients; /** * 存储对象数 */ private long objectSize; /** * 进程系统态消耗(单位:秒) */ private long cpuSys; /** * 进程用户态消耗(单位:秒) */ private long cpuUser; /** * 子进程内核态消耗(单位:秒) */ private long cpuSysChildren; /** * 子进程用户态消耗(单位:秒) */ private long cpuUserChildren; /** * 累加的实例数 */ private int accumulation; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date modifyTime; /** * 命令统计集合 */ private List<AppCommandStats> commandStatsList; /** * 命中率 * * @return */ public long getHitPercent() {<FILL_FUNCTION_BODY>} public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public Date getModifyTime() { return (Date) modifyTime.clone(); } public void setModifyTime(Date modifyTime) { this.modifyTime = (Date) modifyTime.clone(); } }
long total = hits + misses; if (total == 0) { return 0; } else { NumberFormat formatter = new DecimalFormat("0"); return NumberUtils.toLong(formatter.format(hits * 100.0 / total)); }
823
84
907
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/AppUser.java
AppUser
buildFrom
class AppUser implements Serializable { private static final long serialVersionUID = 7425158151337667662L; /** * 自增id */ @ApiModelProperty(value = "用户id",hidden = true) private Long id; /** * 用户名(英文,域账户) */ @ApiModelProperty(value = "用户名(英文,域账户)",required = true) private String name; /** * 密码 */ @ApiModelProperty(value = "密码") private String password; /** * 中文名 */ @ApiModelProperty(value = "中文名",required = true) private String chName; /** * 用户域账户邮箱 */ @ApiModelProperty(value = "用户域账户邮箱",required = true) private String email; /** * 用户手机 */ @ApiModelProperty(value = "用户手机",required = true) private String mobile; /** * 用户微信号 */ @ApiModelProperty(value = "用户微信号",required = true) private String weChat; /** * 用户类型(类型参考AppUserTypeEnum) */ @ApiModelProperty(value = "用户类型",hidden = true) private int type; /** * 是否接收报警 */ @ApiModelProperty(value = "是否接收报警 0:不接收报警 1:接收报警",hidden = true) private int isAlert; /** * 公司名 */ @ApiModelProperty(value = "公司名") private String company; /** * 目的 */ @ApiModelProperty(value = "目的") private String purpose; /** * 注册时间 */ @ApiModelProperty(value = "注册时间") private Date registerTime; public static AppUser buildFrom(Long userId, String name, String chName, String email, String mobile, String weChat, Integer type) { AppUser appUser = new AppUser(); appUser.setId(userId); appUser.setName(name); appUser.setChName(chName); appUser.setEmail(email); appUser.setMobile(mobile); appUser.setWeChat(weChat); appUser.setType(type); return appUser; } public static AppUser buildFrom(Long userId, String name, String chName, String email, String mobile, String weChat, Integer type,Integer isAlert) { AppUser appUser = new AppUser(); appUser.setId(userId); appUser.setName(name); appUser.setChName(chName); appUser.setEmail(email); appUser.setMobile(mobile); appUser.setWeChat(weChat); appUser.setType(type); appUser.setIsAlert(isAlert); return appUser; } public static AppUser buildFrom(Long userId, String name, String chName, String email, String mobile, String weChat, Integer type,Integer isAlert, String company, String purpose) {<FILL_FUNCTION_BODY>} public static AppUser buildFrom(Long userId, String name, String chName, String email, String mobile, String weChat, Integer type,Integer isAlert, String password, String company, String purpose) { AppUser appUser = new AppUser(); appUser.setId(userId); appUser.setName(name); appUser.setChName(chName); appUser.setEmail(email); appUser.setMobile(mobile); appUser.setWeChat(weChat); appUser.setType(type); appUser.setIsAlert(isAlert); appUser.setPassword(password); appUser.setCompany(company); appUser.setPurpose(purpose); return appUser; } public AppUser() { } public AppUser(String name, String chName, String email, String mobile, String weChat, int type) { this.name = name; this.chName = chName; this.email = email; this.mobile = mobile; this.weChat = weChat; this.type = type; } public AppUser(String name, String chName, String email, String mobile, String weChat, int type, int isAlert) { this.name = name; this.chName = chName; this.email = email; this.mobile = mobile; this.weChat = weChat; this.type = type; this.isAlert = isAlert; } }
AppUser appUser = new AppUser(); appUser.setId(userId); appUser.setName(name); appUser.setChName(chName); appUser.setEmail(email); appUser.setMobile(mobile); appUser.setWeChat(weChat); appUser.setType(type); appUser.setIsAlert(isAlert); appUser.setCompany(company); appUser.setPurpose(purpose); return appUser;
1,388
144
1,532
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/DeployInfo.java
DeployInfo
isSentinelNode
class DeployInfo { /** * 部署形态: 参考 ConstUtils * 2: Redis Cluster * 5: Redis+Sentinel * 7: Redis+Twemproxy * 8: Pika+Sentinel * 9: Pika+Twemproxy * 6: Redis Standalone */ private Integer deployType; /** * 分配内存大小,单位M */ private Integer memSize; /** * Redis node */ private String masterIp; private String slaveIp; /** * Pika node */ private String masterPikaIp; private String slavePikaIp; /** * sentinel/twemproxy node */ private String sentinelIp; private String twemproxyIp; public DeployInfo() { } public DeployInfo(Integer deployType, String masterIp, Integer memSize) { this.deployType = deployType; this.masterIp = masterIp; this.memSize = memSize; } public DeployInfo(Integer deployType, String masterIp, Integer memSize, String slaveIp) { this.deployType = deployType; this.masterIp = masterIp; this.memSize = memSize; this.slaveIp = slaveIp; } public DeployInfo(Integer deployType, String sentinelIp) { this.deployType = deployType; this.sentinelIp = sentinelIp; } /** * 获取Redis实例信息 */ public static DeployInfo getRedisInfo(Integer deployType, String masterIp, Integer memSize, String slaveIp) { DeployInfo deployInfo = new DeployInfo(); deployInfo.setDeployType(deployType); deployInfo.setMasterIp(masterIp); deployInfo.setMemSize(memSize); deployInfo.setSlaveIp(slaveIp); return deployInfo; } /** * 获取Pika实例信息 */ public static DeployInfo getPikaInfo(Integer deployType, String masterPikaIp, Integer memSize, String slavePikaIp) { DeployInfo deployInfo = new DeployInfo(); deployInfo.setDeployType(deployType); deployInfo.setMasterPikaIp(masterPikaIp); deployInfo.setMemSize(memSize); deployInfo.setSlavePikaIp(slavePikaIp); return deployInfo; } /** * 获取Sentinel实例信息 */ public static DeployInfo getSentinelInfo(Integer deployType, String sentinelIp) { DeployInfo deployInfo = new DeployInfo(); deployInfo.setDeployType(deployType); deployInfo.setSentinelIp(sentinelIp); return deployInfo; } /** * 获取Twemproxy实例信息 */ public static DeployInfo getTwemproxyInfo(Integer deployType, String twemproxyIp) { DeployInfo deployInfo = new DeployInfo(); deployInfo.setDeployType(deployType); deployInfo.setTwemproxyIp(twemproxyIp); return deployInfo; } /** * 判断是否Redis/Pika节点 */ public static Boolean isRedisNode(int type){ if(type == NodeEnum.REDIS_NODE.getValue()){ return true; } return false; } /** * 判断是否Sentinel/Twemproxy节点 */ public static Boolean isSentinelNode(int type){<FILL_FUNCTION_BODY>} }
if(type == NodeEnum.SENTINEL_NODE.getValue() ){ return true; } return false;
987
36
1,023
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/InstanceAlertConfig.java
InstanceAlertConfig
getCheckCycleMillionTime
class InstanceAlertConfig { /** * 自增id */ private long id; /** * 报警配置 */ private String alertConfig; /** * 报警阀值 */ private String alertValue; /** * 详见CompareTypeEnumNew */ private int compareType; /** * 配置说明 */ private String configInfo; /** * 详见TypeEnum */ private int type; /** * -1全局配置,其他代表实例id */ private long instanceId; /** * 实例信息 */ private InstanceInfo instanceInfo; /** * 相关StatusEnum */ private int status; /** * 详见CheckCycleEnum */ private int checkCycle; /** * 配置更新时间 */ private Date updateTime; /** * 上次检测时间 */ private Date lastCheckTime; /** * 重要度(参照ImportantLevelTypeEnum)(0:一般;1:重要;2:紧急) */ private Integer importantLevel; public Date getUpdateTime() { return (Date) updateTime.clone(); } public void setUpdateTime(Date updateTime) { this.updateTime = (Date) updateTime.clone(); } public Date getLastCheckTime() { return (Date) lastCheckTime.clone(); } public void setLastCheckTime(Date lastCheckTime) { this.lastCheckTime = (Date) lastCheckTime.clone(); } public String getCompareInfo() { return InstanceAlertCompareTypeEnum.getInstanceAlertCompareTypeEnum(compareType).getInfo(); } public Long getCheckCycleMillionTime() {<FILL_FUNCTION_BODY>} public boolean isSpecail() { return instanceId > 0 && (type == InstanceAlertTypeEnum.INSTANCE_ALERT.getValue() || type == InstanceAlertTypeEnum.APP_ALERT.getValue()); } @Override public String toString() { return JSONObject.toJSONString(this); } }
if (InstanceAlertCheckCycleEnum.ONE_MINUTE.getValue() == checkCycle) { return TimeUnit.MINUTES.toMillis(1); } else if (InstanceAlertCheckCycleEnum.FIVE_MINUTE.getValue() == checkCycle) { return TimeUnit.MINUTES.toMillis(5); } else if (InstanceAlertCheckCycleEnum.HALF_HOUR.getValue() == checkCycle) { return TimeUnit.MINUTES.toMillis(30); } else if (InstanceAlertCheckCycleEnum.ONE_HOUR.getValue() == checkCycle) { return TimeUnit.MINUTES.toMillis(60); } else if (InstanceAlertCheckCycleEnum.ONE_DAY.getValue() == checkCycle) { return TimeUnit.DAYS.toMillis(1); } return null;
700
241
941
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/InstanceCommandStats.java
InstanceCommandStats
compareTo
class InstanceCommandStats implements Comparable<InstanceCommandStats> { /** * 应用id */ private long instanceId; /** * 收集时间:格式yyyyMMddHHmm/yyyyMMdd/yyyyMMddHH */ private long collectTime; /** * 命令名称 */ private String commandName; /** * 命令执行次数 */ private long commandCount; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date modifyTime; @Override public int compareTo(InstanceCommandStats o) {<FILL_FUNCTION_BODY>} public Long getTimeStamp() throws ParseException{ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm"); Date date = sdf.parse(String.valueOf(this.collectTime)); return date.getTime(); } public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public Date getModifyTime() { return (Date) modifyTime.clone(); } public void setModifyTime(Date modifyTime) { this.modifyTime = (Date) modifyTime.clone(); } }
if (o.commandCount > this.commandCount) { return 1; } else if (o.commandCount < this.commandCount) { return -1; } return 0;
433
63
496
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/InstanceConfig.java
InstanceConfig
getStatusDesc
class InstanceConfig { private long id; /** * 配置名:为了防止与key冲突 */ private String configKey; /** * 配置值:为了防止与value冲突 */ private String configValue; /** * 配置说明 */ private String info; /** * 更新时间 */ private Date updateTime; /** * Redis类型(参考ConstUtil) */ private int type; /** * 状态,1有效0无效 */ private int status; /** * 配置项绑定redis版本主键id */ private int versionId; public String getStatusDesc() {<FILL_FUNCTION_BODY>} public boolean isEffective() { if (1 == getStatus()) { return true; } return false; } public Date getUpdateTime() { return (Date) updateTime.clone(); } public void setUpdateTime(Date updateTime) { this.updateTime = (Date) updateTime.clone(); } }
if (1 == status) { return "有效"; } else if (0 == status) { return "无效"; } else { return ""; }
358
56
414
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/InstanceInfo.java
InstanceInfo
setRoleDesc
class InstanceInfo implements Serializable { private static final long serialVersionUID = -903896025243493024L; /** * 实例id */ private int id; /** * 应用id */ private long appId; /** * host id */ private long hostId; /** * ip */ private String ip; /** * 端口 */ private int port; /** * 是否启用 0:节点异常,1:正常启用,2:节点下线 */ private int status; /** * 开启的内存 */ private int mem; /** * 连接数 */ private int conn; /** * 启动命令 或者 redis-sentinel的masterName */ private String cmd; private int type; private String typeDesc; private int masterInstanceId; private String masterHost; private int masterPort; private String roleDesc; private int groupId; private Date updateTime; private List<Module> modules; public String getTypeDesc() { if (type <= 0) { typeDesc = ""; } else if (type == ConstUtils.CACHE_TYPE_REDIS_CLUSTER) { typeDesc = "redis-cluster"; } else if (type == ConstUtils.CACHE_REDIS_SENTINEL) { typeDesc = "redis-sentinel"; } else if (type == ConstUtils.CACHE_REDIS_STANDALONE) { typeDesc = "redis-standalone"; } return typeDesc; } public String getStatusDesc() { InstanceStatusEnum instanceStatusEnum = InstanceStatusEnum.getByStatus(status); if (instanceStatusEnum != null) { return instanceStatusEnum.getInfo(); } return ""; } /** * 判断当前节点是否下线 * * @return */ public boolean isOffline() { return status == InstanceStatusEnum.OFFLINE_STATUS.getStatus() || status == InstanceStatusEnum.FORGET_STATUS.getStatus(); } /** * 判断当前节点是否在线 */ public boolean isOnline() { return status == InstanceStatusEnum.GOOD_STATUS.getStatus(); } public String getRoleDesc() { if (type == ConstUtils.CACHE_REDIS_SENTINEL) { return "sentinel"; } else { return roleDesc; } } public void setRoleDesc(BooleanEnum isMaster) {<FILL_FUNCTION_BODY>} public String getHostPort() { return ip + ":" + port; } public boolean isMemcached() { return InstanceInfoEnum.InstanceTypeEnum.MEMCACHE.getType() == type; } public boolean isNutCracker() { return InstanceInfoEnum.InstanceTypeEnum.NUTCRACKER.getType() == type; } public boolean isPika() { return InstanceInfoEnum.InstanceTypeEnum.PIKA.getType() == type; } /** * 是否是redis数据节点 * * @return */ public boolean isRedisData() { if (type == InstanceInfoEnum.InstanceTypeEnum.REDIS_SERVER.getType() || type == InstanceInfoEnum.InstanceTypeEnum.REDIS_CLUSTER.getType()) { return true; } return false; } public Date getUpdateTime() { if(updateTime != null){ return (Date) updateTime.clone(); } return null; } public String getUpdateTimeDesc() { if(updateTime != null){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format((Date) updateTime.clone()); } else { return ""; } } public void setUpdateTime(Date updateTime) { this.updateTime = (Date) updateTime.clone(); } }
if (isMaster == BooleanEnum.OTHER) { roleDesc = "未知"; } else if (isMaster == BooleanEnum.TRUE) { roleDesc = "master"; } else if (isMaster == BooleanEnum.FALSE) { roleDesc = "slave"; }
1,087
75
1,162
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/InstanceSlowLog.java
InstanceSlowLog
getCommand
class InstanceSlowLog { private long id; /** * 实例id */ private long instanceId; /** * app id */ private long appId; /** * ip地址 */ private String ip; /** * port */ private int port; /** * 慢查询日志id */ private long slowLogId; /** * 耗时 */ private int costTime; /** * 命令 */ private String command; /** * 记录创建时间 */ private Timestamp createTime; /** * 慢查询发生时间 */ private Timestamp executeTime; public String getCommand() {<FILL_FUNCTION_BODY>} public Timestamp getCreateTime() { return (Timestamp) createTime.clone(); } public void setCreateTime(Timestamp createTime) { this.createTime = (Timestamp) createTime.clone(); } public Timestamp getExecuteTime() { return (Timestamp) executeTime.clone(); } public void setExecuteTime(Timestamp executeTime) { this.executeTime = (Timestamp) executeTime.clone(); } }
int maxLength = 30; if (StringUtils.isNotBlank(command) && command.length() > maxLength) { return command.substring(0, maxLength) + "..."; } return command;
403
67
470
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/InstanceStats.java
InstanceStats
getHitPercent
class InstanceStats { /* id */ private long id; /* 实例id */ private long instId; /* app id */ private long appId; /* host id */ private long hostId; /* ip地址 */ private String ip; /* port */ private int port; /* 主从,1主2从 */ private byte role; /* 启用实例时设置的内存,单位:byte */ private long maxMemory; /* 实例当前已用的内存,单位:byte */ private long usedMemory; /* * 实例内存使用率 */ private double memUsePercent; /* 当前的item数 */ private long currItems; /* 当前的连接数 */ private int currConnections; /* 未命中数*/ private long misses; /* 命中数 */ private long hits; /* 开始收集时间 */ private Timestamp createTime; /* 最后更新时间 */ private Timestamp modifyTime; /** * 内存碎片率 */ private double memFragmentationRatio; /** * aof阻塞次数 */ private int aofDelayedFsync; private boolean isRun; /** * 实例相关全部统计指标 */ private Map<String,Object> infoMap; public double getMemUsePercent() { if(maxMemory<=0){ return 0.0D; } double percent = 100 * (double) usedMemory / (maxMemory); DecimalFormat df = new DecimalFormat("##.##"); return Double.parseDouble(df.format(percent)); } /** * 命中率 * @return */ public String getHitPercent(){<FILL_FUNCTION_BODY>} public Timestamp getCreateTime() { if(createTime != null){ return (Timestamp) createTime.clone(); } return null; } public void setCreateTime(Timestamp createTime) { this.createTime = (Timestamp) createTime.clone(); } public Timestamp getModifyTime() { return (Timestamp) modifyTime.clone(); } public void setModifyTime(Timestamp modifyTime) { this.modifyTime = (Timestamp) modifyTime.clone(); } }
long totalHits = hits + misses; if (totalHits <= 0) { return "无命令执行"; } double percent = 100 * (double) hits / totalHits; DecimalFormat df = new DecimalFormat("##.##"); return df.format(percent) + "%";
744
95
839
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/MachineInfo.java
MachineInfo
getModifyTime
class MachineInfo { /** * 机器id */ @ApiModelProperty(hidden = true) private long id; /** * ssh用户名 */ @ApiModelProperty(hidden = true) private String sshUser; /** * ssh密码 */ @ApiModelProperty(hidden = true) private String sshPasswd; /** * ip地址 */ @ApiModelProperty(value = "机器ip", required = true) private String ip; /** * 机房 */ @ApiModelProperty(hidden = true) private String room; /** * 内存,单位G */ @ApiModelProperty(value = "内存,单位G", required = true) private int mem; /** * cpu数量 */ @ApiModelProperty(value = "cpu核数", required = true) private int cpu; /** * 磁盘空间, 单位G */ @ApiModelProperty(value = "磁盘空间",required = true) private int disk; /** * 是否虚机,0否,1是 */ @ApiModelProperty(value = "是否虚拟机", required = true) private int virtual; /** * 宿主机ip */ @ApiModelProperty(value = "宿主机ip(虚机需要填写)", required = true) private String realIp; /** * 上线时间 */ @ApiModelProperty(hidden = true) private Date serviceTime; /** * 故障次数 */ @ApiModelProperty(hidden = true) private int faultCount; /** * 修改时间 */ @ApiModelProperty(hidden = true) private Date modifyTime; /** * 是否启用报警,0否,1是 */ @ApiModelProperty(hidden = true) private int warn; /** * 是否可用,MachineInfoEnum.AvailableEnum */ @ApiModelProperty(hidden = true) private int available; /** * 机器类型:详见MachineInfoEnum.TypeEnum */ @ApiModelProperty(hidden = true) private int type; /** * 机器类型:详见MachineInfoEnum.DisTypeEnum */ @ApiModelProperty(hidden = true) private int disType; /** * groupId */ @ApiModelProperty(hidden = true) private int groupId; /** * 额外说明:(例如本机器有其他web或者其他服务) */ @ApiModelProperty(value = "备注说明") private String extraDesc; @ApiModelProperty(value = "如是专用机器,请填写项目名称") private String projectName; /** * 是否收集服务器信息,0否,1是 */ @ApiModelProperty(hidden = true) private int collect; /** * redis版本安装情况 版本号#安装标识 -1:获取安装信息异常 0:未安装 1:安装成功 */ @ApiModelProperty(hidden = true) private String versionInstall; /** * 使用类型:Redis专用机器(0),Redis测试机器(1),混合部署机器(2) */ @ApiModelProperty(value = "使用类型:Redis专用机器(0),Redis测试机器(1),混合部署机器(2),Redis sentienl部署(3)", required = true) private int useType; @ApiModelProperty(value = "机器是否分配,1是0否") private int isAllocating; /** * 是否k8s容器:0:不是 1:是 */ @ApiModelProperty(value = "是否k8s容器:0:不是 1:是", required = false) private int k8sType; @ApiModelProperty(value = "pod变更时间,单位 ms", required = false) private long podUpdateTime; @ApiModelProperty(value = "机架信息", required = false) private String rack; /** * 判断机器是否已经下线 * * @return */ public boolean isOffline() { return MachineInfoEnum.AvailableEnum.NO.getValue() == this.available; } /** * 是否是云主机 * * @return */ public boolean isYunMachine() { //return isYun == 1; return false; } public boolean isK8sMachine(int k8sType) { if (k8sType == 1) { return true; } return false; } /** * 时间格式化 */ public String getUpdateTimeFormat() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(modifyTime); } public Date getModifyTime() {<FILL_FUNCTION_BODY>} public void setModifyTime(Date modifyTime) { if(modifyTime != null){ this.modifyTime = (Date) modifyTime.clone(); } } public Date getServiceTime() { if(serviceTime == null){ return null; } return (Date) serviceTime.clone(); } public void setServiceTime(Date serviceTime) { if(serviceTime != null){ this.serviceTime = (Date) serviceTime.clone(); } } }
if(modifyTime == null){ return null; } return (Date) modifyTime.clone();
1,677
37
1,714
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/MachineStats.java
MachineStats
validate
class MachineStats{ private long id; private long hostId; private String ip; private String cpuUsage; private String load; private String traffic; private String memoryUsageRatio; /** * 如果机器是物理机/虚机,收集内存占用空间正常;如果是容器,收集可能不是实际内存占用空间 */ private String memoryFree; private String memoryTotal; private int memoryAllocated; /** * 机器入库内存 MB */ private int machineMemory; /** * 分配内存 MB */ private int maxMemory; /** * 机器实例使用内存总和 MB */ private int usedMemory; private MachineInfo info; private MachineMemInfo machineMemInfo; private Map<String,Object> moduleInfo; private String versionInfo; private Map<String/**挂载点*/, String/**使用百分比*/> diskUsageMap; /** * 实例个数 */ private int instanceCount; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date modifyTime; /** * Redis是否全部安装成功 0:未全部安装 1:全部安装成功 */ private int isInstall; /** * 时间格式化 */ public String getUpdateTimeFormat() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(modifyTime); } //统计数据是否有效 public boolean validate() {<FILL_FUNCTION_BODY>} public Date getCreateTime() { if(null == createTime){ return null; } return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { if(null == createTime){ this.createTime = null; }else{ this.createTime = (Date) createTime.clone(); } } public Date getModifyTime() { if(null == modifyTime){ return null; } return (Date) modifyTime.clone(); } public void setModifyTime(Date modifyTime) { if(null == modifyTime){ this.modifyTime = null; }else{ this.modifyTime = (Date) modifyTime.clone(); } } }
if (StringUtils.isBlank(load) && StringUtils.isBlank(cpuUsage) && StringUtils.isBlank(memoryFree) && StringUtils.isBlank(memoryTotal)) { return false; } return true;
755
77
832
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/RedisModuleConfig.java
RedisModuleConfig
getStatusDesc
class RedisModuleConfig { private long id; /** * 配置名 */ private String configKey; /** * 配置值 */ private String configValue; /** * 配置说明 */ private String info; /** * 更新时间 */ private Date updateTime; /** * Redis类型(参考ConstUtil) */ private int type; /** * 状态,1有效0无效 */ private int status; /** * 配置项绑定module version版本主键id */ private int versionId; /** * 是否可重置:0:不可;1:可重置 */ private int refresh; /** * module info 表id */ private int moduleId; /** * 配置类型,0:加载和运行配置;1:加载时配置;2:运行时配置 */ private int configType; public String getStatusDesc() {<FILL_FUNCTION_BODY>} public boolean isEffective() { if (1 == getStatus()) { return true; } return false; } }
if (1 == status) { return "有效"; } else if (0 == status) { return "无效"; } else { return ""; }
332
48
380
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/StandardStats.java
StandardStats
getInfoMap
class StandardStats { private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * id */ private long id; /** * 实例IP */ private String ip; /** * 实例端口号/hostId */ private int port; /** * 实例类型 */ private String dbType; /** * 收集时间:格式yyyyMMddHHmm */ private long collectTime; /** * 实例收集的json数据 */ private String infoJson; /** * 与上一次收集差异的json数据 */ private String diffJson; /** * 实例收集的cluster info json数据 */ private String clusterInfoJson; /** * infoJson的Map输出 */ private Map<String, Object> infoMap; /** * diffJson的Map输出 */ private Map<String, Object> diffMap; /** * clusterInfoJson的Map输出 */ private Map<String, Object> clusterInfoMap; private Date createdTime; public Map<String, Object> getInfoMap() {<FILL_FUNCTION_BODY>} public void setInfoMap(Map<String, Object> infoMap) { if (infoJson == null) { JSONObject jsonObject; try { jsonObject = JSONObject.fromObject(infoMap); infoJson = jsonObject.toString(); } catch (Exception e) { logger.error(e.getMessage()); } } this.infoMap = infoMap; } public Map<String, Object> getDiffMap() { if (diffMap != null) { return diffMap; } else { if (StringUtils.isNotBlank(diffJson)) { JSONObject jsonObject; try { jsonObject = JSONObject.fromObject(diffJson); Map<String, Object> map = transferMapByJson(jsonObject); diffMap = map; } catch (Exception e) { logger.error(e.getMessage()); } } } return diffMap; } /** * 递归转换JsonObject * * @param jsonObject * @return */ private Map<String, Object> transferMapByJson(JSONObject jsonObject) { Map<String, Object> map = new LinkedHashMap<String, Object>(); for (Iterator keys = jsonObject.keys(); keys.hasNext(); ) { String key = String.valueOf(keys.next()); Object value = jsonObject.get(key); if (value instanceof JSONObject) { JSONObject subJsonObject = (JSONObject) value; Map<String, Object> subMap = transferMapByJson(subJsonObject); map.put(key, subMap); } else { map.put(key, value); } } return map; } public void setDiffMap(Map<String, Object> diffMap) { if (diffJson == null) { JSONObject jsonObject; try { jsonObject = JSONObject.fromObject(diffMap); diffJson = jsonObject.toString(); } catch (Exception e) { logger.error(e.getMessage()); } } this.diffMap = diffMap; } public Map<String, Object> getClusterInfoMap() { if (clusterInfoMap != null) { return clusterInfoMap; } else { if (StringUtils.isNotBlank(clusterInfoJson)) { JSONObject jsonObject; try { jsonObject = JSONObject.fromObject(clusterInfoJson); Map<String, Object> map = transferMapByJson(jsonObject); clusterInfoMap = map; } catch (Exception e) { logger.error(e.getMessage()); } } } return clusterInfoMap; } public void setClusterInfoMap(Map<String, Object> clusterInfoMap) { if (clusterInfoJson == null) { JSONObject jsonObject; try { jsonObject = JSONObject.fromObject(clusterInfoMap); clusterInfoJson = jsonObject.toString(); } catch (Exception e) { logger.error(e.getMessage()); } } this.clusterInfoMap = clusterInfoMap; } public Date getCreatedTime() { return (Date) createdTime.clone(); } public void setCreatedTime(Date createdTime) { this.createdTime = (Date) createdTime.clone(); } }
if (infoMap != null) { return infoMap; } else { if (StringUtils.isNotBlank(infoJson)) { JSONObject jsonObject; try { jsonObject = JSONObject.fromObject(infoJson); Map<String, Object> map = transferMapByJson(jsonObject); infoMap = map; } catch (Exception e) { logger.error(e.getMessage()); } } } return infoMap;
1,195
125
1,320
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/TimeBetween.java
TimeBetween
getFormatStartDate
class TimeBetween { private long startTime; private long endTime; private Date startDate; private Date endDate; public TimeBetween() { } public TimeBetween(long startTime, long endTime, Date startDate, Date endDate) { this.startTime = startTime; this.endTime = endTime; this.startDate = startDate; this.endDate = endDate; } public String getFormatStartDate() {<FILL_FUNCTION_BODY>} public String getFormatStartDate(String dateFormat) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); if (startDate != null) { return sdf.format(startDate); } return ""; } }
String dateFormat = "yyyy-MM-dd"; SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); if (startDate != null) { return sdf.format(startDate); } return "";
207
62
269
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/TimeDimensionality.java
TimeDimensionality
getSuitableDimensionality
class TimeDimensionality { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final long begin; private final long end; private final int dimensionality; public TimeDimensionality(long begin, long end, String format) { Date beginDate = DateUtil.getDateByFormat(String.valueOf(begin), format); Date endDate = DateUtil.getDateByFormat(String.valueOf(end), format); this.dimensionality = getSuitableDimensionality(beginDate, endDate); if (dimensionality == AppStatsDao.MINUTE_DIMENSIONALITY) { this.begin = Long.parseLong(DateUtil.formatDate(beginDate, "yyyyMMddHHmm")); } else { this.begin = Long.parseLong(DateUtil.formatDate(beginDate, "yyyyMMddHH")); } if (dimensionality == AppStatsDao.MINUTE_DIMENSIONALITY) { this.end = Long.parseLong(DateUtil.formatDate(endDate, "yyyyMMddHHmm")); } else { this.end = Long.parseLong(DateUtil.formatDate(endDate, "yyyyMMddHH")); } } /** * 获取合适的维度 */ private int getSuitableDimensionality(Date begin, Date end) {<FILL_FUNCTION_BODY>} }
try { long s1 = begin.getTime(); long s2 = end.getTime(); long hour = (s2 - s1) / 1000 / 60 / 60; if (hour >= 48) { return AppStatsDao.HOUR_DIMENSIONALITY; } else { return AppStatsDao.MINUTE_DIMENSIONALITY; } } catch (Exception e) { logger.error(e.getMessage(), e); } return AppStatsDao.MINUTE_DIMENSIONALITY;
395
166
561
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/TopologyExamResult.java
TopologyExamResult
getCreateTimeFormat
class TopologyExamResult { private long id; private long appId; private String type; private String status; private String description; private Date createTime; public TopologyExamResult(long appId, String type, String status, String description){ this.appId=appId; this.type=type; this.status=status; this.description=description; this.createTime=new Date(); } public String getCreateTimeFormat() {<FILL_FUNCTION_BODY>} public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } }
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (createTime != null) { return sdf.format(createTime); } return "";
202
58
260
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/entity/TriggerInfo.java
TriggerInfo
getPrevFireDate
class TriggerInfo { private String schedName; private String triggerName; private String triggerGroup; private String jobName; private String jobGroup; private String description; private long nextFireTime; private String nextFireDate; private long prevFireTime; private String prevFireDate; private int priority; private String triggerState; private String triggerType; private long startTime; private String startDate; private long endTime; private String endDate; private String calendarName; private short misfireInstr; private String cron; public String getNextFireDate() { if (nextFireTime > 0) { return DateUtil.formatYYYYMMddHHMMSS(new Date(nextFireTime)); } return ""; } public String getPrevFireDate() {<FILL_FUNCTION_BODY>} public String getStartDate() { if (startTime > 0) { return DateUtil.formatYYYYMMddHHMMSS(new Date(startTime)); } return ""; } public String getEndDate() { if (endTime > 0) { return DateUtil.formatYYYYMMddHHMMSS(new Date(endTime)); } return ""; } }
if (prevFireTime > 0) { return DateUtil.formatYYYYMMddHHMMSS(new Date(prevFireTime)); } return "";
375
48
423
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/InspectorJob.java
InspectorJob
action
class InspectorJob extends CacheBaseJob { private static final long serialVersionUID = -4277329946053271489L; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { long start = System.currentTimeMillis(); SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); Environment env = applicationContext.getBean(Environment.class); if (EnvUtil.isDev(env)) { logger.warn("environment is dev ignored"); return; } // 应用相关 InspectHandler inspectHandler; JobDataMap jobDataMap = context.getMergedJobDataMap(); String inspectorType = MapUtils.getString(jobDataMap, "inspectorType"); if (StringUtils.isBlank(inspectorType)) { logger.error("=====================InspectorJob:inspectorType is null====================="); return; } else if (inspectorType.equals("host")) { inspectHandler = applicationContext.getBean("hostInspectHandler", InspectHandler.class); } else if (inspectorType.equals("app")) { inspectHandler = applicationContext.getBean("appInspectHandler", InspectHandler.class); } else { logger.error("=====================InspectorJob:inspectorType not match:{}=====================", inspectorType); return; } inspectHandler.handle(); long end = System.currentTimeMillis(); logger.info("=====================InspectorJob {} Done! cost={} ms=====================", inspectHandler.getClass().getSimpleName(), (end - start)); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); }
78
447
525
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/AbstractInspectHandler.java
AbstractInspectHandler
handle
class AbstractInspectHandler implements InspectHandler { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired protected InstanceDao instanceDao; @Autowired protected AsyncService asyncService; protected List<Inspector> inspectorList; protected abstract String getThreadPoolKey(); protected abstract Map<String, List<InstanceInfo>> getSplitMap(); public void init() { asyncService.assemblePool(getThreadPoolKey(), new ThreadPoolExecutor(10, 100, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), new NamedThreadFactory(getThreadPoolKey(), true))); } public void handle() {<FILL_FUNCTION_BODY>} public void setInspectorList(List<Inspector> inspectorList) { this.inspectorList = inspectorList; } public List<InstanceInfo> getAllInstanceList() { return instanceDao.getAllInsts(); } }
if (inspectorList == null || inspectorList.isEmpty()) { logger.warn("inspectorList is null"); return; } Map<String, List<InstanceInfo>> splitMap = getSplitMap(); for (Map.Entry<String, List<InstanceInfo>> entry : splitMap.entrySet()) { String splitKey = entry.getKey(); List<InstanceInfo> instances = entry.getValue(); final Map<InspectParamEnum, Object> paramMap = new HashMap<InspectParamEnum, Object>(); paramMap.put(InspectParamEnum.SPLIT_KEY, splitKey); paramMap.put(InspectParamEnum.INSTANCE_LIST, instances); String key = getThreadPoolKey() + "-" + splitKey; asyncService.submitFuture(getThreadPoolKey(), new KeyCallable<Boolean>(key) { @Override public Boolean execute() { for (Inspector inspector : inspectorList) { boolean isSuccess = false; try { isSuccess = inspector.inspect(paramMap); } catch (Throwable e) { logger.error(e.getMessage(), e); } if (!isSuccess) { logger.error(getThreadPoolKey() + "-failed:" + inspector.getClass().getName()); return false; } } return true; } }); }
308
378
686
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/AppClientConnInspector.java
AppClientConnInspector
inspect
class AppClientConnInspector extends BaseAlertService implements Inspector { /** * app统计相关 */ private AppStatsCenter appStatsCenter; /** * 实例统计相关 */ private InstanceStatsCenter instanceStatsCenter; @Override public boolean inspect(Map<InspectParamEnum, Object> paramMap) {<FILL_FUNCTION_BODY>} /** * 获取报警阀值(如果用户预设超过系统预设,以系统为准,反之以用户为准) * @param appDesc * @return */ private int getClientConnThreshold(AppDesc appDesc) { int userClientConnThreshold = appDesc.getClientConnAlertValue(); int systemClientConnThreshold = ConstUtils.APP_CLIENT_CONN_THRESHOLD; return userClientConnThreshold > systemClientConnThreshold ? systemClientConnThreshold : userClientConnThreshold; } /** * 应用连接数报警 * @param appDetailVO * @param appClientConnThreshold * @param instanceCount */ private void alertAppClientConn(final AppDetailVO appDetailVO, final int appClientConnThreshold, final int instanceCount) { AppDesc appDesc = appDetailVO.getAppDesc(); String content = String.format("应用(%s)-客户端连接数报警-预设阀值每个分片为%s-现已达到%s(分片个数:%s)-请及时关注", appDesc.getAppId(), appClientConnThreshold, appDetailVO.getConn(), instanceCount); String title = "CacheCloud系统-客户端连接数报警"; logger.warn("app title {}", title); logger.warn("app content {}", content); appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_CLIENT_CONNECTION, title, content, appDetailVO); emailComponent.sendMail(title, content, appDetailVO.getEmailList(), Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA))); weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList()); } /** * 单个分片连接数报警 * @param instanceStats * @param appDetailVO * @param appClientConnThreshold */ private void alertInstanceClientConn(final InstanceStats instanceStats, final AppDetailVO appDetailVO, final int appClientConnThreshold) { String instanceHostPort = instanceStats.getIp() + ":" + instanceStats.getPort(); String content = String.format("分片(%s,应用(%s))客户端连接数报警-预设%s-现已达到%s-请及时关注", instanceHostPort, instanceStats.getAppId(), appClientConnThreshold, instanceStats.getCurrConnections()); String title = "CacheCloud系统-分片客户端连接数报警"; logger.warn("instance title {}", title); logger.warn("instace content {}", content); appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_SHARD_CLENT_CONNECTION, title, content, appDetailVO, instanceStats); emailComponent.sendMail(title, content, appDetailVO.getEmailList(), Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA))); weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList()); } public void setAppStatsCenter(AppStatsCenter appStatsCenter) { this.appStatsCenter = appStatsCenter; } public void setInstanceStatsCenter(InstanceStatsCenter instanceStatsCenter) { this.instanceStatsCenter = instanceStatsCenter; } }
Long appId = MapUtils.getLong(paramMap, InspectParamEnum.SPLIT_KEY); AppDetailVO appDetailVO = appStatsCenter.getAppDetail(appId); if (appDetailVO == null) { logger.warn("appId {} appDetailVO is empty", appId); return true; } List<InstanceInfo> appInstanceInfoList = (List<InstanceInfo>) paramMap.get(InspectParamEnum.INSTANCE_LIST); if (CollectionUtils.isEmpty(appInstanceInfoList)) { logger.warn("appId {} instanceList is empty", appId); return true; } // 报警阀值 int appClientConnThreshold = getClientConnThreshold(appDetailVO.getAppDesc()); int appClientConnNum = appDetailVO.getConn(); // 阀值乘以分片个数 int instanceCount = appInstanceInfoList.size(); if (appClientConnNum > appClientConnThreshold * instanceCount) { alertAppClientConn(appDetailVO, appClientConnThreshold, instanceCount); } else { for (InstanceInfo instanceInfo : appInstanceInfoList) { if (instanceInfo == null) { continue; } if (instanceInfo.isOffline()) { continue; } if (!TypeUtil.isRedisType(instanceInfo.getType())) { continue; } // 忽略sentinel观察者 if (TypeUtil.isRedisSentinel(instanceInfo.getType())) { continue; } long instanceId = instanceInfo.getId(); InstanceStats instanceStats = instanceStatsCenter.getInstanceStats(instanceId); if (instanceStats == null) { continue; } double instanceClientConnNum = instanceStats.getCurrConnections(); // 大于标准值 if (instanceClientConnNum > appClientConnThreshold) { alertInstanceClientConn(instanceStats, appDetailVO, appClientConnThreshold); } } } return true;
1,046
574
1,620
<methods>public non-sealed void <init>() <variables>protected com.sohu.cache.web.service.AppAlertRecordService appAlertRecordService,protected com.sohu.cache.alert.EmailComponent emailComponent,protected final org.slf4j.Logger logger,protected com.sohu.cache.alert.WeChatComponent weChatComponent
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/AppHitPrecentInspector.java
AppHitPrecentInspector
alertAppHitPrecnt
class AppHitPrecentInspector extends BaseAlertService implements Inspector { /** * app统计相关 */ private AppStatsCenter appStatsCenter; /** * 应用相关dao */ private AppDao appDao; @Override public boolean inspect(Map<InspectParamEnum, Object> paramMap) { Long appId = MapUtils.getLong(paramMap, InspectParamEnum.SPLIT_KEY); List<AppDesc> appDescList = new ArrayList<AppDesc>(); AppDesc app = appDao.getAppDescById(appId); if (app != null) { appDescList.add(app); } if (CollectionUtils.isEmpty(appDescList)) { logger.error("appList is empty, appId={}", appId); return true; } // 执行检查逻辑 for (AppDesc appDesc : appDescList) { // 测试不检查 if (appDesc.getIsTest() == 1) { continue; } long checkAppid = appDesc.getAppId(); // 监控命中率阀值(阀值为0不监控) int hitprecent_alertValue = appDesc.getHitPrecentAlertValue(); if (hitprecent_alertValue == 0) { //logger.error("ignore hitprcent monitor, appId={}", appId); return true; } AppDetailVO appDetailVO = appStatsCenter.getAppDetail(checkAppid); if (appDetailVO == null) { continue; } // 全局命中率 double hitPercent = appDetailVO.getHitPercent(); if (hitPercent < hitprecent_alertValue) { // 报警 alertAppHitPrecnt(appDetailVO); } } return false; } /** * <p> * Description:命中率低于监控阀值 * </p> * * @param appDetailVO 应用信息 * @return void * @author chenshi * @version 1.0 * @date 2017/9/11 */ private void alertAppHitPrecnt(final AppDetailVO appDetailVO) {<FILL_FUNCTION_BODY>} public void setAppStatsCenter(AppStatsCenter appStatsCenter) { this.appStatsCenter = appStatsCenter; } public void setAppDao(AppDao appDao) { this.appDao = appDao; } }
AppDesc appDesc = appDetailVO.getAppDesc(); String content = String.format("应用(%s)-应用平均命中率报警-当前命中率百分之%s-现已低于预设百分之%s-请及时关注", appDesc.getAppId(), appDetailVO.getHitPercent(), appDesc.getHitPrecentAlertValue()); String title = "CacheCloud系统-应用平均命中率报警"; appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_HIT_RATIO, title, content, appDetailVO); emailComponent.sendMail(title, content, appDetailVO.getEmailList(), Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA))); weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList());
664
215
879
<methods>public non-sealed void <init>() <variables>protected com.sohu.cache.web.service.AppAlertRecordService appAlertRecordService,protected com.sohu.cache.alert.EmailComponent emailComponent,protected final org.slf4j.Logger logger,protected com.sohu.cache.alert.WeChatComponent weChatComponent
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/AppInspectHandler.java
AppInspectHandler
getSplitMap
class AppInspectHandler extends AbstractInspectHandler{ private final static String inspectPoolKey="inspector-app-pool"; @Override public String getThreadPoolKey() { return inspectPoolKey; } @Override protected Map<String, List<InstanceInfo>> getSplitMap() {<FILL_FUNCTION_BODY>} }
List<InstanceInfo> list = getAllInstanceList(); Map<String, List<InstanceInfo>> hostMap = new TreeMap<String, List<InstanceInfo>>(); for (InstanceInfo instanceInfo : list) { String appId = String.valueOf(instanceInfo.getAppId()); if (hostMap.containsKey(appId)) { hostMap.get(appId).add(instanceInfo); } else { List<InstanceInfo> hostInstances = new ArrayList<InstanceInfo>(); hostInstances.add(instanceInfo); hostMap.put(appId, hostInstances); } } return hostMap;
101
176
277
<methods>public non-sealed void <init>() ,public List<com.sohu.cache.entity.InstanceInfo> getAllInstanceList() ,public void handle() ,public void init() ,public void setInspectorList(List<com.sohu.cache.inspect.Inspector>) <variables>protected com.sohu.cache.async.AsyncService asyncService,protected List<com.sohu.cache.inspect.Inspector> inspectorList,protected com.sohu.cache.dao.InstanceDao instanceDao,protected final org.slf4j.Logger logger
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/AppMemInspector.java
AppMemInspector
inspect
class AppMemInspector extends BaseAlertService implements Inspector { /** * app统计相关 */ private AppStatsCenter appStatsCenter; /** * 应用相关dao */ private AppDao appDao; /** * 实例统计相关 */ private InstanceStatsCenter instanceStatsCenter; @Override public boolean inspect(Map<InspectParamEnum, Object> paramMap) {<FILL_FUNCTION_BODY>} /** * @param appDetailVO */ private void alertAppMemUse(final AppDetailVO appDetailVO) { AppDesc appDesc = appDetailVO.getAppDesc(); String content = String.format("应用(%s)-内存使用率报警-预设百分之%s-现已达到百分之%s-请及时关注", appDesc.getAppId(), appDesc.getMemAlertValue(), appDetailVO.getMemUsePercent()); String title = "CacheCloud系统-应用内存使用率报警"; appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_MEM_USED_RATIO, title, content, appDetailVO); emailComponent.sendMail(title, content, appDetailVO.getEmailList(), Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA))); weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList()); } private void alertInstanceMemUse(final InstanceStats instanceStats, final AppDetailVO appDetailVO) { String instanceInfo = instanceStats.getIp() + ":" + instanceStats.getPort(); String content = String.format("分片(%s,应用(%s))内存使用率报警-预设百分之%s-现已达到百分之%s-应用的内存使用率百分之%s-请及时关注", instanceInfo, instanceStats.getAppId(), appDetailVO.getAppDesc().getMemAlertValue(), instanceStats.getMemUsePercent(), appDetailVO.getMemUsePercent()); String title = "CacheCloud系统-分片内存使用率报警"; appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.APP_SHARD_MEM_USED_RATIO, title, content, appDetailVO, instanceStats); emailComponent.sendMail(title, content, appDetailVO.getEmailList(), Arrays.asList(emailComponent.getAdminEmail().split(ConstUtils.COMMA))); weChatComponent.sendWeChatToAll(title,content,appDetailVO.getWeChatList()); } public void setAppStatsCenter(AppStatsCenter appStatsCenter) { this.appStatsCenter = appStatsCenter; } public void setAppDao(AppDao appDao) { this.appDao = appDao; } public void setInstanceStatsCenter(InstanceStatsCenter instanceStatsCenter) { this.instanceStatsCenter = instanceStatsCenter; } }
Long appId = MapUtils.getLong(paramMap, InspectParamEnum.SPLIT_KEY); List<AppDesc> appDescList = new ArrayList<AppDesc>(); AppDesc app = appDao.getAppDescById(appId); if (app != null) { appDescList.add(app); } if (CollectionUtils.isEmpty(appDescList)) { logger.error("appList is empty, appId={}", appId); return true; } for (AppDesc appDesc : appDescList) { //测试不检查 if(appDesc.getIsTest() == 1){ continue; } long checkAppId = appDesc.getAppId(); AppDetailVO appDetailVO = appStatsCenter.getAppDetail(checkAppId); if (appDetailVO == null) { continue; } double appMemUsePercent = appDetailVO.getMemUsePercent(); int appUseSetMemAlertValue = appDesc.getMemAlertValue(); // 先检查应用的内存使用率是否超过阀值,如果没有再检查分片 if (appMemUsePercent > appUseSetMemAlertValue) { // 报警 alertAppMemUse(appDetailVO); } else { List<InstanceInfo> appInstanceInfoList = (List<InstanceInfo>) paramMap.get(InspectParamEnum.INSTANCE_LIST); if (CollectionUtils.isNotEmpty(appInstanceInfoList)) { for (InstanceInfo instanceInfo : appInstanceInfoList) { if (instanceInfo == null) { continue; } if (!TypeUtil.isRedisType(instanceInfo.getType())) { continue; } // 忽略sentinel观察者 if (TypeUtil.isRedisSentinel(instanceInfo.getType())) { continue; } long instanceId = instanceInfo.getId(); InstanceStats instanceStats = instanceStatsCenter.getInstanceStats(instanceId); if(instanceStats == null){ continue; } double instanceMemUsePercent = instanceStats.getMemUsePercent(); // 大于标准值 if (instanceMemUsePercent > appUseSetMemAlertValue) { alertInstanceMemUse(instanceStats, appDetailVO); } } } } } return true;
822
655
1,477
<methods>public non-sealed void <init>() <variables>protected com.sohu.cache.web.service.AppAlertRecordService appAlertRecordService,protected com.sohu.cache.alert.EmailComponent emailComponent,protected final org.slf4j.Logger logger,protected com.sohu.cache.alert.WeChatComponent weChatComponent
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/HostInspectHandler.java
HostInspectHandler
getSplitMap
class HostInspectHandler extends AbstractInspectHandler{ private final static String inspectPoolKey="inspector-host-pool"; @Override public String getThreadPoolKey() { return inspectPoolKey; } @Override protected Map<String, List<InstanceInfo>> getSplitMap() {<FILL_FUNCTION_BODY>} }
List<InstanceInfo> list = getAllInstanceList(); Map<String, List<InstanceInfo>> hostMap = new TreeMap<String, List<InstanceInfo>>(); for (InstanceInfo instanceInfo : list) { String host = instanceInfo.getIp(); if (hostMap.containsKey(host)) { hostMap.get(host).add(instanceInfo); } else { List<InstanceInfo> hostInstances = new ArrayList<InstanceInfo>(); hostInstances.add(instanceInfo); hostMap.put(host, hostInstances); } } return hostMap;
101
167
268
<methods>public non-sealed void <init>() ,public List<com.sohu.cache.entity.InstanceInfo> getAllInstanceList() ,public void handle() ,public void init() ,public void setInspectorList(List<com.sohu.cache.inspect.Inspector>) <variables>protected com.sohu.cache.async.AsyncService asyncService,protected List<com.sohu.cache.inspect.Inspector> inspectorList,protected com.sohu.cache.dao.InstanceDao instanceDao,protected final org.slf4j.Logger logger
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/InstanceRunInspector.java
InstanceRunInspector
saveFault
class InstanceRunInspector extends BaseAlertService implements Inspector { /** * 实例相关 */ @Autowired private InstanceDao instanceDao; /** * redis相关 */ @Autowired private RedisCenter redisCenter; /** * 应用相关dao */ @Autowired private AppDao appDao; @Autowired private InstanceFaultDao instanceFaultDao; @Override public boolean inspect(Map<InspectParamEnum, Object> paramMap) { String host = MapUtils.getString(paramMap, InspectParamEnum.SPLIT_KEY); List<InstanceInfo> list = (List<InstanceInfo>) paramMap.get(InspectParamEnum.INSTANCE_LIST); for (InstanceInfo info : list) { final int port = info.getPort(); final int type = info.getType(); long appId = info.getAppId(); if (TypeUtil.isRedisType(type)) { boolean isRun; if (TypeUtil.isRedisSentinel(type)) { isRun = redisCenter.isRun(host, port); } else { isRun = redisCenter.isRun(appId, host, port); } BooleanEnum isUpdate = updateInstanceByRun(isRun, info); // 错误 if (isUpdate != BooleanEnum.OTHER) { alertInstanceInfo(info); } } } return true; } /** * 邮箱+短信 * * @param info */ private void alertInstanceInfo(InstanceInfo info) { sendEmailAlert(info); } /** * 发送邮箱报警 * * @param info */ private void sendEmailAlert(InstanceInfo info) { if (info == null) { return; } String title = "实例(" + info.getIp() + ":" + info.getPort() + ")状态发生变化"; String message = generateMessage(info, true); appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.INSTANCE_RUNNING_STATE_CHANGE, title, message, info); emailComponent.sendMailToAdmin(title, message); } /** * 返回示例消息 * * @param info * @return */ private String generateMessage(InstanceInfo info, boolean isEmail) { StringBuffer message = new StringBuffer(); long appId = info.getAppId(); AppDesc appDesc = appDao.getAppDescById(appId); message.append("CacheCloud系统-实例(" + info.getIp() + ":" + info.getPort() + ")-"); if (info.getStatus() == InstanceStatusEnum.ERROR_STATUS.getStatus()) { message.append("由运行中变为心跳停止"); } else if (info.getStatus() == InstanceStatusEnum.GOOD_STATUS.getStatus()) { message.append("由心跳停止变为运行中"); } if (isEmail) { message.append(", appId:"); message.append(appId + "-" + appDesc.getName()); } else { message.append("-appId(" + appId + "-" + appDesc.getName() + ")"); } return message.toString(); } private void saveFault(InstanceInfo info, boolean isRun) {<FILL_FUNCTION_BODY>} private BooleanEnum updateInstanceByRun(boolean isRun, InstanceInfo info) { try { InstanceInfo info_new = instanceDao.getInstanceInfoById(info.getId()); info.setStatus(info_new.getStatus()); if (isRun) { if (info.getStatus() != InstanceStatusEnum.GOOD_STATUS.getStatus()) { info.setStatus(InstanceStatusEnum.GOOD_STATUS.getStatus()); instanceDao.update(info); logger.warn("instance:{} instance is run", info); saveFault(info, isRun); return BooleanEnum.TRUE; } } else { if (info.getStatus() != InstanceStatusEnum.ERROR_STATUS.getStatus() && info.getStatus() != InstanceStatusEnum.OFFLINE_STATUS.getStatus()) { info.setStatus(InstanceStatusEnum.ERROR_STATUS.getStatus()); instanceDao.update(info); logger.error("instance:{} instance failed", info); saveFault(info, isRun); return BooleanEnum.FALSE; }else if(info.getStatus() == InstanceStatusEnum.OFFLINE_STATUS.getStatus()){ logger.error("instance:{} instance is offline", info); saveFault(info, isRun); return BooleanEnum.OTHER; } } } catch (Exception e) { logger.error(e.getMessage(), e); } return BooleanEnum.OTHER; } }
InstanceFault instanceFault = new InstanceFault(); instanceFault.setAppId((int) info.getAppId()); instanceFault.setInstId(info.getId()); instanceFault.setIp(info.getIp()); instanceFault.setPort(info.getPort()); instanceFault.setType(info.getType()); instanceFault.setCreateTime(new Date()); if (isRun) { instanceFault.setReason("恢复运行"); } else { instanceFault.setReason("心跳停止"); } instanceFaultDao.insert(instanceFault);
1,291
163
1,454
<methods>public non-sealed void <init>() <variables>protected com.sohu.cache.web.service.AppAlertRecordService appAlertRecordService,protected com.sohu.cache.alert.EmailComponent emailComponent,protected final org.slf4j.Logger logger,protected com.sohu.cache.alert.WeChatComponent weChatComponent
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/inspect/impl/InstanceStateInspector.java
InstanceStateInspector
inspect
class InstanceStateInspector extends BaseAlertService { /** * 实例相关 */ @Autowired private InstanceDao instanceDao; @Autowired private AppService appService; @Autowired private UserService userService; @Autowired private Configuration configuration; public boolean inspect() {<FILL_FUNCTION_BODY>} }
List<InstanceAlertValueResult> alertInstInfo = new ArrayList<>(); List<InstanceInfo> heartStopInstances = instanceDao.getAllHeartStopInstance(); if (!CollectionUtils.isEmpty(heartStopInstances)) { for (InstanceInfo info : heartStopInstances) { long appId = info.getAppId(); AppDesc appDesc = appService.getByAppId(appId); appDesc.setOfficer(userService.getOfficerName(appDesc.getOfficer())); InstanceAlertValueResult instanceAlert = new InstanceAlertValueResult(); instanceAlert.setInstanceInfo(info); instanceAlert.setAppId(appId); instanceAlert.setAppDesc(appDesc); instanceAlert.setOtherInfo(InstanceStatusEnum.getByStatus(info.getStatus()).getInfo()); alertInstInfo.add(instanceAlert); } String emailTitle = String.format("Redis实例异常状态监控报警"); Map<String, Object> context = new HashMap<>(); context.put("instanceAlertValueResultList", alertInstInfo); String emailContent = FreemakerUtils.createText("instanceState.ftl", configuration, context); appAlertRecordService.saveAlertInfoByType(AlertTypeEnum.INATANCE_EXCEPTION_STATE_MONITOR, emailTitle, null, alertInstInfo); emailComponent.sendMailToAdmin(emailTitle, emailContent); logger.info(emailContent); } return true;
107
382
489
<methods>public non-sealed void <init>() <variables>protected com.sohu.cache.web.service.AppAlertRecordService appAlertRecordService,protected com.sohu.cache.alert.EmailComponent emailComponent,protected final org.slf4j.Logger logger,protected com.sohu.cache.alert.WeChatComponent weChatComponent
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/interceptor/AppAndInstanceAuthorityInterceptor.java
AppAndInstanceAuthorityInterceptor
preHandle
class AppAndInstanceAuthorityInterceptor extends HandlerInterceptorAdapter { private Logger logger = LoggerFactory.getLogger(AppAndInstanceAuthorityInterceptor.class); @Autowired private AppService appService; @Autowired private UserService userService; @Autowired private InstanceStatsCenter instanceStatsCenter; @Autowired private UserLoginStatusService userLoginStatusService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} /** * 检查用户应用的权限 * * @param response * @param session * @param user * @param appId * @return */ private void checkUserAppPower(HttpServletResponse response, HttpSession session, AppUser user, Long appId) { // 应用下的用户 List<AppToUser> appToUsers = appService.getAppToUserList(appId); if (CollectionUtils.isNotEmpty(appToUsers)) { for (AppToUser tempAppToUser : appToUsers) { if (user.getId().equals(tempAppToUser.getUserId())) { return; } } // 没权限 String path = session.getServletContext().getContextPath(); try { response.sendRedirect(path + "/resources/error/noPower.jsp?appId=" + appId); } catch (IOException e) { logger.error(e.getMessage(), e); } } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
// 1. 获取用户 String userName = userLoginStatusService.getUserNameFromLoginStatus(request); //未登录 if (StringUtils.isBlank(userName)) { String redirectUrl = userLoginStatusService.getRedirectUrl(request); response.sendRedirect(redirectUrl); return false; } AppUser user = userService.getByName(userName); if (user == null || user.getType() == -1) { String redirectUrl = userLoginStatusService.getRegisterUrl(user); response.sendRedirect(redirectUrl); return false; } // 2. 管理员直接跳过 if (AppUserTypeEnum.ADMIN_USER.value().equals(user.getType())) { return true; } // 3. 应用id String appId = request.getParameter("appId"); if (StringUtils.isNotBlank(appId)) { checkUserAppPower(response, request.getSession(true), user, NumberUtils.toLong(appId)); } // 4. 实例权限检测(其实也是应用) String instanceId = request.getParameter("instanceId"); if (StringUtils.isNotBlank(instanceId)) { InstanceInfo instanceInfo = instanceStatsCenter.getInstanceInfo(Long.parseLong(instanceId)); checkUserAppPower(response, request.getSession(true), user, instanceInfo.getAppId()); } return true;
541
417
958
<methods>public void <init>() ,public void afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) throws java.lang.Exception,public void afterConcurrentHandlingStarted(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception,public void postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) throws java.lang.Exception,public boolean preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/interceptor/FrontUserLoginInterceptor.java
FrontUserLoginInterceptor
preHandle
class FrontUserLoginInterceptor extends HandlerInterceptorAdapter { @Autowired private UserService userService; @Autowired private UserLoginStatusService userLoginStatusService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} }
String userName = userLoginStatusService.getUserNameFromLoginStatus(request); //未登录 if (StringUtils.isBlank(userName)) { String redirectUrl = userLoginStatusService.getRedirectUrl(request); response.sendRedirect(redirectUrl); return false; } AppUser user = userService.getByName(userName); //新用户 if (user == null || user.getType() == -1) { String redirectUrl = userLoginStatusService.getRegisterUrl(user); response.sendRedirect(redirectUrl); return false; } request.setAttribute("userInfo", user); request.setAttribute("uri", request.getRequestURI()); return true;
101
210
311
<methods>public void <init>() ,public void afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) throws java.lang.Exception,public void afterConcurrentHandlingStarted(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception,public void postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) throws java.lang.Exception,public boolean preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/interceptor/ManageUserLoginInterceptor.java
ManageUserLoginInterceptor
preHandle
class ManageUserLoginInterceptor extends HandlerInterceptorAdapter { private Logger logger = LoggerFactory.getLogger(ManageUserLoginInterceptor.class); @Autowired private UserService userService; @Autowired private UserLoginStatusService userLoginStatusService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
String userName = userLoginStatusService.getUserNameFromLoginStatus(request); //未登录 if (StringUtils.isBlank(userName)) { String redirectUrl = userLoginStatusService.getRedirectUrl(request); response.sendRedirect(redirectUrl); return false; } AppUser user = userService.getByName(userName); //新用户 if (user == null || user.getType() == -1) { String redirectUrl = userLoginStatusService.getRegisterUrl(user); response.sendRedirect(redirectUrl); return false; } //必须是管理员 if (user.getType() != AppUserTypeEnum.ADMIN_USER.value()) { String redirectUrl = userLoginStatusService.getRedirectUrl(request); response.sendRedirect(redirectUrl); return false; } request.setAttribute("userInfo", user); request.setAttribute("uri", request.getRequestURI()); return true;
221
287
508
<methods>public void <init>() ,public void afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) throws java.lang.Exception,public void afterConcurrentHandlingStarted(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception,public void postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) throws java.lang.Exception,public boolean preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/log/CustLogAppenderInit.java
CustLogAppenderInit
run
class CustLogAppenderInit implements ApplicationRunner{ @Autowired private TaskFlowRecordAppender taskFlowRecordAppender; private final org.slf4j.Logger logger = LoggerFactory.getLogger(CustLogAppenderInit.class); @Override public void run(ApplicationArguments args) throws Exception {<FILL_FUNCTION_BODY>} }
logger.warn("custLogAppender init begin!"); if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); //自定义任务流appender taskFlowRecordAppender.setContext(loggerContext); taskFlowRecordAppender.start(); rootLogger.addAppender(taskFlowRecordAppender); logger.warn("custLogAppender init Done!"); } else { logger.error("custLogAppender init failed , LoggerFactory.getILoggerFactory()={}", LoggerFactory.getILoggerFactory()); }
96
193
289
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/log/TaskFlowRecordAppender.java
TaskFlowRecordAppender
generateCustomLog
class TaskFlowRecordAppender extends AppenderBase<ILoggingEvent> { @Autowired private AssistRedisService assistRedisService; @Override protected void append(ILoggingEvent event) { if (event == null) { return; } Marker marker = event.getMarker(); if (marker != null && marker.getName().equals(BaseTask.MARKER_NAME)) { String taskFlowId = event.getMDCPropertyMap().get(TaskConstants.TASK_STEP_FLOW_ID); if (StringUtils.isBlank(taskFlowId)) { return; } String customLog = generateCustomLog(event); String taskFlowIdKey = ConstUtils.getTaskFlowRedisKey(taskFlowId); assistRedisService.rpush(taskFlowIdKey, customLog); } } private String generateCustomLog(ILoggingEvent event) {<FILL_FUNCTION_BODY>} private String getSimpleClassName(String className) { int index = className.lastIndexOf("."); if (index >= 0) { return className.substring(index + 1); } return className; } }
Date date = new Date(event.getTimeStamp()); String formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date); String threadName = event.getThreadName(); String logLevel = event.getLevel().toString(); String className = event.getLoggerName(); String simpleClassName = getSimpleClassName(className); String formatMessage = event.getFormattedMessage(); return String.format("%s {%s} %s %s - %s", formatDate, threadName, logLevel, simpleClassName, formatMessage);
311
148
459
<methods>public void <init>() ,public void addFilter(Filter<ch.qos.logback.classic.spi.ILoggingEvent>) ,public void clearAllFilters() ,public synchronized void doAppend(ch.qos.logback.classic.spi.ILoggingEvent) ,public List<Filter<ch.qos.logback.classic.spi.ILoggingEvent>> getCopyOfAttachedFiltersList() ,public ch.qos.logback.core.spi.FilterReply getFilterChainDecision(ch.qos.logback.classic.spi.ILoggingEvent) ,public java.lang.String getName() ,public boolean isStarted() ,public void setName(java.lang.String) ,public void start() ,public void stop() ,public java.lang.String toString() <variables>static final int ALLOWED_REPEATS,private int exceptionCount,private FilterAttachableImpl<ch.qos.logback.classic.spi.ILoggingEvent> fai,private boolean guard,protected java.lang.String name,protected volatile boolean started,private int statusRepeatCount
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/machine/MachineProperty.java
MachineProperty
compare
class MachineProperty implements Comparator<MachineProperty>, Serializable { private static final long serialVersionUID = 2498956982032225654L; private long hostId; private long memory; private double traffic; private double load; public MachineProperty() { } public MachineProperty(long hostId, long memory, double traffic, double load) { this.hostId = hostId; this.memory = memory; this.traffic = traffic; this.load = load; } public long getHostId() { return hostId; } public void setHostId(long hostId) { this.hostId = hostId; } public long getMemory() { return memory; } public void setMemory(long memory) { this.memory = memory; } public double getTraffic() { return traffic; } public void setTraffic(double traffic) { this.traffic = traffic; } public double getLoad() { return load; } public void setLoad(double load) { this.load = load; } @Override public int compare(MachineProperty o1, MachineProperty o2) {<FILL_FUNCTION_BODY>} }
return ComparisonChain.start() .compare(o1.traffic, o2.traffic) .compare(o1.load, o2.load) .compare(o2.memory, o1.memory) .result();
348
64
412
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/machine/PortGenerator.java
PortGenerator
getRedisPort
class PortGenerator { private static Logger logger = LoggerFactory.getLogger(PortGenerator.class); /** * redis port常量 */ private static final Integer REDIS_START_PORT = 6379; private static AtomicLongMap<String> redisPortHolder = AtomicLongMap.create(); /** * 返回一个redis的可用端口: * - 1. 通过shell查询redis当前已用的最大port; * - 2. 为什么同步:防止多线程访问时获取到同样的端口; * - 3. 为什么还用原子计数:连续两次调用时,如果进程还没启动,则拿到的仍然是相同的端口; * * @param ip * @return */ public static synchronized Integer getRedisPort(final String ip) {<FILL_FUNCTION_BODY>} @Deprecated public static String getMaxPortStrOld(String ip, int sshPort) throws SSHException { String redisPidCmd = "ps -ef | grep redis | grep -v 'grep' | awk -F '*:' '{print $2}' " + " | awk -F ' ' '{print $1}' | sort -r | head -1"; return SSHUtil.execute(ip, sshPort, ConstUtils.USERNAME, ConstUtils.PASSWORD, redisPidCmd); } /** * 直接解析ps -ef | grep redis | grep -v 'grep' * @param ip * @param sshPort * @return * @throws SSHException */ public static String getMaxPortStr(String ip, int sshPort) throws SSHException { String redisPidCmd = "ps -ef | grep redis | grep -v 'grep'"; String redisProcessStr = SSHUtil.execute(ip, sshPort, ConstUtils.USERNAME, ConstUtils.PASSWORD, redisPidCmd); if (StringUtils.isBlank(redisProcessStr)) { logger.warn("{} excute {}, result is empty", ip, redisPidCmd); return EmptyObjectConstant.EMPTY_STRING; } int maxPort = 0; String[] lines = redisProcessStr.split(SymbolConstant.ENTER); for (String line : lines) { if (StringUtils.isBlank(line)) { continue; } int redisServerIndex = line.indexOf("redis-server"); int redisSentinelIndex = line.indexOf("redis-sentinel"); if (redisServerIndex >= 0) { line = line.substring(redisServerIndex); } if (redisSentinelIndex >= 0) { line = line.substring(redisSentinelIndex); } if (redisServerIndex < 0 && redisSentinelIndex < 0) { continue; } String[] items = line.split(SymbolConstant.SPACE); if (items.length >= 2) { String hostPort = items[1]; if (StringUtils.isBlank(hostPort)) { continue; } String[] hostPortArr = hostPort.split(SymbolConstant.COLON); if (hostPortArr.length != 2) { continue; } String portStr = hostPortArr[1]; if (!NumberUtils.isDigits(portStr)) { continue; } int port = NumberUtils.toInt(portStr); if (port > maxPort) { maxPort = port; } } } return maxPort == 0 ? EmptyObjectConstant.EMPTY_STRING : String.valueOf(maxPort); } }
if (redisPortHolder.get(ip) == 0L) { redisPortHolder.put(ip, REDIS_START_PORT); } String maxPortStr = ""; try { int sshPort = SSHUtil.getSshPort(ip); maxPortStr = getMaxPortStr(ip, sshPort); } catch (SSHException e) { logger.error("cannot get max port of redis by ssh, ip: {}", ip, e); } logger.warn("{} maxPort is {}", ip, maxPortStr); if (StringUtils.isBlank(maxPortStr) || !StringUtils.isNumeric(maxPortStr)) { logger.warn("{} the max port of redis is invalid, maxPortStr: {}", ip, maxPortStr); return (int)redisPortHolder.getAndIncrement(ip); } int availablePort = Integer.parseInt(maxPortStr) + 1; // 兼容连续调用的情况 if (availablePort < redisPortHolder.get(ip)) { availablePort = (int)redisPortHolder.getAndIncrement(ip); } else { // 正常情况,以及兼容系统重启和当前端口不可用的情形 redisPortHolder.put(ip, availablePort + 1L); } logger.warn("first {} maxPort is {}", ip, availablePort); try { while (SSHUtil.isPortUsed(ip, availablePort)) { availablePort++; } } catch (SSHException e) { logger.error("check port error, ip: {}, port: {}", ip, availablePort, e); } logger.warn("final {} maxPort is {}", ip, availablePort); redisPortHolder.put(ip, availablePort + 1L); return availablePort;
1,031
498
1,529
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/machine/impl/MachineCenterImpl.java
MachinetaskCallable
call
class MachinetaskCallable implements Callable<Map<String, Object>> { private String ip; private String cmd; private SSHService sshService; private String type; public MachinetaskCallable(String ip, String cmd, SSHService sshService, String type) { this.ip = ip; this.cmd = cmd; this.sshService = sshService; this.type = type; } @Override public Map<String, Object> call() {<FILL_FUNCTION_BODY>} }
Map<String, Object> machineResult = new HashMap<String, Object>(); String info = null; try { info = sshService.execute(ip, cmd); machineResult.put("ip", ip); if (!StringUtil.isBlank(info)) { if (type.equals(MachineInfoEnum.MachineEnum.CONTAINER.getValue())) { MachineEnv containerEnv = convertContainer(info); if (containerEnv != null) { machineResult.put("envs", containerEnv); machineResult.put("status", MachineEnv.checkContainer(containerEnv)); } else { machineResult.put("status", CheckEnum.EXCEPTION.getValue()); machineResult.put("envs", MachineEnv.getDefaultEnv()); } } else if (type.equals(MachineInfoEnum.MachineEnum.HOST.getValue())) { MachineEnv hostEnv = convertHost(info); if (hostEnv != null) { machineResult.put("envs", hostEnv); machineResult.put("status", MachineEnv.checkHost(hostEnv)); } else { machineResult.put("status", CheckEnum.EXCEPTION.getValue()); machineResult.put("envs", MachineEnv.getDefaultEnv()); } } } else { machineResult.put("status", CheckEnum.EXCEPTION.getValue()); machineResult.put("envs", MachineEnv.getDefaultEnv()); } } catch (SSHException e) { logger.error("MachinetaskCallable ip:{} error msg :{}",ip,e.getMessage()); machineResult.put("status", CheckEnum.EXCEPTION.getValue()); machineResult.put("envs", MachineEnv.getDefaultEnv()); } return machineResult;
140
441
581
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/machine/impl/MachineDeployCenterImpl.java
MachineDeployCenterImpl
removeMachineRoom
class MachineDeployCenterImpl implements MachineDeployCenter { private Logger logger = LoggerFactory.getLogger(MachineDeployCenterImpl.class); @Autowired private MachineDao machineDao; @Autowired private MachineRoomDao machineRoomDao; @Autowired private MachineStatsDao machineStatsDao; @Autowired private ServerStatusDao serverStatusDao; @Autowired private MachineRelationDao machineRelationDao; /** * 将机器加入资源池并统计、监控 * * @param machineInfo * @return */ @Override public boolean addMachine(MachineInfo machineInfo) { boolean success = true; if (machineInfo == null || Strings.isNullOrEmpty(machineInfo.getIp())) { logger.error("machineInfo is null or ip is valid."); return false; } // 将机器信息保存到db中 try { machineDao.saveMachineInfo(machineInfo); } catch (Exception e) { logger.error("save machineInfo: {} to db error.", machineInfo.toString(), e); return false; } if (success) { logger.info("save and deploy machine ok, machineInfo: {}", machineInfo.toString()); } return success; } @Override public boolean addMachineRoom(MachineRoom room) { boolean success = true; try { machineRoomDao.saveRoom(room); } catch (Exception e) { logger.error("save machineRoom: {} to db error.", room.toString(), e); return false; } if (success) { logger.info("save machineRoom ok, machineRoom: {}", room.toString()); } return success; } @Override public boolean removeMachineRoom(int roomId) {<FILL_FUNCTION_BODY>} /** * 删除机器,并删除相关的定时任务 * * @param machineInfo * @return */ @Override public boolean removeMachine(MachineInfo machineInfo) { if (machineInfo == null || Strings.isNullOrEmpty(machineInfo.getIp())) { logger.warn("machineInfo is null or ip is empty."); return false; } String machineIp = machineInfo.getIp(); // 从db中删除machine和相关统计信息 try { machineDao.removeMachineInfoByIp(machineIp); machineStatsDao.deleteMachineStatsByIp(machineIp); serverStatusDao.deleteServerInfo(machineIp); } catch (Exception e) { logger.error("remove machineInfo from db error, machineInfo: {}", machineInfo.toString(), e); return false; } logger.info("remove and undeploy machine ok: {}", machineInfo.toString()); return true; } @Override public void updateMachineRelation(int id, Long taskid, int is_sync) { try { machineRelationDao.updateMachineRelation(id, taskid, is_sync); } catch (Exception e) { logger.error("update machineRelation id:{} taskid :{} error, machineRelation: {}", id, taskid, e.getMessage()); } } public List<MachineRelation> getMachineRelationList(String ip) { List<MachineRelation> relationList = new ArrayList<MachineRelation>(); try { relationList = machineRelationDao.getRelationList(ip); } catch (Exception e) { logger.error("get machine relation : containerIp:{} , error message:{}", ip, e.getMessage(), e); } return relationList; } public SuccessEnum checkMachineSyncStatus(String containerIp, String sourceIp, int is_sync) { List<MachineRelation> machineRelationList = null; try { machineRelationList = machineRelationDao.getMachineSyncStatus(containerIp, sourceIp, is_sync); } catch (Exception e) { logger.error("check machine relation error : containerIp: {} sourceIp:{} is_sync:{} ,error message: {}", containerIp, sourceIp, is_sync, e.getMessage(), e); return SuccessEnum.ERROR; } if (machineRelationList != null && machineRelationList.size() > 0) { logger.info("check machine relation containerIp: {} sourceIp:{} is_sync:{} size :{} ", containerIp, sourceIp, is_sync, machineRelationList.size()); return SuccessEnum.REPEAT; } else { return SuccessEnum.NO_REPEAT; } } }
try { machineRoomDao.removeRoom(roomId); } catch (Exception e) { logger.error("remove machineRoom from db error, machineRoom: {}", roomId, e); return false; } logger.info("remove machineRoom ok: {}", roomId); return true;
1,222
86
1,308
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/protocol/MachineProtocol.java
MachineProtocol
getDir
class MachineProtocol { /** * 统一的目录结构 */ public static final String CONF_DIR = ConstUtils.CACHECLOUD_BASE_DIR + "/cachecloud/conf/"; public static final String DATA_DIR = ConstUtils.CACHECLOUD_BASE_DIR + "/cachecloud/data/"; public static final String LOG_DIR = ConstUtils.CACHECLOUD_BASE_DIR + "/cachecloud/logs/"; /** * k8s容器目录结构 */ public static final String K8S_CONF_DIR = ConstUtils.CACHECLOUD_BASE_DIR + "/cachecloud/conf/%s/"; public static final String K8S_DATA_DIR = ConstUtils.CACHECLOUD_BASE_DIR + "/cachecloud/data/%s/"; public static final String K8S_LOG_DIR = ConstUtils.CACHECLOUD_BASE_DIR + "/cachecloud/logs/%s/"; /** * 配置文件的临时目录; */ public static final String TMP_DIR = "/tmp/cachecloud/"; /** * 编码 */ public static final String ENCODING_UTF8 = "UTF-8"; /** * 配置目录 * @param instanceBasePath * @return */ public static String getConfPath(String instanceBasePath) { return instanceBasePath + "/conf"; } /** * 支持k8s挂载宿主机文件 * * @param host * @return */ public static String getK8sConfDir(String host) { return String.format(K8S_CONF_DIR, host); } public static String getK8sDataDir(String host) { return String.format(K8S_DATA_DIR, host); } public static String getK8sLogDir(String host) { return String.format(K8S_LOG_DIR, host); } /** * 获取k8s相关目录 * * @param host * @param dirType * @return */ public static String getK8sDir(String host, int dirType) { if (dirType == DirEnum.CONF_DIR.getValue()) { return String.format(K8S_CONF_DIR, host); } else if (dirType == DirEnum.DATA_DIR.getValue()) { return String.format(K8S_DATA_DIR, host); } else if (dirType == DirEnum.LOG_DIR.getValue()) { return String.format(K8S_LOG_DIR, host); } return null; } /** * 获取普通容器目录 * * @param dirType * @return */ public static String getDir(int dirType) {<FILL_FUNCTION_BODY>} }
if (dirType == DirEnum.CONF_DIR.getValue()) { return CONF_DIR; } else if (dirType == DirEnum.DATA_DIR.getValue()) { return DATA_DIR; } else if (dirType == DirEnum.LOG_DIR.getValue()) { return LOG_DIR; } return null;
836
99
935
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/protocol/RedisProtocol.java
RedisProtocol
getConfig
class RedisProtocol { private static final String RUN_SHELL_VERSION = "%s/src/redis-server %s > " + MachineProtocol.LOG_DIR + "redis-%d-%s.log 2>&1 &"; private static final String SENTINEL_SHELL_VERSION = "%s/src/redis-sentinel %s --sentinel > " + MachineProtocol.LOG_DIR + "redis-sentinel-%d-%s.log 2>&1 &"; private static final String K8S_RUN_SHELL_VERSION = "%s/src/redis-server %s > %sredis-%d-%s.log 2>&1 &"; private static final String K8S_SENTINEL_SHELL_VERSION = "%s/src/redis-sentinel %s --sentinel > %sredis-sentinel-%d-%s.log 2>&1 &"; private static final String CLUSTER_CONFIG = "redis-cluster-%d.conf"; private static final String COMMON_CONFIG = "redis-sentinel-%d.conf"; /** * 2018-08-28 根据不同版本路径启动redis-cluster * * @param port * @param isCluster * @param dir redis启动路径 * @return 启动redis命令 */ public static String getRunShellByVersion(int port, boolean isCluster, String dir) { return String.format(RUN_SHELL_VERSION, dir, MachineProtocol.CONF_DIR + getConfig(port, isCluster), port, DateUtil.formatYYYYMMddHHMM(new Date())); } /** * 2018-08-28 根据不同版本路径启动redis-sentinel * * @param port * @param dir redis启动路径 * @return 启动redis命令 */ public static String getSentinelShellByVersion(int port, String dir) { return String.format(SENTINEL_SHELL_VERSION, dir, MachineProtocol.CONF_DIR + getConfig(port, false), port, DateUtil.formatYYYYMMddHHMM(new Date())); } /** * 2019-05-14 k8s容器启动路径 /opt/cachecloud/conf/${host}/redis-${port}.conf * * @param host * @param port * @param isCluster * @param dir * @return 启动redis命令 */ public static String getK8sRunShellByVersion(String host, int port, boolean isCluster, String dir) { return String.format(K8S_RUN_SHELL_VERSION, dir, MachineProtocol.getK8sConfDir(host) + getConfig(port, isCluster), MachineProtocol.getK8sLogDir(host), port, DateUtil.formatYYYYMMddHHMM(new Date())); } /** * 2019-05-14 k8s容器启动路径 /opt/cachecloud/conf/${host}/redis-${port}.conf * * @param host * @param port * @param dir * @return 启动redis sentinel命令 */ public static String getK8sSentinelShellByVersion(String host, int port, String dir) { return String.format(K8S_SENTINEL_SHELL_VERSION, dir, MachineProtocol.getK8sConfDir(host) + getConfig(port, false), MachineProtocol.getK8sLogDir(host), port, DateUtil.formatYYYYMMddHHMM(new Date())); } public static String getExecuteCommandShell(String host, int port, String password, String command) { StringBuffer shell = new StringBuffer(); shell.append(String.format("redis-cli -h %s -p %s", host, port)); if (StringUtils.isNotBlank(password)) { shell.append(String.format(" -a %s", password)); } shell.append(String.format(" --raw %s", command)); return shell.toString(); } public static String getExecuteAdminCommandShell(String host, int port, String password, String command) { StringBuffer shell = new StringBuffer(); shell.append(String.format("redis-cli -h %s -p %s", host, port)); if (StringUtils.isNotBlank(password)) { shell.append(String.format(" -a %s", password)); } shell.append(String.format(" %s", command)); return shell.toString(); } public static String getConfig(int port, boolean isCluster) {<FILL_FUNCTION_BODY>} public static String getRedisPortPidFilePath() { return "logs/redis-port.pid"; } private static final String NUT_CRACKER_SHELL = "bin/nutcracker -c %s/%s -p %s/%s -o %s/%s -s %d -v %d"; public static String getNutCrackerConfName() { return "nutcracker.conf"; } public static String getNutCrackerPidName() { return "nutcracker.pid"; } public static String getNutCrackerLogName() { return "nutcracker.log"; } public static String getNutCrackerShell(String confFilePath, String pidPath, String logPath, int statPort, int logLevel) { return String.format(NUT_CRACKER_SHELL, confFilePath, getNutCrackerConfName(), pidPath, getNutCrackerPidName(), logPath, getNutCrackerLogName(), statPort, logLevel); } public static String getNutCrackerStartCmd(String confFilePath, String pidPath, String logPath, int statPort, int logLevel) { return String.format("bin/mon -a 60 -d \"%s\"", getNutCrackerShell(confFilePath, pidPath, logPath, statPort, logLevel)); } public static String getNutCrackerRunCmd(String confFilePath, String pidPath, String logPath, int statPort, int logLevel) { return getNutCrackerShell(confFilePath, pidPath, logPath, statPort, logLevel); } }
if (isCluster) { return String.format(CLUSTER_CONFIG, port); } else { return String.format(COMMON_CONFIG, port); }
1,756
54
1,810
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/RedisClusterNode.java
RedisClusterNode
toString
class RedisClusterNode { /** * 主节点地址 */ private String masterHost; /** * 从节点地址 */ private String slaveHost; public String getMasterHost() { return masterHost; } public void setMasterHost(String masterHost) { this.masterHost = masterHost; } public String getSlaveHost() { return slaveHost; } public void setSlaveHost(String slaveHost) { this.slaveHost = slaveHost; } public RedisClusterNode(String masterHost, String slaveHost) { this.masterHost = masterHost; this.slaveHost = slaveHost; } public RedisClusterNode() { } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "RedisClusterNode{" + "masterHost='" + masterHost + '\'' + ", slaveHost='" + slaveHost + '\'' + '}';
264
51
315
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/AuthUtil.java
AuthUtil
getAppIdMD5
class AuthUtil { //客户端埋点SECRET_KEY,如果使用动态密码,建议客户端自行修改 public final static String SECRET_KEY = "asdfjlajrl2k3jflsdafjal$$$asfdf"; public final static String SPLIT_KEY = ":cc:"; /** * 密码判定 * 初始化用例: * 1:redis未设置密码,未设置password参数 * 2:redis未设置密码,设置password参数:原文 * 3:redis未设置密码,设置password参数:appId * 4:redis未设置密码,设置password参数:appId+MD5 * 5:redis设置密码, 设置password参数:原文 * 6:redis设置密码, 设置password参数:appId * 7:redis设置密码, 设置password参数:appId+MD5 * 运行期修改密码用例: * 1:redis无密码状态,后端设置原文密码后,连接报错重连通信正常 * 2:redis无密码状态,后端设置appId+MD5密码后,连接报错重连通信正常 * 3:redis存在appId密码,后端修改为md5密码后通信正常 * 期望结果: * 1:验证通过 * 2:原文密码,appId,MD5匹配一个,验证通过。 * 3:密码错误,抛出异常。 * tip: update this method without reset isbroken to true and it will fail when previous condition * @param jedis * @return */ public static void auth(Jedis jedis, String password) { if (password == null || password.trim().length() == 0) { //password为空,认为通过 return; } boolean isAuth = authForPassword(jedis, password); if (isAuth) { if (jedis.getClient().isBroken()) { jedis.close(); } } else { throw new JedisConnectionException("invalid password"); } } private static boolean authForPassword(Jedis jedis, String password) { if (password.contains(SPLIT_KEY)) { //password layout: appId+SPLIT_KEY+MD5 String[] split = password.split(SPLIT_KEY); String appId; String md5 = null; if (split.length == 1) { appId = split[0]; } else { appId = split[0]; md5 = split[1]; } // 如果存在md5,优先使用md5验证 if (md5 != null && md5.length() > 0) { boolean auth = checkAuth(jedis, md5, true); if (auth) { return true; } } md5 = getAppIdMD5(appId); return checkAuth(jedis, md5, false); } else { //不包含{SPLIT_KEY},直接认为是密码。 return "OK".equals(jedis.auth(password)); } } public static boolean checkAuth(Jedis jedis, String pass, boolean check) throws JedisDataException { try { jedis.auth(pass); return true; } catch (JedisDataException e) { if (check && e.getMessage() != null && e.getMessage().contains("invalid password")) { // 密码错误,重新验证 return false; } throw e; } } public static String getAppIdMD5(String appId) {<FILL_FUNCTION_BODY>} }
String key = SECRET_KEY + ":" + appId; try { //确定计算方法 MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] md5Bytes = md5.digest(key.getBytes("UTF-8")); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } catch (Exception e) { e.printStackTrace(); } return null;
979
196
1,175
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/ClusterNodeInformationParser.java
ClusterNodeInformationParser
parse
class ClusterNodeInformationParser { private static final String SLOT_IMPORT_IDENTIFIER = "-<-"; private static final String SLOT_IN_TRANSITION_IDENTIFIER = "["; public static final int SLOT_INFORMATIONS_START_INDEX = 8; public static final int HOST_AND_PORT_INDEX = 1; public ClusterNodeInformation parse(String nodeInfo, HostAndPort current) {<FILL_FUNCTION_BODY>} private String[] extractSlotParts(String[] nodeInfoPartArray) { String[] slotInfoPartArray = new String[nodeInfoPartArray.length - SLOT_INFORMATIONS_START_INDEX]; for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) { slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i]; } return slotInfoPartArray; } public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray, HostAndPort current) { String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX]; String[] arrayHostAndPort = stringHostAndPort.split(":"); return new HostAndPort(arrayHostAndPort[0].isEmpty() ? current.getHost() : arrayHostAndPort[0], arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer.parseInt(arrayHostAndPort[1])); } private void fillSlotInformation(String[] slotInfoPartArray, ClusterNodeInformation info) { for (String slotRange : slotInfoPartArray) { fillSlotInformationFromSlotRange(slotRange, info); } } private void fillSlotInformationFromSlotRange(String slotRange, ClusterNodeInformation info) { if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) { // slot is in transition int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]); if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) { // import info.addSlotBeingImported(slot); } else { // migrate (->-) info.addSlotBeingMigrated(slot); } } else if (slotRange.contains("-")) { // slot range String[] slotRangePart = slotRange.split("-"); for (int slot = Integer.parseInt(slotRangePart[0]); slot <= Integer.parseInt(slotRangePart[1]); slot++) { info.addAvailableSlot(slot); } } else { // single slot info.addAvailableSlot(Integer.parseInt(slotRange)); } } }
String[] nodeInfoPartArray = nodeInfo.split(" "); HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray, current); ClusterNodeInformation info = new ClusterNodeInformation(node); if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) { String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray); fillSlotInformation(slotInfoPartArray, info); } return info;
720
126
846
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/JedisUtil.java
JedisUtil
latencyLatest
class JedisUtil { public static final String SENTINEL_FLUSH_CONFIG = "flushconfig"; public static List<LatencyItem> latencyLatest(Jedis jedis){<FILL_FUNCTION_BODY>} public static String sentinelFlushConfig(Jedis jedis){ Client client = jedis.getClient(); client.sentinel(SENTINEL_FLUSH_CONFIG); return client.getStatusCodeReply(); } public static String getHostPort(Jedis jedis){ Client client = jedis.getClient(); return client.getHost() + ":" + client.getPort(); } }
Client client = jedis.getClient(); client.sendCommand(Command.LATENCY, Keyword.LATEST.raw); List<LatencyItem> latencyItems = LatencyItem.from(client.getObjectMultiBulkReply()); return latencyItems;
180
71
251
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/LatencyHistoryItem.java
LatencyHistoryItem
from
class LatencyHistoryItem { private final long timeStamp; private final long executionTime; private static final String COMMA = ","; @SuppressWarnings("unchecked") public LatencyHistoryItem(List<Object> properties) { super(); this.timeStamp = (Long) properties.get(0); this.executionTime = (Long) properties.get(1); } @SuppressWarnings("unchecked") public static List<LatencyHistoryItem> from(List<Object> nestedMultiBulkReply) {<FILL_FUNCTION_BODY>} public long getTimeStamp() { return timeStamp; } public long getExecutionTime() { return executionTime; } @Override public String toString() { return new StringBuilder().append(timeStamp).append(COMMA).append(executionTime).toString(); } }
List<LatencyHistoryItem> items = new ArrayList<>(nestedMultiBulkReply.size()); for (Object obj : nestedMultiBulkReply) { List<Object> properties = (List<Object>) obj; items.add(new LatencyHistoryItem(properties)); } return items;
239
82
321
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/LatencyItem.java
LatencyItem
from
class LatencyItem { private final String event; private final long timeStamp; private final long latestExecutionTime; private final long maxExecutionTime; private static final String COMMA = ","; @SuppressWarnings("unchecked") private LatencyItem(List<Object> properties) { super(); this.event = new String((byte[])properties.get(0)); this.timeStamp = (Long) properties.get(1); this.latestExecutionTime = (Long) properties.get(2); this.maxExecutionTime = (Long) properties.get(3); } @SuppressWarnings("unchecked") public static List<LatencyItem> from(List<Object> nestedMultiBulkReply) {<FILL_FUNCTION_BODY>} public String getEvent() { return event; } public long getTimeStamp() { return timeStamp; } public long getLatestExecutionTime() { return latestExecutionTime; } public long getMaxExecutionTime() { return maxExecutionTime; } @Override public String toString() { return new StringBuilder().append(event).append(COMMA).append(timeStamp).append(COMMA) .append(latestExecutionTime).append(COMMA).append(maxExecutionTime).toString(); } }
List<LatencyItem> items = new ArrayList<>(nestedMultiBulkReply.size()); for (Object obj : nestedMultiBulkReply) { List<Object> properties = (List<Object>) obj; items.add(new LatencyItem(properties)); } return items;
353
80
433
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/PipelineUtil.java
PipelineUtil
joinParameters
class PipelineUtil { public static Response<Object> latencyHistory(Pipeline pipeline, String event){ return pipeline.sendCommand(Command.LATENCY, Keyword.HISTORY.raw, SafeEncoder.encode(event)); } public static Response<Object> latencyReset(Pipeline pipeline, String event){ return pipeline.sendCommand(Command.LATENCY, joinParameters(Keyword.RESET.raw, SafeEncoder.encodeMany(event))); } public static Response<Object> clusterCountKeysInSlot(Pipeline pipeline, int slot){ byte[][] args = new byte[2][]; args[0] = SafeEncoder.encode(Protocol.CLUSTER_COUNTKEYINSLOT); args[1] = SafeEncoder.encode(String.valueOf(slot)); return pipeline.sendCommand(Command.CLUSTER, args); } public static Response<Object> debug(Pipeline pipeline, DebugParams params){ return pipeline.sendCommand(Command.DEBUG, params.getCommand()); } public static Response<Object> memoryUsage(Pipeline pipeline, String key){ return pipeline.sendCommand(Command.MEMORY, Keyword.USAGE.raw, SafeEncoder.encode(key)); } private static byte[][] joinParameters(byte[] first, byte[][] rest) {<FILL_FUNCTION_BODY>} }
byte[][] result = new byte[rest.length + 1][]; result[0] = first; System.arraycopy(rest, 0, result, 1, rest.length); return result;
343
55
398
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/ProtostuffSerializer.java
ProtostuffSerializer
deserialize
class ProtostuffSerializer { private static ConcurrentHashMap<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>(); public <T> byte[] serialize(final T source) { VO<T> vo = new VO<T>(source); final LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); try { final Schema<VO> schema = getSchema(VO.class); return serializeInternal(vo, schema, buffer); } catch (final Exception e) { throw new IllegalStateException(e.getMessage(), e); } finally { buffer.clear(); } } public <T> T deserialize(final byte[] bytes) {<FILL_FUNCTION_BODY>} private <T> byte[] serializeInternal(final T source, final Schema<T> schema, final LinkedBuffer buffer) { return ProtostuffIOUtil.toByteArray(source, schema, buffer); } private <T> T deserializeInternal(final byte[] bytes, final T result, final Schema<T> schema) { ProtostuffIOUtil.mergeFrom(bytes, result, schema); return result; } private static <T> Schema<T> getSchema(Class<T> clazz) { @SuppressWarnings("unchecked") Schema<T> schema = (Schema<T>) cachedSchema.get(clazz); if (schema == null) { schema = RuntimeSchema.createFrom(clazz); cachedSchema.put(clazz, schema); } return schema; } }
try { Schema<VO> schema = getSchema(VO.class); VO vo = deserializeInternal(bytes, schema.newMessage(), schema); if (vo != null && vo.getValue() != null) { return (T) vo.getValue(); } } catch (final Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null;
431
106
537
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/redis/util/VO.java
VO
equals
class VO<T> implements Serializable { private T value; public VO(T value) { this.value = value; } public VO() { } public T getValue() { return value; } @Override public String toString() { return "VO{" + "value=" + value + '}'; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return value != null ? value.hashCode() : 0; } }
if (this == o) return true; if (!(o instanceof VO)) return false; VO vo = (VO) o; if (value != null ? !value.equals(vo.value) : vo.value != null) return false; return true;
167
72
239
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/brevity/BrevitySchedulerJob.java
BrevitySchedulerJob
action
class BrevitySchedulerJob extends CacheBaseJob { private static final long serialVersionUID = 2626836144949582163L; /** * 维护短频任务 * * @param context */ @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); BrevityScheduler brevityScheduler = applicationContext.getBean(BrevityScheduler.class); brevityScheduler.maintainTasks(); } catch (Exception e) { logger.error(e.getMessage(), e); }
98
115
213
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/brevity/DispatcherBrevityScheduleJob.java
DispatcherBrevityScheduleJob
action
class DispatcherBrevityScheduleJob extends CacheBaseJob { private static final long serialVersionUID = 2626836144949582163L; /** * 维护短频任务 * * @param context */ @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); BrevityScheduler brevityScheduler = applicationContext.getBean(BrevityScheduler.class); brevityScheduler.dispatcherTasks(); } catch (Exception e) { logger.error(e.getMessage(), e); }
100
115
215
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/impl/SchedulerCenterImpl.java
SchedulerCenterImpl
getTrigger
class SchedulerCenterImpl implements SchedulerCenter { private Logger logger = LoggerFactory.getLogger(this.getClass()); // 注入预定义的scheduler @Autowired private Scheduler clusterScheduler; @Autowired private QuartzDao quartzDao; /** * 删除trigger * * @param triggerKey * @return */ @Override public boolean unscheduleJob(TriggerKey triggerKey) { boolean opResult = true; try { opResult = clusterScheduler.checkExists(triggerKey); if (opResult) { opResult = clusterScheduler.unscheduleJob(triggerKey); } } catch (SchedulerException e) { logger.error(e.getMessage(), e); opResult = false; } return opResult; } @Override public Trigger getTrigger(TriggerKey triggerKey) {<FILL_FUNCTION_BODY>} @Override public List<TriggerInfo> getAllTriggers() { return quartzDao.getAllTriggers(); } @Override public List<TriggerInfo> getTriggersByNameOrGroup(String query) { return quartzDao.searchTriggerByNameOrGroup(query); } @Override public boolean pauseTrigger(TriggerKey triggerKey) { try { boolean exists = clusterScheduler.checkExists(triggerKey); if (exists) { clusterScheduler.pauseTrigger(triggerKey); return true; } logger.error("triggerKey={} not exists", triggerKey); return false; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } @Override public boolean resumeTrigger(TriggerKey triggerKey) { try { boolean exists = clusterScheduler.checkExists(triggerKey); if (exists) { clusterScheduler.resumeTrigger(triggerKey); return true; } logger.error("triggerKey={} not exists", triggerKey); return false; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } }
Trigger trigger = null; try { trigger = clusterScheduler.getTrigger(triggerKey); } catch (SchedulerException e) { logger.error(e.getMessage(), e); } return trigger;
662
69
731
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/impl/TriggerCenterImpl.java
TriggerCenterImpl
getTriggersByJobGroup
class TriggerCenterImpl implements TriggerCenter { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private Scheduler clusterScheduler; @Autowired private QuartzDao quartzDao; /** * 暂停trigger * * @param triggerKey * @return 操作成功返回true,否则返回false; */ @Override public boolean pauseTrigger(TriggerKey triggerKey) { boolean opResult = true; try { clusterScheduler.pauseTrigger(triggerKey); } catch (SchedulerException e) { logger.error(e.getMessage(), e); opResult = false; } return opResult; } /** * 恢复暂停的trigger * * @param triggerKey */ @Override public boolean resumeTrigger(TriggerKey triggerKey) { boolean opResult = true; try { clusterScheduler.resumeTrigger(triggerKey); } catch (SchedulerException e) { logger.error(e.getMessage(), e); opResult = false; } return opResult; } /** * 删除一个trigger * * @param triggerKey * @return */ @Override public boolean removeTrigger(TriggerKey triggerKey) { boolean opResult = true; try { clusterScheduler.unscheduleJob(triggerKey); } catch (SchedulerException e) { logger.error(e.getMessage(), e); opResult = false; } return opResult; } /** * 查询特定job类型下的所有trigger * * @param jobGroup job类型:redis/machine/machineMonitor * @return */ @Override public List<TriggerInfo> getTriggersByJobGroup(String jobGroup) {<FILL_FUNCTION_BODY>} /** * 返回所有的trigger * * @return */ @Override public List<TriggerInfo> getAllTriggers() { List<TriggerInfo> allTriggers = null; try { allTriggers = quartzDao.getAllTriggers(); } catch (Exception e) { logger.error(e.getMessage(), e); } return allTriggers; } /** * 查询trigger,模糊匹配trigger name或trigger group * * @param queryString trigger name或trigger group的关键字 * @return */ @Override public List<TriggerInfo> searchTriggerByNameOrGroup(String queryString) { List<TriggerInfo> matchTriggers = null; try { matchTriggers = quartzDao.searchTriggerByNameOrGroup(queryString); } catch (Exception e) { logger.error("queryString: {}", queryString, e); } return matchTriggers; } }
List<TriggerInfo> triggersOfGroup = null; try { triggersOfGroup = quartzDao.getTriggersByJobGroup(jobGroup); } catch (Exception e) { logger.error("jobGroup: {}", jobGroup, e); } return triggersOfGroup;
879
86
965
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/AppDailyJob.java
AppDailyJob
action
class AppDailyJob extends CacheBaseJob { private static final long serialVersionUID = 7751425759758902400L; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); Environment env = applicationContext.getBean(Environment.class); if (EnvUtil.isDev(env)) { logger.warn("environment is dev ignored"); return; } try { AppDailyDataCenter appDailyDataCenter = applicationContext.getBean("appDailyDataCenter", AppDailyDataCenter.class); appDailyDataCenter.sendAppDailyEmail(); } catch (Exception e) { logger.error("sendAppDailyEmail error", e.getMessage()); } } catch (SchedulerException e) { logger.error(e.getMessage(), e); }
74
206
280
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/CacheBaseJob.java
CacheBaseJob
execute
class CacheBaseJob implements Job, Serializable { private static final long serialVersionUID = -6605766126594260961L; protected Logger logger = LoggerFactory.getLogger(this.getClass()); protected final static String APPLICATION_CONTEXT_KEY = "applicationContext"; // 抽象方法,由子类实现,即具体的业务逻辑 public abstract void action(JobExecutionContext context); /** * 统计时间 * * @param context * @throws JobExecutionException */ @Override public void execute(JobExecutionContext context) throws JobExecutionException {<FILL_FUNCTION_BODY>} }
long start = System.currentTimeMillis(); this.action(context); long cost = System.currentTimeMillis() - start; if (cost > 2000) { logger.warn("slowJob: job: {}, trigger: {}, cost: {} ms", context.getJobDetail().getKey(), context.getTrigger().getKey(), cost); } else { logger.debug("job: {}, trigger: {}, cost: {} ms", context.getJobDetail().getKey(), context.getTrigger().getKey(), cost); }
194
150
344
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/CleanupDayAppClientStatJob.java
CleanupDayAppClientStatJob
action
class CleanupDayAppClientStatJob extends CacheBaseJob { private static final long serialVersionUID = 8815839394475276540L; /** * 清除命令统计&异常统计 */ private static int BATCH_SIZE = 1000; private static final String CLEAN_APP_CLIENT_COMMAND_MINUTE_STATISTICS = "delete from app_client_command_minute_statistics where current_min < ? limit " + BATCH_SIZE; private static final String CLEAN_APP_CLIENT_EXCEPTION_MINUTE_STATISTICS = "delete from app_client_exception_minute_statistics where current_min < ? limit " + BATCH_SIZE; private static final String CLEAN_APP_CLIENT_LATENCY_COMMAND = "delete from app_client_latency_command where create_time < ? limit " + BATCH_SIZE; private static final String CLEAN_APP_CLIENT_STATISTIC_GATHER = "delete from app_client_statistic_gather where gather_time < ? limit " + BATCH_SIZE; private static final String CLEAN_INSTANCE_LATENCY_HISTORY = "delete from instance_latency_history where execute_date < ? limit " + BATCH_SIZE; JdbcTemplate jdbcTemplate = null; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} /** * 滚动删除表数据 */ private long scrollDelete(String sql, Object time) { long totalCount = 0; while (true) { int cleanCount = jdbcTemplate.update(sql, time); totalCount += cleanCount; if (cleanCount == 0) { break; } } return totalCount; } }
if (!ConstUtils.WHETHER_SCHEDULE_CLEAN_DATA) { logger.warn("whether_schedule_clean_data is false , ignored"); return; } try { logger.warn("begin-CleanupDayAppClientStatJob"); SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_MONTH, -14); long timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm00").format(calendar.getTime())); String date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()); /** * 清除命令统计&异常统计(保存14天) */ long cleanCount = 0; try{ cleanCount = scrollDelete(CLEAN_APP_CLIENT_COMMAND_MINUTE_STATISTICS, timeFormat); logger.warn("clean_app_client_command_minute_statistics count={}", cleanCount); }catch (Exception e){ logger.error("clean_app_client_command_minute_statistics error, ", e); } try{ cleanCount = scrollDelete(CLEAN_APP_CLIENT_EXCEPTION_MINUTE_STATISTICS, timeFormat); logger.warn("clean_app_client_exception_minute_statistics count={}", cleanCount); }catch (Exception e){ logger.error("clean_app_client_exception_minute_statistics error, ", e); } try{ cleanCount = scrollDelete(CLEAN_APP_CLIENT_LATENCY_COMMAND, calendar.getTime()); logger.warn("clean_app_client_latency_command count={}", cleanCount); }catch (Exception e){ logger.error("clean_app_client_latency_command error, ", e); } try{ cleanCount = scrollDelete(CLEAN_APP_CLIENT_STATISTIC_GATHER, date); logger.warn("clean_app_client_statistic_gather count={}", cleanCount); }catch (Exception e){ logger.error("clean_app_client_statistic_gather error, ", e); } try{ cleanCount = scrollDelete(CLEAN_INSTANCE_LATENCY_HISTORY, timeFormat); logger.warn("clean_instance_latency_history count={}", cleanCount); }catch (Exception e){ logger.error("clean_instance_latency_history error, ", e); } logger.warn("end-CleanupDayAppClientStatJob"); } catch (Exception e) { logger.error("CleanupDayAppClientStatJob error, ", e); }
467
762
1,229
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/CleanupDayDimensionalityJob.java
CleanupDayDimensionalityJob
action
class CleanupDayDimensionalityJob extends CacheBaseJob { private static final long serialVersionUID = 8815839394475276540L; private static int BATCH_SIZE = 1000; private static final String CLEAN_APP_HOUR_COMMAND_STATISTICS = "delete from app_hour_command_statistics where create_time < ? limit " + BATCH_SIZE; private static final String CLEAN_APP_MINUTE_COMMAND_STATISTICS = "delete from app_minute_command_statistics where create_time < ? limit " + BATCH_SIZE; private static final String CLEAN_APP_HOUR_STATISTICS = "delete from app_hour_statistics where create_time < ? limit " + BATCH_SIZE; private static final String CLEAN_APP_MINUTE_STATISTICS = "delete from app_minute_statistics where create_time < ? limit " + BATCH_SIZE; /** * 清除客户端耗时汇总数据 */ private static final String CLEAN_APP_CLIENT_MINUTE_COST_TOTAL = "delete from app_client_costtime_minute_stat_total where collect_time < ? limit " + BATCH_SIZE; //清除服务器统计数据 private static final String CLEAN_SERVER_STAT_STATISTICS = "delete from server_stat where cdate < ? limit " + BATCH_SIZE; /** * 清除实例基础统计 */ private static final String CLEAN_INSTANCE_MINUTE_STATS = "delete from instance_minute_stats where collect_time < ? limit " + BATCH_SIZE; JdbcTemplate jdbcTemplate = null; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} /** * 滚动删除表数据 */ private long scrollDelete(String sql, Object time) { long totalCount = 0; while (true) { int cleanCount = jdbcTemplate.update(sql, time); totalCount += cleanCount; if (cleanCount == 0) { break; } } return totalCount; } }
if (!ConstUtils.WHETHER_SCHEDULE_CLEAN_DATA) { logger.warn("whether_schedule_clean_data is false , ignored"); return; } try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); // 清除应用&命令统计数据(保存31天) calendar.add(Calendar.DAY_OF_MONTH, -31); Date time = calendar.getTime(); long cleanCount = 0; cleanCount = scrollDelete(CLEAN_APP_HOUR_COMMAND_STATISTICS, time); logger.warn("clean_app_hour_command_statistics count={}", cleanCount); cleanCount = scrollDelete(CLEAN_APP_MINUTE_COMMAND_STATISTICS, time); logger.warn("clean_app_minute_command_statistics count={}", cleanCount); cleanCount = scrollDelete(CLEAN_APP_HOUR_STATISTICS, time); logger.warn("clean_app_hour_statistics count={}", cleanCount); cleanCount = scrollDelete(CLEAN_APP_MINUTE_STATISTICS, time); logger.warn("clean_app_minute_statistics count={}", cleanCount); //清除服务器统计数据 calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_MONTH, -7); String date = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()); cleanCount = scrollDelete(CLEAN_SERVER_STAT_STATISTICS, date); logger.warn("clean_server_stat_total count={}", cleanCount); long timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm00").format(calendar.getTime())); //清除进程级别统计数据(保存5天) long start = System.currentTimeMillis(); timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm").format(DateUtils.addDays(new Date(), -5))); cleanCount = scrollDelete(CLEAN_INSTANCE_MINUTE_STATS, timeFormat); logger.warn("clean_instance_minute_stats timeFormat={} count={} cost={}s", timeFormat, cleanCount, (System.currentTimeMillis() - start) / 1000); //注销此逻辑,其操作的表已废弃,待统一删除 //清除客户端耗时数据(保存2天) // ClientReportCostDistriService clientReportCostDistriService = applicationContext.getBean( // "clientReportCostDistriService", ClientReportCostDistriService.class); // calendar.setTime(new Date()); // calendar.add(Calendar.DAY_OF_MONTH, -2); // timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm00").format(calendar.getTime())); // cleanCount = clientReportCostDistriService.deleteBeforeCollectTime(timeFormat); // logger.warn("clean_app_client_costtime_minute_stat count={}", cleanCount); //清除客户端耗时汇总数据(保存14天) calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_MONTH, -14); timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm00").format(calendar.getTime())); cleanCount = jdbcTemplate.update(CLEAN_APP_CLIENT_MINUTE_COST_TOTAL, timeFormat); logger.warn("clean_app_client_costtime_minute_stat_total count={}", cleanCount); //清除客户端值数据(保存2天) ClientReportValueDistriService clientReportValueDistriService = applicationContext.getBean( "clientReportValueDistriService", ClientReportValueDistriService.class); calendar.setTime(new Date()); calendar.add(Calendar.DAY_OF_MONTH, -2); timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm00").format(calendar.getTime())); cleanCount = clientReportValueDistriService.deleteBeforeCollectTime(timeFormat); logger.warn("clean_app_client_value_minute_stats count={}", cleanCount); } catch (Exception e) { logger.error(e.getMessage(), e); }
565
1,184
1,749
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/CleanupMinuteDimensionalityJob.java
CleanupMinuteDimensionalityJob
action
class CleanupMinuteDimensionalityJob extends CacheBaseJob { private static final long serialVersionUID = 8815839394475276540L; /** * 实例基准数据,主要用于报警 */ private static final String CLEAN_STANDARD_STATISTICS = "delete from standard_statistics where collect_time < ?"; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
if (!ConstUtils.WHETHER_SCHEDULE_CLEAN_DATA) { logger.warn("whether_schedule_clean_data is false , ignored"); return; } try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); //清除进程级别统计数据(保存最近10分钟) long start = System.currentTimeMillis(); Date date = DateUtils.addMinutes(new Date(), -10); long timeFormat = NumberUtils.toLong(new SimpleDateFormat("yyyyMMddHHmm").format(date)); int cleanCount = jdbcTemplate.update(CLEAN_STANDARD_STATISTICS, timeFormat); logger.warn("clean_standard_statistics timeFormat={} count={} cost:{} ms", timeFormat, cleanCount, (System.currentTimeMillis() - start)); } catch (Exception e) { logger.error(e.getMessage(), e); }
145
317
462
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/ExpAppsDailyJob.java
ExpAppsDailyJob
action
class ExpAppsDailyJob extends CacheBaseJob { private static final long serialVersionUID = 8864245475347417291L; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); Environment env = applicationContext.getBean(Environment.class); if (EnvUtil.isDev(env)) { logger.warn("environment is dev ignored"); return; } try { CoreAppsStatCenter coreAppsStatCenter = applicationContext.getBean("coreAppsStatCenter", CoreAppsStatCenter.class); coreAppsStatCenter.sendExpAppsStatDataEmail(null); logger.info("expAppsStatData daily email"); } catch (Exception e) { logger.error("expAppClientStat daily report error", e.getMessage()); } } catch (SchedulerException e) { logger.error(e.getMessage(), e); }
77
226
303
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/GatherAppClientStatisticsJob.java
GatherAppClientStatisticsJob
fillWithDateFormat
class GatherAppClientStatisticsJob extends CacheBaseJob { private static final long serialVersionUID = 8815839394475276540L; private final static String COLLECT_TIME_FORMAT = "yyyyMMddHHmm00"; @Override public void action(JobExecutionContext context) { try { logger.warn("begin-gatherAppClientStatisticsJob"); SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); AppClientStatisticGatherService appClientStatisticGatherService = applicationContext.getBean("appClientStatisticGatherService", AppClientStatisticGatherService.class); //前5-10分钟 TimeBetween timeBetween = fillWithDateFormat(); long startTime = timeBetween.getStartTime(); long endTime = timeBetween.getEndTime(); appClientStatisticGatherService.bathAdd(startTime, endTime); logger.warn("end-gatherAppClientStatisticsJob, startTime={} endTime:{}", startTime, endTime); } catch (Exception e) { logger.error(e.getMessage(), e); } } private TimeBetween fillWithDateFormat() {<FILL_FUNCTION_BODY>} }
Date endDate = DateUtils.addMinutes(new Date(), -5); Date startDate = DateUtils.addMinutes(endDate, -5); long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT)); long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT)); return new TimeBetween(startTime, endTime, startDate, endDate);
346
117
463
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/InstanceAlertValueJob.java
InstanceAlertValueJob
action
class InstanceAlertValueJob extends CacheBaseJob { private static final long serialVersionUID = 1035952011763660681L; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { long startTime = System.currentTimeMillis(); SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); Environment env = applicationContext.getBean(Environment.class); if (EnvUtil.isDev(env)) { logger.warn("environment is dev ignored"); return; } InstanceAlertConfigService instanceAlertConfigService = applicationContext.getBean("instanceAlertConfigService", InstanceAlertConfigService.class); instanceAlertConfigService.monitorLastMinuteAllInstanceInfo(); logger.info("InstanceAlertValueJob cost time {} ms", (System.currentTimeMillis() - startTime)); } catch (SchedulerException e) { logger.error(e.getMessage(), e); }
82
239
321
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/InstanceStatJob.java
InstanceStatJob
action
class InstanceStatJob extends CacheBaseJob{ @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { long startTime = System.currentTimeMillis(); SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); Environment env = applicationContext.getBean(Environment.class); if (EnvUtil.isDev(env)) { logger.warn("environment is dev ignored"); return; } InstanceStateInspector instanceStateInspector = applicationContext.getBean("instanceStateInspector", InstanceStateInspector.class); instanceStateInspector.inspect(); logger.info("InstanceAlertValueJob cost time {} ms", (System.currentTimeMillis() - startTime)); } catch (SchedulerException e) { logger.error(e.getMessage(), e); }
41
209
250
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/ReviseAppClientStatisGatherJob.java
ReviseAppClientStatisGatherJob
fillWithDateFormat
class ReviseAppClientStatisGatherJob extends CacheBaseJob { private static final long serialVersionUID = -5968147536403452672L; private final static String COLLECT_TIME_FORMAT = "yyyyMMdd000000"; @Override public void action(JobExecutionContext context) { try { logger.warn("begin-reviseAppClientStatisGatherJob"); SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); AppClientStatisticGatherService appClientStatisticGatherService = applicationContext.getBean("appClientStatisticGatherService", AppClientStatisticGatherService.class); //前一天 TimeBetween timeBetween = fillWithDateFormat(); long startTime = timeBetween.getStartTime(); long endTime = timeBetween.getEndTime(); appClientStatisticGatherService.bathSave(startTime, endTime); logger.warn("end-reviseAppClientStatisGatherJob, startTime={} endTime:{}", startTime, endTime); } catch (Exception e) { logger.error(e.getMessage(), e); } } private TimeBetween fillWithDateFormat() {<FILL_FUNCTION_BODY>} }
Date endDate = new Date(); Date startDate = DateUtils.addDays(endDate, -1); long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT)); long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT)); return new TimeBetween(startTime, endTime, startDate, endDate);
353
107
460
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/SystemConfigRefreshJob.java
SystemConfigRefreshJob
action
class SystemConfigRefreshJob extends CacheBaseJob { private static final long serialVersionUID = 7751425759758902400L; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); ConfigService configService = applicationContext.getBean("configService", ConfigService.class); configService.reloadSystemConfig(); } catch (SchedulerException e) { logger.error(e.getMessage(), e); }
81
121
202
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/schedule/jobs/TaskExecuteJob.java
TaskExecuteJob
action
class TaskExecuteJob extends CacheBaseJob { private static final long serialVersionUID = -1697673324465500314L; @Override public void action(JobExecutionContext context) {<FILL_FUNCTION_BODY>} }
long startTime = System.currentTimeMillis(); logger.warn("TaskExecuteJob start"); try { SchedulerContext schedulerContext = context.getScheduler().getContext(); ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY); TaskService taskService = applicationContext.getBean(TaskService.class); taskService.executeNewTask(); } catch (Exception e) { logger.error(e.getMessage(), e); } logger.warn("TaskExecuteJob end, cost time is {} ms", (System.currentTimeMillis() - startTime));
76
160
236
<methods>public non-sealed void <init>() ,public abstract void action(JobExecutionContext) ,public void execute(JobExecutionContext) throws JobExecutionException<variables>protected static final java.lang.String APPLICATION_CONTEXT_KEY,protected org.slf4j.Logger logger,private static final long serialVersionUID
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/ServerStatusCollector.java
ServerStatusCollector
asyncFetchServerStatus
class ServerStatusCollector { private static final Logger logger = LoggerFactory.getLogger(ServerStatusCollector.class); //获取监控结果 public static final String COLLECT_SERVER_STATUS = "[ -e \"" + NMONService.SOCK_LOG + "\" ] && /bin/cat " + NMONService.SOCK_LOG + " >> " + NMONService.NMON_LOG + ";[ -e \"" + NMONService.ULIMIT_LOG + "\" ] && /bin/cat " + NMONService.ULIMIT_LOG + " >> " + NMONService.NMON_LOG + ";/bin/mv " + NMONService.NMON_LOG + " " + NMONService.NMON_OLD_LOG + ";[ $? -eq 0 ] && /bin/cat " + NMONService.NMON_OLD_LOG; //nmon服务 @Autowired private NMONService nmonService; //ssh 模板类 @Autowired private SSHTemplate sshTemplate; //持久化 @Autowired private ServerDataService serverDataService; @Autowired private AsyncService asyncService; @PostConstruct public void init() { asyncService.assemblePool(AsyncThreadPoolFactory.MACHINE_POOL, AsyncThreadPoolFactory.MACHINE_THREAD_POOL); } //异步执行任务 public void asyncFetchServerStatus(final String ip) {<FILL_FUNCTION_BODY>} /** * 抓取服务器状态 * * @param ip */ public void fetchServerStatus(final String ip) { try { sshTemplate.execute(ip, new SSHCallback() { public Result call(SSHSession session) { //尝试收集服务器运行状况 collectServerStatus(ip, session); //启动nmon收集服务器运行状况 OSInfo info = nmonService.start(ip, session); saveServerStatus(ip, info); return null; } }); } catch (Exception e) { logger.error("fetchServerStatus " + ip + " err", e); } } /** * 收集系统状况 * * @param ip * @param session */ private void collectServerStatus(String ip, SSHSession session) { final Server server = new Server(); server.setIp(ip); Result result = session.executeCommand(COLLECT_SERVER_STATUS, new DefaultLineProcessor() { public void process(String line, int lineNum) throws Exception { server.parse(line, null); } }); if (!result.isSuccess()) { logger.error("collect " + ip + " err:" + result.getResult(), result.getExcetion()); } //保存服务器静态信息 serverDataService.saveAndUpdateServerInfo(server); //保存服务器状况信息 serverDataService.saveServerStat(server); } /** * 保存服务器dist信息 * * @param ip * @param osInfo */ private void saveServerStatus(String ip, OSInfo osInfo) { if (osInfo == null) { return; } serverDataService.saveServerInfo(ip, osInfo.getIssue()); } public void setNmonService(NMONService nmonService) { this.nmonService = nmonService; } public void setSshTemplate(SSHTemplate sshTemplate) { this.sshTemplate = sshTemplate; } public void setServerDataService(ServerDataService serverDataService) { this.serverDataService = serverDataService; } public void setAsyncService(AsyncService asyncService) { this.asyncService = asyncService; } }
String key = "collect-server-" + ip; asyncService.submitFuture(AsyncThreadPoolFactory.MACHINE_POOL, new KeyCallable<Boolean>(key) { public Boolean execute() { try { fetchServerStatus(ip); return true; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } });
1,080
119
1,199
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/data/CPU.java
Usage
toString
class Usage{ //代表那个cpu private String name; //用户空间使用率 private float user; //内核空间使用率 private float sys; //wio private float wait; public float getUser() { return user; } public void setUser(float user) { this.user = user; } public float getSys() { return sys; } public void setSys(float sys) { this.sys = sys; } public float getWait() { return wait; } public void setWait(float wait) { this.wait = wait; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Usage [name=" + name + ", user=" + user + ", sys=" + sys + ", wait=" + wait + "]";
270
44
314
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/data/Connection.java
Connection
parse
class Connection implements LineParser{ public static final String FLAG = "TCP"; private int established; private int timeWait; private int orphan; /** * line format: * TCP: inuse 454 orphan 0 tw 159620 alloc 454 mem 79 */ public void parse(String line, String timeKey) throws Exception{<FILL_FUNCTION_BODY>} public int getEstablished() { return established; } public int getTimeWait() { return timeWait; } public int getOrphan() { return orphan; } }
if(line.startsWith(FLAG)) { String[] items = line.split("\\s+"); for(int i = 0; i < items.length; ++i) { if(items[i].equals("inuse")) { established = NumberUtils.toInt(items[i+1]); } else if(items[i].equals("orphan")) { orphan = NumberUtils.toInt(items[i+1]); } else if(items[i].equals("tw")) { timeWait = NumberUtils.toInt(items[i+1]); } } }
186
170
356
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/data/Load.java
Load
toString
class Load implements LineParser{ public static final Pattern PATTERN = Pattern.compile( "^BBBP,[0-9]+,uptime,.*(\\d+\\.\\d+), (\\d+\\.\\d+), (\\d+\\.\\d+)"); //1分钟负载 private float load1; //5分钟负载 private float load5; //15分钟负载 private float load15; /** * line format: * BBBP,585,uptime," 09:35:00 up 567 days, 15:07, 0 users, load average: 0.60, 0.63, 0.67" */ public void parse(String line, String timeKey) throws Exception{ Matcher matcher = PATTERN.matcher(line); if(matcher.find()) { load1 = NumberUtils.toFloat(matcher.group(1)); load5 = NumberUtils.toFloat(matcher.group(2)); load15 = NumberUtils.toFloat(matcher.group(3)); } } public float getLoad1() { return load1; } public float getLoad5() { return load5; } public float getLoad15() { return load15; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Load [load1=" + load1 + ", load5=" + load5 + ", load15=" + load15 + "]";
398
45
443
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/data/Memory.java
Memory
toString
class Memory implements LineParser{ public static final String FLAG = "MEM"; //总内存,单位M private float total; //总空闲内存,单位M private float totalFree; //buffer,单位M private float buffer; //cache,单位M private float cache; //swap,单位M private float swap; //swap空闲内存,单位M private float swapFree; /** * line format: * MEM,Memory MB bx-50-13,memtotal,hightotal,lowtotal,swaptotal,memfree,highfree,lowfree,swapfree,memshared,cached,active,bigfree,buffers,swapcached,inactive * MEM,T0001,48288.7,0.0,48288.7,8189.4,132.6,0.0,132.6,8189.1,-0.0,24210.6,30819.7,-1.0,153.9,0.0,16451.1 */ public void parse(String line, String timeKey) throws Exception{ if(line.startsWith(FLAG)) { String[] items = line.split(","); if(!items[1].equals(timeKey)) { return; } total = NumberUtils.toFloat(items[2]); swap = NumberUtils.toFloat(items[5]); totalFree = NumberUtils.toFloat(items[6]); swapFree = NumberUtils.toFloat(items[9]); cache = NumberUtils.toFloat(items[11]); buffer = NumberUtils.toFloat(items[14]); } } public float getTotal() { return total; } public float getTotalFree() { return totalFree; } public float getBuffer() { return buffer; } public float getCache() { return cache; } public float getSwap() { return swap; } public float getSwapFree() { return swapFree; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "Memory [total=" + total + ", totalFree=" + totalFree + ", buffer=" + buffer + ", cache=" + cache + ", swap=" + swap + ", swapFree=" + swapFree + "]";
619
65
684
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/data/Net.java
Net
caculate
class Net implements LineParser{ public static final String FLAG = "NET,"; private float nin; private float nout; private StringBuilder ninDetail = new StringBuilder(); private StringBuilder noutDetail = new StringBuilder(); private List<NetworkInterfaceCard> ncList = new ArrayList<NetworkInterfaceCard>(); /** * line format: * NET,Network I/O bx-50-13,lo-read-KB/s,eth0-read-KB/s,eth1-read-KB/s,eth2-read-KB/s,eth3-read-KB/s,lo-write-KB/s,eth0-write-KB/s,eth1-write-KB/s,eth2-write-KB/s,eth3-write-KB/s, * NET,T0001,190.3,3317.8,0.0,0.0,0.0,190.3,3377.7,0.0,0.0,0.0, */ public void parse(String line, String timeKey) throws Exception{ if(line.startsWith(FLAG)) { String[] items = line.split(","); if(items[1].startsWith("Network")) { for(int i = 0; i < items.length; ++i) { if(items[i].startsWith("eth")) { NetworkInterfaceCard nic = new NetworkInterfaceCard(); nic.setName(items[i]); nic.setIdx(i); ncList.add(nic); } } } else { for(NetworkInterfaceCard nic : ncList) { nic.setValue(NumberUtils.toFloat(items[nic.getIdx()])); } caculate(); } } } private void caculate() {<FILL_FUNCTION_BODY>} public float getNin() { return nin; } public float getNout() { return nout; } public String getNinDetail() { return ninDetail.toString(); } public String getNoutDetail() { return noutDetail.toString(); } static class NetworkInterfaceCard{ private String name; private float value; private int idx; public String getName() { return name; } public void setName(String name) { this.name = name; } public float getValue() { return value; } public void setValue(float value) { this.value = value; } public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } } }
float totalIn = 0; float totalOut = 0; for(NetworkInterfaceCard nic : ncList) { String[] array = nic.getName().split("-"); if("read".equals(array[1])) { ninDetail.append(array[0]); ninDetail.append(","); ninDetail.append(nic.getValue()); ninDetail.append(";"); totalIn += nic.getValue(); } else if("write".equals(array[1])) { noutDetail.append(array[0]); noutDetail.append(","); noutDetail.append(nic.getValue()); noutDetail.append(";"); totalOut += nic.getValue(); } } nin = BigDecimal.valueOf(totalIn).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(); nout = BigDecimal.valueOf(totalOut).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
783
294
1,077
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/data/OS.java
OS
toString
class OS { //操作系统类型 private OSType osType; //发行版本 private DistributionType distributionType; //发行版本号 private DistributionVersion distributionVersion; //处理器架构 private ProcessorArchitecture processorArchitecture; public OS(OSType osType, DistributionType distributionType, DistributionVersion distributionVersion, ProcessorArchitecture processorArchitecture) { this.osType = osType; this.distributionType = distributionType; this.distributionVersion = distributionVersion; this.processorArchitecture = processorArchitecture; } public OSType getOsType() { return osType; } public void setOsType(OSType osType) { this.osType = osType; } public DistributionType getDistributionType() { return distributionType; } public void setDistributionType(DistributionType distributionType) { this.distributionType = distributionType; } public DistributionVersion getDistributionVersion() { return distributionVersion; } public void setDistributionVersion(DistributionVersion distributionVersion) { this.distributionVersion = distributionVersion; } public ProcessorArchitecture getProcessorArchitecture() { return processorArchitecture; } public void setProcessorArchitecture(ProcessorArchitecture processorArchitecture) { this.processorArchitecture = processorArchitecture; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "OS [osType=" + osType + ", dist=" + distributionType + ", version=" + distributionVersion + ", bit=" + processorArchitecture + "]";
412
56
468
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/server/nmon/NMONService.java
NMONService
start
class NMONService { private static final Logger logger = LoggerFactory.getLogger(NMONService.class); //获取系统版本位数命令 public static final String OS_INFO_CMD = "/bin/uname -a; /bin/cat /etc/issue"; //nmon路径 public static final String NMON_DIR = "/opt/cachecloud/soft/"; //nmon文件名 public static final String NMON = "nmon"; //nmon完整路径 public static final String NMON_FILE = NMON_DIR + NMON; //获取nmon版本 public static final String NMON_VERSION = "[ -e \"" + NMON_FILE + "\" ] && " + NMON_FILE + " -V"; //nmon输出的结果文件 public static final String NMON_LOG = "/tmp/nmon.log"; //nmon输出的老结果文件 public static final String NMON_OLD_LOG = "/tmp/nmon.old.log"; //tcp输出的结果文件 public static final String SOCK_LOG = "/tmp/sock.log"; //ulimit输出的结果文件 public static final String ULIMIT_LOG = "/tmp/ulimit.log"; //nmon监控启动 public static final String START_SERVER_COLLECT = NMON_FILE + " -F " + NMON_LOG + " -s0 -c1;" + "/bin/grep TCP /proc/net/sockstat > " + SOCK_LOG + ";ulimit -n -u > " + ULIMIT_LOG ; //创建nmon路径 public static final String MK_NMON_DIR = "/bin/mkdir -p /opt/cachecloud/soft/"; /** * 启动nmon收集系统状况 * * @param ip * @param session * @return @OSInfo 收集到的操作系统信息 */ public OSInfo start(String ip, SSHSession session) {<FILL_FUNCTION_BODY>} /** * 尝试修复启动失败的错误 * * @param ip * @param session */ private OSInfo initNmon(String ip, SSHSession session) { //获取nmon版本 String version = getNMONVersion(ip, session); //获取操作系统原始信息 OSInfo osInfo = getOSInfo(ip, session); OS os = null; //nmon文件不存在,需要根据操作系统识别是否支持 if (null == version) { logger.warn("{} not exist {}", ip, NMON_FILE); //将原始信息转换为可识别的操作系统 os = OSFactory.getOS(osInfo); } else { //nmon存在,但是版本有问题,此时不应该再判断系统信息了,直接用默认的 logger.warn("{} {} version err:" + version, ip, NMON_FILE); os = OSFactory.getDefaultOS(osInfo); } if (os == null) { logger.error("unkonw os info={}", osInfo); return null; } //获取nmon文件 File nmonFile = NMONFileFactory.getNMONFile(os); if (nmonFile == null) { logger.warn("{} no corresponding nmon file", os); nmonFile = NMONFileFactory.getNMONFile(OSFactory.getDefaultOS(osInfo)); } //将nmon文件传输至服务器 sendNMONToServer(ip, session, nmonFile); return osInfo; } /** * 获取nmon文件版本 * * @param ip * @param session * @return 存在返回版本,不存在返回null, 执行错误返回异常 */ private String getNMONVersion(String ip, SSHSession session) { Result nmonVersionResult = session.executeCommand(NMON_VERSION); if (nmonVersionResult.isSuccess()) { return nmonVersionResult.getResult(); } else { logger.error(NMON_VERSION + " err:" + nmonVersionResult.getResult(), nmonVersionResult.getExcetion()); } return null; } /** * 获取操作系统信息 * * @param ip * @param session * @return OSInfo */ private OSInfo getOSInfo(String ip, SSHSession session) { final OSInfo osInfo = new OSInfo(); session.executeCommand(OS_INFO_CMD, new DefaultLineProcessor() { public void process(String line, int lineNum) throws Exception { switch (lineNum) { case 1: osInfo.setUname(line); break; case 2: osInfo.setIssue(line); break; default: break; } } }); return osInfo; } /** * 将nmon文件scp到服务器上 * * @param ip * @param session * @param nmonFile */ private void sendNMONToServer(String ip, SSHSession session, File nmonFile) { Result mkResult = session.executeCommand(MK_NMON_DIR); if (!mkResult.isSuccess()) { logger.error("mkdir err:" + mkResult.getResult(), mkResult.getExcetion()); return; } Result scpRst = session.scpToFile(nmonFile.getAbsolutePath(), NMON, NMON_DIR); if (scpRst.isSuccess()) { logger.info("scp {} to {} success", nmonFile.getAbsolutePath(), ip); } else { logger.error("scp to " + ip + " err", scpRst.getExcetion()); } } }
Result startCollectResult = session.executeCommand(START_SERVER_COLLECT); if (!startCollectResult.isSuccess()) { logger.error("start nmon " + ip + " err:" + startCollectResult.getResult(), startCollectResult.getExcetion()); //执行命令没有发生异常,则nmon可能不存在或有问题 if (startCollectResult.getExcetion() == null) { //尝试处理出错信息 return initNmon(ip, session); } } return null;
1,614
147
1,761
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/ssh/SSHClient.java
SSHClient
connect
class SSHClient { // 服务器 ssh 用户 private String serverUser; // 服务器 ssh 密码 private String serverPassword; // 服务器 ssh 端口 private Integer serverPort; // 服务器 ssh 链接建立超时时间 private Integer serverConnectTimeout; // 服务器 ssh 操作超时时间 private Integer serverOPTimeout; // 服务器 ssh 私钥 private String privateKeyPath; private SshClient client; public void init() throws GeneralSecurityException, IOException { client = buildSshClient(); if (StringUtils.isNotEmpty(privateKeyPath)) { setAuthByKey(client); } client.setPasswordIdentityProvider(PasswordIdentityProvider.wrapPasswords(getServerPassword())); client.start(); } private SshClient buildSshClient() { SshClient client = SshClient.setUpDefaultClient(); client.setSessionHeartbeat(Session.HeartbeatType.IGNORE, TimeUnit.SECONDS, 10); return client; } private void setAuthByKey(SshClient client) throws GeneralSecurityException, IOException { KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser(); Collection<KeyPair> keys = loader.loadKeyPairs(null, Paths.get(privateKeyPath), null); client.setKeyIdentityProvider(KeyIdentityProvider.wrapKeyPairs(keys)); } /** * 连接服务器 * * @param ip * @return * @throws IOException */ public ClientSession connect(String ip) throws IOException {<FILL_FUNCTION_BODY>} }
ClientSession session = getClient().connect(getServerUser(), ip, getServerPort()).verify(getServerConnectTimeout(), TimeUnit.MILLISECONDS).getSession(); session.auth().verify(getServerConnectTimeout(), TimeUnit.MILLISECONDS); return session;
435
72
507
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/ssh/SSHMachineInfo.java
SSHMachineInfo
equals
class SSHMachineInfo { /** * ip */ private String ip; /** * 用户名 */ private String username; /** * 登录方式 */ private int authType; /** * 密码 */ private String password; @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(ip, username, authType, password); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SSHMachineInfo that = (SSHMachineInfo) o; return authType == that.authType && Objects.equals(ip, that.ip) && Objects.equals(password, that.password) && Objects.equals(username, that.username);
144
96
240
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/ssh/SSHServiceImpl.java
SSHServiceImpl
matchCpuLine
class SSHServiceImpl implements SSHService { private Logger logger = LoggerFactory.getLogger(SSHServiceImpl.class); @Autowired private MachineDao machineDao; private Map<String, MachineInfo> machineIpInfoMap = new ConcurrentHashMap<String, MachineInfo>(); private Map<String, Long> appNameIdMap = new ConcurrentHashMap<String, Long>(); @Autowired(required = false) private SSHTemplate sshTemplate; @Override public String execute(String ip, int port, String username, String password, final String command) throws SSHException { Result rst = executeWithResult(ip, port, username, password, command); if (rst.isSuccess()) { return rst.getResult(); } return ""; } @Override public Result executeWithResult(String ip, int port, String username, String password, final String command) throws SSHException { return sshTemplate.execute(ip, port, username, password, new SSHCallback() { public Result call(SSHSession session) { return session.executeCommand(command); } }); } @Override public Result executeWithResult(String ip, int port, String username, String password, final String command, int timeoutMills) throws SSHException { return sshTemplate.execute(ip, port, username, password, new SSHCallback() { public Result call(SSHSession session) { return session.executeCommand(command, timeoutMills); } }); } @Override public Result executeWithResult(String ip, String cmd) throws SSHException { return executeWithResult(ip, getSshPort(ip), ConstUtils.USERNAME, ConstUtils.PASSWORD, cmd); } public Result executeWithResult(String ip, String cmd, int millsSecond) throws SSHException { return executeWithResult(ip, getSshPort(ip), ConstUtils.USERNAME, ConstUtils.PASSWORD, cmd, millsSecond); } @Override public Result scpFileToRemote(String ip, int port, String username, String password, final String localPath, final String remoteDir) throws SSHException { return sshTemplate.execute(ip, port, username, password, new SSHCallback() { public Result call(SSHSession session) { return session.scpToDir(localPath, remoteDir, "0644"); } }); } @Override public Result scpFileToRemote(String ip, String localPath, String remoteDir) throws SSHException { return scpFileToRemote(ip, getSshPort(ip), ConstUtils.USERNAME, ConstUtils.PASSWORD, localPath, remoteDir); } @Override public String execute(String ip, String cmd) throws SSHException { return execute(ip, getSshPort(ip), ConstUtils.USERNAME, ConstUtils.PASSWORD, cmd); } @Override public boolean isPortUsed(String ip, int port) throws SSHException { /** * 执行ps命令,查看端口,以确认刚才执行的shell命令是否成功,返回一般是这样的: * root 12510 12368 0 14:34 pts/0 00:00:00 redis-server *:6379 */ String psCmd = "/bin/ps -ef | grep %s | grep -v grep"; psCmd = String.format(psCmd, port); String psResponse = execute(ip, psCmd); boolean isUsed = false; if (StringUtils.isNotBlank(psResponse)) { String[] resultArr = psResponse.split(System.lineSeparator()); for (String resultLine : resultArr) { if (resultLine.contains(String.valueOf(port))) { isUsed = true; break; } } } return isUsed; } @Override public int getSshPort(String ip) { /** * 如果ssh默认端口不是22,请自行实现该逻辑 */ return ConstUtils.SSH_PORT_DEFAULT; } /** * 匹配字符串中的数字 * * @param content * @return */ private static String matchMemLineNumber(String content) { String result = EMPTY_STRING; if (content == null || EMPTY_STRING.equals(content.trim())) { return result; } Pattern pattern = Pattern.compile("(\\d+)"); Matcher matcher = pattern.matcher(content); if (matcher.find()) { result = matcher.group(1); } return result; } /** * 从top的cpuLine解析出us * * @param cpuLine * @return */ private static double getUsCpu(String cpuLine) { if (cpuLine == null || EMPTY_STRING.equals(cpuLine.trim())) { return 0; } String[] items = cpuLine.split(COMMA); if (items.length < 1) { return 0; } String usCpuStr = items[0]; return NumberUtils.toDouble(matchCpuLine(usCpuStr)); } private static String matchCpuLine(String content) {<FILL_FUNCTION_BODY>} public MachineInfo getMachineInfo(String ip) { MachineInfo machineInfo = machineIpInfoMap.get(ip); if (machineInfo == null) { machineInfo = machineDao.getMachineInfoByIp(ip); machineIpInfoMap.put(ip, machineInfo); } return machineInfo; } public Long getAppId(String name) { Long appId = appNameIdMap.get(name); return appId; } }
String result = EMPTY_STRING; if (content == null || EMPTY_STRING.equals(content.trim())) { return result; } Pattern pattern = Pattern.compile("(\\d+).(\\d+)"); Matcher matcher = pattern.matcher(content); if (matcher.find()) { result = matcher.group(); } return result;
1,667
117
1,784
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/ssh/SSHSessionPooledObjectFactory.java
SSHSessionPooledObjectFactory
makeObject
class SSHSessionPooledObjectFactory implements KeyedPooledObjectFactory<SSHMachineInfo, ClientSession> { private final Logger logger = LoggerFactory.getLogger(getClass()); private SSHClient sshClient; public SSHSessionPooledObjectFactory() throws GeneralSecurityException, IOException { sshClient = new SSHClient(); sshClient.setServerUser(ConstUtils.USERNAME); sshClient.setServerPassword(ConstUtils.PASSWORD); sshClient.setServerPort(ConstUtils.SSH_PORT_DEFAULT); sshClient.setServerConnectTimeout(ConstUtils.SSH_CONNECTION_TIMEOUT); if (ConstUtils.SSH_AUTH_TYPE == SshAuthTypeEnum.PUBLIC_KEY.getValue()) { sshClient.setPrivateKeyPath(ConstUtils.PUBLIC_KEY_PEM); } sshClient.init(); } @Override public PooledObject<ClientSession> makeObject(SSHMachineInfo sshMachineInfo) throws Exception {<FILL_FUNCTION_BODY>} @Override public void destroyObject(SSHMachineInfo sshMachineInfo, PooledObject<ClientSession> pooledObject) throws Exception { ClientSession clientSession = pooledObject.getObject(); if (clientSession != null) { try { clientSession.close(); } catch (Exception e) { logger.warn("close err, key:{}", sshMachineInfo, e); } } logger.info("destroy object {}", sshMachineInfo); } @Override public boolean validateObject(SSHMachineInfo sshMachineInfo, PooledObject<ClientSession> pooledObject) { boolean closed = pooledObject.getObject().isClosed(); if (closed) { logger.warn("{} session closed", sshMachineInfo); return false; } return true; } @Override public void activateObject(SSHMachineInfo sshMachineInfo, PooledObject<ClientSession> pooledObject) throws Exception { } @Override public void passivateObject(SSHMachineInfo sshMachineInfo, PooledObject<ClientSession> pooledObject) throws Exception { } }
int port = ConstUtils.SSH_PORT_DEFAULT; ClientSession session = sshClient.getClient().connect(ConstUtils.USERNAME, sshMachineInfo.getIp(), port).verify(ConstUtils.SSH_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS).getSession(); session.setUsername(sshMachineInfo.getUsername()); if(sshMachineInfo.getAuthType() == SshAuthTypeEnum.PASSWORD.getValue()){ session.addPasswordIdentity(sshMachineInfo.getPassword()); }else if(sshMachineInfo.getAuthType() == SshAuthTypeEnum.PUBLIC_KEY.getValue()){ KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser(); Collection<KeyPair> keys = loader.loadKeyPairs(null, Paths.get(ConstUtils.PUBLIC_KEY_PEM), null); session.addPublicKeyIdentity(keys.iterator().next()); } session.auth().verify(ConstUtils.SSH_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); logger.info("create object, key:{}", sshMachineInfo); return new DefaultPooledObject<>(session);
544
296
840
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/ssh/SSHTemplate.java
SSHSession
scp
class SSHSession { private String address; private ClientSession clientSession; private SSHSession(ClientSession clientSession, String address) { this.clientSession = clientSession; this.address = address; } /** * 执行命令并返回结果,可以执行多次 * @param cmd * @return 执行成功Result为true,并携带返回信息,返回信息可能为null * 执行失败Result为false,并携带失败信息 * 执行异常Result为false,并携带异常 */ public Result executeCommand(String cmd) { return executeCommand(cmd, OP_TIMEOUT); } public Result executeCommand(String cmd, int timoutMillis) { return executeCommand(cmd, null, timoutMillis); } public Result executeCommand(String cmd, LineProcessor lineProcessor) { return executeCommand(cmd, lineProcessor, OP_TIMEOUT); } /** * 执行命令并返回结果,可以执行多次 * @param cmd * @param lineProcessor 回调处理行 * @return 如果lineProcessor不为null,那么永远返回Result.true */ public Result executeCommand(String cmd, LineProcessor lineProcessor, int timoutMillis) { try (ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ClientChannel channel = clientSession.createExecChannel(cmd)) { channel.setOut(stdout); channel.setErr(stderr); channel.open().verify(timoutMillis); // Wait (forever) for the channel to close - signalling command finished channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0L); LineProcessor tmpLP = lineProcessor; // 如果客户端需要进行行处理,则直接进行回调 if (tmpLP != null) { processStream(new ByteArrayInputStream(stdout.toByteArray()), tmpLP); } else { StringBuilder buffer = new StringBuilder(); tmpLP = generateDefaultLineProcessor(buffer); processStream(new ByteArrayInputStream(stdout.toByteArray()), tmpLP); if (buffer.length() > 0) { return new Result(true, buffer.toString()); } } if(tmpLP.lineNum() == 0) { // 返回为null代表可能有异常,需要检测标准错误输出,以便记录日志 Result errResult = tryLogError(new ByteArrayInputStream(stderr.toByteArray()), cmd); if (errResult != null) { return errResult; } } return new Result(true, null); } catch (Exception e) { logger.error("execute ip:{} cmd:{}", address, cmd, e); return new Result(e); } } private Result tryLogError(InputStream is, String cmd) { StringBuilder buffer = new StringBuilder(); LineProcessor lp = generateDefaultLineProcessor(buffer); processStream(is, lp); String errInfo = buffer.length() > 0 ? buffer.toString() : null; if (errInfo != null) { logger.error("address " + address + " execute cmd:({}), err:{}", cmd, errInfo); return new Result(false, errInfo); } return null; } /** * Copy a set of local files to a remote directory, uses the specified mode when * creating the file on the remote side. * @param localFiles * Path and name of local file. * @param remoteFile * name of remote file. * @param remoteTargetDirectory * Remote target directory. Use an empty string to specify the default directory. * @param mode * a four digit string (e.g., 0644, see "man chmod", "man open") * @throws IOException */ public Result scp(String[] localFiles, String remoteFile, String remoteTargetDirectory, String mode) {<FILL_FUNCTION_BODY>} public Result scpToDir(String localFile, String remoteTargetDirectory) { return scpToDir(localFile, remoteTargetDirectory, "0744"); } public Result scpToDir(String localFile, String remoteTargetDirectory, String mode) { return scp(new String[] { localFile }, null, remoteTargetDirectory, mode); } public Result scpToDir(String[] localFile, String remoteTargetDirectory) { return scp(localFile, null, remoteTargetDirectory, "0744"); } public Result scpToFile(String localFile, String remoteFile, String remoteTargetDirectory) { return scpToFile(localFile, remoteFile, remoteTargetDirectory, "0744"); } public Result scpToFile(String localFile, String remoteFile, String remoteTargetDirectory, String mode) { return scp(new String[] { localFile }, remoteFile, remoteTargetDirectory, "0744"); } }
try { ScpClient client = ScpClientCreator.instance().createScpClient(clientSession); String separator = FileSystems.getDefault().getSeparator(); if(localFiles.length == 1){ if(StringUtils.isBlank(remoteFile)){ client.upload(localFiles, remoteTargetDirectory, ScpClient.Option.TargetIsDirectory); int index = localFiles[0].lastIndexOf(separator); if(index <= 0){ index = 0; }else{ index = index + 1; } String fileName = localFiles[0].substring(index); clientSession.executeRemoteCommand("chmod " + mode + " \"" + remoteTargetDirectory + "/" + fileName + "\""); } else { client.upload(localFiles, remoteTargetDirectory + "/" + remoteFile); clientSession.executeRemoteCommand("chmod " + mode + " \"" + remoteTargetDirectory + "/" + remoteFile + "\""); } } else { client.upload(localFiles, remoteTargetDirectory, ScpClient.Option.TargetIsDirectory); StringBuffer sb = new StringBuffer(); List<String> files = Arrays.asList(localFiles); String remoteFiles = files.stream().map(file -> { int index = file.lastIndexOf(separator); if(index <= 0){ index = 0; }else{ index = index + 1; } return " \"" + remoteTargetDirectory + "/" + file.substring(index) + "\""; }).collect(Collectors.joining(" ")); clientSession.executeRemoteCommand("chmod " + mode + " " + remoteFiles); } return new Result(true); } catch (Exception e) { logger.error("scp local="+Arrays.toString(localFiles) + " to " + remoteTargetDirectory + " remote=" + remoteFile + " err", e); return new Result(e); }
1,262
499
1,761
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/stats/admin/impl/CoreAppsStatCenterImpl.java
CoreAppsStatCenterImpl
sendExpAppsStatDataEmail
class CoreAppsStatCenterImpl implements CoreAppsStatCenter { @Autowired private AppService appService; @Autowired private AppDao appDao; @Autowired private UserService userService; @Autowired private ResourceDao resourceDao; @Autowired private EmailComponent emailComponent; @Autowired private Configuration configuration; @Autowired private MachineCenter machineCenter; @Override public boolean sendExpAppsStatDataEmail(String searchDate) {<FILL_FUNCTION_BODY>} public void noticeExpAppsDaily(String searchDate, Map<String, AppDesc> appDescMap, Map<String, List<Map<String, Object>>> appClientGatherStatGroup,Map<String,Object> exceptionMachineEnv) { String title = String.format("【CacheCloud】%s应用日报", searchDate); Map<String, Object> context = new HashMap<>(); context.put("appDescMap", appDescMap); context.put("appClientGatherStatGroup", appClientGatherStatGroup); context.put("exceptionMachineEnv", exceptionMachineEnv); context.put("searchDate", searchDate); String mailContent = FreemakerUtils.createText("expAppsDaily.ftl", configuration, context); log.info("noticeExpAppsDaily sendMailToAdmin, title:{}, mailContent:{}", title, mailContent); // 发送管理员 emailComponent.sendDailyMail(title, mailContent, Arrays.asList(AlertUtils.EMAILS.split(",")), null); log.info("noticeExpAppsDaily success"); } }
try { log.info("sendExpAppsStatDataEmail"); if (StringUtil.isBlank(searchDate)) { //默认发送前一天的日报 Date startDate = DateUtils.addDays(new Date(), -1); searchDate = DateUtil.formatDate(startDate, "yyyy-MM-dd"); } List<AppDesc> appDescList = appDao.getOnlineAppsNonTest(); appDescList.forEach(appDesc -> { String versionName = Optional.ofNullable(resourceDao.getResourceById(appDesc.getVersionId())).map(ver -> ver.getName()).orElse(""); appDesc.setVersionName(versionName); appDesc.setOfficer(userService.getOfficerName(appDesc.getOfficer())); }); Map<String, AppDesc> appDescMap = appDescList.stream().collect(Collectors.toMap(appDesc -> String.valueOf(appDesc.getAppId()), Function.identity())); Map<String, List<Map<String, Object>>> appClientGatherStatGroup = appService.getFilterAppClientStatGather(-1, searchDate); // 获取异常的宿主或容器信息 Map<String, Object> exceptionMachineEnv = machineCenter.getExceptionMachineEnv(DateUtils.addDays(new Date(), -1)); noticeExpAppsDaily(searchDate, appDescMap, appClientGatherStatGroup,exceptionMachineEnv); return true; } catch (Exception e) { log.error(e.getMessage(), e); return false; }
429
404
833
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/stats/app/impl/AppDataMigrateCenterImpl.java
AppDataMigrateCenterImpl
processRedisMigrateToolStats
class AppDataMigrateCenterImpl implements AppDataMigrateCenter { @Autowired private AppDataMigrateStatusDao appDataMigrateStatusDao; @Autowired private MachineCenter machineCenter; @Override public String showDataMigrateLog(long id, int pageSize) { AppDataMigrateStatus appDataMigrateStatus = appDataMigrateStatusDao.get(id); if (appDataMigrateStatus == null) { return ""; } try { int migrateStatus = appDataMigrateStatus.getStatus(); String logPath = appDataMigrateStatus.getLogPath(); String host = appDataMigrateStatus.getMigrateMachineIp(); MachineInfo machineInfo = machineCenter.getMachineInfoByIp(host); if (machineInfo != null && machineInfo.getAvailable() == MachineInfoEnum.AvailableEnum.YES.getValue()) { StringBuilder command = new StringBuilder(); command.append("tail -n").append(pageSize).append(" ").append(logPath); String result = SSHUtil.execute(host, command.toString()); int logStatus = migrateStatus; if (StringUtils.isNotEmpty(result) && result.contains(RedisShakeEnum.LOG_ERROR.getKeyword())) { logStatus = AppDataMigrateStatusEnum.ERROR.getStatus(); } else if (StringUtils.isNotEmpty(result) && (result.contains(RedisShakeEnum.LOG_SYNC_RDB_DONE.getKeyword()) || result.contains(RedisShakeEnum.LOG_FORWARD_COMMANDS.getKeyword()))) { logStatus = AppDataMigrateStatusEnum.FULL_END.getStatus(); } else if (StringUtils.isNotEmpty(result) && result.contains(RedisShakeEnum.LOG_SYNCING.getKeyword())) { logStatus = AppDataMigrateStatusEnum.START.getStatus(); } else if (StringUtils.isNotEmpty(result) && result.contains(RedisShakeEnum.LOG_WAITING_SOURCE_RDB.getKeyword())) { logStatus = AppDataMigrateStatusEnum.PREPARE.getStatus(); } if (migrateStatus != logStatus) { appDataMigrateStatusDao.updateStatus(id, logStatus); } return result; } else { log.warn("machine ip:{} is offline", host); return ""; } } catch (SSHException e) { log.error(e.getMessage(), e); return ""; } } @Override public String showCheckDataLog(long id, int pageSize) { AppDataMigrateStatus appDataMigrateStatus = appDataMigrateStatusDao.get(id); if (appDataMigrateStatus == null) { return ""; } String migrateId = appDataMigrateStatus.getMigrateId(); String logPath = ConstUtils.getRedisFullCheckResultDir() + "log-" + migrateId + ".log"; String host = appDataMigrateStatus.getMigrateMachineIp(); StringBuilder command = new StringBuilder(); command.append("tail -n").append(pageSize).append(" ").append(logPath); try { return SSHUtil.execute(host, command.toString()); } catch (SSHException e) { log.error(e.getMessage(), e); return ""; } } @Override public String showDataMigrateConf(long id) { AppDataMigrateStatus appDataMigrateStatus = appDataMigrateStatusDao.get(id); if (appDataMigrateStatus == null) { return ""; } String configPath = appDataMigrateStatus.getConfigPath(); String host = appDataMigrateStatus.getMigrateMachineIp(); String command = "cat " + configPath; try { return SSHUtil.execute(host, command); } catch (SSHException e) { log.error(e.getMessage(), e); return ""; } } @Override public Map<RedisMigrateToolConstant, Map<String, Object>> showMiragteToolProcess(long id) { AppDataMigrateStatus appDataMigrateStatus = appDataMigrateStatusDao.get(id); if (appDataMigrateStatus == null) { return Collections.emptyMap(); } String info = ""; String host = appDataMigrateStatus.getMigrateMachineIp(); int port = appDataMigrateStatus.getMigrateMachinePort(); Jedis jedis = null; try { jedis = new Jedis(host, port, 5000); info = jedis.info(); } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (jedis != null) { jedis.close(); } } if (StringUtils.isBlank(info)) { return Collections.emptyMap(); } return processRedisMigrateToolStats(info); } @Override public List<AppDataMigrateStatus> search(AppDataMigrateSearch appDataMigrateSearch) { try { // List<Long> onMigrateIds = appDataMigrateStatusDao.getAllOnMigrateId(); // onMigrateIds.parallelStream().map(migrateId -> showDataMigrateLog(migrateId, 100)).collect(Collectors.toList()); return appDataMigrateStatusDao.search(appDataMigrateSearch); } catch (Exception e) { log.error(e.getMessage(), e); return Collections.emptyList(); } } @Override public int getMigrateTaskCount(AppDataMigrateSearch appDataMigrateSearch) { try { return appDataMigrateStatusDao.getMigrateTaskCount(appDataMigrateSearch); } catch (Exception e) { log.error(e.getMessage(), e); return 0; } } /** * 处理迁移工具状态 * * @param statResult * @return */ private Map<RedisMigrateToolConstant, Map<String, Object>> processRedisMigrateToolStats(String statResult) {<FILL_FUNCTION_BODY>} }
Map<RedisMigrateToolConstant, Map<String, Object>> redisStatMap = new HashMap<RedisMigrateToolConstant, Map<String, Object>>(); String[] data = statResult.split("\r\n"); String key; int i = 0; int length = data.length; while (i < length) { if (data[i].contains("#")) { int index = data[i].indexOf('#'); key = data[i].substring(index + 1); ++i; RedisMigrateToolConstant redisMigrateToolConstant = RedisMigrateToolConstant.value(key.trim()); if (redisMigrateToolConstant == null) { continue; } Map<String, Object> sectionMap = new LinkedHashMap<String, Object>(); while (i < length && data[i].contains(":")) { String[] pair = data[i].split(":"); sectionMap.put(pair[0], pair[1]); i++; } redisStatMap.put(redisMigrateToolConstant, sectionMap); } else { i++; } } return redisStatMap;
1,671
306
1,977
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/swagger/Swagger2.java
Swagger2
apiInfo
class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.sohu.cache.web.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() {<FILL_FUNCTION_BODY>} }
return new ApiInfoBuilder() .title("CacheCloud项目 RESTful APIs") .description("CacheCloud项目后台api接口文档") .version("1.0") .build();
124
56
180
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/entity/InstanceBigKey.java
InstanceBigKey
getLengthFormat
class InstanceBigKey { private long id; /** * 实例id */ private long instanceId; /** * app id */ private long appId; /** * 工单id */ private long auditId; /** * ip地址 */ private String ip; /** * port */ private int port; /** * 1主2从 */ private int role; /** * bigkey */ private String bigKey; /** * 类型 */ private String type; /** * 长度 */ private long length; /** * 创建时间 */ private Date createTime; public String getLengthFormat() {<FILL_FUNCTION_BODY>} /*public long getId() { return id; } public void setId(long id) { this.id = id; } public long getInstanceId() { return instanceId; } public void setInstanceId(long instanceId) { this.instanceId = instanceId; } public long getAppId() { return appId; } public void setAppId(long appId) { this.appId = appId; } public long getAuditId() { return auditId; } public void setAuditId(long auditId) { this.auditId = auditId; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public int getRole() { return role; } public void setRole(int role) { this.role = role; } public String getBigKey() { return bigKey; } public void setBigKey(String bigKey) { this.bigKey = bigKey; } public String getType() { return type; } public void setType(String type) { this.type = type; } public long getLength() { return length; } public void setLength(long length) { this.length = length; }*/ public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } }
if (RedisDataStructureTypeEnum.string.getValue().equals(type)) { return new DecimalFormat("#,###").format(length); } else { return length + "个元素"; }
721
56
777
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/entity/RedisServerNode.java
RedisServerNode
transferFromPika
class RedisServerNode { private long taskId; private String ip; private int port; private int role; private int maxmemory; private String masterHost; private int masterPort; private String masterName; public RedisServerNode() { } public RedisServerNode(String ip, int port) { this.ip = ip; this.port = port; } public RedisServerNode(String ip, int port, String masterName) { this.ip = ip; this.port = port; this.masterName = masterName; } public RedisServerNode(String ip, int port, int maxmemory) { this.ip = ip; this.port = port; this.maxmemory = maxmemory; } public RedisServerNode(String ip, int port, int role, int maxmemory, String masterHost, int masterPort) { this.ip = ip; this.port = port; this.role = role; this.maxmemory = maxmemory; this.masterHost = masterHost; this.masterPort = masterPort; } public String genHostAndPort() { return masterHost + ":" + masterPort; } public boolean isMaster() { return role == InstanceRoleEnum.MASTER.getRole(); } public boolean isSlave() { return role == InstanceRoleEnum.SLAVE.getRole(); } @Override public String toString() { return "RedisServerNode [taskId=" + taskId + ", ip=" + ip + ", port=" + port + ", role=" + role + ", maxmemory=" + maxmemory + ", masterHost=" + masterHost + ", masterPort=" + masterPort + ", masterName=" + masterName + "]"; } public String getUniqKey() { return ip + "-" + port + "-" + masterName; } public static RedisServerNode transferFromPika(PikaNode pikaNode) {<FILL_FUNCTION_BODY>} }
RedisServerNode redisServerNode = new RedisServerNode(); redisServerNode.setIp(pikaNode.getIp()); redisServerNode.setMasterHost(pikaNode.getMasterHost()); redisServerNode.setMasterName(pikaNode.getMasterName()); redisServerNode.setMasterPort(pikaNode.getMasterPort()); redisServerNode.setPort(pikaNode.getPort()); redisServerNode.setRole(pikaNode.getRole()); redisServerNode.setTaskId(pikaNode.getTaskId()); return redisServerNode;
550
157
707
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/entity/TaskQueue.java
TaskQueue
getCostSeconds
class TaskQueue { /** * 自增id */ private long id; /** * 进行任务的ip:port */ private String executeIpPort; /** * 应用id */ private long appId; /** * 类名 */ private String className; /** * 全局参数:json格式,内容会变 */ private String param; /** * 初始化参数:json格式,内容不变 */ private String initParam; /** * 状态,详见com.sohu.cache.task.constant.TaskQueueEnum.TaskStatusEnum */ private int status; /** * 父任务id */ private long parentTaskId; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; /** * 开始时间 */ private Date startTime; /** * 结束时间 */ private Date endTime; /** * 优先级 */ private int priority = 50; /** * 错误代码,详见 TaskQueueEnum.TaskErrorCodeEnum */ private int errorCode; /** * 错误消息 */ private String errorMsg = ""; /** * 备注 */ private String taskNote = ""; /** * 重要信息 */ private String importantInfo = ""; /** * 任务流 */ private List<TaskStepFlow> taskStepFlowList; public Map<String, Object> getParamMap() { if (StringUtils.isEmpty(param)) { return Collections.emptyMap(); } return JSONObject.parseObject(param); } public String getPrettyParam() { if (StringUtils.isEmpty(param)) { return null; } JSONObject jsonObject = JSONObject.parseObject(param); return JSONObject.toJSONString(jsonObject, true); } public String getStatusDesc() { TaskStatusEnum taskStatusEnum = TaskStatusEnum.getTaskStatusEnum(status); if (taskStatusEnum != null) { return taskStatusEnum.getInfo(); } return ""; } public String getProgress() { if (CollectionUtils.isEmpty(taskStepFlowList)) { return ""; } int success = 0; int total = taskStepFlowList.size(); for (TaskStepFlow taskStepFlow : taskStepFlowList) { if (taskStepFlow.isSkip() || taskStepFlow.isSuccess()) { success++; } } double percent = success * 100.0 / total * 1.0; return new DecimalFormat("#.00").format(percent) + "%"; } public String getCostSeconds() {<FILL_FUNCTION_BODY>} public boolean isSuccess() { return TaskStatusEnum.SUCCESS.getStatus() == status; } public boolean isRunning() { return TaskStatusEnum.RUNNING.getStatus() == status; } public boolean isAbort() { return TaskStatusEnum.ABORT.getStatus() == status; } public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public Date getUpdateTime() { return (Date) updateTime.clone(); } public void setUpdateTime(Date updateTime) { this.updateTime = (Date) updateTime.clone(); } public Date getStartTime() { return (Date) startTime.clone(); } public void setStartTime(Date startTime) { this.startTime = (Date) startTime.clone(); } public Date getEndTime() { return (Date) endTime.clone(); } public void setEndTime(Date endTime) { this.endTime = (Date) endTime.clone(); } }
if (status != TaskStatusEnum.SUCCESS.getStatus()) { return ""; } if (endTime != null && startTime != null) { long ms = (endTime.getTime() - startTime.getTime()) / 1000; return String.valueOf(ms); } return "";
1,089
89
1,178
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/entity/TaskStepFlow.java
TaskStepFlow
getCostSeconds
class TaskStepFlow { /** * 自增id */ private long id; /** * 任务id */ private long taskId; /** * 子任务id */ private long childTaskId; /** * 类名 */ private String className; /** * 步骤名 */ private String stepName; /** * 序号 */ private int orderNo; /** * 状态, 参考:TaskFlowStatusEnum */ private int status; /** * 日志 */ private String log = ""; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; /** * 开始时间 */ private Date startTime; /** * 结束时间 */ private Date endTime; /** * 执行ip:port */ private String executeIpPort; /** * 任务流描述 */ private TaskStepMeta taskStepMeta; public boolean isSuccess() { return status == TaskFlowStatusEnum.SUCCESS.getStatus(); } public boolean isSkip() { return status == TaskFlowStatusEnum.SKIP.getStatus(); } public String getExecuteIpPort() { return executeIpPort; } public void setExecuteIpPort(String executeIpPort) { this.executeIpPort = executeIpPort; } public TaskStepMeta getTaskStepMeta() { return taskStepMeta; } public void setTaskStepMeta(TaskStepMeta taskStepMeta) { this.taskStepMeta = taskStepMeta; } public String getStatusDesc() { TaskFlowStatusEnum taskFlowStatusEnum = TaskFlowStatusEnum.getTaskFlowStatusEnum(status); if (taskFlowStatusEnum != null) { return taskFlowStatusEnum.getInfo(); } return ""; } public String getCostSeconds() {<FILL_FUNCTION_BODY>} public Date getCreateTime() { return (Date) createTime.clone(); } public void setCreateTime(Date createTime) { this.createTime = (Date) createTime.clone(); } public Date getUpdateTime() { return (Date) updateTime.clone(); } public void setUpdateTime(Date updateTime) { this.updateTime = (Date) updateTime.clone(); } public Date getStartTime() { return (Date) startTime.clone(); } public void setStartTime(Date startTime) { this.startTime = (Date) startTime.clone(); } public Date getEndTime() { return (Date) endTime.clone(); } public void setEndTime(Date endTime) { this.endTime = (Date) endTime.clone(); } }
if (status != TaskFlowStatusEnum.SUCCESS.getStatus()) { return ""; } if (endTime != null && startTime != null) { long ms = (endTime.getTime() - startTime.getTime()) / 1000; return String.valueOf(ms); } return "";
792
90
882
<no_super_class>
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/OffLineAppTask.java
OffLineAppTask
init
class OffLineAppTask extends BaseTask { private long appId; private AppDesc appDesc; private AppUser userInfo; private long auditId; @Autowired private AppService appService; @Autowired private InstanceDao instanceDao; @Resource(name = "appEmailUtil") private AppEmailUtil appEmailUtil; @Override public List<String> getTaskSteps() { List<String> taskStepList = Lists.newArrayList(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 2. 执行应用下线处理 taskStepList.add("executeOffLineApp"); // 3. 更新应用信息 taskStepList.add("updateAppStatus"); return taskStepList; } /** * 初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() {<FILL_FUNCTION_BODY>} /** * 2. 执行应用下线操作 * * @return */ public TaskFlowStatusEnum executeOffLineApp() { logger.info("executeOffLineApp"); if (auditId > 0) { appAuditDao.updateAppAuditUser(auditId, 2, userInfo.getId()); } List<InstanceInfo> instanceInfos = instanceDao.getInstListByAppId(appId); int type = appDesc.getType(); List<Boolean> isShutDownList = Lists.newArrayList(); if (instanceInfos != null) { isShutDownList = instanceInfos.parallelStream() .map(instanceInfo -> instanceOffline(instanceInfo, type)) .collect(Collectors.toList()); } if (isShutDownList.contains(false)) { appEmailUtil.noticeOfflineApp(userInfo, appId, false); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } private boolean instanceOffline(InstanceInfo instanceInfo, int type) { final String ip = instanceInfo.getIp(); final int port = instanceInfo.getPort(); boolean isShutdown = TypeUtil.isRedisType(type) ? redisCenter.shutdown(appId, ip, port) : true; if(isShutdown){ isShutdown = redisCenter.checkShutdownSuccess(instanceInfo); } if (isShutdown) { instanceInfo.setStatus(InstanceStatusEnum.OFFLINE_STATUS.getStatus()); instanceDao.update(instanceInfo); } else { logger.error("task {} appId {} {}:{} redis not shutdown!", taskId, appId, ip, port); return false; } return true; } /** * 3. 更新应用信息,发送邮件 * * @return */ public TaskFlowStatusEnum updateAppStatus() { logger.info("updateAppStatus"); appDesc.setStatus(AppStatusEnum.STATUS_OFFLINE.getStatus()); if (auditId > 0) { appAuditDao.updateAppAudit(auditId, 1); } int count = appService.update(appDesc); if (count > 0) { appEmailUtil.noticeOfflineApp(userInfo, appId, true); return TaskFlowStatusEnum.SUCCESS; } else { appEmailUtil.noticeOfflineApp(userInfo, appId, false); return TaskFlowStatusEnum.ABORT; } } }
TaskFlowStatusEnum taskFlowStatusEnum = super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY, -1); if (auditId <= 0) { logger.info(marker, "task {} auditId {} is wrong", taskId, auditId); } appDesc = appService.getByAppId(appId); if (appDesc == null) { logger.error(marker, "task {} appId {} appDesc is not exist", taskId, appId); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } Object userObject = MapUtils.getObject(paramMap, TaskConstants.USER_INFO_KEY, null); if (userObject instanceof JSONObject) { JSONObject userJson = (JSONObject) userObject; userInfo = JSONObject.parseObject(JSON.toJSONString(userJson), AppUser.class); } if (userInfo == null) { logger.error(marker, "task {} appId {} userInfo is not exist", taskId, appId); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } else { if (!ConstUtils.SUPER_MANAGER.contains(userInfo.getName())) { logger.error("task {} appId {} user {} who hope to offline hasn't privilege", taskId, appId, userInfo.getName()); taskFlowStatusEnum = TaskFlowStatusEnum.ABORT; } } if (taskFlowStatusEnum == TaskFlowStatusEnum.ABORT) { appEmailUtil.noticeOfflineApp(userInfo, appId, false); } return taskFlowStatusEnum;
927
495
1,422
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/analysis/RedisServerIdleKeyAnalysisTask.java
RedisServerIdleKeyAnalysisTask
idleKeyAnalysis
class RedisServerIdleKeyAnalysisTask extends BaseTask { private String host; private int port; private long appId; private long auditId; /** * 扫描master */ private final static int SCAN_COUNT = 100; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<String>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); //检查实例是否运行 taskStepList.add("checkIsRun"); //idle key分析 taskStepList.add("idleKeyAnalysis"); return taskStepList; } /** * 初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } host = MapUtils.getString(paramMap, TaskConstants.HOST_KEY); if (StringUtils.isBlank(host)) { logger.error(marker, "task {} host is empty", taskId); return TaskFlowStatusEnum.ABORT; } port = MapUtils.getIntValue(paramMap, TaskConstants.PORT_KEY); if (port <= 0) { logger.error(marker, "task {} port {} is wrong", taskId, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum checkIsRun() { if (!redisCenter.isRun(appId, host, port)) { logger.error(marker, "{} {}:{} is not run", appId, host, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum idleKeyAnalysis() {<FILL_FUNCTION_BODY>} }
long startTime = System.currentTimeMillis(); //本地结果集 AtomicLongMap<IdleTimeDistriEnum> idleTimeCountMap = AtomicLongMap.create(); Jedis jedis = null; try { jedis = redisCenter.getJedis(appId, host, port); jedis.readonly(); //如果 long dbSize = jedis.dbSize(); if (dbSize == 0) { logger.info(marker, "{} {}:{} dbsize is {}", appId, host, port, dbSize); return TaskFlowStatusEnum.SUCCESS; } logger.info(marker, "{} {}:{} total key is {} ", appId, host, port, dbSize); ScanParams scanParams = new ScanParams().count(SCAN_COUNT); byte[] cursor = "0".getBytes(Charset.forName("UTF-8")); long count = 0; int totalSplit = 10; int curSplit = 1; while (true) { int retryTimes = 10; try { ScanResult<byte[]> scanResult = jedis.scan(cursor, scanParams); cursor = scanResult.getCursorAsBytes(); List<byte[]> keyList = scanResult.getResult(); //pipeline object idle Pipeline pipeline = jedis.pipelined(); keyList.stream().forEach(key -> pipeline.objectIdletime(key)); List<Object> idleTimeList; try { idleTimeList = pipeline.syncAndReturnAll(); } catch (JedisRedirectionException e) { continue;// ignore } idleTimeList.stream() .filter(obj -> obj != null && (obj instanceof Long)) .forEach(obj -> { long idleSeconds = (long) obj; long idleHours = idleSeconds / 3600; IdleTimeDistriEnum idleTimeDistriEnum = IdleTimeDistriEnum .getRightIdleDistri(idleHours); if (idleTimeDistriEnum == null) { logger.error(marker, "idleHours {} {} IdleTimeDistriEnum is null", idleHours, idleSeconds); } else { idleTimeCountMap.incrementAndGet(idleTimeDistriEnum); } }); count += keyList.size(); if (count > dbSize / totalSplit * curSplit) { logger.info(marker, "{} {}:{} has already anlysis {}% {} key ", appId, host, port, curSplit * 10, count); curSplit++; } // @TODO暂时写死 TimeUnit.MILLISECONDS.sleep(2); } catch (Exception e) { logger.error(marker, e.getMessage(), e); } finally { //防止无限循环 if (Arrays.equals("0".getBytes(Charset.forName("UTF-8")), cursor)) { break; } } } logger.info(marker, "{} {}:{} analysis idle key successfully, cost time is {} ms, total key is {}", appId, host, port, (System.currentTimeMillis() - startTime), count); String idleKeyResultKey = ConstUtils.getRedisServerIdleKey(appId, auditId); idleTimeCountMap.asMap().entrySet().stream().forEach(entry -> { String member = entry.getKey().getValue(); assistRedisService.zincrby(idleKeyResultKey, entry.getValue(), member); logger.info(marker, "{} {} {}:{} idle distri {} {}", idleKeyResultKey, appId, host, port, entry.getKey(), entry.getValue()); }); return TaskFlowStatusEnum.SUCCESS; } catch (RuntimeException e) { throw e; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } finally { if (jedis != null) { jedis.close(); } }
631
1,060
1,691
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/analysis/RedisServerKeyTtlAnalysisTask.java
RedisServerKeyTtlAnalysisTask
keyTtlAnalysis
class RedisServerKeyTtlAnalysisTask extends BaseTask { private String host; private int port; private long appId; private long auditId; /** * 扫描slave */ private final static int SCAN_COUNT = 100; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<String>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 检查实例是否运行 taskStepList.add("checkIsRun"); // key类型分析 taskStepList.add("keyTtlAnalysis"); return taskStepList; } /** * 初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } host = MapUtils.getString(paramMap, TaskConstants.HOST_KEY); if (StringUtils.isBlank(host)) { logger.error(marker, "task {} host is empty", taskId); return TaskFlowStatusEnum.ABORT; } port = MapUtils.getIntValue(paramMap, TaskConstants.PORT_KEY); if (port <= 0) { logger.error(marker, "task {} port {} is wrong", taskId, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum checkIsRun() { if (!redisCenter.isRun(appId, host, port)) { logger.error(marker, "{} {}:{} is not run", appId, host, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum keyTtlAnalysis() {<FILL_FUNCTION_BODY>} }
long startTime = System.currentTimeMillis(); //本地结果集 AtomicLongMap<TtlTimeDistriEnum> ttlTimeCountMap = AtomicLongMap.create(); Jedis jedis = null; try { jedis = redisCenter.getJedis(appId, host, port); jedis.readonly(); long dbSize = jedis.dbSize(); if (dbSize == 0) { logger.info(marker, "{} {}:{} dbsize is {}", appId, host, port, dbSize); return TaskFlowStatusEnum.SUCCESS; } logger.info(marker, "{} {}:{} total key is {} ", appId, host, port, dbSize); ScanParams scanParams = new ScanParams().count(SCAN_COUNT); byte[] cursor = "0".getBytes(Charset.forName("UTF-8")); long count = 0; int totalSplit = 10; int curSplit = 1; while (true) { try { ScanResult<byte[]> scanResult = jedis.scan(cursor, scanParams); cursor = scanResult.getCursorAsBytes(); List<byte[]> keyList = scanResult.getResult(); Pipeline pipeline = jedis.pipelined(); keyList.stream().forEach(key -> pipeline.ttl(key)); List<Object> ttlObjectList; try { ttlObjectList = pipeline.syncAndReturnAll(); } catch (JedisRedirectionException e) { continue;// ignore } ttlObjectList.stream() .filter(obj -> obj != null && (obj instanceof Long)) .forEach(obj -> { long ttlSeconds = (long) obj; TtlTimeDistriEnum ttlTimeDistriEnum; if (ttlSeconds == -1) { ttlTimeDistriEnum = TtlTimeDistriEnum.BETWEEN_PERSIST_HOURS; } else { long ttlHours = ttlSeconds / 3600; ttlTimeDistriEnum = TtlTimeDistriEnum.getRightTtlDistri(ttlHours); } if (ttlTimeDistriEnum == null) { logger.error(marker, "ttlSeconds {} TtlTimeDistriEnum is null", ttlSeconds); } ttlTimeCountMap.incrementAndGet(ttlTimeDistriEnum); }); count += keyList.size(); if (count > dbSize / totalSplit * curSplit) { logger.info(marker, "{} {}:{} has already anlysis {}% {} key ", appId, host, port, curSplit * 10, count); curSplit++; } } catch (Exception e) { logger.error(marker, e.getMessage(), e); } finally { //防止无限循环 if (Arrays.equals("0".getBytes(Charset.forName("UTF-8")), cursor)) { break; } } } logger.info(marker, "{} {}:{} analysis key ttl successfully, cost time is {} ms, total key is {}", appId, host, port, (System.currentTimeMillis() - startTime), count); String keyTtlResultKey = ConstUtils.getRedisServerTtlKey(appId, auditId); ttlTimeCountMap.asMap().entrySet().stream().forEach(entry -> { String ttlDistri = entry.getKey().getValue(); assistRedisService.zincrby(keyTtlResultKey, entry.getValue(), ttlDistri); logger.info(marker, "{} {} {}:{} ttl distri {} {}", keyTtlResultKey, appId, host, port, ttlDistri, entry.getValue()); }); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } finally { if (jedis != null) { jedis.close(); } }
632
1,066
1,698
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/analysis/RedisServerKeyTypeAnalysisTask.java
RedisServerKeyTypeAnalysisTask
keyTypeAnalysis
class RedisServerKeyTypeAnalysisTask extends BaseTask { private String host; private int port; private long appId; private long auditId; /** * 扫描slave */ private final static int SCAN_COUNT = 100; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<String>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 检查实例是否运行 taskStepList.add("checkIsRun"); // key类型分析 taskStepList.add("keyTypeAnalysis"); return taskStepList; } /** * 初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } host = MapUtils.getString(paramMap, TaskConstants.HOST_KEY); if (StringUtils.isBlank(host)) { logger.error(marker, "task {} host is empty", taskId); return TaskFlowStatusEnum.ABORT; } port = MapUtils.getIntValue(paramMap, TaskConstants.PORT_KEY); if (port <= 0) { logger.error(marker, "task {} port {} is wrong", taskId, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum checkIsRun() { if (!redisCenter.isRun(appId, host, port)) { logger.error(marker, "{} {}:{} is not run", appId, host, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum keyTypeAnalysis() {<FILL_FUNCTION_BODY>} }
long startTime = System.currentTimeMillis(); Jedis jedis = null; try { jedis = redisCenter.getJedis(appId, host, port); jedis.readonly(); long dbSize = jedis.dbSize(); if (dbSize == 0) { logger.info(marker, "{} {}:{} dbsize is {}", appId, host, port, dbSize); return TaskFlowStatusEnum.SUCCESS; } logger.info(marker, "{} {}:{} total key is {} ", appId, host, port, dbSize); ScanParams scanParams = new ScanParams().count(SCAN_COUNT); byte[] cursor = "0".getBytes(Charset.forName("UTF-8")); AtomicLongMap<String> typeCountMap = AtomicLongMap.create(); long count = 0; int totalSplit = 10; int curSplit = 1; while (true) { try { ScanResult<byte[]> scanResult = jedis.scan(cursor, scanParams); cursor = scanResult.getCursorAsBytes(); List<byte[]> keyList = scanResult.getResult(); Pipeline pipeline = jedis.pipelined(); keyList.stream().forEach(key -> pipeline.type(key)); List<Object> typeObjectList; try { typeObjectList = pipeline.syncAndReturnAll(); } catch (JedisRedirectionException e) { continue; // ignore } typeObjectList.stream() .filter(type -> !"none".equalsIgnoreCase(String.valueOf(type)) && (type instanceof String)) .forEach(type -> typeCountMap.incrementAndGet(String.valueOf(type))); count += keyList.size(); if (count > dbSize / totalSplit * curSplit) { logger.info(marker, "{} {}:{} has already anlysis {}% {} key ", appId, host, port, curSplit * 10, count); curSplit++; } } catch (Exception e) { logger.error(marker, e.getMessage(), e); } finally { //防止无限循环 if (Arrays.equals("0".getBytes(Charset.forName("UTF-8")), cursor)) { break; } } } logger.info(marker, "{} {}:{} analysis key type successfully, cost time is {} ms, total key is {}", appId, host, port, (System.currentTimeMillis() - startTime), count); String keyTypeResultKey = ConstUtils.getRedisServerTypeKey(appId, auditId); typeCountMap.asMap().entrySet().stream().forEach(entry -> { String type = entry.getKey(); assistRedisService.zincrby(keyTypeResultKey, entry.getValue(), type); logger.info(marker, "{} {} {}:{} type distri {} {}", keyTypeResultKey, appId, host, port, type, entry.getValue()); }); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } finally { if (jedis != null) { jedis.close(); } }
629
862
1,491
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/analysis/RedisServerKeyValueAnalysisTask.java
RedisServerKeyValueAnalysisTask
getTaskSteps
class RedisServerKeyValueAnalysisTask extends BaseTask { private String host; private int port; private long appId; private long auditId; /** * 扫描slave */ private final static int SCAN_COUNT = 100; @Override public List<String> getTaskSteps() {<FILL_FUNCTION_BODY>} /** * 初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } host = MapUtils.getString(paramMap, TaskConstants.HOST_KEY); if (StringUtils.isBlank(host)) { logger.error(marker, "task {} host is empty", taskId); return TaskFlowStatusEnum.ABORT; } port = MapUtils.getIntValue(paramMap, TaskConstants.PORT_KEY); if (port <= 0) { logger.error(marker, "task {} port {} is wrong", taskId, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum checkIsRun() { if (!redisCenter.isRun(appId, host, port)) { logger.error(marker, "{} {}:{} is not run", appId, host, port); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } public TaskFlowStatusEnum keyValueAnalysis() { long startTime = System.currentTimeMillis(); //本地结果集 Map<ValueSizeDistriEnum, Long> valueSizeCountMap = new HashMap<ValueSizeDistriEnum, Long>(); Jedis jedis = null; try { jedis = redisCenter.getJedis(appId, host, port);; jedis.readonly(); long dbSize = jedis.dbSize(); if (dbSize == 0) { logger.info(marker, "{} {}:{} dbsize is {}", appId, host, port, dbSize); return TaskFlowStatusEnum.SUCCESS; } logger.info(marker, "{} {}:{} total key is {} ", appId, host, port, dbSize); ScanParams scanParams = new ScanParams().count(SCAN_COUNT); byte[] cursor = "0".getBytes(Charset.forName("UTF-8")); long count = 0; int totalSplit = 10; int curSplit = 1; while (true) { try { ScanResult<byte[]> scanResult = jedis.scan(cursor, scanParams); cursor = scanResult.getCursorAsBytes(); List<byte[]> keyList = scanResult.getResult(); for (byte[] key : keyList) { String debug = null; try { // key 可能不存在,报 ERR no such key debug = jedis.debug(DebugParams.OBJECT(new String(key, Charset.forName("UTF-8")))); } catch (JedisException e) { logger.warn("debug-object-error: key={}", new String(key, Charset.forName("UTF-8"))); //ignore } if (StringUtils.isBlank(debug)) { continue; } long valueBytes = NumberUtils.toLong(debug.split(" ")[4].split(":")[1]); ValueSizeDistriEnum valueSizeDistriEnum = ValueSizeDistriEnum.getRightSizeBetween(valueBytes); if (valueSizeDistriEnum == null) { logger.warn("key {} valueBytes {} is wrong", key, valueBytes); continue; } if (valueSizeCountMap.containsKey(valueSizeDistriEnum)) { valueSizeCountMap.put(valueSizeDistriEnum, valueSizeCountMap.get(valueSizeDistriEnum) + 1); } else { valueSizeCountMap.put(valueSizeDistriEnum, 1L); } } count += keyList.size(); if (count > dbSize / totalSplit * curSplit) { logger.info(marker, "{} {}:{} has already anlysis {}% {} key ", appId, host, port, curSplit * 10, count); curSplit++; } } catch (Exception e) { logger.error(marker, e.getMessage(), e); } finally { //防止无限循环 if (Arrays.equals("0".getBytes(Charset.forName("UTF-8")), cursor)) { break; } } } logger.info(marker, "{} {}:{} analysis key value size successfully, cost time is {} ms, total key is {}", appId, host, port, (System.currentTimeMillis() - startTime), count); if (MapUtils.isNotEmpty(valueSizeCountMap)) { String keyValueSizeResultKey = ConstUtils.getRedisServerValueSizeKey(appId, auditId); for (Entry<ValueSizeDistriEnum, Long> entry : valueSizeCountMap.entrySet()) { String valueSizeDistri = entry.getKey().getValue(); assistRedisService.zincrby(keyValueSizeResultKey, entry.getValue(), valueSizeDistri); logger.info(marker, "{} {} {}:{} value size distri {} {}", keyValueSizeResultKey, appId, host, port, valueSizeDistri, entry.getValue()); } } else { logger.error(marker, "{} {}:{} value size distri is empty", appId, host, port); } return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } finally { if (jedis != null) { jedis.close(); } } } }
List<String> taskStepList = new ArrayList<String>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 检查实例是否运行 taskStepList.add("checkIsRun"); // key类型分析 taskStepList.add("keyValueAnalysis"); return taskStepList;
1,671
83
1,754
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/daily/MachineExamTask.java
MachineExamTask
getTaskSteps
class MachineExamTask extends BaseTask { private List<String> machineIpList; private Integer useType; private List<MachineStats> machineStatsList = Lists.newArrayList(); private Map<String, Integer> machineInstanceCountMap = Maps.newHashMap(); private List<Map> examResult = Lists.newArrayList(); @Override public List<String> getTaskSteps() {<FILL_FUNCTION_BODY>} @Override public TaskStepFlowEnum.TaskFlowStatusEnum init() { super.init(); useType = MapUtils.getInteger(paramMap, TaskConstants.USE_TYPE_KEY, null); machineIpList = (List) MapUtils.getObject(paramMap, TaskConstants.MACHINE_IP_LIST_KEY); return TaskStepFlowEnum.TaskFlowStatusEnum.SUCCESS; } /** * 1. 准备任务参数 * * @return */ public TaskFlowStatusEnum prepareAppParam() { for (String ip : machineIpList) { List<MachineStats> list = machineCenter.getMachineStats(ip, useType, null,null, null, -1, null); machineStatsList.addAll(list); } machineInstanceCountMap = machineCenter.getMachineInstanceCountMap(); if (machineStatsList.isEmpty() || machineInstanceCountMap.isEmpty()) { return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } /** * 2. 执行机器故障检查 * * @return */ public TaskFlowStatusEnum executeMachineExam() { for (MachineStats machineStats : machineStatsList) { String ip = machineStats.getIp(); double mem = (double) machineStats.getInfo().getMem();//G double usedMem = machineStats.getMachineMemInfo().getUsedMemRss() / 1024 / 1024 / 1024;//byte double applyMem = (double) machineStats.getMachineMemInfo().getApplyMem() / 1024 / 1024 / 1024;//byte double usedMemRatio = usedMem / mem; double applyMemRatio = applyMem / mem; int cpu = machineStats.getInfo().getCpu(); int usedCpu = machineInstanceCountMap.get(ip); double usedCpuRatio = (double) usedCpu / cpu; if (judgeMemUsed(usedMemRatio, mem) || judgeMemUsed(applyMemRatio, mem) || judgeCpuUsed(usedCpuRatio)) { examResult.add( new HashMap<String, String>() {{ put(MachineExamContants.MACHINE_IP, ip); put(MachineExamContants.MEM, String.valueOf(mem)); put(MachineExamContants.APPLY_MEM, String.valueOf(applyMem)); put(MachineExamContants.APPLY_MEM_RATIO, String.valueOf(applyMemRatio)); put(MachineExamContants.USED_MEM, String.valueOf(usedMem)); put(MachineExamContants.USED_MEM_RATIO, String.valueOf(usedMemRatio)); put(MachineExamContants.CPU, String.valueOf(cpu)); put(MachineExamContants.USED_CPU, String.valueOf(usedCpu)); put(MachineExamContants.USED_CPU_RATIO, String.valueOf(usedCpuRatio)); }} ); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3. 检查结果展示 * * @return */ public TaskFlowStatusEnum showMachineExamResult() { return TaskFlowStatusEnum.SUCCESS; } private boolean judgeMemUsed(double ratio, double mem) { if (mem > 20 && ratio > MachineExamContants.defult_memUseThreshold) { return true; } else if (mem > 10 && mem <= 20 && ratio > MachineExamContants.middle_memUseThreshold) { return true; } else if (mem <= 10 && ratio > MachineExamContants.small_memUseThreshold) { return true; } return false; } private boolean judgeCpuUsed(double ratio) { if (ratio >= MachineExamContants.BASE_RATIO) { return true; } return false; } }
List<String> taskStepList = new ArrayList<String>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 准备任务参数 taskStepList.add("prepareAppParam"); // 2. 执行机器故障检查 taskStepList.add("executeMachineExam"); // 3. 检查结果展示 taskStepList.add("showMachineExamResult"); return taskStepList;
1,162
115
1,277
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/AppBigKeyTask.java
AppBigKeyTask
updateAudit
class AppBigKeyTask extends BaseTask { private long appId; private long auditId; private long fromBytes; private long toBytes; private int size; private List<RedisServerNode> redisServerNodes; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 检查集群参数 taskStepList.add("checkAppParam"); // 2.1 创建delete key taskStepList.add("createAppBigKeyTask"); // 2.2 等到delete key完成 taskStepList.add("waitAppBigKeyTaskFinish"); // 4. 工单审批 taskStepList.add("updateAudit"); return taskStepList; } /** * 0.初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } fromBytes = MapUtils.getLongValue(paramMap, "fromBytes"); if (fromBytes <= 0) { logger.info(marker, "task {} fromBytes is empty", taskId); } size = MapUtils.getIntValue(paramMap, "size"); if (size <= -2) { logger.error(marker, "task {} size {} is wrong", taskId, size); return TaskFlowStatusEnum.ABORT; } //redis server list String redisServerNodesStr = MapUtils.getString(paramMap, TaskConstants.REDIS_SERVER_NODES_KEY); if (StringUtils.isNotBlank(redisServerNodesStr)) { redisServerNodes = JSONArray.parseArray(redisServerNodesStr, RedisServerNode.class); if (CollectionUtils.isEmpty(redisServerNodes)) { logger.error(marker, "task {} redisServerNodes is empty", taskId); return TaskFlowStatusEnum.ABORT; } logger.info(marker, "user paramMap node: {}", redisServerNodesStr); } return TaskFlowStatusEnum.SUCCESS; } /** * 1.检查应用参数 * * @return */ public TaskFlowStatusEnum checkAppParam() { AppDesc appDesc = appDao.getAppDescById(appId); if (appDesc == null) { logger.error(marker, "appId {} appDesc is null", appId); return TaskFlowStatusEnum.ABORT; } if (!appDesc.isOnline()) { logger.error(marker, "appId {} is must be online, ", appId); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } /** * 2.1.创建delete key子任务 */ public TaskFlowStatusEnum createAppBigKeyTask() { redisServerNodes = buildRedisServerNodes(redisServerNodes, appId); paramMap.put(TaskConstants.REDIS_SERVER_NODES_KEY, redisServerNodes); for (RedisServerNode redisServerNode : redisServerNodes) { //跳过已经执行完毕的节点 if (redisServerNode.getTaskId() > 0) { continue; } String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); try { long childTaskId = taskService.addInstanceBigKeyTask(appId, host, port, fromBytes, toBytes, size, auditId, taskId); redisServerNode.setTaskId(childTaskId); logger.info(marker, "appId {} {}:{} instanceBigKeyTask create successfully", appId, host, port); } catch (Exception e) { logger.error(marker, "appId {} {}:{} instanceBigKeyTask create fail", appId, host, port); logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } return TaskFlowStatusEnum.SUCCESS; } /** * 2.2.等待delkey子任务完成 * * @return */ public TaskFlowStatusEnum waitAppBigKeyTaskFinish() { for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long childTaskId = redisServerNode.getTaskId(); TaskFlowStatusEnum taskFlowStatusEnum = waitTaskFinish(childTaskId, TaskConstants.REDIS_SERVER_DIAGNOSTIC_TIMEOUT); if (taskFlowStatusEnum.equals(TaskFlowStatusEnum.ABORT)) { logger.error(marker, "appId {} {}:{} instanceBigKeyTask execute fail", appId, host, port); return TaskFlowStatusEnum.ABORT; } else { logger.info(marker, "appId {} {}:{} instanceBigKeyTask execute successfully", appId, host, port); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3.通过初审:资源分配 */ public TaskFlowStatusEnum updateAudit() {<FILL_FUNCTION_BODY>} }
try { AppDesc appDesc = appService.getByAppId(appId); appAuditDao.updateAppAudit(auditId, AppCheckEnum.APP_PASS.value()); StringBuffer content = new StringBuffer(); content.append(String.format("应用(%s-%s) appBigKeyTask 完成", appDesc.getAppId(), appDesc.getName())); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; }
1,519
152
1,671
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/AppDelKeyTask.java
AppDelKeyTask
checkAppParam
class AppDelKeyTask extends BaseTask { private long appId; private long auditId; private String pattern; private List<RedisServerNode> redisServerNodes; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 检查集群参数 taskStepList.add("checkAppParam"); // 2.1 创建delete key taskStepList.add("createAppDelKeyTask"); // 2.2 等到delete key完成 taskStepList.add("waitAppDelKeyTaskFinish"); // 4. 工单审批 taskStepList.add("updateAudit"); return taskStepList; } /** * 0.初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } pattern = MapUtils.getString(paramMap, "pattern"); if (StringUtils.isBlank(pattern)) { logger.info(marker, "task {} pattern is empty", taskId); } //redis server list String redisServerNodesStr = MapUtils.getString(paramMap, TaskConstants.REDIS_SERVER_NODES_KEY); if (StringUtils.isNotBlank(redisServerNodesStr)) { redisServerNodes = JSONArray.parseArray(redisServerNodesStr, RedisServerNode.class); if (CollectionUtils.isEmpty(redisServerNodes)) { logger.error(marker, "task {} redisServerNodes is empty", taskId); return TaskFlowStatusEnum.ABORT; } logger.info(marker, "user paramMap node: {}", redisServerNodesStr); } return TaskFlowStatusEnum.SUCCESS; } /** * 1.检查应用参数 * * @return */ public TaskFlowStatusEnum checkAppParam() {<FILL_FUNCTION_BODY>} /** * 2.1.创建delete key子任务 */ public TaskFlowStatusEnum createAppDelKeyTask() { redisServerNodes = buildRedisServerNodes(redisServerNodes, appId); paramMap.put(TaskConstants.REDIS_SERVER_NODES_KEY, redisServerNodes); for (RedisServerNode redisServerNode : redisServerNodes) { //跳过已经执行完毕的节点 if (redisServerNode.getTaskId() > 0) { continue; } String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); try { long childTaskId = taskService.addInstanceDelKeyTask(appId, host, port, pattern, auditId, taskId); redisServerNode.setTaskId(childTaskId); logger.info(marker, "appId {} {}:{} instanceDelKeyTask create successfully", appId, host, port); } catch (Exception e) { logger.error(marker, "appId {} {}:{} instanceDelKeyTask create fail", appId, host, port); logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } return TaskFlowStatusEnum.SUCCESS; } /** * 2.2.等待delkey子任务完成 * * @return */ public TaskFlowStatusEnum waitAppDelKeyTaskFinish() { for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long childTaskId = redisServerNode.getTaskId(); TaskFlowStatusEnum taskFlowStatusEnum = waitTaskFinish(childTaskId, TaskConstants.REDIS_SERVER_DIAGNOSTIC_TIMEOUT); if (taskFlowStatusEnum.equals(TaskFlowStatusEnum.ABORT)) { logger.error(marker, "appId {} {}:{} instanceDelKeyTask execute fail", appId, host, port); return TaskFlowStatusEnum.ABORT; } else { logger.info(marker, "appId {} {}:{} instanceDelKeyTask execute successfully", appId, host, port); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3.通过初审:资源分配 */ public TaskFlowStatusEnum updateAudit() { try { AppDesc appDesc = appService.getByAppId(appId); appAuditDao.updateAppAudit(auditId, AppCheckEnum.APP_PASS.value()); StringBuffer content = new StringBuffer(); content.append(String.format("应用(%s-%s)的del key完成", appDesc.getAppId(), appDesc.getName())); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } }
AppDesc appDesc = appDao.getAppDescById(appId); if (appDesc == null) { logger.error(marker, "appId {} appDesc is null", appId); return TaskFlowStatusEnum.ABORT; } if (!appDesc.isOnline()) { logger.error(marker, "appId {} is must be online, ", appId); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS;
1,461
126
1,587
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/AppHotKeyTask.java
AppHotKeyTask
checkAppParam
class AppHotKeyTask extends BaseTask { private long appId; private long auditId; private String command; private List<RedisServerNode> redisServerNodes; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 检查集群参数 taskStepList.add("checkAppParam"); // 2.1 创建delete key taskStepList.add("createAppHotKeyTask"); // 2.2 等到delete key完成 taskStepList.add("waitAppHotKeyTaskFinish"); // 4. 工单审批 taskStepList.add("updateAudit"); return taskStepList; } /** * 0.初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } command = MapUtils.getString(paramMap, "command"); if (StringUtils.isBlank(command)) { logger.error(marker, "task {} command {} is wrong", taskId, command); return TaskFlowStatusEnum.ABORT; } //redis server list String redisServerNodesStr = MapUtils.getString(paramMap, TaskConstants.REDIS_SERVER_NODES_KEY); if (StringUtils.isNotBlank(redisServerNodesStr)) { redisServerNodes = JSONArray.parseArray(redisServerNodesStr, RedisServerNode.class); if (CollectionUtils.isEmpty(redisServerNodes)) { logger.error(marker, "task {} redisServerNodes is empty", taskId); return TaskFlowStatusEnum.ABORT; } logger.info(marker, "user paramMap node: {}", redisServerNodesStr); } return TaskFlowStatusEnum.SUCCESS; } /** * 1.检查应用参数 * * @return */ public TaskFlowStatusEnum checkAppParam() {<FILL_FUNCTION_BODY>} /** * 2.1.创建hotkey子任务 */ public TaskFlowStatusEnum createAppHotKeyTask() { redisServerNodes = buildRedisServerNodes(redisServerNodes, appId); paramMap.put(TaskConstants.REDIS_SERVER_NODES_KEY, redisServerNodes); for (RedisServerNode redisServerNode : redisServerNodes) { //跳过已经执行完毕的节点 if (redisServerNode.getTaskId() > 0) { continue; } String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); try { long childTaskId = taskService.addInstanceHotKeyTask(appId, host, port, command, auditId, taskId); redisServerNode.setTaskId(childTaskId); logger.info(marker, "appId {} {}:{} instanceHotKeyTask create successfully", appId, host, port); } catch (Exception e) { logger.error(marker, "appId {} {}:{} instanceHotKeyTask create fail", appId, host, port); logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } return TaskFlowStatusEnum.SUCCESS; } /** * 2.2.等待hotkey子任务完成 * * @return */ public TaskFlowStatusEnum waitAppHotKeyTaskFinish() { for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long childTaskId = redisServerNode.getTaskId(); TaskFlowStatusEnum taskFlowStatusEnum = waitTaskFinish(childTaskId, TaskConstants.REDIS_SERVER_DIAGNOSTIC_TIMEOUT); if (taskFlowStatusEnum.equals(TaskFlowStatusEnum.ABORT)) { logger.error(marker, "appId {} {}:{} instanceHotKeyTask execute fail", appId, host, port); return TaskFlowStatusEnum.ABORT; } else { logger.info(marker, "appId {} {}:{} instanceHotKeyTask execute successfully", appId, host, port); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3.通过初审:资源分配 */ public TaskFlowStatusEnum updateAudit() { try { AppDesc appDesc = appService.getByAppId(appId); appAuditDao.updateAppAudit(auditId, AppCheckEnum.APP_PASS.value()); StringBuffer content = new StringBuffer(); content.append(String.format("应用(%s-%s)的hotkey完成", appDesc.getAppId(), appDesc.getName())); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } }
AppDesc appDesc = appDao.getAppDescById(appId); if (appDesc == null) { logger.error(marker, "appId {} appDesc is null", appId); return TaskFlowStatusEnum.ABORT; } if (!appDesc.isOnline()) { logger.error(marker, "appId {} is must be online, ", appId); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS;
1,475
126
1,601
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/AppIdleKeyTask.java
AppIdleKeyTask
init
class AppIdleKeyTask extends BaseTask { private long appId; private long idleTime; private int size; private long auditId; private List<RedisServerNode> redisServerNodes; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 检查集群参数 taskStepList.add("checkAppParam"); // 2.1 创建delete key taskStepList.add("createAppIdleKeyTask"); // 2.2 等到delete key完成 taskStepList.add("waitAppIdleKeyTaskFinish"); // 4. 工单审批 taskStepList.add("updateAudit"); return taskStepList; } /** * 0.初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() {<FILL_FUNCTION_BODY>} /** * 1.检查应用参数 * * @return */ public TaskFlowStatusEnum checkAppParam() { AppDesc appDesc = appDao.getAppDescById(appId); if (appDesc == null) { logger.error(marker, "appId {} appDesc is null", appId); return TaskFlowStatusEnum.ABORT; } if (!appDesc.isOnline()) { logger.error(marker, "appId {} is must be online, ", appId); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } /** * 2.1.创建delete key子任务 */ public TaskFlowStatusEnum createAppIdleKeyTask() { redisServerNodes = buildRedisServerNodes(redisServerNodes, appId); paramMap.put(TaskConstants.REDIS_SERVER_NODES_KEY, redisServerNodes); for (RedisServerNode redisServerNode : redisServerNodes) { //跳过已经执行完毕的节点 if (redisServerNode.getTaskId() > 0) { continue; } String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); try { long childTaskId = taskService.addInstanceIdleKeyTask(appId, host, port, idleTime, size, auditId, taskId); redisServerNode.setTaskId(childTaskId); logger.info(marker, "appId {} {}:{} instanceIdleKeyTask create successfully", appId, host, port); } catch (Exception e) { logger.error(marker, "appId {} {}:{} instanceIdleKeyTask create fail", appId, host, port); logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } return TaskFlowStatusEnum.SUCCESS; } /** * 2.2.等待delkey子任务完成 * * @return */ public TaskFlowStatusEnum waitAppIdleKeyTaskFinish() { for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long childTaskId = redisServerNode.getTaskId(); TaskFlowStatusEnum taskFlowStatusEnum = waitTaskFinish(childTaskId, TaskConstants.REDIS_SERVER_DIAGNOSTIC_TIMEOUT); if (taskFlowStatusEnum.equals(TaskFlowStatusEnum.ABORT)) { logger.error(marker, "appId {} {}:{} instanceIdleKeyTask execute fail", appId, host, port); return TaskFlowStatusEnum.ABORT; } else { logger.info(marker, "appId {} {}:{} instanceIdleKeyTask execute successfully", appId, host, port); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3.通过初审:资源分配 */ public TaskFlowStatusEnum updateAudit() { try { AppDesc appDesc = appService.getByAppId(appId); appAuditDao.updateAppAudit(auditId, AppCheckEnum.APP_PASS.value()); StringBuffer content = new StringBuffer(); content.append(String.format("应用(%s-%s) appIdleKeyTask 完成", appDesc.getAppId(), appDesc.getName())); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } }
super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } idleTime = MapUtils.getIntValue(paramMap, "idleTime"); if (idleTime <= 0) { logger.error(marker, "task {} idleTime {} is wrong", taskId, idleTime); return TaskFlowStatusEnum.ABORT; } size = MapUtils.getIntValue(paramMap, "size"); if (size <= -2) { logger.error(marker, "task {} size {} is wrong", taskId, size); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } //redis server list String redisServerNodesStr = MapUtils.getString(paramMap, TaskConstants.REDIS_SERVER_NODES_KEY); if (StringUtils.isNotBlank(redisServerNodesStr)) { redisServerNodes = JSONArray.parseArray(redisServerNodesStr, RedisServerNode.class); if (CollectionUtils.isEmpty(redisServerNodes)) { logger.error(marker, "task {} redisServerNodes is empty", taskId); return TaskFlowStatusEnum.ABORT; } logger.info(marker, "user paramMap node: {}", redisServerNodesStr); } return TaskFlowStatusEnum.SUCCESS;
1,225
464
1,689
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/AppScanKeyTask.java
AppScanKeyTask
createAppScanKeyTask
class AppScanKeyTask extends BaseTask { private long appId; private long auditId; private String pattern; private int size; private List<RedisServerNode> redisServerNodes; private final static long SCANKEY_SLEEP_BASE = 20000000; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<String>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 检查集群参数 taskStepList.add("checkAppParam"); // 2. redis server big key分析 taskStepList.add("createAppScanKeyTask"); taskStepList.add("waitAppScanKeyTaskFinish"); // 3. 工单审批 taskStepList.add("updateAudit"); return taskStepList; } /** * 0.初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } pattern = MapUtils.getString(paramMap, "pattern"); if (StringUtils.isBlank(pattern)) { logger.info(marker, "task {} pattern is empty", taskId); } size = MapUtils.getIntValue(paramMap, "size"); if (size <= 0) { logger.error(marker, "task {} size {} is wrong", taskId, size); return TaskFlowStatusEnum.ABORT; } //redis server list String redisServerNodesStr = MapUtils.getString(paramMap, TaskConstants.REDIS_SERVER_NODES_KEY); if (StringUtils.isNotBlank(redisServerNodesStr)) { redisServerNodes = JSONArray.parseArray(redisServerNodesStr, RedisServerNode.class); if (CollectionUtils.isEmpty(redisServerNodes)) { logger.error(marker, "task {} redisServerNodes is empty", taskId); return TaskFlowStatusEnum.ABORT; } logger.info(marker, "user paramMap node: {}", redisServerNodesStr); } return TaskFlowStatusEnum.SUCCESS; } /** * 1.检查应用参数 * * @return */ public TaskFlowStatusEnum checkAppParam() { AppDesc appDesc = appDao.getAppDescById(appId); if (appDesc == null) { logger.error(marker, "appId {} appDesc is null", appId); return TaskFlowStatusEnum.ABORT; } if (!appDesc.isOnline()) { logger.error(marker, "appId {} is must be online, ", appId); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } /** * 2.1.创建scan key子任务 */ public TaskFlowStatusEnum createAppScanKeyTask() {<FILL_FUNCTION_BODY>} /** * 2.2.等待scankey子任务完成 * * @return */ public TaskFlowStatusEnum waitAppScanKeyTaskFinish() { for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long childTaskId = redisServerNode.getTaskId(); TaskFlowStatusEnum taskFlowStatusEnum = waitTaskFinish(childTaskId, TaskConstants.REDIS_SERVER_DIAGNOSTIC_TIMEOUT); if (taskFlowStatusEnum.equals(TaskFlowStatusEnum.ABORT)) { logger.error(marker, "appId {} {}:{} instanceScanKeyTask execute fail", appId, host, port); return TaskFlowStatusEnum.ABORT; } else { logger.info(marker, "appId {} {}:{} instanceScanKeyTask execute successfully", appId, host, port); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3.通过初审:资源分配 */ public TaskFlowStatusEnum updateAudit() { try { AppDesc appDesc = appService.getByAppId(appId); appAuditDao.updateAppAudit(auditId, AppCheckEnum.APP_PASS.value()); StringBuffer content = new StringBuffer(); content.append(String.format("应用(%s-%s)的scan key完成", appDesc.getAppId(), appDesc.getName())); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } }
redisServerNodes = buildRedisServerNodes(redisServerNodes, appId); paramMap.put(TaskConstants.REDIS_SERVER_NODES_KEY, redisServerNodes); // 每个server的dbsize Map<String, Long> redisServerDbSizeMap = new HashMap<>(); for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long dbSize = redisCenter.getDbSize(appId, redisServerNode.getIp(), redisServerNode.getPort()); logger.info(marker, "appId {} {}:{} dbSize is {} ", appId, host, port, dbSize); redisServerDbSizeMap.put(host + ":" + port, dbSize); } long keyCounter = 0; int factor = 1; for (RedisServerNode redisServerNode : redisServerNodes) { //跳过已经执行完毕的节点 if (redisServerNode.getTaskId() > 0) { continue; } long sleepCounter = factor * SCANKEY_SLEEP_BASE; String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); try { long dbSize = redisServerDbSizeMap.get(host + ":" + port); keyCounter += dbSize; long childTaskId = taskService.addInstanceScanKeyTask(appId, auditId, host, port, pattern, size, taskId); redisServerNode.setTaskId(childTaskId); logger.info(marker, "appId {} {}:{} redis scanKeyTask create successfully", appId, host, port); // 超额就sleep if (keyCounter > sleepCounter) { factor++; sleepSeconds(120); } } catch (Exception e) { logger.error(marker, "appId {} {}:{} redis scanKeyTask create fail", appId, host, port); logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } return TaskFlowStatusEnum.SUCCESS;
1,372
570
1,942
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/AppSlotAnalysisTask.java
AppSlotAnalysisTask
getTaskSteps
class AppSlotAnalysisTask extends BaseTask { private long appId; private long auditId; private List<RedisServerNode> redisServerNodes; @Override public List<String> getTaskSteps() {<FILL_FUNCTION_BODY>} /** * 0.初始化参数 * * @return */ @Override public TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskFlowStatusEnum.ABORT; } //redis server list String redisServerNodesStr = MapUtils.getString(paramMap, TaskConstants.REDIS_SERVER_NODES_KEY); if (StringUtils.isNotBlank(redisServerNodesStr)) { redisServerNodes = JSONArray.parseArray(redisServerNodesStr, RedisServerNode.class); if (CollectionUtils.isEmpty(redisServerNodes)) { logger.error(marker, "task {} redisServerNodes is empty", taskId); return TaskFlowStatusEnum.ABORT; } logger.info(marker, "user paramMap node: {}", redisServerNodesStr); } return TaskFlowStatusEnum.SUCCESS; } /** * 1.检查应用参数 * * @return */ public TaskFlowStatusEnum checkAppParam() { AppDesc appDesc = appDao.getAppDescById(appId); if (appDesc == null) { logger.error(marker, "appId {} appDesc is null", appId); return TaskFlowStatusEnum.ABORT; } if (!appDesc.isOnline()) { logger.error(marker, "appId {} is must be online, ", appId); return TaskFlowStatusEnum.ABORT; } return TaskFlowStatusEnum.SUCCESS; } /** * 2.1.创建appSlotAnalysisTask子任务 */ public TaskFlowStatusEnum createAppSlotAnalysisTask() { redisServerNodes = buildRedisServerNodes(redisServerNodes, appId); paramMap.put(TaskConstants.REDIS_SERVER_NODES_KEY, redisServerNodes); for (RedisServerNode redisServerNode : redisServerNodes) { //跳过已经执行完毕的节点 if (redisServerNode.getTaskId() > 0) { continue; } String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); try { long childTaskId = taskService.addInstanceSlotAnalysisTask(appId, host, port, auditId, taskId); redisServerNode.setTaskId(childTaskId); logger.info(marker, "appId {} {}:{} instanceSlotAnalysisTask create successfully", appId, host, port); } catch (Exception e) { logger.error(marker, "appId {} {}:{} instanceSlotAnalysisTask create fail", appId, host, port); logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } return TaskFlowStatusEnum.SUCCESS; } /** * 2.2.等待appSlotAnalysisTask子任务完成 * * @return */ public TaskFlowStatusEnum waitAppSlotAnalysisTaskFinish() { for (RedisServerNode redisServerNode : redisServerNodes) { String host = redisServerNode.getIp(); int port = redisServerNode.getPort(); long childTaskId = redisServerNode.getTaskId(); TaskFlowStatusEnum taskFlowStatusEnum = waitTaskFinish(childTaskId, TaskConstants.REDIS_SERVER_DIAGNOSTIC_TIMEOUT); if (taskFlowStatusEnum.equals(TaskFlowStatusEnum.ABORT)) { logger.error(marker, "appId {} {}:{} instanceSlotAnalysisTask execute fail", appId, host, port); return TaskFlowStatusEnum.ABORT; } else { logger.info(marker, "appId {} {}:{} instanceSlotAnalysisTask execute successfully", appId, host, port); } } return TaskFlowStatusEnum.SUCCESS; } /** * 3.通过初审:资源分配 */ public TaskFlowStatusEnum updateAudit() { try { AppDesc appDesc = appService.getByAppId(appId); appAuditDao.updateAppAudit(auditId, AppCheckEnum.APP_PASS.value()); StringBuffer content = new StringBuffer(); content.append(String.format("应用(%s-%s)slotAnalysisTask完成", appDesc.getAppId(), appDesc.getName())); return TaskFlowStatusEnum.SUCCESS; } catch (Exception e) { logger.error(marker, e.getMessage(), e); return TaskFlowStatusEnum.ABORT; } } }
List<String> taskStepList = new ArrayList<>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 1. 检查集群参数 taskStepList.add("checkAppParam"); // 2.1 创建 appSlotAnalysisTask taskStepList.add("createAppSlotAnalysisTask"); // 2.2 等到 ppSlotAnalysisTask完成 taskStepList.add("waitAppSlotAnalysisTaskFinish"); // 4. 工单审批 taskStepList.add("updateAudit"); return taskStepList;
1,398
151
1,549
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService
sohutv_cachecloud
cachecloud/cachecloud-web/src/main/java/com/sohu/cache/task/tasks/diagnosticTask/InstanceDelKeyTask.java
InstanceDelKeyTask
delKey
class InstanceDelKeyTask extends BaseTask { private String host; private int port; private long appId; private String pattern; private long auditId; private long parentTaskId; private final static int SCAN_COUNT = 100; private final static String CONDITION_TEMPLATE = "pattern:{0}"; @Override public List<String> getTaskSteps() { List<String> taskStepList = new ArrayList<>(); taskStepList.add(TaskConstants.INIT_METHOD_KEY); // 检查实例是否运行 taskStepList.add("checkIsRun"); // delete key taskStepList.add("delKey"); return taskStepList; } /** * 1.初始化参数 */ @Override public TaskStepFlowEnum.TaskFlowStatusEnum init() { super.init(); appId = MapUtils.getLongValue(paramMap, TaskConstants.APPID_KEY); if (appId <= 0) { logger.error(marker, "task {} appId {} is wrong", taskId, appId); return TaskStepFlowEnum.TaskFlowStatusEnum.ABORT; } auditId = MapUtils.getLongValue(paramMap, TaskConstants.AUDIT_ID_KEY); if (auditId <= 0) { logger.error(marker, "task {} auditId {} is wrong", taskId, auditId); return TaskStepFlowEnum.TaskFlowStatusEnum.ABORT; } host = MapUtils.getString(paramMap, TaskConstants.HOST_KEY); if (StringUtils.isBlank(host)) { logger.error(marker, "task {} host is empty", taskId); return TaskStepFlowEnum.TaskFlowStatusEnum.ABORT; } port = MapUtils.getIntValue(paramMap, TaskConstants.PORT_KEY); if (port <= 0) { logger.error(marker, "task {} port {} is wrong", taskId, port); return TaskStepFlowEnum.TaskFlowStatusEnum.ABORT; } pattern = MapUtils.getString(paramMap, "pattern"); if (StringUtils.isBlank(pattern)) { logger.info(marker, "task {} pattern is empty", taskId); } parentTaskId = MapUtils.getLongValue(paramMap, "parentTaskId"); return TaskStepFlowEnum.TaskFlowStatusEnum.SUCCESS; } /** * 2.检查run以及slave * * @return */ public TaskStepFlowEnum.TaskFlowStatusEnum checkIsRun() { if (!redisCenter.isRun(appId, host, port)) { logger.error(marker, "{} {}:{} is not run", appId, host, port); return TaskStepFlowEnum.TaskFlowStatusEnum.ABORT; } return TaskStepFlowEnum.TaskFlowStatusEnum.SUCCESS; } /** * 3.scanKey * * @return */ public TaskStepFlowEnum.TaskFlowStatusEnum delKey() {<FILL_FUNCTION_BODY>} }
DiagnosticTaskRecord record = new DiagnosticTaskRecord(); record.setAppId(appId); record.setAuditId(auditId); String hostPost = host + ":" + port; record.setNode(hostPost); record.setDiagnosticCondition(MessageFormat.format(CONDITION_TEMPLATE, pattern)); record.setTaskId(taskId); record.setParentTaskId(parentTaskId); record.setType(DiagnosticTypeEnum.DEL_KEY.getType()); record.setStatus(0); diagnosticTaskRecordDao.insertDiagnosticTaskRecord(record); long recordId = record.getId(); /** * 扫描删除,计时开始*/ long startTime = System.currentTimeMillis(); Jedis jedis = null; try { jedis = redisCenter.getJedis(appId, host, port); long dbSize = jedis.dbSize(); if (dbSize == 0) { logger.info(marker, "{} {}:{} dbsize is {}", appId, host, port, dbSize); diagnosticTaskRecordDao.updateDiagnosticStatus(recordId, "", 1, System.currentTimeMillis() - startTime); return TaskStepFlowEnum.TaskFlowStatusEnum.SUCCESS; } logger.info(marker, "{} {}:{} total key is {} ", appId, host, port, dbSize); // scan参数 byte[] cursor = "0".getBytes(Charset.forName("UTF-8")); ScanParams scanParams = StringUtil.isBlank(pattern) ? new ScanParams().count(SCAN_COUNT) : new ScanParams().match(pattern).count(SCAN_COUNT); long count = 0; int totalSplit = 10; int curSplit = 1; while (true) { try { ScanResult<byte[]> scanResult = jedis.scan(cursor, scanParams); cursor = scanResult.getCursorAsBytes(); List<byte[]> keyList = scanResult.getResult(); //pipeline unlink Pipeline pipeline = jedis.pipelined(); keyList.stream().forEach(key -> pipeline.unlink(key)); List<Object> unlinkList; try { unlinkList = pipeline.syncAndReturnAll(); } catch (JedisRedirectionException e) { continue;// ignoreu } count += keyList.size(); if (count > dbSize / totalSplit * curSplit) { logger.info(marker, "{} {}:{} has already delete {}% {} key ", appId, host, port, curSplit * 10, count); curSplit++; } // @TODO暂时写死 TimeUnit.MILLISECONDS.sleep(10); } catch (Exception e) { logger.error(marker, e.getMessage(), e); } finally { //防止无限循环 if (Arrays.equals("0".getBytes(Charset.forName("UTF-8")), cursor)) { break; } } } long cost = System.currentTimeMillis() - startTime; /** * 计时结束*/ //更新记录 diagnosticTaskRecordDao.updateDiagnosticStatus(recordId, String.valueOf(count), 1, cost); logger.info(marker, "{} {}:{} del key successfully, cost time is {} ms, total key is {}", appId, host, port, cost, count); return TaskStepFlowEnum.TaskFlowStatusEnum.SUCCESS; } catch (RuntimeException e) { diagnosticTaskRecordDao.updateDiagnosticStatus(recordId, "", 2, 0); throw e; } catch (Exception e) { logger.error(marker, "redis-cli -h {} -p {} admin auth error", host, port); logger.error(marker, "del key appId {} {}:{} error:" + e.getMessage(), appId, host, port, e); diagnosticTaskRecordDao.updateDiagnosticStatus(recordId, "", 2, 0); return TaskStepFlowEnum.TaskFlowStatusEnum.ABORT; } finally { if (jedis != null) { jedis.close(); } }
811
1,101
1,912
<methods>public non-sealed void <init>() ,public static java.lang.String generateMasterName(java.lang.String, int) ,public Map<java.lang.String,java.lang.Object> getParamMap() ,public abstract List<java.lang.String> getTaskSteps() ,public com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum init() ,public void setParamMap(Map<java.lang.String,java.lang.Object>) <variables>public static final java.lang.String MARKER_NAME,private static final java.lang.String NUT_CRACKER_TEMPLATE_FILE,private static final java.lang.String NUT_CRACKER_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String PIKA_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_FILE,private static final java.lang.String REDIS_COMMON_TEMPLATE_NO_CPUIDX_FILE,private static final java.lang.String REDIS_MIGRATE_TOOL_TEMPLATE_FILE,private static final java.lang.String REDIS_PORT_TEMPLATE_FILE,protected com.sohu.cache.dao.AppAuditDao appAuditDao,protected com.sohu.cache.dao.AppDao appDao,protected com.sohu.cache.web.util.AppEmailUtil appEmailUtil,protected java.lang.String appEnvName,protected com.sohu.cache.web.service.AppService appService,protected com.sohu.cache.stats.app.AppStatsCenter appStatsCenter,protected com.sohu.cache.task.util.AppWechatUtil appWechatUtil,protected com.sohu.cache.redis.AssistRedisService assistRedisService,protected com.sohu.cache.dao.DiagnosticTaskRecordDao diagnosticTaskRecordDao,protected org.springframework.core.env.Environment environment,protected com.sohu.cache.dao.InstanceBigKeyDao instanceBigKeyDao,protected com.sohu.cache.dao.InstanceDao instanceDao,protected com.sohu.cache.stats.instance.InstanceDeployCenter instanceDeployCenter,protected com.sohu.cache.web.service.InstancePortService instancePortService,protected com.sohu.cache.dao.InstanceStatsDao instanceStatsDao,protected org.slf4j.Logger logger,protected com.sohu.cache.machine.MachineCenter machineCenter,protected com.sohu.cache.dao.MachineDao machineDao,protected com.sohu.cache.dao.MachineRelationDao machineRelationDao,protected com.sohu.cache.dao.MachineRoomDao machineRoomDao,protected com.sohu.cache.dao.MachineStatsDao machineStatsDao,public static final org.slf4j.Marker marker,protected com.sohu.cache.web.service.ModuleService moduleService,protected Map<java.lang.String,java.lang.Object> paramMap,protected com.sohu.cache.redis.RedisCenter redisCenter,protected com.sohu.cache.redis.RedisConfigTemplateService redisConfigTemplateService,protected com.sohu.cache.redis.RedisDeployCenter redisDeployCenter,protected com.sohu.cache.dao.ResourceDao resourceDao,protected com.sohu.cache.web.service.ResourceService resourceService,protected com.sohu.cache.ssh.SSHService sshService,protected long taskId,protected com.sohu.cache.task.TaskService taskService