v1.1初始化

This commit is contained in:
qiminbao
2025-10-21 14:16:25 +08:00
parent 36ff2dbb48
commit 62c8736728
31 changed files with 2023 additions and 2595 deletions
@@ -3,9 +3,11 @@ package com.tongran.agent.client;
import com.tongran.agent.client.core.config.GlobalConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.tongran.agent.client", "cn.hutool.extra.spring"})
public class TrAgentClientApplication {
public static void main(String[] args) {
@@ -9,7 +9,13 @@ public class ApplicationProperties {
private String name;
private String version;
private String confPath;
private String logicalNode;
private String scriptPath;
private String tmpPath;
private String tempPath;
// Getter 和 Setter 方法
public String getName() {
return name;
@@ -26,4 +32,44 @@ public class ApplicationProperties {
public void setVersion(String version) {
this.version = version;
}
public String getConfPath() {
return confPath;
}
public void setConfPath(String confPath) {
this.confPath = confPath;
}
public String getLogicalNode() {
return logicalNode;
}
public void setLogicalNode(String logicalNode) {
this.logicalNode = logicalNode;
}
public String getScriptPath() {
return scriptPath;
}
public void setScriptPath(String scriptPath) {
this.scriptPath = scriptPath;
}
public String getTmpPath() {
return tmpPath;
}
public void setTmpPath(String tmpPath) {
this.tmpPath = tmpPath;
}
public String getTempPath() {
return tempPath;
}
public void setTempPath(String tempPath) {
this.tempPath = tempPath;
}
}
@@ -20,45 +20,29 @@ public class GlobalConfig {
*/
public static long startupTime;
/**
* 注册标识
*/
public static boolean isRegister = false;
/**
* 客户端ID - 对应平台唯一SN
* 客户端ID
*/
public static String CLIENT_ID;
/**
* 交换机信息
* 设备SN
*/
public static String SWITCH_COMMUNITY; //团名
public static String SWITCH_IP; //交换机IP
public static int SWITCH_PORT; //交换机端口
public static LinkedHashMap<String, String> SWITCH_NET_OID = new LinkedHashMap<>(); //交换机网络端口发现OID
public static LinkedHashMap<String, String> SWITCH_MODULE_OID = new LinkedHashMap<>(); //交换机光模块发现OID
public static LinkedHashMap<String, String> SWITCH_MPU_OID = new LinkedHashMap<>(); //交换机MPU发现OID
public static LinkedHashMap<String, String> SWITCH_PWR_OID = new LinkedHashMap<>(); //交换机电源发现OID
public static LinkedHashMap<String, String> SWITCH_FAN_OID = new LinkedHashMap<>(); //交换机风扇发现OID
public static LinkedHashMap<String, String> SWITCH_OTHER_OID = new LinkedHashMap<>(); //交换机系统其他OID
public static String OTHER_INDEX_PARAM = "entIndex"; //交换机其他监控项索引参数
public static String OTHER_INDEX_OID = "";
public static List<String> OTHER_FILTER = new ArrayList<>(); //过滤值
public static String NET_INDEX_PARAM = "ifIndex"; //交换机网络端口索引参数
public static String NET_INDEX_OID = "";
public static List<String> NET_FILTER = new ArrayList<>(); //过滤值
public static String MODULE_INDEX_PARAM = "fiberEntIndex"; //交换机光模块端口索引参数
public static String MODULE_INDEX_OID = "";
public static List<String> MODULE_FILTER = new ArrayList<>(); //过滤值
public static String MPU_INDEX_PARAM = "mpuEntIndex"; //交换机MPU索引参数
public static String MPU_INDEX_OID = "";
public static List<String> MPU_FILTER = new ArrayList<>(); //过滤值
public static String PWR_INDEX_PARAM = "pwrEntIndex"; //交换机电源索引参数
public static String PWR_INDEX_OID = "";
public static List<String> PWR_FILTER = new ArrayList<>(); //过滤值
public static String FAN_INDEX_PARAM = "fanEntIndex"; //交换机风扇索引参数
public static String FAN_INDEX_OID = "";
public static List<String> FAN_FILTER = new ArrayList<>(); //过滤值
public static String DEVICE_SN;
/**
* 最新策略信息
*/
public static long MONITOR_TIME = 0L;
public static long SCRIPT_TIME = 0L;
public static long VERSION_TIME = 0L;
/**
* 采集标识
*/
@@ -114,51 +98,6 @@ public class GlobalConfig {
public static long systemUptimeInterval = 300; //系统正常运行时间采集间隔
public static boolean procNumCollect = false; //进程数采集
public static long procNumInterval = 300; //进程数采集间隔
/**
* 采集交换机监控
*/
public static boolean switchNetCollect = false; //交换机网络采集
public static long switchNetInterval = 300; //交换机网络采集间隔
public static boolean switchModuleCollect = false; //光模块采集
public static long switchModuleInterval = 300; //光模块采集间隔
public static boolean switchMpuCollect = false; //MPU采集
public static long switchMpuInterval = 300; //MPU采集间隔
public static boolean switchPwrCollect = false; //电源采集
public static long switchPwrInterval = 300; //电源采集间隔
public static boolean switchFanCollect = false; //风扇采集
public static long switchFanInterval = 300; //风扇采集间隔
/**
* 采集交换机其他监控
*/
public static boolean switchSysDescrCollect = false; //系统描述采集
public static long switchSysDescrInterval = 300; //系统描述采集间隔
public static boolean switchSysObjectIDCollect = false; //系统Object ID采集
public static long switchSysObjectIDInterval = 300; //系统Object ID采集间隔
public static boolean switchSysUpTimeCollect = false; //系统运行时间采集
public static long switchSysUpTimeInterval = 300; //系统运行时间采集间隔
public static boolean switchSysContactCollect = false; //系统联系信息采集
public static long switchSysContactInterval = 300; //系统联系信息采集间隔
public static boolean switchSysNameCollect = false; //系统名称采集
public static long switchSysNameInterval = 300; //系统名称采集间隔
public static boolean switchSysLocationCollect = false; //系统位置采集
public static long switchSysLocationInterval = 300; //系统位置采集间隔
public static boolean switchHwStackSystemMacCollect = false; //系统MAC地址采集
public static long switchHwStackSystemMacInterval = 300; //系统MAC地址采集间隔
public static boolean switchEntIndexCollect = false; //设备索引采集
public static long switchEntIndexInterval = 300; //设备索引采集间隔
public static boolean switchEntPhysicalNameCollect = false; //设备名称采集
public static long switchEntPhysicalNameInterval = 300; //设备名称采集间隔
public static boolean switchEntPhysicalSoftwareRevCollect = false; //设备软件版本采集
public static long switchEntPhysicalSoftwareRevInterval = 300; //设备软件版本采集间隔
public static boolean switchHwEntityCpuUsageCollect = false; //设备CPU使用率(%)采集
public static long switchHwEntityCpuUsageInterval = 300; //设备CPU使用率(%)采集间隔
public static boolean switchHwEntityMemUsageCollect = false; //设备内存使用率(%)采集
public static long switchHwEntityMemUsageInterval = 300; //设备内存使用率(%)采集间隔
public static boolean switchHwAveragePowerCollect = false; //系统平均功率(mW)采集
public static long switchHwAveragePowerInterval = 300; //系统平均功率(mW)采集间隔
public static boolean switchHwCurrentPowerCollect = false; //系统实时功率(mW)采集
public static long switchHwCurrentPowerInterval = 300; //系统实时功率(mW)采集间隔
/**
* 告警
@@ -166,18 +105,6 @@ public class GlobalConfig {
public static boolean IS_ALARM = false;
public static long ALARM_INTERVAL = 60;
public static List<AlarmEO> ALARM_LIST = new ArrayList<>(); //告警设置信息
/**
* 告警监控
*/
public static boolean systemCpuUti = false; //CPU使用率
public static boolean memoryUtilization = false; //内存利用率
public static boolean systemSwapSizePercent = false; //可用交换空间百分比
public static boolean systemUsersNum = false; //登录用户数
public static boolean vfsFsUtil = false; //挂载点的空间利用率
public static boolean netIfStatus = false; //网络运行状态UP变down
public static boolean netUtil = false; //网络带宽使用率
public static boolean containerMemUtil = false; //容器内存使用率
public static boolean extraPorts = false; //多余端口
/**
* 所有网络接口
@@ -11,11 +11,18 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
public enum MsgEnum {
建立连接("CONNECT"),
建立连接应答("CONNECT_RSP"),
注册("REGISTER"),
注册应答("REGISTER_RSP"),
获取最新策略("GET_POLICY"),
获取最新策略应答("GET_POLICY_RSP"),
断开("DISCONNECT"),
断开应答("DISCONNECT_RSP"),
@@ -48,14 +55,6 @@ public enum MsgEnum {
关闭所有系统采集应答("SYSTEM_COLLECT_STOP_RSP"),
开启或更新交换机采集("SWITCH_COLLECT_START"),
开启或更新交换机采集应答("SWITCH_COLLECT_START_RSP"),
关闭所有交换机采集("SWITCH_COLLECT_STOP"),
关闭所有交换机采集应答("SWITCH_COLLECT_STOP_RSP"),
告警设置("ALARM_SET"),
告警设置应答("ALARM_SET_RSP"),
@@ -5,8 +5,6 @@ import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@@ -16,11 +14,8 @@ public class AgentVersionUpdateEO {
//文件地址,外网HTTPS)地址
private String fileUrl;
//保存文件地址
private String filePath;
//命令
private List<String> commands;
//文件MD5
private String fileMd5;
//执行方式:0、立即执行;1、定时执行;
private int method;
@@ -6,7 +6,6 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
@Data
@Builder
@@ -17,16 +16,12 @@ public class ScriptPolicyEO implements Serializable {
private static final long serialVersionUID = -1267013167162440612L;
private String policyName;
/**
* 文件
*/
private List<ScriptFile> files;
//目标路径地址
private String filePath;
//文件类型为1、外网HTTPS)时必传
private String fileUrl;
//命令
private List<String> commands;
//脚本参数
private String commandParams;
//执行方式:0、立即执行;1、定时执行;
private int method;
@@ -34,25 +29,4 @@ public class ScriptPolicyEO implements Serializable {
//执行方式为1、定时执行时必传-指定时间
private long policyTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ScriptFile{
//文件类型:0、平台文件地址;1、外网HTTP(S)
private int fileType;
//文件类型为1、外网HTTP(S)时必传
private String fileUrl;
//文件类型为0、平台文件地址时必传(文件名)
private String fileName;
//文件类型为0、平台文件地址时必传(文件流)
private String fileData;
}
}
@@ -0,0 +1,24 @@
package com.tongran.agent.client.core.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "网卡信息")
public class NetworkInterfaceInfo {
String name; // 接口名称:eth0, enp3s0
String mac; // MAC 地址
String ipv4; // IPv4 地址
String gateway; // 网关
String publicIp; // 公网 IP
String carrier; // 运营商
String province; // 省
String city; // 市
}
@@ -1,22 +0,0 @@
package com.tongran.agent.client.netty;
import com.tongran.agent.client.netty.config.BaseNettyConfig;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* Netty配置
*/
@Data
@Configuration
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@ConfigurationProperties(prefix = "tcp.netty.charge")
public class AgentNettyConfig extends BaseNettyConfig {
private static final long serialVersionUID = -4284214721383107291L;
}
@@ -1,57 +0,0 @@
package com.tongran.agent.client.netty;
import com.tongran.agent.client.netty.handler.AgentDecoderHandler;
import com.tongran.agent.client.netty.handler.AgentDispatcherHandler;
import com.tongran.agent.client.netty.handler.AgentEncoderHandler;
import com.tongran.agent.client.netty.handler.TCPListenHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
public class AgentNettyServer extends BaseNettyServer {
@Resource
private AgentNettyConfig config;
@Resource
private TCPListenHandler tcpListenHandler;
@Resource
private AgentDecoderHandler decoderHandler;
@Resource
private AgentEncoderHandler encoderHandler;
@Resource
private AgentDispatcherHandler dispatcherHandler;
protected AgentNettyServer(AgentNettyConfig config) {
super(config);
}
@Bean(name = "NettyCharge", initMethod = "start", destroyMethod = "stop")
BaseNettyServer run() {
config.setHander(new ChannelInitializer<NioSocketChannel>() {
@Override
public void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new IdleStateHandler(config.readerIdleTime, config.writerIdleTime, config.allIdleTime));// 心跳
ch.pipeline().addLast(tcpListenHandler);// 监听器
//入栈
ch.pipeline().addLast(decoderHandler);//解码器
//出栈
ch.pipeline().addLast(encoderHandler);//加码器
// 业务分发是入站最后一个处理器, 出站第一个处理器, 位置要放在最后
ch.pipeline().addLast(businessGroup, dispatcherHandler);//业务分发 这里使用业务线程组
}
});
return new AgentNettyServer(config);
}
}
@@ -0,0 +1,16 @@
package com.tongran.agent.client.netty.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "netty.server")
public class AgentNettyConfig {
private String host;
private int port;
}
@@ -0,0 +1,39 @@
package com.tongran.agent.client.netty.config;
import java.util.Objects;
/**
* 连接配置信息
*/
public class ConnectionConfig {
private final String connectionKey;
private final String host;
private final int port;
private final int timeout;
public ConnectionConfig(String connectionKey, String host, int port, int timeout) {
this.connectionKey = connectionKey;
this.host = host;
this.port = port;
this.timeout = timeout;
}
// Getter方法
public String getConnectionKey() { return connectionKey; }
public String getHost() { return host; }
public int getPort() { return port; }
public int getTimeout() { return timeout; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConnectionConfig that = (ConnectionConfig) o;
return Objects.equals(connectionKey, that.connectionKey);
}
@Override
public int hashCode() {
return Objects.hash(connectionKey);
}
}
@@ -4,6 +4,7 @@ import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.tongran.agent.client.core.config.ApplicationProperties;
import com.tongran.agent.client.core.config.GlobalConfig;
import com.tongran.agent.client.core.enums.MsgEnum;
import com.tongran.agent.client.core.eo.AgentVersionUpdateEO;
@@ -13,8 +14,6 @@ import com.tongran.agent.client.netty.annotation.AgentDispatcher;
import com.tongran.agent.client.netty.basics.AgentHandler;
import com.tongran.agent.client.netty.model.UpMsgResponse;
import com.tongran.agent.client.scheduler.service.AdvancedAsyncDownloader;
import com.tongran.agent.client.scheduler.service.AppInitializer;
import com.tongran.agent.client.scheduler.task.SpecificTimeTaskService;
import com.tongran.agent.client.service.AgentService;
import com.tongran.agent.client.utils.AgentDataUtil;
import com.tongran.agent.client.utils.AgentUtil;
@@ -24,262 +23,61 @@ import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
@Component
public class AgentEndpoint {
@Resource
private AppInitializer appInitializer;
@Resource
private SpecificTimeTaskService taskService;
@Resource
private AgentService agentService;
@Resource
private ApplicationProperties properties;
@AgentDispatcher(msgId = MsgEnum.注册)
@AgentDispatcher(msgId = MsgEnum.建立连接应答)
public class ConnectHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
JSONObject json = new JSONObject();
json.put("resCode",1);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.建立连接应答.getValue())
.content(json.toString()).build();
}
}
@AgentDispatcher(msgId = MsgEnum.注册应答)
public class RegisterHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
//更改全局变量
JSONObject jsonObject = JSONObject.parseObject(data);
if(jsonObject.containsKey("switchBoard")){
String switchBoard = jsonObject.getString("switchBoard");
jsonObject = JSONObject.parseObject(switchBoard);
if(jsonObject.containsKey("community")){
GlobalConfig.SWITCH_COMMUNITY = jsonObject.getString("community");
}
if(jsonObject.containsKey("ip")){
GlobalConfig.SWITCH_IP = jsonObject.getString("ip");
}
if(jsonObject.containsKey("port")){
GlobalConfig.SWITCH_PORT = jsonObject.getInteger("port");
}
if(jsonObject.containsKey("netOID")){
String netOID = jsonObject.getString("netOID");
if(StringUtils.isNotBlank(netOID)){
LinkedHashMap<String, String> map = JSON.parseObject(netOID, new TypeReference<LinkedHashMap<String, String>>() {});
GlobalConfig.SWITCH_NET_OID = map;
LinkedHashMap<String,String> m = AgentUtil.swapMap(map);
if(m.containsKey(GlobalConfig.NET_INDEX_PARAM)){
GlobalConfig.NET_INDEX_OID = m.get(GlobalConfig.NET_INDEX_PARAM);
}
}
}
if(jsonObject.containsKey("moduleOID")){
String moduleOID = jsonObject.getString("moduleOID");
if(StringUtils.isNotBlank(moduleOID)){
LinkedHashMap<String, String> map = JSON.parseObject(moduleOID, new TypeReference<LinkedHashMap<String, String>>() {});
GlobalConfig.SWITCH_MODULE_OID = map;
LinkedHashMap<String,String> m = AgentUtil.swapMap(map);
if(m.containsKey(GlobalConfig.MODULE_INDEX_PARAM)){
GlobalConfig.MODULE_INDEX_OID = m.get(GlobalConfig.MODULE_INDEX_PARAM);
}
}
}
if(jsonObject.containsKey("mpuOID")){
String mpuOID = jsonObject.getString("mpuOID");
if(StringUtils.isNotBlank(mpuOID)){
LinkedHashMap<String, String> map = JSON.parseObject(mpuOID, new TypeReference<LinkedHashMap<String, String>>() {});
GlobalConfig.SWITCH_MPU_OID = map;
LinkedHashMap<String,String> m = AgentUtil.swapMap(map);
if(m.containsKey(GlobalConfig.MPU_INDEX_PARAM)){
GlobalConfig.MPU_INDEX_OID = m.get(GlobalConfig.MPU_INDEX_PARAM);
}
}
}
if(jsonObject.containsKey("pwrOID")){
String pwrOID = jsonObject.getString("pwrOID");
if(StringUtils.isNotBlank(pwrOID)){
LinkedHashMap<String, String> map = JSON.parseObject(pwrOID, new TypeReference<LinkedHashMap<String, String>>() {});
GlobalConfig.SWITCH_PWR_OID = map;
LinkedHashMap<String,String> m = AgentUtil.swapMap(map);
if(m.containsKey(GlobalConfig.PWR_INDEX_PARAM)){
GlobalConfig.PWR_INDEX_OID = m.get(GlobalConfig.PWR_INDEX_PARAM);
}
}
}
if(jsonObject.containsKey("fanOID")){
String fanOID = jsonObject.getString("fanOID");
if(StringUtils.isNotBlank(fanOID)){
LinkedHashMap<String, String> map = JSON.parseObject(fanOID, new TypeReference<LinkedHashMap<String, String>>() {});
GlobalConfig.SWITCH_FAN_OID = map;
LinkedHashMap<String,String> m = AgentUtil.swapMap(map);
if(m.containsKey(GlobalConfig.FAN_INDEX_PARAM)){
GlobalConfig.FAN_INDEX_OID = m.get(GlobalConfig.FAN_INDEX_PARAM);
}
}
}
if(jsonObject.containsKey("otherOID")){
String otherOID = jsonObject.getString("otherOID");
if(StringUtils.isNotBlank(otherOID)){
LinkedHashMap<String, String> map = JSON.parseObject(otherOID, new TypeReference<LinkedHashMap<String, String>>() {});
GlobalConfig.SWITCH_OTHER_OID = map;
LinkedHashMap<String,String> m = AgentUtil.swapMap(map);
if(m.containsKey(GlobalConfig.OTHER_INDEX_PARAM)){
GlobalConfig.OTHER_INDEX_OID = m.get(GlobalConfig.OTHER_INDEX_PARAM);
}
}
}
if(jsonObject.containsKey("filters")){
String filters = jsonObject.getString("filters");
if(StringUtils.isNotBlank(filters)){
JSONObject object = JSONObject.parseObject(filters);
if(object.containsKey("netOID")){
String netOID = object.getString("netOID");
if(StringUtils.isNotBlank(netOID)){
List<String> list = JSON.parseObject(netOID, new TypeReference<List<String>>() {});
GlobalConfig.NET_FILTER = list;
}
}
if(object.containsKey("moduleOID")){
String moduleOID = object.getString("moduleOID");
if(StringUtils.isNotBlank(moduleOID)){
List<String> list = JSON.parseObject(moduleOID, new TypeReference<List<String>>() {});
GlobalConfig.MODULE_FILTER = list;
}
}
if(object.containsKey("mpuOID")){
String mpuOID = object.getString("mpuOID");
if(StringUtils.isNotBlank(mpuOID)){
List<String> list = JSON.parseObject(mpuOID, new TypeReference<List<String>>() {});
GlobalConfig.MPU_FILTER = list;
}
}
if(object.containsKey("pwrOID")){
String pwrOID = object.getString("pwrOID");
if(StringUtils.isNotBlank(pwrOID)){
List<String> list = JSON.parseObject(pwrOID, new TypeReference<List<String>>() {});
GlobalConfig.PWR_FILTER = list;
}
}
if(object.containsKey("fanOID")){
String fanOID = object.getString("fanOID");
if(StringUtils.isNotBlank(fanOID)){
List<String> list = JSON.parseObject(fanOID, new TypeReference<List<String>>() {});
GlobalConfig.FAN_FILTER = list;
}
}
if(object.containsKey("otherOID")){
String otherOID = object.getString("otherOID");
if(StringUtils.isNotBlank(otherOID)){
List<String> list = JSON.parseObject(otherOID, new TypeReference<List<String>>() {});
GlobalConfig.OTHER_FILTER = list;
}
}
}
}
JSONObject object = JSONObject.parseObject(data);
int resCode = 0;
if(object.containsKey("resCode")){
resCode = object.getInteger("resCode");
}
GlobalConfig.isCollect = true;
GlobalConfig.CLIENT_ID = clientId;
//调用采集任务
try {
appInitializer.run();
} catch (Exception e) {
e.printStackTrace();
//注册成功,更新外置文件注册标识
if(resCode == 1){
//检查外置目录是否存在
if(AdvancedAsyncDownloader.createSingleDirectoryIfNotExists(properties.getConfPath())){
String[] lines = {
"register=1"
};
AgentUtil.bufferedWriter(properties.getConfPath()+"/register.conf",lines);
}
GlobalConfig.isRegister = true;
//取消注册定时任务
agentService.cancelTask("register");
agentService.start();
}
AssertLog.info("SWITCH_NET_OID={}",JSON.toJSONString(GlobalConfig.SWITCH_NET_OID));
AssertLog.info("SWITCH_MODULE_OID={}",JSON.toJSONString(GlobalConfig.SWITCH_MODULE_OID));
AssertLog.info("SWITCH_MPU_OID={}",JSON.toJSONString(GlobalConfig.SWITCH_MPU_OID));
AssertLog.info("SWITCH_PWR_OID={}",JSON.toJSONString(GlobalConfig.SWITCH_PWR_OID));
AssertLog.info("SWITCH_FAN_OID={}",JSON.toJSONString(GlobalConfig.SWITCH_FAN_OID));
AssertLog.info("SWITCH_OTHER_OID={}",JSON.toJSONString(GlobalConfig.SWITCH_OTHER_OID));
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMag","");
json.put("timestamp",timestamp);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.注册应答.getValue())
.content(json.toString()).build();
return null;
}
}
@AgentDispatcher(msgId = MsgEnum.断开)
public class DisconnectHandler implements AgentHandler {
@AgentDispatcher(msgId = MsgEnum.获取最新策略应答)
public class GetPolicyRspHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
//更改全局变量
GlobalConfig.isCollect = false;
//调用采集任务
agentService.cancelCollect();
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMag","");
json.put("timestamp",timestamp);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.断开应答.getValue())
.content(json.toString()).build();
}
}
@AgentDispatcher(msgId = MsgEnum.开启或更新系统采集)
public class SysCollectStartHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
//更改全局变量
agentService.systemCollectStart(data);
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMag","");
json.put("timestamp",timestamp);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.开启或更新系统采集应答.getValue()).content(json.toString()).build();
}
}
@AgentDispatcher(msgId = MsgEnum.关闭所有系统采集)
public class SysCollectStopHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
//更改全局变量
agentService.systemCollectStop();
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMag","");
json.put("timestamp",timestamp);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.关闭所有系统采集应答.getValue()).content(json.toString()).build();
}
}
@AgentDispatcher(msgId = MsgEnum.开启或更新交换机采集)
public class SwitchCollectStartHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
//更改全局变量
agentService.switchCollectStart(data);
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMag","");
json.put("timestamp",timestamp);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.开启或更新交换机采集应答.getValue()).content(json.toString()).build();
}
}
@AgentDispatcher(msgId = MsgEnum.关闭所有交换机采集)
public class SwitchCollectStopHandler implements AgentHandler {
@Override
public UpMsgResponse upHandle(String data, String clientId) {
//更改全局变量
agentService.switchCollectStop();
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMag","");
json.put("timestamp",timestamp);
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.关闭所有交换机采集应答.getValue()).content(json.toString()).build();
agentService.getPolicy(data);
return null;
}
}
@@ -323,18 +121,11 @@ public class AgentEndpoint {
if(jsonObject.containsKey("policyName")) {
policy.setPolicyName(jsonObject.getString("policyName"));
}
if(jsonObject.containsKey("files")) {
String files = jsonObject.getString("files");
List<ScriptPolicyEO.ScriptFile> fileList = JSON.parseObject(files, new TypeReference<List<ScriptPolicyEO.ScriptFile>>() {});
policy.setFiles(fileList);
if(jsonObject.containsKey("fileUrl")) {
policy.setFileUrl(jsonObject.getString("fileUrl"));
}
if(jsonObject.containsKey("filePath")) {
policy.setFilePath(jsonObject.getString("filePath"));
}
if(jsonObject.containsKey("commands")) {
String commands = jsonObject.getString("commands");
List<String> commandList = JSON.parseObject(commands, new TypeReference<List<String>>() {});
policy.setCommands(commandList);
if(jsonObject.containsKey("commandParams")) {
policy.setCommandParams(jsonObject.getString("commandParams"));
}
if(jsonObject.containsKey("method")) {
policy.setMethod(jsonObject.getInteger("method"));
@@ -343,81 +134,30 @@ public class AgentEndpoint {
policy.setPolicyTime(jsonObject.getLong("policyTime"));
}
boolean isFalse = false;
if(StringUtils.isNotBlank(policy.getFilePath())){
if(AdvancedAsyncDownloader.createSingleDirectoryIfNotExists(policy.getFilePath())){
if(CollectionUtil.isNotEmpty(policy.getFiles())){
isFalse = true;
GlobalConfig.DOWN_FILES.put(policy.getPolicyName(), policy.getFiles().size());
for (ScriptPolicyEO.ScriptFile f : policy.getFiles()) {
String finalSaveDir = policy.getFilePath();
//文件类型:0、平台文件地址;1、外网HTTP(S)
if(f.getFileType() == 0){
String filePath = policy.getFilePath() + "/" + f.getFileName();
// 移除Base64 URL前缀(如果存在)
// if (f.getFileData().contains(",")) {
// f.setFileData(f.getFileData().split(",")[1]);
// }
try {
AgentUtil.base64ToFile(f.getFileData(), filePath);
System.out.println("文件保存成功: " + filePath);
isFalse = true;
try {
AgentDataUtil.chmod(filePath,"+x");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
isFalse = false;
System.err.println("文件保存失败: " + e.getMessage());
}
}else{
AdvancedAsyncDownloader.downloadWithProgress(f.getFileUrl(), finalSaveDir, f.getFileName(), progress -> {
System.out.printf("下载进度: %.1f%%\n", progress);
}).thenAccept(filePath -> {
System.out.println("下载完成: " + filePath);
try {
AgentDataUtil.chmod(finalSaveDir+"/"+f.getFileName(),"775");
int count = GlobalConfig.DOWN_FILES.get(policy.getPolicyName());
if(count > 1){
GlobalConfig.DOWN_FILES.put(policy.getPolicyName(), count--);
}else{
//所有文件下载完成,执行脚本命令
agentService.command(policy, clientId,MsgEnum.执行脚本策略应答.getValue());
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).exceptionally(ex -> {
System.err.println("下载错误: " + ex.getMessage());
return null;
});
// Java8FileDownloader.DownloadResult result = Java8FileDownloader.downloadFile(f.getFileUrl(), finalSaveDir, f.getFileName());
// // 验证下载是否完成
// if (result.isSuccess()) {
// boolean isComplete = Java8FileDownloader.verifyFileCompletion(
// result.getFilePath(), result.getExpectedSize());
// if(isComplete){
// isFalse = true;
// System.out.println("下载完成: " + finalSaveDir+"/"+f.getFileName());
// try {
// AgentDataUtil.chmod(finalSaveDir+"/"+f.getFileName(),"775");
// } catch (IOException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }else{
// isFalse = false;
// System.err.println("下载失败");
// }
// }
}
if(AdvancedAsyncDownloader.createSingleDirectoryIfNotExists(properties.getTmpPath()+"/script")){
if(StringUtils.isNotBlank(policy.getFileUrl())){
isFalse = true;
String fileName = policy.getFileUrl().substring(policy.getFileUrl().lastIndexOf('/') + 1);
//异步下载脚本
AdvancedAsyncDownloader.downloadWithProgress(policy.getFileUrl(), properties.getTmpPath()+"/script", fileName, progress -> {
System.out.printf("下载进度: %.1f%%\n", progress);
}).thenAccept(filePath -> {
System.out.println("下载完成: " + filePath);
try {
AgentDataUtil.chmod(properties.getTmpPath()+"/script/"+fileName,"775");
String params = properties.getTmpPath()+"/script/"+fileName+" " + policy.getCommandParams();
policy.setCommandParams(params);
//所有文件下载完成,执行脚本命令
agentService.command(policy, GlobalConfig.CLIENT_ID,MsgEnum.执行脚本策略应答.getValue());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).exceptionally(ex -> {
System.err.println("下载错误: " + ex.getMessage());
return null;
});
}
}
//判断是否需要保存文件
@@ -440,48 +180,61 @@ public class AgentEndpoint {
AgentVersionUpdateEO versionUpdateEO = JSON.parseObject(data, AgentVersionUpdateEO.class);
ScriptPolicyEO policy = ScriptPolicyEO.builder()
.method(versionUpdateEO.getMethod())
.commandParams("systemctl restart tragent")
.policyTime(versionUpdateEO.getPolicyTime())
.build();
JSONObject jsonObject = JSONObject.parseObject(data);
if(jsonObject.containsKey("commands")) {
String commands = jsonObject.getString("commands");
List<String> commandList = JSON.parseObject(commands, new TypeReference<List<String>>() {});
policy.setCommands(commandList);
}
boolean isFalse = false;
if(StringUtils.isNotBlank(versionUpdateEO.getFileUrl())){
isFalse = true;
String finalSaveDir = versionUpdateEO.getFilePath();
AdvancedAsyncDownloader.downloadWithProgress(versionUpdateEO.getFileUrl(), finalSaveDir, null, progress -> {
String fileName = versionUpdateEO.getFileUrl().substring(versionUpdateEO.getFileUrl().lastIndexOf('/') + 1);
AdvancedAsyncDownloader.downloadWithProgress(versionUpdateEO.getFileUrl(), properties.getTempPath(), fileName, progress -> {
System.out.printf("下载进度: %.1f%%\n", progress);
}).thenAccept(filePath -> {
System.out.println("下载完成: " + filePath);
try {
//更改全局变量
GlobalConfig.isCollect = false;
//调用采集任务
agentService.cancelCollect();
//所有文件下载完成,执行脚本命令
agentService.command(policy, clientId,MsgEnum.Agent版本更新应答.getValue());
//验证文件MD5
String md5 = AgentUtil.getFileMD5(properties.getTempPath()+"/"+fileName);
if(StringUtils.isNotBlank(md5) && StringUtils.isNotBlank(versionUpdateEO.getFileMd5())
&& StringUtils.equals(md5,versionUpdateEO.getFileMd5())){
//更改全局变量
GlobalConfig.isCollect = false;
//调用采集任务
agentService.cancelCollect();
//所有文件下载完成,执行脚本命令
agentService.command(policy, clientId,MsgEnum.Agent版本更新应答.getValue());
}else{
//发送更新失败
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",0);
json.put("resMsg", "版本策略MD5验证失败");
json.put("timestamp",timestamp);
agentService.sendMessage(MsgEnum.Agent版本更新应答.getValue(), json.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}).exceptionally(ex -> {
System.err.println("下载错误: " + ex.getMessage());
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject json = new JSONObject();
json.put("resCode",0);
json.put("resMsg", "版本策略文件下载失败");
json.put("timestamp",timestamp);
agentService.sendMessage(MsgEnum.Agent版本更新应答.getValue(), json.toString());
return null;
});
}
//判断是否需要保存文件
if(!isFalse){
agentService.command(policy, clientId,MsgEnum.Agent版本更新应答.getValue());
return null;
}else{
if(isFalse){
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMsg", "Agent版本更新文件保存中");
return UpMsgResponse.builder().clientId(clientId).dataType(MsgEnum.Agent版本更新应答.getValue()).content(json.toString()).build();
}
return null;
}
}
@@ -1,84 +0,0 @@
package com.tongran.agent.client.netty.handler;
import com.tongran.agent.client.core.config.GlobalConfig;
import com.tongran.agent.client.core.session.SessionManager;
import com.tongran.agent.client.scheduler.service.AppInitializer;
import com.tongran.agent.client.service.AgentService;
import com.tongran.agent.client.utils.AssertLog;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
/**
* @Description: TCP消息适配器
*/
@Component
@ChannelHandler.Sharable
public class TCPListenHandler extends ChannelInboundHandlerAdapter {
@Resource
private AppInitializer appInitializer;
private final SessionManager sessionManager;
@Resource
private AgentService agentService;
public TCPListenHandler() {
this.sessionManager = SessionManager.getInstance();
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
AssertLog.info("<<<<<<[终端连接]{}", ctx.channel().remoteAddress());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
AssertLog.info(">>>>>>[断开连接]{}", sessionManager.client(ctx));
sessionManager.remove(ctx.channel());
try {
GlobalConfig.isCollect = false;
agentService.cancelCollect();
appInitializer.run();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
if (e instanceof IOException) {
AssertLog.info("<<<<<<[终端断开连接]{} {}", sessionManager.client(ctx), e.getMessage());
agentService.cancelCollect();
} else {
AssertLog.info(">>>>>>[消息处理异常]" + sessionManager.client(ctx), e);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
IdleState state = event.state();
if (state == IdleState.READER_IDLE || state == IdleState.WRITER_IDLE || state == IdleState.ALL_IDLE) {
AssertLog.warn(">>>>>>[终端心跳超时]{} {}", state, sessionManager.client(ctx));
sessionManager.remove(ctx.channel());
ctx.close();
try {
GlobalConfig.isCollect = false;
appInitializer.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
@@ -1,24 +0,0 @@
package com.tongran.agent.client.netty.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.stereotype.Component;
/**
* @Description: UDP消息适配器
*/
@Component
@ChannelHandler.Sharable
public class UDPListenHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
DatagramPacket packet = (DatagramPacket) msg;
ByteBuf buf = packet.content();
buf.clear();// 暂未实现
}
}
@@ -1,17 +1,35 @@
package com.tongran.agent.client.scheduler.service;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tongran.agent.client.core.config.GlobalConfig;
import com.tongran.agent.client.core.enums.MsgEnum;
import com.tongran.agent.client.core.vo.NetworkInterfaceInfo;
import com.tongran.agent.client.netty.MultiTargetNettyClient;
import com.tongran.agent.client.netty.model.Message;
import com.tongran.agent.client.service.AgentService;
import com.tongran.agent.client.utils.AgentUtil;
import com.tongran.agent.client.utils.AssertLog;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class AppInitializer implements CommandLineRunner {
private final BusinessTasks businessTasks;
private final DynamicTaskService dynamicTaskService;
@Resource
private MultiTargetNettyClient client;
@Resource
private AgentService agentService;
// 使用构造函数注入,避免循环依赖
public AppInitializer(DynamicTaskService dynamicTaskService,
@Lazy BusinessTasks businessTasks) {
@@ -21,64 +39,73 @@ public class AppInitializer implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("应用启动完成,开始初始化定时任务...");
if(GlobalConfig.isCollect){
// 开启定时任务
initScheduledTasks();
}
System.out.println("定时任务初始化完成");
AssertLog.info("创建连接");
// 建立连接
initConnection();
// 检查保活脚本
agentService.checkTrAgent();
AssertLog.info("创建连接完成");
}
private void initScheduledTasks() {
// 每30秒执行心跳任务
AssertLog.info("初始化启动心跳定时任务 - 延迟: {}ms, 间隔: {}ms", 15000, 30000);
dynamicTaskService.scheduleTask("heartbeat",
businessTasks::heartbeatTask, 15000, 30000);
// long milli = AgentUtil.getMillisToNextMinute() + 60000;
// // 每300秒执行CPU信息采集任务
// AssertLog.info("初始化启动CPU信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 300000);
// dynamicTaskService.scheduleTask("cpu",
// businessTasks::cpuTask, milli, 300000); // 25秒后开始,每300秒执行
//
// // 每300秒执行磁盘信息采集任务
// AssertLog.info("初始化启动磁盘信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 300000);
// dynamicTaskService.scheduleTask("disk",
// businessTasks::diskTask, milli, 300000); // 35秒后开始,每300秒执行
//
// // 每300秒执行系统信息采集任务
// AssertLog.info("初始化启动系统信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 300000);
// dynamicTaskService.scheduleTask("system",
// businessTasks::systemTask, milli, 300000); // 40秒后开始,每300秒执行
//
// // 每300秒执行容器信息采集任务
// AssertLog.info("初始化启动容器信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 300000);
// dynamicTaskService.scheduleTask("docker",
// businessTasks::dockerTask, milli, 300000); // 45秒后开始,每300秒执行
//
// // 每300秒执行内存信息采集任务
// AssertLog.info("初始化启动内存信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 300000);
// dynamicTaskService.scheduleTask("memory",
// businessTasks::memoryTask, milli, 300000); // 55秒后开始,每300秒执行
//
//
// //获取当前时间距离下一个“分钟为 0 或 5”的时间点还差多少毫秒
// long millis = AgentUtil.millisecondsToNext5Minute();
// // 每300秒执行网络信息采集任务
// AssertLog.info("初始化启动网络信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", millis, 300000);
// dynamicTaskService.scheduleTask("net",
// businessTasks::netTask, millis, 300000); // 65秒后开始,每300秒执行
//
// // 每300秒执行挂载信息采集任务
// AssertLog.info("初始化启动挂载信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 300000);
// dynamicTaskService.scheduleTask("point",
// businessTasks::pointTask, milli, 300000); // 75秒后开始,每300秒执行
//
// // 每300秒执行交换机信息采集任务
// AssertLog.info("初始化启动交换机信息采集定时任务 - 延迟: {}ms, 间隔: {}ms", millis, 300000);
// dynamicTaskService.scheduleTask("switchBoard",
// businessTasks::switchBoardTask, millis, 300000); // 85秒后开始,每300秒执行
private void initConnection() {
boolean success = true;
int activeConnect = client.getActiveConnections();
AssertLog.info("activeConnect={}",activeConnect);
if(activeConnect == 0){
success = agentService.connection();
}
if(success){
AssertLog.info("连接成功,发送初始连接消息");
//连接成功,发送初始连接消息
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject object = new JSONObject();
object.put("clientId", GlobalConfig.CLIENT_ID);
object.put("sn", GlobalConfig.DEVICE_SN);
object.put("timestamp", timestamp);
Message msg = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.建立连接.getValue()).data(object.toString()).build();
// 将对象转为 JSON 字符串
client.sendMessages(GlobalConfig.CLIENT_ID, msg);
// 等待3秒
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
//判断是否发送注册信息
if(GlobalConfig.isRegister){
//已注册,发送心跳
// 创建心跳定时任务
AssertLog.info("启动心跳定时任务 - 延迟: {}ms, 间隔: {}ms", 15000, 30000);
dynamicTaskService.scheduleTask("heartbeat", businessTasks::heartbeatTask, 15000, 30000);
// 创建获取最新策略定时任务
long milli = AgentUtil.getMillisToNextMinute() + 60000;
AssertLog.info("启动更新策略定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 60000);
dynamicTaskService.scheduleTask("policy", businessTasks::policyTask, milli, 60000);
}else{
//未注册,发送注册
try {
long timestamps = System.currentTimeMillis();
timestamps = Math.round(timestamps / 1000.0);
List<NetworkInterfaceInfo> infos = AgentUtil.collectNetworkInfo();
JSONObject objects = new JSONObject();
objects.put("clientId", GlobalConfig.CLIENT_ID);
objects.put("sn", GlobalConfig.DEVICE_SN);
objects.put("networkInfo", JSON.toJSONString(infos));
objects.put("timestamp", timestamps);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.注册.getValue()).data(objects.toString()).build();
// 将对象转为 JSON 字符串
client.sendMessages(GlobalConfig.CLIENT_ID, message);
} catch (Exception e) {
e.printStackTrace();
}
//设置注册定时任务,收注册成功后取消该定时任务
dynamicTaskService.scheduleTask("register", businessTasks::registerTask, 60000, 300000);
}
}else{
//连接建立失败,3分钟后重试
dynamicTaskService.scheduleTask("connection", businessTasks::connectionTask, 60000, 180000);
}
}
}
@@ -9,6 +9,8 @@ import com.tongran.agent.client.core.config.GlobalConfig;
import com.tongran.agent.client.core.enums.MsgEnum;
import com.tongran.agent.client.core.session.SessionManager;
import com.tongran.agent.client.core.vo.*;
import com.tongran.agent.client.netty.MultiTargetNettyClient;
import com.tongran.agent.client.netty.config.AgentNettyConfig;
import com.tongran.agent.client.netty.model.Message;
import com.tongran.agent.client.service.*;
import com.tongran.agent.client.utils.AgentUtil;
@@ -53,26 +55,9 @@ public class BusinessTasks {
private final AtomicInteger systemUptimeTask = new AtomicInteger(0);
private final AtomicInteger procNumTask = new AtomicInteger(0);
private final AtomicInteger switchNetTask = new AtomicInteger(0);
private final AtomicInteger switchModuleTask = new AtomicInteger(0);
private final AtomicInteger switchMpuTask = new AtomicInteger(0);
private final AtomicInteger switchPwrTask = new AtomicInteger(0);
private final AtomicInteger switchFanTask = new AtomicInteger(0);
private final AtomicInteger switchSysDescrTask = new AtomicInteger(0);
private final AtomicInteger switchSysObjectIDTask = new AtomicInteger(0);
private final AtomicInteger switchSysUpTimeTask = new AtomicInteger(0);
private final AtomicInteger switchSysContactTask = new AtomicInteger(0);
private final AtomicInteger switchSysNameTask = new AtomicInteger(0);
private final AtomicInteger switchSysLocationTask = new AtomicInteger(0);
private final AtomicInteger switchHwStackSystemMacTask = new AtomicInteger(0);
private final AtomicInteger switchEntIndexTask = new AtomicInteger(0);
private final AtomicInteger switchEntPhysicalNameTask = new AtomicInteger(0);
private final AtomicInteger switchEntPhysicalSoftwareRevTask = new AtomicInteger(0);
private final AtomicInteger switchHwEntityCpuUsageTask = new AtomicInteger(0);
private final AtomicInteger switchHwEntityMemUsageTask = new AtomicInteger(0);
private final AtomicInteger switchHwAveragePowerTask = new AtomicInteger(0);
private final AtomicInteger switchHwCurrentPowerTask = new AtomicInteger(0);
private final AtomicInteger policyTask = new AtomicInteger(0);
private final AtomicInteger registerTask = new AtomicInteger(0);
private final AtomicInteger connectionTask = new AtomicInteger(0);
@@ -104,9 +89,6 @@ public class BusinessTasks {
@Resource
private NetService netService;
@Resource
private SwitchBoardService switchBoardService;
@Resource
private SystemService systemService;
@@ -116,6 +98,15 @@ public class BusinessTasks {
@Resource
private ApplicationProperties properties;
@Resource
private MultiTargetNettyClient client;
@Resource
private AgentNettyConfig config;
@Resource
private AgentService agentService;
/**
* 任务1:心跳上报任务
*/
@@ -130,6 +121,9 @@ public class BusinessTasks {
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送心跳包
JSONObject object = new JSONObject();
object.put("clientId", GlobalConfig.CLIENT_ID);
object.put("logicalNode", properties.getLogicalNode());
object.put("sn", GlobalConfig.DEVICE_SN);
object.put("strength","31");
object.put("name", properties.getName());
object.put("version", properties.getVersion());
@@ -734,476 +728,118 @@ public class BusinessTasks {
}
/**
* 任务26交换机网络采集
* 任务26获取最新策略
*/
@Async("taskExecutor")
public void switchNetTask() {
public void policyTask() {
long timestamp = AgentUtil.roundMinutes();
int count = switchNetTask.incrementAndGet();
AssertLog.info("交换机网络采集定时任务执行 - 时间: {}task #{}", LocalDateTime.now(), count);
int count = policyTask.incrementAndGet();
AssertLog.info("获取最新策略定时任务执行 - 时间: {}task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchNetCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
// 发送更新策略
JSONObject object = new JSONObject();
object.put("clientId", GlobalConfig.CLIENT_ID);
object.put("sn",GlobalConfig.DEVICE_SN);
object.put("timestamp",timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.获取最新策略.getValue()).data(object.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机网络信息包={}",JSON.toJSONString(message));
AssertLog.info("发送获取最新策略信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机网络采集定时任务执行 - task #{} completed", count);
AssertLog.info("获取最新策略定时任务执行 - task #{} completed", count);
}
/**
* 任务27交换机光模块采集
* 任务27注册重试
*/
@Async("taskExecutor")
public void switchModuleTask() {
long timestamp = AgentUtil.roundMinutes();
int count = switchModuleTask.incrementAndGet();
AssertLog.info("交换机光模块采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchModuleCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机光模块信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机光模块采集定时任务执行 - task #{} completed", count);
}
/**
* 任务28:交换机MPU采集
*/
@Async("taskExecutor")
public void switchMpuTask() {
public void registerTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchMpuTask.incrementAndGet();
AssertLog.info("交换机MPU采集定时任务执行 - 时间: {}task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchMpuCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机MPU信息包={}",JSON.toJSONString(message));
int count = registerTask.incrementAndGet();
AssertLog.info("注册重试定时任务执行 - 时间: {}task #{}", LocalDateTime.now(), count);
boolean success = true;
int activeConnect = client.getActiveConnections();
AssertLog.info("注册重试定时任务执行 - 时间: {}activeConnect={}", LocalDateTime.now(), activeConnect);
if(activeConnect == 0){
success = agentService.connection();
}
AssertLog.info("交换机MPU采集定时任务执行 - task #{} completed", count);
if(success){
try {
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
List<NetworkInterfaceInfo> infos = AgentUtil.collectNetworkInfo();
JSONObject object = new JSONObject();
object.put("clientId", GlobalConfig.CLIENT_ID);
object.put("sn", GlobalConfig.DEVICE_SN);
object.put("networkInfo", JSON.toJSONString(infos));
object.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.注册.getValue()).data(object.toString()).build();
// 将对象转为 JSON 字符串
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送注册重试={}",JSON.toJSONString(message));
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
AssertLog.info("注册重试定时任务执行 - 时间: {},建立连接失败", LocalDateTime.now());
}
AssertLog.info("注册重试定时任务执行 - task #{} completed", count);
}
/**
* 任务29:交换机电源采集
* 任务28:建立连接重试
*/
@Async("taskExecutor")
public void switchPwrTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchPwrTask.incrementAndGet();
AssertLog.info("交换机电源采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchPwrCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
public void connectionTask() {
int count = connectionTask.incrementAndGet();
AssertLog.info("建立连接重试定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
boolean success = client.createConnection(GlobalConfig.CLIENT_ID, config.getHost(), config.getPort(), 5);
if(success){
//连接成功,发送初始连接消息
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
JSONObject object = new JSONObject();
object.put("clientId", GlobalConfig.CLIENT_ID);
object.put("sn", GlobalConfig.DEVICE_SN);
object.put("timestamp", timestamp);
Message msg = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.建立连接.getValue()).data(object.toString()).build();
// 将对象转为 JSON 字符串
client.sendMessages(GlobalConfig.CLIENT_ID, msg);
//判断是否发送注册信息
if(GlobalConfig.isRegister){
//已注册,发送心跳
// 创建心跳定时任务
AssertLog.info("启动心跳定时任务 - 延迟: {}ms, 间隔: {}ms", 15000, 30000);
dynamicTaskService.scheduleTask("heartbeat", businessTasks::heartbeatTask, 15000, 30000);
// 创建获取最新策略定时任务
long milli = AgentUtil.getMillisToNextMinute() + 60000;
AssertLog.info("启动更新策略定时任务 - 延迟: {}ms, 间隔: {}ms", milli, 60000);
dynamicTaskService.scheduleTask("policy", businessTasks::policyTask, milli, 60000);
}else{
//未注册,发送注册
try {
long timestamps = System.currentTimeMillis();
timestamps = Math.round(timestamps / 1000.0);
List<NetworkInterfaceInfo> infos = AgentUtil.collectNetworkInfo();
JSONObject objects = new JSONObject();
objects.put("clientId", GlobalConfig.CLIENT_ID);
objects.put("sn", GlobalConfig.DEVICE_SN);
objects.put("networkInfo", JSON.toJSONString(infos));
objects.put("timestamp", timestamps);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.注册.getValue()).data(objects.toString()).build();
// 将对象转为 JSON 字符串
client.sendMessages(GlobalConfig.CLIENT_ID, message);
} catch (Exception e) {
e.printStackTrace();
}
//设置注册定时任务,收注册成功后取消该定时任务
dynamicTaskService.scheduleTask("register", businessTasks::registerTask, 0, 300000);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机电源信息包={}",JSON.toJSONString(message));
dynamicTaskService.cancelTask("connectionTask");
}
AssertLog.info("交换机电源采集定时任务执行 - task #{} completed", count);
}
/**
* 任务30:交换机风扇采集
*/
@Async("taskExecutor")
public void switchFanTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchFanTask.incrementAndGet();
AssertLog.info("交换机风扇采集采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchFanCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机风扇信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机风扇采集定时任务执行 - task #{} completed", count);
}
/**
* 任务31:交换机其他信息-系统描述采集
*/
@Async("taskExecutor")
public void switchSysDescrTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchSysDescrTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统描述采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchSysDescrCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统描述信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统描述采集定时任务执行 - task #{} completed", count);
}
/**
* 任务32:交换机其他信息-系统ObjectID采集
*/
@Async("taskExecutor")
public void switchSysObjectIDTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchSysObjectIDTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统ObjectID采集定时任务执行 - 时间: {}task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchSysObjectIDCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统ObjectID信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统ObjectID采集定时任务执行 - task #{} completed", count);
}
/**
* 任务33:交换机其他信息-系统运行时间采集
*/
@Async("taskExecutor")
public void switchSysUpTimeTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchSysUpTimeTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统运行时间采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchSysUpTimeCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统运行时间信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统运行时间采集定时任务执行 - task #{} completed", count);
}
/**
* 任务34:交换机其他信息-系统联系信息采集
*/
@Async("taskExecutor")
public void switchSysContactTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchSysContactTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统联系信息采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchSysContactCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统联系信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统联系信息采集定时任务执行 - task #{} completed", count);
}
/**
* 任务35:交换机其他信息-系统名称采集
*/
@Async("taskExecutor")
public void switchSysNameTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchSysNameTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统名称采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchSysNameCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统名称信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统名称信息采集定时任务执行 - task #{} completed", count);
}
/**
* 任务36:交换机其他信息-系统位置采集
*/
@Async("taskExecutor")
public void switchSysLocationTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchSysLocationTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统位置采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchSysLocationCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统位置信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统位置采集定时任务执行 - task #{} completed", count);
}
/**
* 任务37:交换机其他信息-系统MAC地址采集
*/
@Async("taskExecutor")
public void switchHwStackSystemMacTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchHwStackSystemMacTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统MAC地址采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchHwStackSystemMacCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统MAC地址信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统MAC地址采集定时任务执行 - task #{} completed", count);
}
/**
* 任务38:交换机其他信息-设备索引采集
*/
@Async("taskExecutor")
public void switchEntIndexTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchEntIndexTask.incrementAndGet();
AssertLog.info("交换机其他信息-设备索引采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchEntIndexCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-设备索引信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-设备索引采集定时任务执行 - task #{} completed", count);
}
/**
* 任务39:交换机其他信息-设备名称采集
*/
@Async("taskExecutor")
public void switchEntPhysicalNameTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchEntPhysicalNameTask.incrementAndGet();
AssertLog.info("交换机其他信息-设备名称采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchEntPhysicalNameCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-设备名称信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-设备名称采集定时任务执行 - task #{} completed", count);
}
/**
* 任务40:交换机其他信息-设备软件版本采集
*/
@Async("taskExecutor")
public void switchEntPhysicalSoftwareRevTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchEntPhysicalSoftwareRevTask.incrementAndGet();
AssertLog.info("交换机其他信息-设备软件版本采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchEntPhysicalSoftwareRevCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-设备软件版本信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-设备软件版本采集定时任务执行 - task #{} completed", count);
}
/**
* 任务41:交换机其他信息-设备CPU使用率采集
*/
@Async("taskExecutor")
public void switchHwEntityCpuUsageTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchHwEntityCpuUsageTask.incrementAndGet();
AssertLog.info("交换机其他信息-设备CPU使用率采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchHwEntityCpuUsageCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-设备CPU使用率信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-设备CPU使用率采集定时任务执行 - task #{} completed", count);
}
/**
* 任务42:交换机其他信息-设备内存使用率采集
*/
@Async("taskExecutor")
public void switchHwEntityMemUsageTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchHwEntityMemUsageTask.incrementAndGet();
AssertLog.info("交换机其他信息-设备内存使用率采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchHwEntityMemUsageCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-设备内存使用率信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-设备内存使用率采集定时任务执行 - task #{} completed", count);
}
/**
* 任务43:交换机其他信息-系统平均功率采集
*/
@Async("taskExecutor")
public void switchHwAveragePowerTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchHwAveragePowerTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统平均功率采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchHwAveragePowerCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统平均功率信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统平均功率采集定时任务执行 - task #{} completed", count);
}
/**
* 任务44:交换机其他信息-系统实时功率采集
*/
@Async("taskExecutor")
public void switchHwCurrentPowerTask() {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
int count = switchHwCurrentPowerTask.incrementAndGet();
AssertLog.info("交换机其他信息-系统实时功率采集定时任务执行 - 时间: {},task #{}", LocalDateTime.now(), count);
// 判定客户端与服务端是否连接
if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
// 发送交换机信息包
JSONObject jsonObject = new JSONObject();
String data = switchBoardService.getSwitchDataByType("switchHwCurrentPowerCollect");
if(StringUtils.isNotBlank(data)){
jsonObject = JSONObject.parseObject(data);
}
jsonObject.put("timestamp", timestamp);
Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.交换机上报.getValue()).data(jsonObject.toString()).build();
sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
AssertLog.info("发送交换机其他信息-系统实时功率信息包={}",JSON.toJSONString(message));
}
AssertLog.info("交换机其他信息-系统实时功率采集定时任务执行 - task #{} completed", count);
AssertLog.info("建立连接重试定时任务执行 - task #{} completed", count);
}
@@ -6,7 +6,6 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.List;
@Data
@Builder
@@ -15,7 +14,7 @@ import java.util.List;
public class SpecificTimeRequest {
private String taskId;
private String taskName;
private List<String> taskData;
private String taskData;
private String clientId;
private String dataType;
@@ -1,10 +1,13 @@
package com.tongran.agent.client.scheduler.task;
import com.alibaba.fastjson2.JSONObject;
import com.tongran.agent.client.core.config.ApplicationProperties;
import com.tongran.agent.client.core.enums.MsgEnum;
import com.tongran.agent.client.core.session.SessionManager;
import com.tongran.agent.client.netty.model.Message;
import com.tongran.agent.client.scheduler.service.AsyncCommandExecutor;
import com.tongran.agent.client.utils.AgentDataUtil;
import com.tongran.agent.client.utils.AgentUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
@@ -21,6 +24,9 @@ import java.util.concurrent.TimeUnit;
public class SpecificTimeTaskService {
protected final SessionManager sessionManager;
@Resource
private ApplicationProperties properties;
@Resource
private SpecificTimeTaskConfig taskConfig;
@@ -73,52 +79,54 @@ public class SpecificTimeTaskService {
try {
System.out.println("处理业务: " + request.getTaskData());
String key = request.getTaskName()+"-"+System.currentTimeMillis();
for (String command : request.getTaskData()) {
if(StringUtils.equals(request.getDataType(), MsgEnum.Agent版本更新应答.getValue())){
try {
System.out.println("重启进程已启动,当前服务退出");
System.out.println("command="+command);
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c",
command);
pb.start();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}else{
List<String> cmd = Arrays.asList(command.split("\\s+"));
CompletableFuture<AsyncCommandExecutor.CommandResult> future =
AsyncCommandExecutor.executeCommandAsync(
cmd,
100, TimeUnit.SECONDS);
future.thenAccept(result -> {
JSONObject jsonObject = new JSONObject();
jsonObject.put("command", command);
jsonObject.put("resOut", result.getOutput());
System.out.println("JSON: " + jsonObject.toJSONString()); // 注意:toJSONString()
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMsg", "");
json.put("result", jsonObject.toJSONString());
Message message = Message.builder().clientId(request.getClientId()).dataType(request.getDataType()).data(jsonObject.toJSONString()).build();
if (Objects.nonNull(sessionManager.getSessionById(request.getClientId()))) {
System.out.println("发送执行结果: " + json.toJSONString()); // 注意:toJSONString()
sessionManager.writeAndFlush(sessionManager.getSessionById(request.getClientId()).getChannel(), message);
}
}).exceptionally(ex -> {
System.err.println("执行失败: " + ex.getMessage());
JSONObject json = new JSONObject();
json.put("resCode",0);
json.put("resMsg", "执行失败:Policy execute filed");
json.put("result", "");
Message message = Message.builder().clientId(request.getClientId()).dataType(request.getDataType()).data(json.toJSONString()).build();
if (Objects.nonNull(sessionManager.getSessionById(request.getClientId()))) {
sessionManager.writeAndFlush(sessionManager.getSessionById(request.getClientId()).getChannel(), message);
}
return null;
});
if(StringUtils.equals(request.getDataType(), MsgEnum.Agent版本更新应答.getValue())){
try {
//设置检查回滚任务
String SCRIPT_PATH = properties.getScriptPath()+"/rollback-tragent.sh";
AgentDataUtil.chmod(SCRIPT_PATH,"775");
AgentUtil.scheduleScriptIn3Minutes(SCRIPT_PATH);
System.out.println("重启进程已启动,当前服务退出");
System.out.println("command="+request.getTaskData());
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c",
request.getTaskData());
pb.start();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}else{
List<String> cmd = Arrays.asList(request.getTaskData().split("\\s+"));
CompletableFuture<AsyncCommandExecutor.CommandResult> future =
AsyncCommandExecutor.executeCommandAsync(
cmd,
100, TimeUnit.SECONDS);
future.thenAccept(result -> {
JSONObject jsonObject = new JSONObject();
jsonObject.put("command", request.getTaskData());
jsonObject.put("resOut", result.getOutput());
System.out.println("JSON: " + jsonObject.toJSONString()); // 注意:toJSONString()
JSONObject json = new JSONObject();
json.put("resCode",1);
json.put("resMsg", "");
json.put("result", jsonObject.toJSONString());
Message message = Message.builder().clientId(request.getClientId()).dataType(request.getDataType()).data(jsonObject.toJSONString()).build();
if (Objects.nonNull(sessionManager.getSessionById(request.getClientId()))) {
System.out.println("发送执行结果: " + json.toJSONString()); // 注意:toJSONString()
sessionManager.writeAndFlush(sessionManager.getSessionById(request.getClientId()).getChannel(), message);
}
}).exceptionally(ex -> {
System.err.println("执行失败: " + ex.getMessage());
JSONObject json = new JSONObject();
json.put("resCode",0);
json.put("resMsg", "执行失败:Policy execute filed");
json.put("result", "");
Message message = Message.builder().clientId(request.getClientId()).dataType(request.getDataType()).data(json.toJSONString()).build();
if (Objects.nonNull(sessionManager.getSessionById(request.getClientId()))) {
sessionManager.writeAndFlush(sessionManager.getSessionById(request.getClientId()).getChannel(), message);
}
return null;
});
}
// 调用其他服务等
} catch (Exception e) {
@@ -5,15 +5,21 @@ import com.tongran.agent.client.core.eo.ScriptPolicyEO;
public interface AgentService {
void cancelCollect();
void systemCollectStart(String data);
void systemCollectStop();
void switchCollectStart(String data);
void switchCollectStop();
void alarmMonitor();
void command(ScriptPolicyEO policy, String clientId, String dataType);
void cancelTask(String taskId);
void start();
void getPolicy(String data);
void checkTrAgent();
void sendMessage(String type, String data);
boolean connection();
}
@@ -5,7 +5,4 @@ import com.tongran.agent.client.core.vo.SwitchBoardVO;
import java.util.List;
public interface SwitchBoardService {
List<SwitchBoardVO> switchBoardList(long timestamp);
String getSwitchDataByType(String type);
}
File diff suppressed because it is too large Load Diff
@@ -1,571 +1,9 @@
package com.tongran.agent.client.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tongran.agent.client.core.config.GlobalConfig;
import com.tongran.agent.client.core.vo.SwitchBoardVO;
import com.tongran.agent.client.service.SwitchBoardService;
import com.tongran.agent.client.utils.AssertLog;
import org.apache.commons.lang3.StringUtils;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class SwitchBoardServiceImpl implements SwitchBoardService {
@Override
public List<SwitchBoardVO> switchBoardList(long timestamp) {
List<SwitchBoardVO> list = new ArrayList<>();
// System.out.println("==================== 交换机流量信息 ====================");
try {
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
// 3. 获取交换机基本信息
getSystemInfo(snmp, target);
// 4. 获取接口信息
list = getInterfaceInfo(snmp, target, timestamp);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
@Override
public String getSwitchDataByType(String type) {
JSONObject json = new JSONObject();
json.put("type",type);
switch(type){
case "switchNetCollect":
json.put("value",handleSwitchNet());
break;
case "switchModuleCollect":
json.put("value",handleSwitchModule());
break;
case "switchMpuCollect":
json.put("value",handleSwitchMpu());
break;
case "switchPwrCollect":
json.put("value",handleSwitchPwr());
break;
case "switchFanCollect":
json.put("value",handleSwitchFan());
break;
default:
json.put("value",handleSwitchOther(type));
break;
}
return json.toString();
}
private String handleSwitchNet(){
// System.out.println("==================== 交换机网络信息 ====================");
String result = "";
try {
if(GlobalConfig.SWITCH_NET_OID.isEmpty()){
return result;
}
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
result = getInterfaceInfoByType(snmp, target, "switchNet", GlobalConfig.SWITCH_NET_OID);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String handleSwitchModule(){
// System.out.println("==================== 交换机光模块信息 ====================");
String result = "";
try {
if(GlobalConfig.SWITCH_MODULE_OID.isEmpty()){
return result;
}
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
result = getInterfaceInfoByType(snmp, target, "switchModule", GlobalConfig.SWITCH_MODULE_OID);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String handleSwitchMpu(){
// System.out.println("==================== 交换机MPU信息 ====================");
String result = "";
try {
if(GlobalConfig.SWITCH_MPU_OID.isEmpty()){
return result;
}
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
result = getInterfaceInfoByType(snmp, target, "switchMpu", GlobalConfig.SWITCH_MPU_OID);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String handleSwitchPwr(){
// System.out.println("==================== 交换机电源信息 ====================");
String result = "";
try {
if(GlobalConfig.SWITCH_PWR_OID.isEmpty()){
return result;
}
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
result = getInterfaceInfoByType(snmp, target, "switchPwr", GlobalConfig.SWITCH_PWR_OID);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String handleSwitchFan(){
// System.out.println("==================== 交换机风扇信息 ====================");
String result = "";
try {
if(GlobalConfig.SWITCH_FAN_OID.isEmpty()){
return result;
}
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
result = getInterfaceInfoByType(snmp, target, "switchFan", GlobalConfig.SWITCH_FAN_OID);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String handleSwitchOther(String type){
// System.out.println("==================== 交换机系统其他信息 ====================");
String result = "";
try {
if(GlobalConfig.SWITCH_OTHER_OID.isEmpty()){
return result;
}
// 1. 创建传输映射
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
// 2. 创建目标对象
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
target.setRetries(2);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version2c);
result = getInterfaceInfoByType(snmp, target, type, GlobalConfig.SWITCH_OTHER_OID);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private static void getSystemInfo(Snmp snmp, Target target) throws IOException {
// 系统描述 OID
String[] systemOIDs = {
"1.3.6.1.2.1.1.1.0", // sysDescr
"1.3.6.1.2.1.1.5.0", // sysName
"1.3.6.1.2.1.1.6.0", // sysLocation
"1.3.6.1.2.1.1.4.0", // sysContact
"1.3.6.1.2.1.1.3.0" // sysUpTime
};
PDU pdu = new PDU();
for (String oid : systemOIDs) {
pdu.add(new VariableBinding(new OID(oid)));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, target);
if (event != null && event.getResponse() != null) {
// System.out.println("\n=== 交换机基本信息 ===");
for (VariableBinding vb : event.getResponse().getVariableBindings()) {
System.out.printf("%-30s: %s%n",
getOIDDescription(vb.getOid().toString()),
vb.getVariable());
}
}
}
private static List<SwitchBoardVO> getInterfaceInfo(Snmp snmp, Target target, long timestamp) throws IOException {
// 获取接口数量
String ifNumberOID = "1.3.6.1.2.1.2.1.0";
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(ifNumberOID)));
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, target);
if (event == null || event.getResponse() == null) {
System.err.println("无法获取接口数量");
return null;
}
int ifNumber = event.getResponse().get(0).getVariable().toInt();
System.out.println("\n=== 接口数量: " + ifNumber + " ===");
// 获取每个接口的信息
String[] ifOIDs = {
"1.3.6.1.2.1.2.2.1.2", // ifDescr
"1.3.6.1.2.1.2.2.1.3", // ifType
"1.3.6.1.2.1.2.2.1.5", // ifSpeed
"1.3.6.1.2.1.2.2.1.8", // ifOperStatus
"1.3.6.1.2.1.31.1.1.1.6", // ifInOctets
"1.3.6.1.2.1.31.1.1.1.10" // ifOutOctets
// "1.3.6.1.2.1.2.2.1.10", // ifInOctets
// "1.3.6.1.2.1.2.2.1.16" // ifOutOctets
};
System.out.printf("%-5s %-15s %-10s %-15s %-8s %-12s %-12s%n",
"Index", "Name", "Type", "Speed", "Status", "InBytes", "OutBytes");
List<SwitchBoardVO> list = new ArrayList<>();
for (int i = 1; i <= ifNumber; i++) {
pdu = new PDU();
for (String baseOID : ifOIDs) {
pdu.add(new VariableBinding(new OID(baseOID + "." + i)));
}
pdu.setType(PDU.GET);
event = snmp.send(pdu, target);
if (event != null && event.getResponse() != null) {
VariableBinding[] vbs = event.getResponse().getVariableBindings().toArray(new VariableBinding[0]);
String ifName = vbs[0].getVariable().toString();
String ifType = getInterfaceType(vbs[1].getVariable().toInt());
String speed = formatSpeed(vbs[2].getVariable().toInt());
String status = getOperStatus(vbs[3].getVariable().toInt());
long inBytes = vbs[4].getVariable().toLong();
long outBytes = vbs[5].getVariable().toLong();
SwitchBoardVO boardVO = SwitchBoardVO.builder()
.name(ifName)
.switchIp(GlobalConfig.SWITCH_IP)
.type(ifType)
.status(status)
.inBytes(inBytes)
.outBytes(outBytes)
.timestamp(timestamp)
.build();
list.add(boardVO);
System.out.printf("%-5d %-15s %-10s %-15s %-8s %-12d %-12d%n",
i, ifName, ifType, speed, status, inBytes, outBytes);
}
}
return list;
}
// 辅助方法
private static String getOIDDescription(String oid) {
switch(oid) {
case "1.3.6.1.2.1.1.1.0": return "系统描述";
case "1.3.6.1.2.1.1.5.0": return "系统名称";
case "1.3.6.1.2.1.1.6.0": return "物理位置";
case "1.3.6.1.2.1.1.4.0": return "联系人";
case "1.3.6.1.2.1.1.3.0": return "运行时间";
default: return oid;
}
}
private static String getInterfaceType(int type) {
switch(type) {
case 6: return "Ethernet";
case 23: return "PPP";
case 24: return "Loopback";
case 53: return "VLAN";
case 131: return "Tunnel";
default: return "其他("+type+")";
}
}
private static String formatSpeed(int speed) {
if (speed >= 1000000000) {
return (speed / 1000000000) + " Gbps";
} else if (speed >= 1000000) {
return (speed / 1000000) + " Mbps";
} else if (speed >= 1000) {
return (speed / 1000) + " Kbps";
}
return speed + " bps";
}
private static String getOperStatus(int status) {
switch(status) {
case 1: return "Up";
case 2: return "Down";
case 3: return "Testing";
case 4: return "Unknown";
case 5: return "Dormant";
case 6: return "NotPresent";
case 7: return "LowerLayerDown";
default: return "未知";
}
}
private static String getInterfaceInfoByType(Snmp snmp, Target target, String type, LinkedHashMap<String,String> oidParams) throws IOException {
if(oidParams.isEmpty()){
return "";
}
JSONObject json = new JSONObject();
// 获取接口数量
String ifNumberOID = "";
List<String> filter_value = new ArrayList<>();
if(StringUtils.equals(type,"switchNet")){
ifNumberOID = GlobalConfig.NET_INDEX_OID;
filter_value = GlobalConfig.NET_FILTER;
}else if(StringUtils.equals(type,"switchModule")){
ifNumberOID = GlobalConfig.MODULE_INDEX_OID;
filter_value = GlobalConfig.MODULE_FILTER;
}else if(StringUtils.equals(type,"switchMpu")){
ifNumberOID = GlobalConfig.MPU_INDEX_OID;
filter_value = GlobalConfig.MPU_FILTER;
}else if(StringUtils.equals(type,"switchPwr")){
ifNumberOID = GlobalConfig.PWR_INDEX_OID;
filter_value = GlobalConfig.PWR_FILTER;
}else if(StringUtils.equals(type,"switchFan")){
ifNumberOID = GlobalConfig.FAN_INDEX_OID;
filter_value = GlobalConfig.FAN_FILTER;
}else {
ifNumberOID = GlobalConfig.OTHER_INDEX_OID;
filter_value = GlobalConfig.OTHER_FILTER;
}
AssertLog.info("交换机采集type={},筛选端口={}",type,JSON.toJSONString(filter_value));
if(StringUtils.isBlank(ifNumberOID)){
System.err.println("未初始化索引OID");
return "";
}
OID oid = new OID(ifNumberOID);
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(ifNumberOID)));
pdu.setType(PDU.GETBULK);
pdu.setMaxRepetitions(100); // 每次获取最多 100 个
pdu.setNonRepeaters(0);
List<Integer> indexes = new ArrayList<>();
boolean finished = false;
while (!finished) {
ResponseEvent response = snmp.send(pdu, target);
PDU responsePdu = response.getResponse();
if (responsePdu == null) {
System.err.println("Timeout: No response from device.");
break;
}
if (responsePdu.getErrorStatus() != 0) {
System.err.println("Error: " + responsePdu.getErrorStatusText());
break;
}
// 处理每个返回结果
for (VariableBinding vb : responsePdu.getVariableBindings()) {
OID returnedOid = vb.getOid();
// 检查是否仍在目标 OID 子树下
if (!returnedOid.startsWith(oid)) {
finished = true;
break;
}
// 提取最后一个值:就是 ifIndex 编号
int ifIndex = returnedOid.get(returnedOid.size() - 1);
int value = vb.getVariable().toInt();
if(CollectionUtil.isEmpty(filter_value)){
// AssertLog.info("交换机采集type={},索引返回:值={}",type,vb);
indexes.add(ifIndex);
}else{
if(filter_value.contains(String.valueOf(value))){
// AssertLog.info("交换机采集type={},索引返回:值={}",type,vb);
indexes.add(ifIndex);
}
}
}
// 更新下一次请求的起始 OIDSNMP Walk
pdu.set(0, new VariableBinding(responsePdu.getVariableBindings().get(0).getOid()));
}
if(CollectionUtil.isEmpty(indexes)){
System.err.println("返回获取索引列表为空");
return "";
}
//去重
indexes = indexes.stream().distinct().collect(Collectors.toList());
// System.out.println("\n=== 接口数量: " + indexes.size() + " ===");
// System.out.println("\n=== 接口列表: " + JSON.toJSONString(indexes));
String[] ifOIDs = oidParams.keySet().toArray(new String[0]);
String[] params = oidParams.values().toArray(new String[0]);
if(!StringUtils.equals(type,"switchNet") && !StringUtils.equals(type,"switchModule")
&& !StringUtils.equals(type,"switchMpu") && !StringUtils.equals(type,"switchPwr")
&& !StringUtils.equals(type,"switchFan")){
String os = "";
String ps = "";
for (int i = 0; i < params.length; i++) {
if(type.toLowerCase().contains(params[i].toLowerCase())){
if(StringUtils.isBlank(ps)){
ps += params[i];
os += ifOIDs[i];
}else {
ps += "," + params[i];
os += "," + ifOIDs[i];
}
}
}
ifOIDs = os.split(",");
params = ps.split(",");
List<Integer> otherList = new ArrayList<>();
otherList.add(indexes.get(0));
indexes = otherList;
}
// 获取每个接口的信息
// String[] ifOIDs = {
// "1.3.6.1.2.1.2.2.1.2", // ifDescr
// "1.3.6.1.2.1.2.2.1.3", // ifType
// "1.3.6.1.2.1.2.2.1.5", // ifSpeed
// "1.3.6.1.2.1.2.2.1.8", // ifOperStatus
// "1.3.6.1.2.1.31.1.1.1.6", // ifInOctets
// "1.3.6.1.2.1.31.1.1.1.10" // ifOutOctets
//// "1.3.6.1.2.1.2.2.1.10", // ifInOctets
//// "1.3.6.1.2.1.2.2.1.16" // ifOutOctets
// };
if(ifOIDs == null || ifOIDs.length == 0){
return "";
}
List<String> list = new ArrayList<>();
for (int i = 0; i < indexes.size(); i++) {
pdu = new PDU();
for (String baseOID : ifOIDs) {
pdu.add(new VariableBinding(new OID(baseOID + "." + indexes.get(i))));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, target);
// System.out.printf("%-5s %-15s %-10s %-15s %-8s %-12s %-12s%n",
// "Index", "Name", "Type", "Speed", "Status", "InBytes", "OutBytes");
// if (event != null && event.getResponse() != null) {
// VariableBinding[] vbs = event.getResponse().getVariableBindings().toArray(new VariableBinding[0]);
// String ifName = vbs[0].getVariable().toString();
// String ifType = getInterfaceType(vbs[1].getVariable().toInt());
// String speed = formatSpeed(vbs[2].getVariable().toInt());
// String status = getOperStatus(vbs[3].getVariable().toInt());
// long inBytes = vbs[4].getVariable().toLong();
// long outBytes = vbs[5].getVariable().toLong();
// System.out.printf("%-15s %-10s %-15s %-8s %-12d %-12d%n",
// ifName, ifType, speed, status, inBytes, outBytes);
// }
if (event != null && event.getResponse() != null) {
VariableBinding[] vbs = event.getResponse().getVariableBindings().toArray(new VariableBinding[0]);
for (int m = 0; m < params.length; m++) {
// AssertLog.info("参数名:{},值={}", params[m],vbs[m]);
json.put(params[m],vbs[m].getVariable().toString());
}
}
list.add(json.toString());
}
return JSON.toJSONString(list);
}
/**
* 结果封装类
*/
public static class MapArrays {
private final String[] keys;
private final String[] values;
public MapArrays(String[] keys, String[] values) {
this.keys = keys != null ? keys : new String[0];
this.values = values != null ? values : new String[0];
}
public String[] getKeys() {
return keys;
}
public String[] getValues() {
return values;
}
public int size() {
return keys.length;
}
public boolean isEmpty() {
return keys.length == 0;
}
@Override
public String toString() {
return "Keys: " + Arrays.toString(keys) +
"\nValues: " + Arrays.toString(values);
}
}
}
@@ -1,15 +1,17 @@
package com.tongran.agent.client.utils;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tongran.agent.client.core.vo.NetworkInterfaceInfo;
import org.snmp4j.smi.OID;
import oshi.hardware.NetworkIF;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
@@ -240,4 +242,314 @@ public class AgentUtil {
return swapped;
}
/**
* 收集所有 Ethernet 类型网卡信息
*/
public static List<NetworkInterfaceInfo> collectNetworkInfo() throws Exception {
List<NetworkInterfaceInfo> result = new ArrayList<>();
// String publicIp = getPublicIp(); // 获取公网 IP(全局出口)
String ipInfo = PublicIpFetcher.getPublicIp();
// System.out.println("完整信息: " + ipInfo);
String publicIp = PublicIpFetcher.extractIp(ipInfo);
if (publicIp != null) {
System.out.println("公网 IP: " + publicIp);
} else {
System.out.println("未能提取 IP 地址");
}
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
// 跳过回环、虚拟、关闭的接口
if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) continue;
// 判断是否为 Ethernet(通过名称约定:eth*, en*, 等)
String name = ni.getName();
if (!isEthernetInterface(name)) continue;
NetworkInterfaceInfo info = NetworkInterfaceInfo.builder()
.name(name)
.mac(getMacAddress(ni))
.ipv4(getIPv4Address(ni))
.gateway(getGatewayAddress()) // 网关通常是默认路由,全局一致
.publicIp(publicIp)
.build();
// 如果有公网 IP,查询归属地
if (publicIp != null && !publicIp.isEmpty()) {
JSONObject location = queryIpLocation(publicIp);
if (location != null) {
info.setCarrier(location.getStr("org", "未知").replaceAll("^AS\\d+\\s*", ""));
info.setProvince(location.getStr("region", "未知"));
info.setCity(location.getStr("city", "未知"));
} else {
info.setCarrier("查询失败");
info.setProvince("查询失败");
info.setCity("查询失败");
}
}
result.add(info);
}
return result;
}
/**
* 判断是否为 Ethernet 类型网卡(基于常见命名)
*/
private static boolean isEthernetInterface(String name) {
return name.startsWith("eth") || // Linux 传统
name.startsWith("en") || // systemd 命名 (enp3s0)
name.startsWith("em"); // 有些主板网卡
}
/**
* 获取 MAC 地址
*/
private static String getMacAddress(NetworkInterface ni) {
try {
byte[] mac = ni.getHardwareAddress();
if (mac == null) return "N/A";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X", mac[i]));
if (i < mac.length - 1) sb.append(":");
}
return sb.toString();
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取第一个 IPv4 地址
*/
private static String getIPv4Address(NetworkInterface ni) {
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (addr instanceof Inet4Address) {
return addr.getHostAddress();
}
}
return "N/A";
}
/**
* 获取默认网关(调用 shell 命令)
*/
private static String getGatewayAddress() {
try {
Process process = Runtime.getRuntime().exec("ip route");
java.util.Scanner scanner = new java.util.Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.startsWith("default")) {
String[] parts = line.split(" ");
return parts[2]; // default via <gateway> dev ...
}
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
return "N/A";
}
/**
* 获取公网 IP
*/
private static String getPublicIp() {
return sendHttpGet("https://ifconfig.me");
}
/**
* 查询 IP 归属地(使用 ipinfo.io
*/
private static JSONObject queryIpLocation(String ip) {
String url = "https://ipinfo.io/" + ip + "/json";
String response = sendHttpGet(url);
AssertLog.info("查询 IP 归属地={}", response);
if (response != null) {
try {
return new JSONObject(response);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 发送 HTTP GET 请求
*/
private static String sendHttpGet(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
java.util.Scanner scanner = new java.util.Scanner(conn.getInputStream());
String result = scanner.useDelimiter("\\A").next();
scanner.close();
return result;
}
} catch (Exception e) {
System.err.println("HTTP 请求失败: " + e.getMessage());
}
return null;
}
public static void bufferedWriter(String filePath, String[] lines){
try (BufferedWriter writer = Files.newBufferedWriter(
Paths.get(filePath),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE, // 创建文件
StandardOpenOption.TRUNCATE_EXISTING // 覆盖写入
)) {
for (String line : lines) {
writer.write(line);
writer.newLine(); // 换行
}
System.out.println("文件写入完成!");
} catch (IOException e) {
System.err.println("写入异常:" + e.getMessage());
e.printStackTrace();
}
}
/**
* 获取 /etc/issue 文件的第二行内容
* @return 第二行字符串,如果不存在则返回 null
*/
public static String getDeviceSN() {
Path issuePath = Paths.get("/etc/issue");
if (!Files.exists(issuePath)) {
System.err.println("文件不存在: /etc/issue");
return null;
}
if (!Files.isReadable(issuePath)) {
System.err.println("无读取权限: /etc/issue");
return null;
}
try (BufferedReader reader = Files.newBufferedReader(issuePath)) {
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) { // 只计数非空行
lineNumber++;
if (lineNumber == 2) {
return line;
}
}
}
// 如果文件少于两行
System.err.println("文件行数不足,只有 " + lineNumber + "");
return null;
} catch (NoSuchFileException e) {
System.err.println("文件未找到: " + e.getMessage());
return null;
} catch (IOException e) {
System.err.println("读取文件异常: " + e.getMessage());
return null;
}
}
public static void main(String[] args) throws Exception {
List<NetworkInterfaceInfo> infos = collectNetworkInfo();
for (NetworkInterfaceInfo info : infos) {
System.out.println(info);
}
}
public static String getFileMD5(String filePath) {
// 检查文件是否存在
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
System.out.println("文件不存在: " + filePath);
return null;
}
// 检查是否是文件(不是目录)
if (!Files.isRegularFile(path)) {
System.out.println("路径不是文件: " + filePath);
return null;
}
// 检查文件是否可读
if (!Files.isReadable(path)) {
System.out.println("文件不可读: " + filePath);
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
}
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException | IOException e) {
System.out.println("计算MD5失败: " + e.getMessage());
return null;
}
}
/**
* 安排脚本在 3 分钟后执行
*/
public static void scheduleScriptIn3Minutes(String SCRIPT_PATH) {
// 使用 at 命令:3 minutes from now
String atCommand = String.format("echo '%s' | at now + 3 minutes", SCRIPT_PATH);
ProcessBuilder pb = new ProcessBuilder("bash", "-c", atCommand);
pb.redirectErrorStream(true); // 合并 stdout 和 stderr
try {
Process process = pb.start();
// 读取命令输出(at 通常会打印任务编号)
java.io.BufferedReader reader = new java.io.BufferedReader(
new java.io.InputStreamReader(process.getInputStream())
);
String line;
StringBuilder output = new StringBuilder();
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
reader.close();
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("✅ 成功安排脚本在 3 分钟后执行:");
System.out.println(" 脚本: " + SCRIPT_PATH);
if (output.length() > 0) {
System.out.println(" at 响应: " + output.toString().trim());
}
} else {
System.err.println("❌ 调度失败,exit code: " + exitCode);
System.err.println(" 输出: " + output.toString().trim());
}
} catch (IOException | InterruptedException e) {
System.err.println("执行 at 命令时出错: " + e.getMessage());
e.printStackTrace();
}
}
}
@@ -0,0 +1,47 @@
package com.tongran.agent.client.utils;
import com.tongran.agent.client.netty.config.ConnectionConfig;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class ClientExample {
public static void main(String[] args) {
EnhancedConnectionManager manager = new EnhancedConnectionManager();
try {
// 配置多个连接
List<ConnectionConfig> configs = Arrays.asList(
// new ConnectionConfig("db_server", "192.168.1.101", 3306, 5),
// new ConnectionConfig("redis_server", "192.168.1.102", 6379, 3),
// new ConnectionConfig("api_server", "api.example.com", 8080, 10),
new ConnectionConfig("server1", "127.0.0.1", 6610, 5)
);
// 批量创建连接
Map<String, Boolean> results = manager.createConnections(configs);
System.out.println("连接创建结果: " + results);
// 等待连接建立
Thread.sleep(3000);
// 根据消息类型路由
manager.routeMessageByType("TYPE_A", "Database query");
// manager.routeMessageByType("TYPE_B", "Cache operation");
// manager.routeMessageByType("UNKNOWN", "Broadcast message");
// 检查连接状态
Map<String, Boolean> status = manager.getConnectionStatus();
System.out.println("连接状态: " + status);
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
// manager.shutdown();
}
}
}
@@ -0,0 +1,109 @@
package com.tongran.agent.client.utils;
import java.io.*;
import java.util.concurrent.TimeUnit;
public class CrontabManager {
// // 要添加的定时任务
// private static final String CRON_JOB = "*/10 * * * * /usr/local/tongran/sbin/test2.sh >/dev/null 2>&1";
// // 用于判断是否已存在的关键标识(可以是脚本路径)
// private static final String JOB_IDENTIFIER = "/usr/local/tongran/sbin/test2.sh";
/**
* 检查并添加定时任务
*/
public static boolean ensureCronJobExists(String CRON_JOB, String JOB_IDENTIFIER) {
try {
// 1. 读取当前用户的 crontab
ProcessBuilder pb = new ProcessBuilder("crontab", "-l");
pb.redirectErrorStream(true);
Process process = pb.start();
// 设置超时(防止卡死)
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroy();
throw new IOException("crontab -l timeout");
}
StringBuilder crontabContent = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
crontabContent.append(line).append("\n");
}
}
int exitCode = process.exitValue();
if (exitCode != 0 && exitCode != 1) {
// exit code 1 表示没有 crontab 文件(正常)
throw new IOException("crontab -l failed with exit code: " + exitCode);
}
String content = crontabContent.toString();
// 2. 检查是否已存在该任务
if (content.contains(JOB_IDENTIFIER)) {
System.out.println("Crontab 任务已存在,无需添加。");
return true;
}
// 3. 如果不存在,追加任务
String newCrontab;
if (content.trim().isEmpty()) {
// 原来没有 crontab
newCrontab = CRON_JOB + "\n";
} else {
// 原来有 crontab,在末尾添加新任务
newCrontab = content;
if (!content.endsWith("\n")) {
newCrontab += "\n";
}
newCrontab += CRON_JOB + "\n";
}
// 4. 写入新的 crontab
ProcessBuilder pbWrite = new ProcessBuilder("crontab", "-");
pbWrite.redirectErrorStream(true);
Process writeProcess = pbWrite.start();
try (OutputStreamWriter writer = new OutputStreamWriter(writeProcess.getOutputStream())) {
writer.write(newCrontab);
writer.flush();
}
if (!writeProcess.waitFor(5, TimeUnit.SECONDS)) {
writeProcess.destroy();
throw new IOException("crontab - write timeout");
}
int writeExitCode = writeProcess.exitValue();
if (writeExitCode != 0) {
throw new IOException("crontab - write failed with exit code: " + writeExitCode);
}
System.out.println("Crontab 任务添加成功:\n" + CRON_JOB);
return true;
} catch (IOException | InterruptedException e) {
System.err.println("操作 crontab 失败:" + e.getMessage());
e.printStackTrace();
return false;
}
}
// === 使用示例 ===
public static void main(String[] args) {
// 要添加的定时任务
String CRON_JOB = "*/10 * * * * /usr/local/tongran/sbin/test2.sh >/dev/null 2>&1";
// 用于判断是否已存在的关键标识(可以是脚本路径)
String JOB_IDENTIFIER = "/usr/local/tongran/sbin/test2.sh";
// boolean success = ensureCronJobExists(CRON_JOB,JOB_IDENTIFIER);
// if (success) {
// System.out.println("✅ Crontab 状态正常。");
// } else {
// System.err.println("❌ 操作失败,请检查权限或路径。");
// }
}
}
@@ -0,0 +1,82 @@
package com.tongran.agent.client.utils;
import com.tongran.agent.client.netty.config.ConnectionConfig;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 增强版连接管理器
*/
public class EnhancedConnectionManager {
// private final MultiTargetNettyClient client;
private final Map<String, ConnectionConfig> connectionConfigs;
public EnhancedConnectionManager() {
// this.client = new MultiTargetNettyClient();
this.connectionConfigs = new ConcurrentHashMap<>();
}
/**
* 批量创建连接
*/
public Map<String, Boolean> createConnections(List<ConnectionConfig> configs) {
Map<String, Boolean> results = new HashMap<>();
// configs.forEach(config -> {
// boolean success = client.createConnection(
// config.getConnectionKey(),
// config.getHost(),
// config.getPort(),
// config.getTimeout()
// );
// if (success) {
// connectionConfigs.put(config.getConnectionKey(), config);
// }
// results.put(config.getConnectionKey(), success);
// });
return results;
}
/**
* 根据消息类型路由到不同连接
*/
public void routeMessageByType(String messageType, String message) {
// 这里可以根据业务逻辑决定发送到哪个连接
// switch (messageType) {
// case "TYPE_A":
// client.sendMessage("server1", "[TYPE_A] " + message);
// break;
// case "TYPE_B":
// client.sendMessage("server2", "[TYPE_B] " + message);
// break;
// case "TYPE_C":
// client.sendMessage("server3", "[TYPE_C] " + message);
// break;
// default:
// // 广播到所有连接
// connectionConfigs.keySet().forEach(key ->
// client.sendMessage(key, "[BROADCAST] " + message));
// }
}
/**
* 获取所有连接状态
*/
public Map<String, Boolean> getConnectionStatus() {
Map<String, Boolean> status = new HashMap<>();
// connectionConfigs.forEach((key, config) -> {
// // 这里可以添加更详细的状态检查
// status.put(key, client.sendMessage(key, "PING"));
// });
return status;
}
// public void shutdown() {
// client.shutdown();
// }
}
@@ -0,0 +1,125 @@
package com.tongran.agent.client.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
public class MachineFingerprint {
/**
* 获取服务器硬件指纹:MD5( MAC + CPU信息 )
*/
public static String getHardwareFingerprint() {
StringBuilder data = new StringBuilder();
// 1. 获取第一个非回环网卡的 MAC 地址
String mac = getFirstValidMacAddress();
if (mac != null) {
data.append(mac);
System.out.println("MAC 信息="+mac);
} else {
System.err.println("无法获取 MAC 地址");
}
// 2. 获取 CPU 信息(如 CPU 型号、序列号)
String cpuInfo = getCpuInfo();
if (cpuInfo != null) {
System.out.println("CPU 信息="+cpuInfo);
data.append(cpuInfo);
} else {
System.err.println("无法获取 CPU 信息");
}
data.append(System.currentTimeMillis());
if (data.length() == 0) {
return "unknown";
}
// 3. 生成 MD5
return md5(data.toString());
}
/**
* 获取第一个非回环、UP 状态网卡的 MAC 地址
*/
private static String getFirstValidMacAddress() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
if (ni.isLoopback() || !ni.isUp()) continue;
byte[] mac = ni.getHardwareAddress();
if (mac != null && mac.length > 0) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X", mac[i]));
if (i < mac.length - 1) sb.append(":");
}
return sb.toString();
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
/**
* 读取 CPU 信息(CPU 型号 + 序列号,如果存在)
*/
private static String getCpuInfo() {
StringBuilder cpuInfo = new StringBuilder();
try {
Process process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
boolean found = false;
while ((line = reader.readLine()) != null) {
if (line.contains("model name")) {
cpuInfo.append(line.split(":")[1].trim()).append(";");
found = true;
}
// 树莓派等设备有 cpu serial
if (line.contains("Serial")) {
cpuInfo.append("Serial=").append(line.split(":")[1].trim());
found = true;
}
// 多数 x86 服务器没有 serial,可用 processor 数量做补充
if (line.startsWith("processor")) {
// 可选:记录核心数
}
}
reader.close();
return found ? cpuInfo.toString() : null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 生成 MD5 哈希
*/
private static String md5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 算法不可用", e);
}
}
// ================== 测试 ==================
public static void main(String[] args) {
String fingerprint = getHardwareFingerprint();
System.out.println("服务器硬件指纹 (MD5): " + fingerprint);
}
}
@@ -0,0 +1,80 @@
package com.tongran.agent.client.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PublicIpFetcher {
private static final String IP_SERVICE_URL = "https://myip.ipip.net";
private static final int TIMEOUT_MS = 10_000; // 10秒超时
/**
* 获取公网 IP(包含归属地信息)
*
* @return IP 信息字符串,如 "当前 IP112.96.15.145,来自于:中国 广东省 深圳市 联通"
* @throws IOException 如果网络请求失败
*/
public static String getPublicIp() throws IOException {
URL url = new URL(IP_SERVICE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
connection.setConnectTimeout(TIMEOUT_MS);
connection.setReadTimeout(TIMEOUT_MS);
// 发起请求
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new IOException("HTTP " + responseCode + " from " + IP_SERVICE_URL);
}
// 读取响应(注意:myip.ipip.net 返回的是 GBK 编码)
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "GBK"))) { // 使用 GBK 解码
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString().trim();
}
}
/**
* 从返回文本中提取纯 IP 地址(如 112.96.15.145
*
* @param ipInfo 来自 getPublicIp() 的完整信息
* @return 纯 IP 字符串,提取失败返回 null
*/
public static String extractIp(String ipInfo) {
if (ipInfo == null || ipInfo.isEmpty()) return null;
// 匹配 IP 地址的正则
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");
java.util.regex.Matcher matcher = pattern.matcher(ipInfo);
return matcher.find() ? matcher.group(1) : null;
}
// === 使用示例 ===
public static void main(String[] args) {
try {
String ipInfo = getPublicIp();
System.out.println("完整信息: " + ipInfo);
String pureIp = extractIp(ipInfo);
if (pureIp != null) {
System.out.println("公网 IP: " + pureIp);
} else {
System.out.println("未能提取 IP 地址");
}
} catch (IOException e) {
System.err.println("获取公网 IP 失败: " + e.getMessage());
e.printStackTrace();
}
}
}