diff --git a/pom.xml b/pom.xml
index 4609be9..2e349d2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -143,6 +143,15 @@
org.springframework.boot
spring-boot-maven-plugin
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+ true
+
+
diff --git a/src/main/java/com/tongran/agent/client/TrAgentClientApplication.java b/src/main/java/com/tongran/agent/client/TrAgentClientApplication.java
index 0d1b715..9a61c3b 100644
--- a/src/main/java/com/tongran/agent/client/TrAgentClientApplication.java
+++ b/src/main/java/com/tongran/agent/client/TrAgentClientApplication.java
@@ -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) {
diff --git a/src/main/java/com/tongran/agent/client/core/config/ApplicationProperties.java b/src/main/java/com/tongran/agent/client/core/config/ApplicationProperties.java
index 3929b2c..eea1148 100644
--- a/src/main/java/com/tongran/agent/client/core/config/ApplicationProperties.java
+++ b/src/main/java/com/tongran/agent/client/core/config/ApplicationProperties.java
@@ -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;
+ }
}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/core/config/GlobalConfig.java b/src/main/java/com/tongran/agent/client/core/config/GlobalConfig.java
index 966fa15..3c179ff 100644
--- a/src/main/java/com/tongran/agent/client/core/config/GlobalConfig.java
+++ b/src/main/java/com/tongran/agent/client/core/config/GlobalConfig.java
@@ -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 SWITCH_NET_OID = new LinkedHashMap<>(); //交换机网络端口发现OID
- public static LinkedHashMap SWITCH_MODULE_OID = new LinkedHashMap<>(); //交换机光模块发现OID
- public static LinkedHashMap SWITCH_MPU_OID = new LinkedHashMap<>(); //交换机MPU发现OID
- public static LinkedHashMap SWITCH_PWR_OID = new LinkedHashMap<>(); //交换机电源发现OID
- public static LinkedHashMap SWITCH_FAN_OID = new LinkedHashMap<>(); //交换机风扇发现OID
- public static LinkedHashMap SWITCH_OTHER_OID = new LinkedHashMap<>(); //交换机系统其他OID
- public static String OTHER_INDEX_PARAM = "entIndex"; //交换机其他监控项索引参数
- public static String OTHER_INDEX_OID = "";
- public static List OTHER_FILTER = new ArrayList<>(); //过滤值
- public static String NET_INDEX_PARAM = "ifIndex"; //交换机网络端口索引参数
- public static String NET_INDEX_OID = "";
- public static List NET_FILTER = new ArrayList<>(); //过滤值
- public static String MODULE_INDEX_PARAM = "fiberEntIndex"; //交换机光模块端口索引参数
- public static String MODULE_INDEX_OID = "";
- public static List MODULE_FILTER = new ArrayList<>(); //过滤值
- public static String MPU_INDEX_PARAM = "mpuEntIndex"; //交换机MPU索引参数
- public static String MPU_INDEX_OID = "";
- public static List MPU_FILTER = new ArrayList<>(); //过滤值
- public static String PWR_INDEX_PARAM = "pwrEntIndex"; //交换机电源索引参数
- public static String PWR_INDEX_OID = "";
- public static List PWR_FILTER = new ArrayList<>(); //过滤值
- public static String FAN_INDEX_PARAM = "fanEntIndex"; //交换机风扇索引参数
- public static String FAN_INDEX_OID = "";
- public static List 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 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; //多余端口
/**
* 所有网络接口
diff --git a/src/main/java/com/tongran/agent/client/core/enums/MsgEnum.java b/src/main/java/com/tongran/agent/client/core/enums/MsgEnum.java
index 5f4e5b2..a701c34 100644
--- a/src/main/java/com/tongran/agent/client/core/enums/MsgEnum.java
+++ b/src/main/java/com/tongran/agent/client/core/enums/MsgEnum.java
@@ -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"),
diff --git a/src/main/java/com/tongran/agent/client/core/eo/AgentVersionUpdateEO.java b/src/main/java/com/tongran/agent/client/core/eo/AgentVersionUpdateEO.java
index 6408c1d..71a060c 100644
--- a/src/main/java/com/tongran/agent/client/core/eo/AgentVersionUpdateEO.java
+++ b/src/main/java/com/tongran/agent/client/core/eo/AgentVersionUpdateEO.java
@@ -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 {
//文件地址,外网HTTP(S)地址
private String fileUrl;
- //保存文件地址
- private String filePath;
-
- //命令
- private List commands;
+ //文件MD5
+ private String fileMd5;
//执行方式:0、立即执行;1、定时执行;
private int method;
diff --git a/src/main/java/com/tongran/agent/client/core/eo/ScriptPolicyEO.java b/src/main/java/com/tongran/agent/client/core/eo/ScriptPolicyEO.java
index e75da24..e720707 100644
--- a/src/main/java/com/tongran/agent/client/core/eo/ScriptPolicyEO.java
+++ b/src/main/java/com/tongran/agent/client/core/eo/ScriptPolicyEO.java
@@ -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 files;
- //目标路径地址
- private String filePath;
+ //文件类型为1、外网HTTP(S)时必传
+ private String fileUrl;
- //命令
- private List 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;
-
- }
-
}
diff --git a/src/main/java/com/tongran/agent/client/core/vo/NetworkInterfaceInfo.java b/src/main/java/com/tongran/agent/client/core/vo/NetworkInterfaceInfo.java
new file mode 100644
index 0000000..8d95ec2
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/core/vo/NetworkInterfaceInfo.java
@@ -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; // 市
+
+}
diff --git a/src/main/java/com/tongran/agent/client/netty/AgentNettyConfig.java b/src/main/java/com/tongran/agent/client/netty/AgentNettyConfig.java
deleted file mode 100644
index 7c6a06e..0000000
--- a/src/main/java/com/tongran/agent/client/netty/AgentNettyConfig.java
+++ /dev/null
@@ -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;
-
-}
diff --git a/src/main/java/com/tongran/agent/client/netty/AgentNettyServer.java b/src/main/java/com/tongran/agent/client/netty/AgentNettyServer.java
deleted file mode 100644
index 16f6b8c..0000000
--- a/src/main/java/com/tongran/agent/client/netty/AgentNettyServer.java
+++ /dev/null
@@ -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() {
- @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);
- }
-
-}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/netty/config/AgentNettyConfig.java b/src/main/java/com/tongran/agent/client/netty/config/AgentNettyConfig.java
new file mode 100644
index 0000000..98f6d04
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/netty/config/AgentNettyConfig.java
@@ -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;
+
+}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/netty/config/ConnectionConfig.java b/src/main/java/com/tongran/agent/client/netty/config/ConnectionConfig.java
new file mode 100644
index 0000000..6bb5f68
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/netty/config/ConnectionConfig.java
@@ -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);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/netty/enpoint/AgentEndpoint.java b/src/main/java/com/tongran/agent/client/netty/enpoint/AgentEndpoint.java
index b837d6b..cf3ddf5 100644
--- a/src/main/java/com/tongran/agent/client/netty/enpoint/AgentEndpoint.java
+++ b/src/main/java/com/tongran/agent/client/netty/enpoint/AgentEndpoint.java
@@ -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 map = JSON.parseObject(netOID, new TypeReference>() {});
- GlobalConfig.SWITCH_NET_OID = map;
- LinkedHashMap 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 map = JSON.parseObject(moduleOID, new TypeReference>() {});
- GlobalConfig.SWITCH_MODULE_OID = map;
- LinkedHashMap 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 map = JSON.parseObject(mpuOID, new TypeReference>() {});
- GlobalConfig.SWITCH_MPU_OID = map;
- LinkedHashMap 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 map = JSON.parseObject(pwrOID, new TypeReference>() {});
- GlobalConfig.SWITCH_PWR_OID = map;
- LinkedHashMap 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 map = JSON.parseObject(fanOID, new TypeReference>() {});
- GlobalConfig.SWITCH_FAN_OID = map;
- LinkedHashMap 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 map = JSON.parseObject(otherOID, new TypeReference>() {});
- GlobalConfig.SWITCH_OTHER_OID = map;
- LinkedHashMap 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 list = JSON.parseObject(netOID, new TypeReference>() {});
- GlobalConfig.NET_FILTER = list;
- }
- }
- if(object.containsKey("moduleOID")){
- String moduleOID = object.getString("moduleOID");
- if(StringUtils.isNotBlank(moduleOID)){
- List list = JSON.parseObject(moduleOID, new TypeReference>() {});
- GlobalConfig.MODULE_FILTER = list;
- }
- }
- if(object.containsKey("mpuOID")){
- String mpuOID = object.getString("mpuOID");
- if(StringUtils.isNotBlank(mpuOID)){
- List list = JSON.parseObject(mpuOID, new TypeReference>() {});
- GlobalConfig.MPU_FILTER = list;
- }
- }
- if(object.containsKey("pwrOID")){
- String pwrOID = object.getString("pwrOID");
- if(StringUtils.isNotBlank(pwrOID)){
- List list = JSON.parseObject(pwrOID, new TypeReference>() {});
- GlobalConfig.PWR_FILTER = list;
- }
- }
- if(object.containsKey("fanOID")){
- String fanOID = object.getString("fanOID");
- if(StringUtils.isNotBlank(fanOID)){
- List list = JSON.parseObject(fanOID, new TypeReference>() {});
- GlobalConfig.FAN_FILTER = list;
- }
- }
- if(object.containsKey("otherOID")){
- String otherOID = object.getString("otherOID");
- if(StringUtils.isNotBlank(otherOID)){
- List list = JSON.parseObject(otherOID, new TypeReference>() {});
- 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 fileList = JSON.parseObject(files, new TypeReference>() {});
- 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 commandList = JSON.parseObject(commands, new TypeReference>() {});
- 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 commandList = JSON.parseObject(commands, new TypeReference>() {});
- 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;
}
}
diff --git a/src/main/java/com/tongran/agent/client/netty/handler/TCPListenHandler.java b/src/main/java/com/tongran/agent/client/netty/handler/TCPListenHandler.java
deleted file mode 100644
index fd4d386..0000000
--- a/src/main/java/com/tongran/agent/client/netty/handler/TCPListenHandler.java
+++ /dev/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();
- }
- }
- }
- }
-
-}
diff --git a/src/main/java/com/tongran/agent/client/netty/handler/UDPListenHandler.java b/src/main/java/com/tongran/agent/client/netty/handler/UDPListenHandler.java
deleted file mode 100644
index 9b4a9e1..0000000
--- a/src/main/java/com/tongran/agent/client/netty/handler/UDPListenHandler.java
+++ /dev/null
@@ -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();// 暂未实现
- }
-
-}
diff --git a/src/main/java/com/tongran/agent/client/scheduler/service/AppInitializer.java b/src/main/java/com/tongran/agent/client/scheduler/service/AppInitializer.java
index 9f059a5..94367bb 100644
--- a/src/main/java/com/tongran/agent/client/scheduler/service/AppInitializer.java
+++ b/src/main/java/com/tongran/agent/client/scheduler/service/AppInitializer.java
@@ -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 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);
+ }
}
}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/scheduler/service/BusinessTasks.java b/src/main/java/com/tongran/agent/client/scheduler/service/BusinessTasks.java
index 6f590a3..2e916dd 100644
--- a/src/main/java/com/tongran/agent/client/scheduler/service/BusinessTasks.java
+++ b/src/main/java/com/tongran/agent/client/scheduler/service/BusinessTasks.java
@@ -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 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 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);
}
diff --git a/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeRequest.java b/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeRequest.java
index 14b3d37..db78e36 100644
--- a/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeRequest.java
+++ b/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeRequest.java
@@ -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 taskData;
+ private String taskData;
private String clientId;
private String dataType;
diff --git a/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeTaskService.java b/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeTaskService.java
index 47622b5..ad02e9b 100644
--- a/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeTaskService.java
+++ b/src/main/java/com/tongran/agent/client/scheduler/task/SpecificTimeTaskService.java
@@ -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 cmd = Arrays.asList(command.split("\\s+"));
- CompletableFuture 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 cmd = Arrays.asList(request.getTaskData().split("\\s+"));
+ CompletableFuture 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) {
diff --git a/src/main/java/com/tongran/agent/client/service/AgentService.java b/src/main/java/com/tongran/agent/client/service/AgentService.java
index 217d8e9..c9adb9b 100644
--- a/src/main/java/com/tongran/agent/client/service/AgentService.java
+++ b/src/main/java/com/tongran/agent/client/service/AgentService.java
@@ -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();
}
diff --git a/src/main/java/com/tongran/agent/client/service/SwitchBoardService.java b/src/main/java/com/tongran/agent/client/service/SwitchBoardService.java
index 5fc1209..4a49acc 100644
--- a/src/main/java/com/tongran/agent/client/service/SwitchBoardService.java
+++ b/src/main/java/com/tongran/agent/client/service/SwitchBoardService.java
@@ -5,7 +5,4 @@ import com.tongran.agent.client.core.vo.SwitchBoardVO;
import java.util.List;
public interface SwitchBoardService {
- List switchBoardList(long timestamp);
-
- String getSwitchDataByType(String type);
}
diff --git a/src/main/java/com/tongran/agent/client/service/impl/AgentServiceImpl.java b/src/main/java/com/tongran/agent/client/service/impl/AgentServiceImpl.java
index 02ffbcc..1895940 100644
--- a/src/main/java/com/tongran/agent/client/service/impl/AgentServiceImpl.java
+++ b/src/main/java/com/tongran/agent/client/service/impl/AgentServiceImpl.java
@@ -1,33 +1,38 @@
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.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;
import com.tongran.agent.client.core.eo.CollectEO;
import com.tongran.agent.client.core.eo.ScriptPolicyEO;
import com.tongran.agent.client.core.session.SessionManager;
+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.scheduler.service.AdvancedAsyncDownloader;
import com.tongran.agent.client.scheduler.service.AsyncCommandExecutor;
import com.tongran.agent.client.scheduler.service.BusinessTasks;
import com.tongran.agent.client.scheduler.service.DynamicTaskService;
import com.tongran.agent.client.scheduler.task.SpecificTimeRequest;
import com.tongran.agent.client.scheduler.task.SpecificTimeTaskService;
import com.tongran.agent.client.service.AgentService;
-import com.tongran.agent.client.utils.AgentUtil;
-import com.tongran.agent.client.utils.AssertLog;
+import com.tongran.agent.client.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
+import java.io.File;
import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@@ -42,6 +47,15 @@ public class AgentServiceImpl implements AgentService {
@Resource
private SpecificTimeTaskService taskService;
+ @Resource
+ private ApplicationProperties properties;
+
+ @Resource
+ private MultiTargetNettyClient client;
+
+ @Resource
+ private AgentNettyConfig config;
+
// 在注入点使用@Lazy
@Autowired
public AgentServiceImpl(DynamicTaskService dynamicTaskService,
@@ -54,338 +68,10 @@ public class AgentServiceImpl implements AgentService {
@Override
public void cancelCollect() {
systemCollectStop();
- switchCollectStop();
dynamicTaskService.cancelTask("alarmTask");
dynamicTaskService.cancelTask("heartbeat");
}
- @Override
- public void systemCollectStart(String data) {
- //更改全局变量
- JSONObject jsonObject = JSONObject.parseObject(data);
- if(jsonObject.containsKey("collects")){
- String collects = jsonObject.getString("collects");
- List configList = JSON.parseObject(collects, new TypeReference>() {});
- AssertLog.info("开启或更新系统采集={}", JSON.toJSONString(configList));
- for (CollectEO c : configList) {
- String type = c.getType();
- boolean collect = c.isCollect();
- int interval = c.getInterval();
- AssertLog.info("开启或更新系统采集2,type={}, collect={}", type, collect);
- switch(type) {
- case "cpuCollect": //cpu采集
- //判断与上次有无变化
- if(GlobalConfig.cpuCollect != collect || GlobalConfig.cpuInterval != interval){
- GlobalConfig.cpuCollect = collect;
- if(collect){
- GlobalConfig.cpuInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::cpuTask, milli, GlobalConfig.cpuInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.cpuInterval = 300;
- }
- }
- break;
- case "vfsCollect": //挂载采集
- if(GlobalConfig.vfsCollect != collect || GlobalConfig.vfsInterval != interval){
- GlobalConfig.vfsCollect = collect;
- if(collect){
- GlobalConfig.vfsInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::pointTask, milli, GlobalConfig.vfsInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.vfsInterval = 300;
- }
- }
- break;
- case "netCollect": //网络采集
- if(GlobalConfig.netCollect != collect || GlobalConfig.netInterval != interval){
- GlobalConfig.netCollect = collect;
- if(collect){
-// GlobalConfig.netInterval = interval;
- long milli = AgentUtil.millisecondsToNext5Minute();
- dynamicTaskService.scheduleTask(type,
- businessTasks::netTask, milli, GlobalConfig.netInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.netInterval = 300;
- }
- }
- break;
- case "diskCollect": //磁盘采集
- if(GlobalConfig.diskCollect != collect || GlobalConfig.diskInterval != interval){
- GlobalConfig.diskCollect = collect;
- if(collect){
- GlobalConfig.diskInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::diskTask, milli, GlobalConfig.diskInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.diskInterval = 300;
- }
- }
- break;
- case "dockerCollect": //docker采集
- if(GlobalConfig.dockerCollect != collect || GlobalConfig.dockerInterval != interval){
- GlobalConfig.dockerCollect = collect;
- if(collect){
- GlobalConfig.dockerInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::dockerTask, milli, GlobalConfig.dockerInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.dockerInterval = 300;
- }
- }
- break;
- case "systemSwapSizeFreeCollect": //交换卷/文件的可用空间(字节)采集
- if(GlobalConfig.systemSwapSizeFreeCollect != collect || GlobalConfig.systemSwapSizeFreeInterval != interval){
- GlobalConfig.systemSwapSizeFreeCollect = collect;
- if(collect){
- GlobalConfig.systemSwapSizeFreeInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemSwapSizeFreeTask, milli, GlobalConfig.systemSwapSizeFreeInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemSwapSizeFreeInterval = 300;
- }
- }
- break;
- case "memoryUtilizationCollect": //内存利用率采集
- if(GlobalConfig.memoryUtilizationCollect != collect || GlobalConfig.memoryUtilizationInterval != interval){
- GlobalConfig.memoryUtilizationCollect = collect;
- if(collect){
- GlobalConfig.memoryUtilizationInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::memoryUtilizationTask, milli, GlobalConfig.memoryUtilizationInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.memoryUtilizationInterval = 300;
- }
- }
- break;
- case "systemSwapSizePercentCollect": //可用交换空间百分比采集
- if(GlobalConfig.systemSwapSizePercentCollect != collect || GlobalConfig.systemSwapSizePercentInterval != interval){
- GlobalConfig.systemSwapSizePercentCollect = collect;
- if(collect){
- GlobalConfig.systemSwapSizePercentInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemSwapSizePercentTask, milli, GlobalConfig.systemSwapSizePercentInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemSwapSizePercentInterval = 300;
- }
- }
- break;
- case "memorySizeAvailableCollect": //可用内存采集
- if(GlobalConfig.memorySizeAvailableCollect != collect || GlobalConfig.memorySizeAvailableInterval != interval){
- GlobalConfig.memorySizeAvailableCollect = collect;
- if(collect){
- GlobalConfig.memorySizeAvailableInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::memorySizeAvailableTask, milli, GlobalConfig.memorySizeAvailableInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.memorySizeAvailableInterval = 300;
- }
- }
- break;
- case "memorySizePercentCollect": //可用内存百分比采集
- if(GlobalConfig.memorySizePercentCollect != collect || GlobalConfig.memorySizePercentInterval != interval){
- GlobalConfig.memorySizePercentCollect = collect;
- if(collect){
- GlobalConfig.memorySizePercentInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::memorySizePercentTask, milli, GlobalConfig.memorySizePercentInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.memorySizePercentInterval = 300;
- }
- }
- break;
- case "memorySizeTotalCollect": //总内存采集
- if(GlobalConfig.memorySizeTotalCollect != collect || GlobalConfig.memorySizeTotalInterval != interval){
- GlobalConfig.memorySizeTotalCollect = collect;
- if(collect){
- GlobalConfig.memorySizeTotalInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::memorySizeTotalTask, milli, GlobalConfig.memorySizeTotalInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.memorySizeTotalInterval = 300;
- }
- }
- break;
- case "systemSwOsCollect": //操作系统采集
- if(GlobalConfig.systemSwOsCollect != collect || GlobalConfig.systemSwOsInterval != interval){
- GlobalConfig.systemSwOsCollect = collect;
- if(collect){
- GlobalConfig.systemSwOsInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemSwOsTask, milli, GlobalConfig.systemSwOsInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemSwOsInterval = 300;
- }
- }
- break;
- case "systemSwArchCollect": //操作系统架构采集
- if(GlobalConfig.systemSwArchCollect != collect || GlobalConfig.systemSwArchInterval != interval){
- GlobalConfig.systemSwArchCollect = collect;
- if(collect){
- GlobalConfig.systemSwArchInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemSwArchTask, milli, GlobalConfig.systemSwArchInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemSwArchInterval = 300;
- }
- }
- break;
- case "kernelMaxprocCollect": //最大进程数采集
- if(GlobalConfig.kernelMaxprocCollect != collect || GlobalConfig.kernelMaxprocInterval != interval){
- GlobalConfig.kernelMaxprocCollect = collect;
- if(collect){
- GlobalConfig.kernelMaxprocInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::kernelMaxprocTask, milli, GlobalConfig.kernelMaxprocInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.kernelMaxprocInterval = 300;
- }
- }
- break;
- case "procNumRunCollect": //正在运行的进程数采集
- if(GlobalConfig.procNumRunCollect != collect || GlobalConfig.procNumRunInterval != interval){
- GlobalConfig.procNumRunCollect = collect;
- if(collect){
- GlobalConfig.procNumRunInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::procNumRunTask, milli, GlobalConfig.procNumRunInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.procNumRunInterval = 300;
- }
- }
- break;
- case "systemUsersNumCollect": //登录用户数采集
- if(GlobalConfig.systemUsersNumCollect != collect || GlobalConfig.systemUsersNumInterval != interval){
- GlobalConfig.systemUsersNumCollect = collect;
- if(collect){
- GlobalConfig.systemUsersNumInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemUsersNumTask, milli, GlobalConfig.systemUsersNumInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemUsersNumInterval = 300;
- }
- }
- break;
- case "systemDiskSizeTotalCollect": //硬盘总可用空间采集
- if(GlobalConfig.systemDiskSizeTotalCollect != collect || GlobalConfig.systemDiskSizeTotalInterval != interval){
- GlobalConfig.systemDiskSizeTotalCollect = collect;
- if(collect){
- GlobalConfig.systemDiskSizeTotalInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemDiskSizeTotalTask, milli, GlobalConfig.systemDiskSizeTotalInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemDiskSizeTotalInterval = 300;
- }
- }
- break;
- case "systemBoottimeCollect": //系统启动时间采集
- if(GlobalConfig.systemBoottimeCollect != collect || GlobalConfig.systemBoottimeInterval != interval){
- GlobalConfig.systemBoottimeCollect = collect;
- if(collect){
- GlobalConfig.systemBoottimeInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemBoottimeTask, milli, GlobalConfig.systemBoottimeInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemBoottimeInterval = 300;
- }
- }
- break;
- case "systemUnameCollect": //系统描述采集
- if(GlobalConfig.systemUnameCollect != collect || GlobalConfig.systemUnameInterval != interval){
- GlobalConfig.systemUnameCollect = collect;
- if(collect){
- GlobalConfig.systemUnameInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemUnameTask, milli, GlobalConfig.systemUnameInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemUnameInterval = 300;
- }
- }
- break;
- case "systemLocaltimeCollect": //系统本地时间采集
- if(GlobalConfig.systemLocaltimeCollect != collect || GlobalConfig.systemLocaltimeInterval != interval){
- GlobalConfig.systemLocaltimeCollect = collect;
- if(collect){
- GlobalConfig.systemLocaltimeInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemLocaltimeTask, milli, GlobalConfig.systemLocaltimeInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemLocaltimeInterval = 300;
- }
- }
- break;
- case "systemUptimeCollect": //系统正常运行时间采集
- if(GlobalConfig.systemUptimeCollect != collect || GlobalConfig.systemUptimeInterval != interval){
- GlobalConfig.systemUptimeCollect = collect;
- if(collect){
- GlobalConfig.systemUptimeInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::systemUptimeTask, milli, GlobalConfig.systemUptimeInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.systemUptimeInterval = 300;
- }
- }
- break;
- default: //系统其他采集
- GlobalConfig.procNumCollect = collect;
- if(collect){
- GlobalConfig.procNumInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::procNumTask, milli, GlobalConfig.procNumInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.procNumInterval = 300;
- }
- }
- }
- }
- }
-
-
-
@Override
public void systemCollectStop() {
String[] arr = {"cpuCollect","vfsCollect","netCollect","diskCollect","dockerCollect","systemSwapSizeFreeCollect","memoryUtilizationCollect"
@@ -447,341 +133,6 @@ public class AgentServiceImpl implements AgentService {
GlobalConfig.procNumInterval = 300; //进程数采集间隔
}
- @Override
- public void switchCollectStart(String data) {
- //更改全局变量
- JSONObject jsonObject = JSONObject.parseObject(data);
- if(jsonObject.containsKey("collects")){
- String collects = jsonObject.getString("collects");
- List configList = JSON.parseObject(collects, new TypeReference>() {});
- for (CollectEO c : configList) {
- String type = c.getType();
- boolean collect = c.isCollect();
- int interval = c.getInterval();
- boolean flag = false;
- switch(type) {
- case "switchNetCollect": //交换机网络采集
- if(GlobalConfig.switchNetCollect != collect || GlobalConfig.switchNetInterval != interval){
- GlobalConfig.switchNetCollect = collect;
- if(collect){
- GlobalConfig.switchNetInterval = 300;
- long milli = AgentUtil.millisecondsToNext5Minute();
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchNetTask, milli, GlobalConfig.switchNetInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchNetInterval = 300;
- }
- }
- break;
- case "switchModuleCollect": //光模块采集
- if(GlobalConfig.switchModuleCollect != collect || GlobalConfig.switchModuleInterval != interval){
- GlobalConfig.switchModuleCollect = collect;
- if(collect){
- GlobalConfig.switchModuleInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchModuleTask, milli, GlobalConfig.switchModuleInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchModuleInterval = 300;
- }
- }
- break;
- case "switchMpuCollect": //MPU采集
- if(GlobalConfig.switchMpuCollect != collect || GlobalConfig.switchMpuInterval != interval){
- GlobalConfig.switchMpuCollect = collect;
- if(collect){
- GlobalConfig.switchMpuInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchMpuTask, milli, GlobalConfig.switchMpuInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchMpuInterval = 300;
- }
- }
- break;
- case "switchPwrCollect": //电源采集
- if(GlobalConfig.switchPwrCollect != collect || GlobalConfig.switchPwrInterval != interval){
- GlobalConfig.switchPwrCollect = collect;
- if(collect){
- GlobalConfig.switchPwrInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchPwrTask, milli, GlobalConfig.switchPwrInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchPwrInterval = 300;
- }
- }
- break;
- case "switchFanCollect": //风扇采集
- if(GlobalConfig.switchFanCollect != collect || GlobalConfig.switchFanInterval != interval){
- GlobalConfig.switchFanCollect = collect;
- if(collect){
- GlobalConfig.switchFanInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchFanTask, milli, GlobalConfig.switchFanInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchFanInterval = 300;
- }
- }
- break;
- case "switchSysDescrCollect":
- if(GlobalConfig.switchSysDescrCollect != collect || GlobalConfig.switchSysDescrInterval != interval){
- GlobalConfig.switchSysDescrCollect = collect;
- if(collect){
- GlobalConfig.switchSysDescrInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchSysDescrTask, milli, GlobalConfig.switchSysDescrInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchSysDescrInterval = 300;
- }
- }
- break;
- case "switchSysObjectIDCollect":
- if(GlobalConfig.switchSysObjectIDCollect != collect || GlobalConfig.switchSysObjectIDInterval != interval){
- GlobalConfig.switchSysObjectIDCollect = collect;
- if(collect){
- GlobalConfig.switchSysObjectIDInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchSysObjectIDTask, milli, GlobalConfig.switchSysObjectIDInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchSysObjectIDInterval = 300;
- }
- }
- break;
- case "switchSysUpTimeCollect":
- if(GlobalConfig.switchSysUpTimeCollect != collect || GlobalConfig.switchSysUpTimeInterval != interval){
- GlobalConfig.switchSysUpTimeCollect = collect;
- if(collect){
- GlobalConfig.switchSysUpTimeInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchSysUpTimeTask, milli, GlobalConfig.switchSysUpTimeInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchSysUpTimeInterval = 300;
- }
- }
- break;
- case "switchSysContactCollect":
- if(GlobalConfig.switchSysContactCollect != collect || GlobalConfig.switchSysContactInterval != interval){
- GlobalConfig.switchSysContactCollect = collect;
- if(collect){
- GlobalConfig.switchSysContactInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchSysContactTask, milli, GlobalConfig.switchSysContactInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchSysContactInterval = 300;
- }
- }
- break;
- case "switchSysNameCollect":
- if(GlobalConfig.switchSysNameCollect != collect || GlobalConfig.switchSysNameInterval != interval){
- GlobalConfig.switchSysNameCollect = collect;
- if(collect){
- GlobalConfig.switchSysNameInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchSysNameTask, milli, GlobalConfig.switchSysNameInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchSysNameInterval = 300;
- }
- }
- break;
- case "switchSysLocationCollect":
- if(GlobalConfig.switchSysLocationCollect != collect || GlobalConfig.switchSysLocationInterval != interval){
- GlobalConfig.switchSysLocationCollect = collect;
- if(collect){
- GlobalConfig.switchSysLocationInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchSysLocationTask, milli, GlobalConfig.switchSysLocationInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchSysLocationInterval = 300;
- }
- }
- break;
- case "switchHwStackSystemMacCollect":
- if(GlobalConfig.switchHwStackSystemMacCollect != collect || GlobalConfig.switchHwStackSystemMacInterval != interval){
- GlobalConfig.switchHwStackSystemMacCollect = collect;
- if(collect){
- GlobalConfig.switchHwStackSystemMacInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchHwStackSystemMacTask, milli, GlobalConfig.switchHwStackSystemMacInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchHwStackSystemMacInterval = 300;
- }
- }
- break;
- case "switchEntIndexCollect":
- if(GlobalConfig.switchEntIndexCollect != collect || GlobalConfig.switchEntIndexInterval != interval){
- GlobalConfig.switchEntIndexCollect = collect;
- if(collect){
- GlobalConfig.switchEntIndexInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchEntIndexTask, milli, GlobalConfig.switchEntIndexInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchEntIndexInterval = 300;
- }
- }
- break;
- case "switchEntPhysicalNameCollect":
- if(GlobalConfig.switchEntPhysicalNameCollect != collect || GlobalConfig.switchEntPhysicalNameInterval != interval){
- GlobalConfig.switchEntPhysicalNameCollect = collect;
- if(collect){
- GlobalConfig.switchEntPhysicalNameInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchEntPhysicalNameTask, milli, GlobalConfig.switchEntPhysicalNameInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchEntPhysicalNameInterval = 300;
- }
- }
- break;
- case "switchEntPhysicalSoftwareRevCollect":
- if(GlobalConfig.switchEntPhysicalSoftwareRevCollect != collect || GlobalConfig.switchEntPhysicalSoftwareRevInterval != interval){
- GlobalConfig.switchEntPhysicalSoftwareRevCollect = collect;
- if(collect){
- GlobalConfig.switchEntPhysicalSoftwareRevInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchEntPhysicalSoftwareRevTask, milli, GlobalConfig.switchEntPhysicalSoftwareRevInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchEntPhysicalSoftwareRevInterval = 300;
- }
- }
- break;
- case "switchHwEntityCpuUsageCollect":
- if(GlobalConfig.switchHwEntityCpuUsageCollect != collect || GlobalConfig.switchHwEntityCpuUsageInterval != interval){
- GlobalConfig.switchHwEntityCpuUsageCollect = collect;
- if(collect){
- GlobalConfig.switchHwEntityCpuUsageInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchHwEntityCpuUsageTask, milli, GlobalConfig.switchHwEntityCpuUsageInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchHwEntityCpuUsageInterval = 300;
- }
- }
- break;
- case "switchHwEntityMemUsageCollect":
- if(GlobalConfig.switchHwEntityMemUsageCollect != collect || GlobalConfig.switchHwEntityMemUsageInterval != interval){
- GlobalConfig.switchHwEntityMemUsageCollect = collect;
- if(collect){
- GlobalConfig.switchHwEntityMemUsageInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchHwEntityMemUsageTask, milli, GlobalConfig.switchHwEntityMemUsageInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchHwEntityMemUsageInterval = 300;
- }
- }
- break;
- case "switchHwAveragePowerCollect":
- if(GlobalConfig.switchHwAveragePowerCollect != collect || GlobalConfig.switchHwAveragePowerInterval != interval){
- GlobalConfig.switchHwAveragePowerCollect = collect;
- if(collect){
- GlobalConfig.switchHwAveragePowerInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchHwAveragePowerTask, milli, GlobalConfig.switchHwAveragePowerInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchHwAveragePowerInterval = 300;
- }
- }
- break;
- default: //系统其他采集
- if(GlobalConfig.switchHwCurrentPowerCollect != collect || GlobalConfig.switchHwCurrentPowerInterval != interval){
- GlobalConfig.switchHwCurrentPowerCollect = collect;
- if(collect){
- GlobalConfig.switchHwCurrentPowerInterval = interval;
- long milli = AgentUtil.getMillisToNextMinute() + 60000;
- dynamicTaskService.scheduleTask(type,
- businessTasks::switchHwCurrentPowerTask, milli, GlobalConfig.switchHwCurrentPowerInterval*1000L);
- }else{
- dynamicTaskService.cancelTask(type);
- GlobalConfig.switchHwCurrentPowerInterval = 300;
- }
- }
- }
- }
- }
- }
-
- @Override
- public void switchCollectStop() {
- String[] arr = {"switchNetCollect","switchModuleCollect","switchMpuCollect","switchPwrCollect","switchFanCollect","switchSysDescrCollect"
- ,"switchSysObjectIDCollect","switchSysUpTimeCollect","switchSysContactCollect","switchSysNameCollect","switchSysLocationCollect"
- ,"switchHwStackSystemMacCollect","switchEntIndexCollect","switchEntPhysicalNameCollect","switchEntPhysicalSoftwareRevCollect"
- ,"switchHwEntityCpuUsageCollect","switchHwEntityMemUsageCollect","switchHwAveragePowerCollect","switchHwCurrentPowerCollect"};
- for (String taskId : arr) {
- dynamicTaskService.cancelTask(taskId);
- }
- GlobalConfig.switchNetCollect = false; //交换机网络采集
- GlobalConfig.switchNetInterval = 300; //交换机网络采集间隔
- GlobalConfig.switchModuleCollect = false; //光模块采集
- GlobalConfig.switchModuleInterval = 300; //光模块采集间隔
- GlobalConfig.switchMpuCollect = false; //MPU采集
- GlobalConfig.switchMpuInterval = 300; //MPU采集间隔
- GlobalConfig.switchPwrCollect = false; //电源采集
- GlobalConfig.switchPwrInterval = 300; //电源采集间隔
- GlobalConfig.switchFanCollect = false; //风扇采集
- GlobalConfig.switchFanInterval = 300; //风扇采集间隔
- /**
- * 交换机其他监控
- */
- GlobalConfig.switchSysDescrCollect = false; //系统描述采集
- GlobalConfig.switchSysDescrInterval = 300; //系统描述采集间隔
- GlobalConfig.switchSysObjectIDCollect = false; //系统Object ID采集
- GlobalConfig.switchSysObjectIDInterval = 300; //系统Object ID采集间隔
- GlobalConfig.switchSysUpTimeCollect = false; //系统运行时间采集
- GlobalConfig.switchSysUpTimeInterval = 300; //系统运行时间采集间隔
- GlobalConfig.switchSysContactCollect = false; //系统联系信息采集
- GlobalConfig.switchSysContactInterval = 300; //系统联系信息采集间隔
- GlobalConfig.switchSysNameCollect = false; //系统名称采集
- GlobalConfig.switchSysNameInterval = 300; //系统名称采集间隔
- GlobalConfig.switchSysLocationCollect = false; //系统位置采集
- GlobalConfig.switchSysLocationInterval = 300; //系统位置采集间隔
- GlobalConfig.switchHwStackSystemMacCollect = false; //系统MAC地址采集
- GlobalConfig.switchHwStackSystemMacInterval = 300; //系统MAC地址采集间隔
- GlobalConfig.switchEntIndexCollect = false; //设备索引采集
- GlobalConfig.switchEntIndexInterval = 300; //设备索引采集间隔
- GlobalConfig.switchEntPhysicalNameCollect = false; //设备名称采集
- GlobalConfig.switchEntPhysicalNameInterval = 300; //设备名称采集间隔
- GlobalConfig.switchEntPhysicalSoftwareRevCollect = false; //设备软件版本采集
- GlobalConfig.switchEntPhysicalSoftwareRevInterval = 300; //设备软件版本采集间隔
- GlobalConfig.switchHwEntityCpuUsageCollect = false; //设备CPU使用率(%)采集
- GlobalConfig.switchHwEntityCpuUsageInterval = 300; //设备CPU使用率(%)采集间隔
- GlobalConfig.switchHwEntityMemUsageCollect = false; //设备内存使用率(%)采集
- GlobalConfig.switchHwEntityMemUsageInterval = 300; //设备内存使用率(%)采集间隔
- GlobalConfig.switchHwAveragePowerCollect = false; //系统平均功率(mW)采集
- GlobalConfig.switchHwAveragePowerInterval = 300; //系统平均功率(mW)采集间隔
- GlobalConfig.switchHwCurrentPowerCollect = false; //系统实时功率(mW)采集
- GlobalConfig.switchHwCurrentPowerInterval = 300; //系统实时功率(mW)采集间隔
- }
-
@Override
public void alarmMonitor() {
if(GlobalConfig.IS_ALARM){
@@ -802,114 +153,719 @@ public class AgentServiceImpl implements AgentService {
public void command(ScriptPolicyEO policy, String clientId, String dataType) {
long timestamp = System.currentTimeMillis();
timestamp = Math.round(timestamp / 1000.0);
- if(CollectionUtil.isNotEmpty(policy.getCommands())){
- //执行方式:0、立即执行;1、定时执行;
- if(policy.getMethod() == 1){
- SpecificTimeRequest request = SpecificTimeRequest.builder()
- .taskId("")
- .taskName(policy.getPolicyName())
- .taskData(policy.getCommands())
- .specificDateTime(AgentUtil.toLocalDateTime(policy.getPolicyTime(),true))
- .clientId(clientId)
- .dataType(dataType)
- .build();
- try {
- taskService.createSpecificTimeTask(request);
- JSONObject json = new JSONObject();
- json.put("resCode",1);
- json.put("resMsg", "执行脚本策略定时任务保存成功");
- json.put("timestamp",timestamp);
- // 判定客户端与服务端是否连接
- if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
- Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.执行脚本策略应答.getValue())
- .data(json.toString()).build();
- sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
- AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
- }
- } catch (Exception e) {
- JSONObject json = new JSONObject();
- json.put("resCode",0);
- json.put("resMsg", "执行脚本策略定时任务保存失败");
- json.put("timestamp",timestamp);
- // 判定客户端与服务端是否连接
- if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
- Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.执行脚本策略应答.getValue())
- .data(json.toString()).build();
- sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
- AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
- }
+ //执行方式:0、立即执行;1、定时执行;
+ if(policy.getMethod() == 1){
+ SpecificTimeRequest request = SpecificTimeRequest.builder()
+ .taskId("")
+ .taskName(policy.getPolicyName())
+ .taskData(policy.getCommandParams())
+ .specificDateTime(AgentUtil.toLocalDateTime(policy.getPolicyTime(),true))
+ .clientId(clientId)
+ .dataType(dataType)
+ .build();
+ try {
+ taskService.createSpecificTimeTask(request);
+ JSONObject json = new JSONObject();
+ json.put("resCode",1);
+ json.put("resMsg", "执行脚本策略定时任务保存成功");
+ json.put("timestamp",timestamp);
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.执行脚本策略应答.getValue())
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
}
- }else{
- for (String command : policy.getCommands()) {
- if(StringUtils.equals(dataType, 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 cmd = Arrays.asList(command.split("\\s+"));
- CompletableFuture future =
- AsyncCommandExecutor.executeCommandAsync(
- cmd,
- 100, TimeUnit.SECONDS);
- future.thenAccept(result -> {
- if (result.isSuccess()) {
- System.out.println("脚本执行成功");
- System.out.println("[成功resOut] " + result.getOutput());
- } else {
- System.out.println("脚本执行失败");
- System.out.println("[失败resOut] " + result.getOutput());
- }
- JSONObject rse = new JSONObject();
- rse.put("command",command);
- rse.put("resOut", result.getOutput());
- long timestamps = System.currentTimeMillis();
- timestamps = Math.round(timestamps / 1000.0);
- JSONObject json = new JSONObject();
- json.put("resCode",1);
- json.put("resMsg", "");
- json.put("timestamp",timestamps);
- json.put("result", rse.toString());
- // 判定客户端与服务端是否连接
- if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
- Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(dataType)
- .data(json.toString()).build();
- sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
- AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
- }
- }).exceptionally(ex -> {
- System.err.println("执行失败: " + ex.getMessage());
- JSONObject rse = new JSONObject();
- rse.put("command",command);
- rse.put("resOut", "脚本执行失败");
- long timestamps = System.currentTimeMillis();
- timestamps = Math.round(timestamps / 1000.0);
- JSONObject json = new JSONObject();
- json.put("resCode",1);
- json.put("resMsg", "");
- json.put("timestamp",timestamps);
- json.put("result", rse.toString());
- // 判定客户端与服务端是否连接
- if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
- Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(dataType)
- .data(json.toString()).build();
- sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
- AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
- }
- return null;
- });
- }
+ } catch (Exception e) {
+ JSONObject json = new JSONObject();
+ json.put("resCode",0);
+ json.put("resMsg", "执行脚本策略定时任务保存失败");
+ json.put("timestamp",timestamp);
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.执行脚本策略应答.getValue())
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
}
}
+ }else{
+ if(StringUtils.equals(dataType, MsgEnum.Agent版本更新应答.getValue())){
+ try {
+ //设置检查回滚任务
+ String SCRIPT_PATH = properties.getScriptPath()+"/rollback-tragent.sh";
+ AgentDataUtil.chmod(SCRIPT_PATH,"775");
+ AgentUtil.scheduleScriptIn3Minutes(SCRIPT_PATH);
+ System.out.println("重启进程已启动,当前服务退出");
+ ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c",
+ policy.getCommandParams());
+ pb.start();
+ System.exit(0);
+ } catch (IOException | InterruptedException e) {
+ e.printStackTrace();
+ }
+ }else{
+ List cmd = Arrays.asList(policy.getCommandParams().split("\\s+"));
+ CompletableFuture future =
+ AsyncCommandExecutor.executeCommandAsync(
+ cmd,
+ 100, TimeUnit.SECONDS);
+ future.thenAccept(result -> {
+ if (result.isSuccess()) {
+ System.out.println("脚本执行成功");
+ System.out.println("[成功resOut] " + result.getOutput());
+ } else {
+ System.out.println("脚本执行失败");
+ System.out.println("[失败resOut] " + result.getOutput());
+ }
+ JSONObject rse = new JSONObject();
+ rse.put("command",policy.getCommandParams());
+ rse.put("resOut", result.getOutput());
+ long timestamps = System.currentTimeMillis();
+ timestamps = Math.round(timestamps / 1000.0);
+ JSONObject json = new JSONObject();
+ json.put("resCode",1);
+ json.put("resMsg", "");
+ json.put("timestamp",timestamps);
+ json.put("result", rse.toString());
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(dataType)
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
+ }
+ }).exceptionally(ex -> {
+ System.err.println("执行失败: " + ex.getMessage());
+ JSONObject rse = new JSONObject();
+ rse.put("command",policy.getCommandParams());
+ rse.put("resOut", "脚本执行失败");
+ long timestamps = System.currentTimeMillis();
+ timestamps = Math.round(timestamps / 1000.0);
+ JSONObject json = new JSONObject();
+ json.put("resCode",1);
+ json.put("resMsg", "");
+ json.put("timestamp",timestamps);
+ json.put("result", rse.toString());
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(dataType)
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送执行脚本策略应答={}",JSON.toJSONString(message));
+ }
+ return null;
+ });
+ }
}
}
+ @Override
+ public void cancelTask(String taskId) {
+ dynamicTaskService.cancelTask(taskId);
+ }
+
+ @Override
+ public void start() {
+ // 创建心跳定时任务
+ 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);
+ }
+
+ @Override
+ public void getPolicy(String data) {
+ JSONObject jsonObject = JSONObject.parseObject(data);
+ //监控策略
+ if(jsonObject.containsKey("monitors")){
+ String monitors = jsonObject.getString("monitors");
+ JSONObject monitorJson = JSONObject.parseObject(monitors);
+ long upTime = 0;
+ if(monitorJson.containsKey("upTime")){
+ upTime = monitorJson.getLong("upTime");
+ }
+ //判断监控策略最新更新时间戳,不一致则进行更新策略
+ if(upTime != 0 && GlobalConfig.MONITOR_TIME != upTime){
+ if(monitorJson.containsKey("contents")){
+ List list = new ArrayList<>();
+ list.add("upTime:"+upTime);
+ list.add("contents:[");
+ String contents = monitorJson.getString("contents");
+ List collectList = JSON.parseObject(contents, new TypeReference>() {});
+ AssertLog.info("开启或更新监控策略={}", JSON.toJSONString(collectList));
+ for (CollectEO c : collectList) {
+ list.add(JSON.toJSONString(c));
+ String type = c.getType();
+ boolean collect = c.isCollect();
+ int interval = c.getInterval();
+ switch(type) {
+ case "cpuCollect": //cpu采集
+ //判断与上次有无变化
+ if(GlobalConfig.cpuCollect != collect || GlobalConfig.cpuInterval != interval){
+ GlobalConfig.cpuCollect = collect;
+ if(collect){
+ GlobalConfig.cpuInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::cpuTask, milli, GlobalConfig.cpuInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.cpuInterval = 300;
+ }
+ }
+ break;
+ case "vfsCollect": //挂载采集
+ if(GlobalConfig.vfsCollect != collect || GlobalConfig.vfsInterval != interval){
+ GlobalConfig.vfsCollect = collect;
+ if(collect){
+ GlobalConfig.vfsInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::pointTask, milli, GlobalConfig.vfsInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.vfsInterval = 300;
+ }
+ }
+ break;
+ case "netCollect": //网络采集
+ if(GlobalConfig.netCollect != collect || GlobalConfig.netInterval != interval){
+ GlobalConfig.netCollect = collect;
+ if(collect){
+// GlobalConfig.netInterval = interval;
+ long milli = AgentUtil.millisecondsToNext5Minute();
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::netTask, milli, GlobalConfig.netInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.netInterval = 300;
+ }
+ }
+ break;
+ case "diskCollect": //磁盘采集
+ if(GlobalConfig.diskCollect != collect || GlobalConfig.diskInterval != interval){
+ GlobalConfig.diskCollect = collect;
+ if(collect){
+ GlobalConfig.diskInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::diskTask, milli, GlobalConfig.diskInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.diskInterval = 300;
+ }
+ }
+ break;
+ case "dockerCollect": //docker采集
+ if(GlobalConfig.dockerCollect != collect || GlobalConfig.dockerInterval != interval){
+ GlobalConfig.dockerCollect = collect;
+ if(collect){
+ GlobalConfig.dockerInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::dockerTask, milli, GlobalConfig.dockerInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.dockerInterval = 300;
+ }
+ }
+ break;
+ case "systemSwapSizeFreeCollect": //交换卷/文件的可用空间(字节)采集
+ if(GlobalConfig.systemSwapSizeFreeCollect != collect || GlobalConfig.systemSwapSizeFreeInterval != interval){
+ GlobalConfig.systemSwapSizeFreeCollect = collect;
+ if(collect){
+ GlobalConfig.systemSwapSizeFreeInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemSwapSizeFreeTask, milli, GlobalConfig.systemSwapSizeFreeInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemSwapSizeFreeInterval = 300;
+ }
+ }
+ break;
+ case "memoryUtilizationCollect": //内存利用率采集
+ if(GlobalConfig.memoryUtilizationCollect != collect || GlobalConfig.memoryUtilizationInterval != interval){
+ GlobalConfig.memoryUtilizationCollect = collect;
+ if(collect){
+ GlobalConfig.memoryUtilizationInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::memoryUtilizationTask, milli, GlobalConfig.memoryUtilizationInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.memoryUtilizationInterval = 300;
+ }
+ }
+ break;
+ case "systemSwapSizePercentCollect": //可用交换空间百分比采集
+ if(GlobalConfig.systemSwapSizePercentCollect != collect || GlobalConfig.systemSwapSizePercentInterval != interval){
+ GlobalConfig.systemSwapSizePercentCollect = collect;
+ if(collect){
+ GlobalConfig.systemSwapSizePercentInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemSwapSizePercentTask, milli, GlobalConfig.systemSwapSizePercentInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemSwapSizePercentInterval = 300;
+ }
+ }
+ break;
+ case "memorySizeAvailableCollect": //可用内存采集
+ if(GlobalConfig.memorySizeAvailableCollect != collect || GlobalConfig.memorySizeAvailableInterval != interval){
+ GlobalConfig.memorySizeAvailableCollect = collect;
+ if(collect){
+ GlobalConfig.memorySizeAvailableInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::memorySizeAvailableTask, milli, GlobalConfig.memorySizeAvailableInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.memorySizeAvailableInterval = 300;
+ }
+ }
+ break;
+ case "memorySizePercentCollect": //可用内存百分比采集
+ if(GlobalConfig.memorySizePercentCollect != collect || GlobalConfig.memorySizePercentInterval != interval){
+ GlobalConfig.memorySizePercentCollect = collect;
+ if(collect){
+ GlobalConfig.memorySizePercentInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::memorySizePercentTask, milli, GlobalConfig.memorySizePercentInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.memorySizePercentInterval = 300;
+ }
+ }
+ break;
+ case "memorySizeTotalCollect": //总内存采集
+ if(GlobalConfig.memorySizeTotalCollect != collect || GlobalConfig.memorySizeTotalInterval != interval){
+ GlobalConfig.memorySizeTotalCollect = collect;
+ if(collect){
+ GlobalConfig.memorySizeTotalInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::memorySizeTotalTask, milli, GlobalConfig.memorySizeTotalInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.memorySizeTotalInterval = 300;
+ }
+ }
+ break;
+ case "systemSwOsCollect": //操作系统采集
+ if(GlobalConfig.systemSwOsCollect != collect || GlobalConfig.systemSwOsInterval != interval){
+ GlobalConfig.systemSwOsCollect = collect;
+ if(collect){
+ GlobalConfig.systemSwOsInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemSwOsTask, milli, GlobalConfig.systemSwOsInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemSwOsInterval = 300;
+ }
+ }
+ break;
+ case "systemSwArchCollect": //操作系统架构采集
+ if(GlobalConfig.systemSwArchCollect != collect || GlobalConfig.systemSwArchInterval != interval){
+ GlobalConfig.systemSwArchCollect = collect;
+ if(collect){
+ GlobalConfig.systemSwArchInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemSwArchTask, milli, GlobalConfig.systemSwArchInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemSwArchInterval = 300;
+ }
+ }
+ break;
+ case "kernelMaxprocCollect": //最大进程数采集
+ if(GlobalConfig.kernelMaxprocCollect != collect || GlobalConfig.kernelMaxprocInterval != interval){
+ GlobalConfig.kernelMaxprocCollect = collect;
+ if(collect){
+ GlobalConfig.kernelMaxprocInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::kernelMaxprocTask, milli, GlobalConfig.kernelMaxprocInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.kernelMaxprocInterval = 300;
+ }
+ }
+ break;
+ case "procNumRunCollect": //正在运行的进程数采集
+ if(GlobalConfig.procNumRunCollect != collect || GlobalConfig.procNumRunInterval != interval){
+ GlobalConfig.procNumRunCollect = collect;
+ if(collect){
+ GlobalConfig.procNumRunInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::procNumRunTask, milli, GlobalConfig.procNumRunInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.procNumRunInterval = 300;
+ }
+ }
+ break;
+ case "systemUsersNumCollect": //登录用户数采集
+ if(GlobalConfig.systemUsersNumCollect != collect || GlobalConfig.systemUsersNumInterval != interval){
+ GlobalConfig.systemUsersNumCollect = collect;
+ if(collect){
+ GlobalConfig.systemUsersNumInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemUsersNumTask, milli, GlobalConfig.systemUsersNumInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemUsersNumInterval = 300;
+ }
+ }
+ break;
+ case "systemDiskSizeTotalCollect": //硬盘总可用空间采集
+ if(GlobalConfig.systemDiskSizeTotalCollect != collect || GlobalConfig.systemDiskSizeTotalInterval != interval){
+ GlobalConfig.systemDiskSizeTotalCollect = collect;
+ if(collect){
+ GlobalConfig.systemDiskSizeTotalInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemDiskSizeTotalTask, milli, GlobalConfig.systemDiskSizeTotalInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemDiskSizeTotalInterval = 300;
+ }
+ }
+ break;
+ case "systemBoottimeCollect": //系统启动时间采集
+ if(GlobalConfig.systemBoottimeCollect != collect || GlobalConfig.systemBoottimeInterval != interval){
+ GlobalConfig.systemBoottimeCollect = collect;
+ if(collect){
+ GlobalConfig.systemBoottimeInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemBoottimeTask, milli, GlobalConfig.systemBoottimeInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemBoottimeInterval = 300;
+ }
+ }
+ break;
+ case "systemUnameCollect": //系统描述采集
+ if(GlobalConfig.systemUnameCollect != collect || GlobalConfig.systemUnameInterval != interval){
+ GlobalConfig.systemUnameCollect = collect;
+ if(collect){
+ GlobalConfig.systemUnameInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemUnameTask, milli, GlobalConfig.systemUnameInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemUnameInterval = 300;
+ }
+ }
+ break;
+ case "systemLocaltimeCollect": //系统本地时间采集
+ if(GlobalConfig.systemLocaltimeCollect != collect || GlobalConfig.systemLocaltimeInterval != interval){
+ GlobalConfig.systemLocaltimeCollect = collect;
+ if(collect){
+ GlobalConfig.systemLocaltimeInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemLocaltimeTask, milli, GlobalConfig.systemLocaltimeInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemLocaltimeInterval = 300;
+ }
+ }
+ break;
+ case "systemUptimeCollect": //系统正常运行时间采集
+ if(GlobalConfig.systemUptimeCollect != collect || GlobalConfig.systemUptimeInterval != interval){
+ GlobalConfig.systemUptimeCollect = collect;
+ if(collect){
+ GlobalConfig.systemUptimeInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::systemUptimeTask, milli, GlobalConfig.systemUptimeInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.systemUptimeInterval = 300;
+ }
+ }
+ break;
+ default: //系统其他采集
+ GlobalConfig.procNumCollect = collect;
+ if(collect){
+ GlobalConfig.procNumInterval = interval;
+ long milli = AgentUtil.getMillisToNextMinute() + 60000;
+ dynamicTaskService.scheduleTask(type,
+ businessTasks::procNumTask, milli, GlobalConfig.procNumInterval*1000L);
+ }else{
+ dynamicTaskService.cancelTask(type);
+ GlobalConfig.procNumInterval = 300;
+ }
+ }
+ }
+ list.add("]");
+ String[] lines = list.stream().toArray(String[]::new);
+ //检查外置目录是否存在
+ if(AdvancedAsyncDownloader.createSingleDirectoryIfNotExists(properties.getConfPath())){
+ AgentUtil.bufferedWriter(properties.getConfPath()+"/monitor.conf",lines);
+ }
+ }
+ GlobalConfig.MONITOR_TIME = upTime;
+ }
+ }
+ //脚本策略
+ if(jsonObject.containsKey("scripts")){
+ String scripts = jsonObject.getString("scripts");
+ JSONObject scriptJson = JSONObject.parseObject(scripts);
+ long upTime = 0;
+ if(scriptJson.containsKey("upTime")){
+ upTime = scriptJson.getLong("upTime");
+ }
+ //判断脚本策略最新更新时间戳,不一致则进行更新策略
+ if(upTime != 0 && GlobalConfig.SCRIPT_TIME != upTime){
+ if(scriptJson.containsKey("contents")) {
+ String contents = scriptJson.getString("contents");
+ List scriptList = JSON.parseObject(contents, new TypeReference>() {
+ });
+ AssertLog.info("开启或更新脚本策略={}", JSON.toJSONString(scriptList));
+ for (ScriptPolicyEO policy : scriptList) {
+ if(AdvancedAsyncDownloader.createSingleDirectoryIfNotExists(properties.getTmpPath()+"/script")){
+ if(StringUtils.isNotBlank(policy.getFileUrl())){
+ 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);
+ //所有文件下载完成,执行脚本命令
+ command(policy, GlobalConfig.CLIENT_ID,MsgEnum.执行脚本策略应答.getValue());
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InterruptedException 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);
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.执行脚本策略应答.getValue())
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送脚本策略应答={}",JSON.toJSONString(message));
+ }
+ return null;
+ });
+ }
+ }
+ }
+ }
+ GlobalConfig.SCRIPT_TIME = upTime;
+ }
+ }
+ //版本策略
+ if(jsonObject.containsKey("versions")){
+ String versions = jsonObject.getString("versions");
+ JSONObject versionJson = JSONObject.parseObject(versions);
+ long upTime = 0;
+ if(versionJson.containsKey("upTime")){
+ upTime = versionJson.getLong("upTime");
+ }
+ //判断版本策略最新更新时间戳,不一致则进行更新策略
+ if(upTime != 0 && GlobalConfig.VERSION_TIME != upTime){
+ if(versionJson.containsKey("contents")) {
+ String contents = versionJson.getString("contents");
+ List versionList = JSON.parseObject(contents, new TypeReference>() {
+ });
+ AssertLog.info("开启或更新版本策略={}", JSON.toJSONString(versionList));
+ try {
+ AgentDataUtil.chmod(properties.getScriptPath()+"/restart-tragent.sh","775");
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ for (AgentVersionUpdateEO versionUpdateEO : versionList) {
+ ScriptPolicyEO policy = ScriptPolicyEO.builder()
+ .method(versionUpdateEO.getMethod())
+ .commandParams(properties.getScriptPath()+"/restart-tragent.sh")
+ .policyTime(versionUpdateEO.getPolicyTime())
+ .build();
+ if(StringUtils.isNotBlank(versionUpdateEO.getFileUrl())){
+ 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 {
+ //验证文件MD5
+ String md5 = AgentUtil.getFileMD5(properties.getTempPath()+"/"+fileName);
+ if(StringUtils.isNotBlank(md5) && StringUtils.isNotBlank(versionUpdateEO.getFileMd5())
+ && StringUtils.equals(md5,versionUpdateEO.getFileMd5())){
+ //更改全局变量
+ GlobalConfig.isCollect = false;
+ //关闭采集任务
+ cancelCollect();
+ //所有文件下载完成,执行脚本命令
+ command(policy, GlobalConfig.CLIENT_ID,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);
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.Agent版本更新应答.getValue())
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送版本策略应答={}",JSON.toJSONString(message));
+ }
+ }
+ } 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);
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(MsgEnum.Agent版本更新应答.getValue())
+ .data(json.toString()).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送版本策略应答={}",JSON.toJSONString(message));
+ }
+ return null;
+ });
+ }
+ }
+ }
+ GlobalConfig.VERSION_TIME = upTime;
+ }
+ }
+
+ }
+
+ @Override
+ public void checkTrAgent() {
+ // 脚本路径(用于验证脚本是否存在)
+ String SCRIPT_PATH = properties.getScriptPath()+"/check-tragent.sh";
+ try {
+ AgentDataUtil.chmod(SCRIPT_PATH,"775");
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ // 要添加的定时任务(每10分钟执行一次,且静默输出)
+ String TARGET_CRON = "*/10 * * * * "+properties.getScriptPath()+"/check-tragent.sh >/dev/null 2>&1";
+
+ boolean success = CrontabManager.ensureCronJobExists(TARGET_CRON, SCRIPT_PATH);
+ if (success) {
+ System.out.println("✅ Crontab 状态正常。");
+ } else {
+ System.err.println("❌ 操作失败,请检查权限或路径。");
+ }
+ }
+
+ @Override
+ public void sendMessage(String type, String data) {
+ // 判定客户端与服务端是否连接
+ if (Objects.nonNull(sessionManager.getSessionById(GlobalConfig.CLIENT_ID))) {
+ Message message = Message.builder().clientId(GlobalConfig.CLIENT_ID).dataType(type)
+ .data(data).build();
+ sessionManager.writeAndFlush(sessionManager.getSessionById(GlobalConfig.CLIENT_ID).getChannel(), message);
+ AssertLog.info("发送={}",JSON.toJSONString(message));
+ }
+ }
+
+ @Override
+ public boolean connection() {
+ String clientId = MachineFingerprint.getHardwareFingerprint();
+ //初始化SN信息
+ GlobalConfig.DEVICE_SN = AgentUtil.getDeviceSN();
+ //检查外置目录是否存在
+ if(AdvancedAsyncDownloader.createSingleDirectoryIfNotExists(properties.getConfPath())){
+ //检查agent是否已注册
+ File regFile = new File(properties.getConfPath()+"/register.conf");
+ if (regFile.exists()) {
+ Properties props = new Properties();
+ try (InputStream input = Files.newInputStream(Paths.get(properties.getConfPath()+"/register.conf"))) {
+ // 加载配置文件
+ props.load(input);
+ // 为全局变量赋值
+ String register = props.getProperty("register", "0");
+ if(StringUtils.equals(register,"1")){
+ GlobalConfig.isRegister = true;
+ }
+ } catch (IOException e) {
+ System.err.println("无法加载注册配置文件,使用默认值");
+ } catch (NumberFormatException e) {
+ System.err.println("注册配置文件格式错误: " + e.getMessage());
+ }
+ } else {
+ String[] lines = {
+ "register=0"
+ };
+ AgentUtil.bufferedWriter(properties.getConfPath()+"/register.conf",lines);
+ }
+ //检查clientID是否存在
+ File clientFile = new File(properties.getConfPath()+"/client.conf");
+ if (clientFile.exists()) {
+ Properties props = new Properties();
+ try (InputStream input = Files.newInputStream(Paths.get(properties.getConfPath()+"/client.conf"))) {
+ // 加载配置文件
+ props.load(input);
+ // 为全局变量赋值
+ String id = props.getProperty("clientId", "");
+ if(StringUtils.isNotBlank(id)){
+ GlobalConfig.CLIENT_ID = id;
+ }else{
+ String[] lines = {
+ "clientId="+clientId
+ };
+ AgentUtil.bufferedWriter(properties.getConfPath()+"/client.conf",lines);
+ GlobalConfig.CLIENT_ID = clientId;
+ }
+ } catch (IOException e) {
+ System.err.println("无法加载client配置文件,使用默认值");
+ } catch (NumberFormatException e) {
+ System.err.println("client配置文件格式错误: " + e.getMessage());
+ }
+ } else {
+ String[] lines = {
+ "clientId="+clientId
+ };
+ AgentUtil.bufferedWriter(properties.getConfPath()+"/client.conf",lines);
+ GlobalConfig.CLIENT_ID = clientId;
+ }
+ }
+ return client.createConnection(GlobalConfig.CLIENT_ID, config.getHost(), config.getPort(), 5);
+ }
+
public void caseTypeBySystem(String type, int interval, boolean collect){
diff --git a/src/main/java/com/tongran/agent/client/service/impl/SwitchBoardServiceImpl.java b/src/main/java/com/tongran/agent/client/service/impl/SwitchBoardServiceImpl.java
index 337a827..616d66d 100644
--- a/src/main/java/com/tongran/agent/client/service/impl/SwitchBoardServiceImpl.java
+++ b/src/main/java/com/tongran/agent/client/service/impl/SwitchBoardServiceImpl.java
@@ -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 switchBoardList(long timestamp) {
- List 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 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 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 oidParams) throws IOException {
- if(oidParams.isEmpty()){
- return "";
- }
- JSONObject json = new JSONObject();
- // 获取接口数量
- String ifNumberOID = "";
- List 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 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);
- }
- }
- }
- // 更新下一次请求的起始 OID(SNMP 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 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 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);
- }
- }
}
diff --git a/src/main/java/com/tongran/agent/client/utils/AgentUtil.java b/src/main/java/com/tongran/agent/client/utils/AgentUtil.java
index eff99c2..cb63ffd 100644
--- a/src/main/java/com/tongran/agent/client/utils/AgentUtil.java
+++ b/src/main/java/com/tongran/agent/client/utils/AgentUtil.java
@@ -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 collectNetworkInfo() throws Exception {
+ List 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 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 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 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 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();
+ }
+ }
+
}
diff --git a/src/main/java/com/tongran/agent/client/utils/ClientExample.java b/src/main/java/com/tongran/agent/client/utils/ClientExample.java
new file mode 100644
index 0000000..398d6ad
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/utils/ClientExample.java
@@ -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 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 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 status = manager.getConnectionStatus();
+ System.out.println("连接状态: " + status);
+
+ Thread.sleep(5000);
+
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+// manager.shutdown();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/utils/CrontabManager.java b/src/main/java/com/tongran/agent/client/utils/CrontabManager.java
new file mode 100644
index 0000000..0d029ae
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/utils/CrontabManager.java
@@ -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("❌ 操作失败,请检查权限或路径。");
+// }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/utils/EnhancedConnectionManager.java b/src/main/java/com/tongran/agent/client/utils/EnhancedConnectionManager.java
new file mode 100644
index 0000000..f8f59cc
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/utils/EnhancedConnectionManager.java
@@ -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 connectionConfigs;
+
+ public EnhancedConnectionManager() {
+// this.client = new MultiTargetNettyClient();
+ this.connectionConfigs = new ConcurrentHashMap<>();
+ }
+
+ /**
+ * 批量创建连接
+ */
+ public Map createConnections(List configs) {
+ Map 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 getConnectionStatus() {
+ Map status = new HashMap<>();
+// connectionConfigs.forEach((key, config) -> {
+// // 这里可以添加更详细的状态检查
+// status.put(key, client.sendMessage(key, "PING"));
+// });
+ return status;
+ }
+
+// public void shutdown() {
+// client.shutdown();
+// }
+}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/utils/MachineFingerprint.java b/src/main/java/com/tongran/agent/client/utils/MachineFingerprint.java
new file mode 100644
index 0000000..56e1fa7
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/utils/MachineFingerprint.java
@@ -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 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);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/tongran/agent/client/utils/PublicIpFetcher.java b/src/main/java/com/tongran/agent/client/utils/PublicIpFetcher.java
new file mode 100644
index 0000000..902d27e
--- /dev/null
+++ b/src/main/java/com/tongran/agent/client/utils/PublicIpFetcher.java
@@ -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 信息字符串,如 "当前 IP:112.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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml
index 498fd0b..edac848 100644
--- a/src/main/resources/application-dev.yml
+++ b/src/main/resources/application-dev.yml
@@ -1,7 +1,8 @@
server:
- port: 7010
+ port: 7011
servlet:
context-path: /tr-agent-client
+
# 接口文档配置
knife4j:
@@ -13,10 +14,13 @@ logging:
file:
path: /usr/local/tongran/logs
-tcp:
- netty:
- charge:
- enable: true
- name: AGENT-CLIENT-服务
- port: 6610
- readerIdleTime: 300
\ No newline at end of file
+netty:
+ server:
+ host: 127.0.0.1
+ port: 6620
+ client:
+ client-id: client-001
+ reconnect-interval: 5
+ maxReconnectAttempts: 10 # 最大重连次数
+ initialReconnectDelay: 1000 # 初始重连延迟(毫秒)
+ maxReconnectDelay: 30000 # 最大重连延迟(毫秒)
\ No newline at end of file
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 721702c..994a280 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -6,7 +6,12 @@ spring:
matching-strategy: ant_path_matcher
application:
name: tr-agent-client
- version: 1.0
+ version: 1.1
+ conf-path: /usr/local/tongran/conf
+ script-path: /usr/local/tongran/sbin
+ tmp-path: /usr/local/tongran/tmp
+ temp-path: /usr/local/tongran/temp
+ logical-node: beijing1
web:
resources:
static-locations: classpath*:/META-INF/resources/