增加TCP数据头

This commit is contained in:
qiminbao
2025-08-25 18:02:41 +08:00
parent 09ac62bca1
commit bddbf10503
22 changed files with 46 additions and 95 deletions
@@ -56,7 +56,7 @@ public class CpuScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("CPU").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("CPU").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送CPU信息包={}",json); AssertLog.info("发送CPU信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -59,7 +59,7 @@ public class DiskScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("DISK").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("DISK").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送磁盘信息包={}",json); AssertLog.info("发送磁盘信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -59,7 +59,7 @@ public class DockerScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("DOCKER").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("DOCKER").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送容器信息包={}",json); AssertLog.info("发送容器信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -58,7 +58,7 @@ public class HeartScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("HEARTBEAT").data(object.toString()).build(); Message message = Message.builder().clientId(clientId).dataType("HEARTBEAT").data(object.toString()).build();
// 将对象转为 JSON 字符串 标识 // 将对象转为 JSON 字符串 标识
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送心跳包={}",json); AssertLog.info("发送心跳包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
}; };
@@ -57,7 +57,7 @@ public class MemoryScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("MEMORY").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("MEMORY").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送内存信息包={}",json); AssertLog.info("发送内存信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -59,7 +59,7 @@ public class NetScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("NET").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("NET").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送网卡信息包={}",json); AssertLog.info("发送网卡信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -59,7 +59,7 @@ public class PointScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("POINT").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("POINT").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送挂载点信息包={}",json); AssertLog.info("发送挂载点信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -57,7 +57,7 @@ public class SwitchBoardScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("SWITCHBOARD").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("SWITCHBOARD").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送交换机信息包={}",json); AssertLog.info("发送交换机信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -56,7 +56,7 @@ public class SysScheduler {
String clientId = AgentUtil.getMotherboardUUID(); String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("SYSTEM").data(data).build(); Message message = Message.builder().clientId(clientId).dataType("SYSTEM").data(data).build();
// 将对象转为 JSON 字符串 // 将对象转为 JSON 字符串
String json = JSON.toJSONString(message); String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送系统信息包={}",json); AssertLog.info("发送系统信息包={}",json);
nettyTcpClient.sendMessage(json); nettyTcpClient.sendMessage(json);
} }
@@ -27,7 +27,7 @@ public class GlobalConfig {
private static void loadConfigFromFile() { private static void loadConfigFromFile() {
Properties props = new Properties(); Properties props = new Properties();
try (InputStream input = Files.newInputStream(Paths.get("/data/agent-server/config/switch_config.txt"))) { try (InputStream input = Files.newInputStream(Paths.get("/usr/local/tongran/config/switch_config.txt"))) {
// 加载配置文件 // 加载配置文件
props.load(input); props.load(input);
@@ -28,7 +28,7 @@ public class DiskServiceImpl implements DiskService {
DiskVO diskVO = DiskVO.builder().build(); DiskVO diskVO = DiskVO.builder().build();
diskVO.setName(disk.getName());//磁盘名称 diskVO.setName(disk.getName());//磁盘名称
diskVO.setSerial(disk.getSerial());//序列号 diskVO.setSerial(disk.getSerial());//序列号
diskVO.setTotal(disk.getSize());//磁盘大小GB diskVO.setTotal(disk.getSize());//磁盘大小
diskVO.setWriteTimes(disk.getWrites());//磁盘写入次数 diskVO.setWriteTimes(disk.getWrites());//磁盘写入次数
diskVO.setReadTimes(disk.getReads());//磁盘读取次数 diskVO.setReadTimes(disk.getReads());//磁盘读取次数
diskVO.setWriteBytes(disk.getReadBytes());//磁盘写入字节 diskVO.setWriteBytes(disk.getReadBytes());//磁盘写入字节
@@ -73,8 +73,8 @@ public class NetServiceImpl implements NetService {
if(Objects.nonNull(netVO)){ if(Objects.nonNull(netVO)){
netVO.setInDropped(net.getInDrops());//入站丢包 netVO.setInDropped(net.getInDrops());//入站丢包
netVO.setOutDropped(net.getCollisions());//出站丢包 netVO.setOutDropped(net.getCollisions());//出站丢包
netVO.setInSpeed(FormatUtil.formatBytes(bytesRecv));//接收流量 netVO.setInSpeed(bytesRecv);//接收流量
netVO.setOutSpeed(FormatUtil.formatBytes(bytesSent));//发送流量 netVO.setOutSpeed(bytesSent);//发送流量
list.add(netVO); list.add(netVO);
} }
} }
@@ -114,12 +114,13 @@ public class SystemServiceImpl implements SystemService {
} }
// 获取硬盘总可用空间 // 获取硬盘总可用空间
public double diskSpace() { public long diskSpace() {
double diskSizeTotal = 0; long diskSizeTotal = 0;
File[] roots = File.listRoots(); File[] roots = File.listRoots();
// System.out.println("\n===== 硬盘空间信息 ====="); // System.out.println("\n===== 硬盘空间信息 =====");
for (File root : roots) { for (File root : roots) {
diskSizeTotal += (double) root.getFreeSpace() / (1024 * 1024 * 1024); diskSizeTotal += root.getFreeSpace();
// diskSizeTotal += (double) root.getFreeSpace() / (1024 * 1024 * 1024);
// System.out.printf("磁盘: %s\n", root.getAbsolutePath()); // System.out.printf("磁盘: %s\n", root.getAbsolutePath());
// System.out.printf("总空间: %.2f GB\n", (double) root.getTotalSpace() / (1024 * 1024 * 1024)); // System.out.printf("总空间: %.2f GB\n", (double) root.getTotalSpace() / (1024 * 1024 * 1024));
// System.out.printf("可用空间: %.2f GB\n", (double) root.getFreeSpace() / (1024 * 1024 * 1024)); // System.out.printf("可用空间: %.2f GB\n", (double) root.getFreeSpace() / (1024 * 1024 * 1024));
@@ -22,7 +22,7 @@ public class DiskVO implements Serializable {
@Schema(description = "序列号") @Schema(description = "序列号")
private String serial; private String serial;
@Schema(description = "磁盘大小GB") @Schema(description = "磁盘大小")
private long total; private long total;
@Schema(description = "磁盘写入速率") @Schema(description = "磁盘写入速率")
@@ -17,7 +17,7 @@ public class MemoryVO implements Serializable {
private static final long serialVersionUID = 2L; private static final long serialVersionUID = 2L;
@Schema(description = "交换卷/文件的可用空间(字节)") @Schema(description = "交换卷/文件的可用空间(字节)")
private double swapSizeFree; private long swapSizeFree;
@Schema(description = "内存利用率") @Schema(description = "内存利用率")
private double untilzation; private double untilzation;
@@ -38,12 +38,12 @@ public class NetVO implements Serializable {
private long outDropped; private long outDropped;
@Schema(description = "发送流量") @Schema(description = "发送流量")
private String outSpeed; private long outSpeed;
@Schema(description = "接收流量") @Schema(description = "接收流量")
private String inSpeed; private long inSpeed;
@Schema(description = "接收速度") // @Schema(description = "接收速度")
private String speed; // private String speed;
} }
@@ -31,8 +31,8 @@ public class SystemVO implements Serializable {
@Schema(description = "登录用户数") @Schema(description = "登录用户数")
private int usersNum; private int usersNum;
@Schema(description = "硬盘:总可用空间") @Schema(description = "硬盘:总可用空间(字节)")
private double diskSizeTotal; private long diskSizeTotal;
@Schema(description = "系统启动时间") @Schema(description = "系统启动时间")
private long bootTime; private long bootTime;
@@ -46,13 +46,10 @@ public class SystemVO implements Serializable {
@Schema(description = "系统正常运行时间") @Schema(description = "系统正常运行时间")
private long upTime; private long upTime;
@Schema(description = "进程数")
private double procNum;
private String uuid; private String uuid;
@Schema(description = "时间戳") // @Schema(description = "时间戳")
private long timeStamp; // private long timeStamp;
} }
@@ -2,13 +2,13 @@ package com.tongran.agentserver.server.netty;
import com.tongran.agentserver.server.netty.config.AgentNettyConfig; import com.tongran.agentserver.server.netty.config.AgentNettyConfig;
import com.tongran.agentserver.server.netty.handler.DecoderHandler; import com.tongran.agentserver.server.netty.handler.DecoderHandler;
import com.tongran.agentserver.server.netty.handler.EncoderHandler;
import com.tongran.agentserver.server.netty.handler.NettyClientHandler; import com.tongran.agentserver.server.netty.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*; import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -60,7 +60,7 @@ public class NettyTcpClient {
ChannelPipeline pipeline = ch.pipeline(); ChannelPipeline pipeline = ch.pipeline();
// 添加编解码器 // 添加编解码器
pipeline.addLast("decoder", new DecoderHandler()); pipeline.addLast("decoder", new DecoderHandler());
pipeline.addLast("encoder", new EncoderHandler()); pipeline.addLast("encoder", new StringEncoder());
// 添加心跳机制 // 添加心跳机制
pipeline.addLast("idleStateHandler", pipeline.addLast("idleStateHandler",
new IdleStateHandler(0, 0, 90, TimeUnit.SECONDS)); new IdleStateHandler(0, 0, 90, TimeUnit.SECONDS));
@@ -1,11 +1,6 @@
package com.tongran.agentserver.server.netty.handler; package com.tongran.agentserver.server.netty.handler;
import com.alibaba.fastjson2.JSONObject;
import com.tongran.agentserver.server.netty.annotation.AgentDispatcher;
import com.tongran.agentserver.server.netty.basics.AgentDispatcherManager; import com.tongran.agentserver.server.netty.basics.AgentDispatcherManager;
import com.tongran.agentserver.server.netty.basics.AgentHandler;
import com.tongran.agentserver.server.netty.model.Message;
import com.tongran.agentserver.server.netty.model.UpMsgResponse;
import com.tongran.agentserver.utils.AssertLog; import com.tongran.agentserver.utils.AssertLog;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
@@ -33,20 +28,19 @@ public class DecoderHandler extends ChannelInboundHandlerAdapter {
ByteBuf byteBuf = (ByteBuf) msg; ByteBuf byteBuf = (ByteBuf) msg;
String messages = byteBuf.toString(CharsetUtil.UTF_8); // 指定字符集解码 String messages = byteBuf.toString(CharsetUtil.UTF_8); // 指定字符集解码
AssertLog.info("<<[up]:[up-content]==>{}", messages); AssertLog.info("<<[up]:[up-content]==>{}", messages);
boolean startsWith = messages.startsWith("agent-server:"); // JSONObject jsonObject = JSONObject.parseObject(messages);
boolean endsWith = messages.endsWith("@tong-ran"); // String clientId = jsonObject.getString("clientId");
if(startsWith && endsWith){ // String dataType = jsonObject.getString("dataType");
JSONObject jsonObject = JSONObject.parseObject(messages); // AgentHandler msgHandler = agentDispatcherManager.getHandler(dataType + "&" + AgentDispatcher.VersionEnum.V1.value);
String clientId = jsonObject.getString("clientId"); // UpMsgResponse response = msgHandler.upHandle(messages,clientId);
String dataType = jsonObject.getString("dataType"); // if(Objects.nonNull(response)){
AgentHandler msgHandler = agentDispatcherManager.getHandler(dataType + "&" + AgentDispatcher.VersionEnum.V1.value); // Message agentMessage = Message.builder().build();
UpMsgResponse response = msgHandler.upHandle(messages,clientId); // agentMessage.setClientId(clientId);
Message agentMessage = Message.builder().build(); // agentMessage.setDataType(response.getDataType());
agentMessage.setClientId(clientId); // agentMessage.setData(response.getContent());
agentMessage.setDataType(response.getDataType()); // String json = "agent-tcp:"+ JSON.toJSONString(agentMessage)+"@tong-ran";
agentMessage.setData(response.getContent()); // ctx.fireChannelRead(json);//传递到下一个handler
ctx.fireChannelRead(agentMessage);//传递到下一个handler // }
}
byteBuf.release(); // 释放 ByteBuf 资源(重要!) byteBuf.release(); // 释放 ByteBuf 资源(重要!)
} else { } else {
System.out.println("Unexpected message type: " + msg.getClass()); System.out.println("Unexpected message type: " + msg.getClass());
@@ -1,41 +0,0 @@
package com.tongran.agentserver.server.netty.handler;
import com.alibaba.fastjson2.JSON;
import com.tongran.agentserver.server.netty.model.Message;
import com.tongran.agentserver.utils.AssertLog;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
@Component
@ChannelHandler.Sharable
public class EncoderHandler extends ChannelOutboundHandlerAdapter {
/**
* 消息解码器
*/
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof Message) {
Message entity = (Message) msg;
if (StringUtils.isBlank(entity.getData())) {
AssertLog.error(">>[down]:errorContent:{}", msg);
return;
}
AssertLog.info(">>[down]:[content]==>{}", entity.getData());
String json = "agent-tcp:"+JSON.toJSONString(entity)+"@tong-ran";
byte[] bytes = json.getBytes(StandardCharsets.UTF_8); // 显式指定 UTF-8
// byte[] bytes = EscapeUtil.hexStringToByteArray(entity.getContent());
ByteBuf buf = Unpooled.wrappedBuffer(bytes);
ctx.write(buf, promise);
}
}
}
+2 -2
View File
@@ -11,11 +11,11 @@ knife4j:
# 日志配置 # 日志配置
logging: logging:
file: file:
path: /data/agent-server/logs path: /usr/local/tongran/logs
netty: netty:
server: server:
host: 127.0.0.1 host: 172.16.15.103
port: 6610 port: 6610
client: client:
client-id: client-001 client-id: client-001
+2 -2
View File
@@ -11,11 +11,11 @@ knife4j:
# 日志配置 # 日志配置
logging: logging:
file: file:
path: /data/agent-server/logs path: /usr/local/tongran/logs
netty: netty:
server: server:
host: 127.0.0.1 host: 172.16.15.103
port: 6610 port: 6610
client: client:
client-id: client-001 client-id: client-001