增加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();
Message message = Message.builder().clientId(clientId).dataType("CPU").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送CPU信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -59,7 +59,7 @@ public class DiskScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("DISK").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送磁盘信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -59,7 +59,7 @@ public class DockerScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("DOCKER").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送容器信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -58,7 +58,7 @@ public class HeartScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("HEARTBEAT").data(object.toString()).build();
// 将对象转为 JSON 字符串 标识
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送心跳包={}",json);
nettyTcpClient.sendMessage(json);
};
@@ -57,7 +57,7 @@ public class MemoryScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("MEMORY").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送内存信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -59,7 +59,7 @@ public class NetScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("NET").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送网卡信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -59,7 +59,7 @@ public class PointScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("POINT").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送挂载点信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -57,7 +57,7 @@ public class SwitchBoardScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("SWITCHBOARD").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送交换机信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -56,7 +56,7 @@ public class SysScheduler {
String clientId = AgentUtil.getMotherboardUUID();
Message message = Message.builder().clientId(clientId).dataType("SYSTEM").data(data).build();
// 将对象转为 JSON 字符串
String json = JSON.toJSONString(message);
String json = "agent-tcp:"+JSON.toJSONString(message)+"@tong-ran";
AssertLog.info("发送系统信息包={}",json);
nettyTcpClient.sendMessage(json);
}
@@ -27,7 +27,7 @@ public class GlobalConfig {
private static void loadConfigFromFile() {
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);
@@ -28,7 +28,7 @@ public class DiskServiceImpl implements DiskService {
DiskVO diskVO = DiskVO.builder().build();
diskVO.setName(disk.getName());//磁盘名称
diskVO.setSerial(disk.getSerial());//序列号
diskVO.setTotal(disk.getSize());//磁盘大小GB
diskVO.setTotal(disk.getSize());//磁盘大小
diskVO.setWriteTimes(disk.getWrites());//磁盘写入次数
diskVO.setReadTimes(disk.getReads());//磁盘读取次数
diskVO.setWriteBytes(disk.getReadBytes());//磁盘写入字节
@@ -73,8 +73,8 @@ public class NetServiceImpl implements NetService {
if(Objects.nonNull(netVO)){
netVO.setInDropped(net.getInDrops());//入站丢包
netVO.setOutDropped(net.getCollisions());//出站丢包
netVO.setInSpeed(FormatUtil.formatBytes(bytesRecv));//接收流量
netVO.setOutSpeed(FormatUtil.formatBytes(bytesSent));//发送流量
netVO.setInSpeed(bytesRecv);//接收流量
netVO.setOutSpeed(bytesSent);//发送流量
list.add(netVO);
}
}
@@ -114,12 +114,13 @@ public class SystemServiceImpl implements SystemService {
}
// 获取硬盘总可用空间
public double diskSpace() {
double diskSizeTotal = 0;
public long diskSpace() {
long diskSizeTotal = 0;
File[] roots = File.listRoots();
// System.out.println("\n===== 硬盘空间信息 =====");
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("总空间: %.2f GB\n", (double) root.getTotalSpace() / (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 = "序列号")
private String serial;
@Schema(description = "磁盘大小GB")
@Schema(description = "磁盘大小")
private long total;
@Schema(description = "磁盘写入速率")
@@ -17,7 +17,7 @@ public class MemoryVO implements Serializable {
private static final long serialVersionUID = 2L;
@Schema(description = "交换卷/文件的可用空间(字节)")
private double swapSizeFree;
private long swapSizeFree;
@Schema(description = "内存利用率")
private double untilzation;
@@ -38,12 +38,12 @@ public class NetVO implements Serializable {
private long outDropped;
@Schema(description = "发送流量")
private String outSpeed;
private long outSpeed;
@Schema(description = "接收流量")
private String inSpeed;
private long inSpeed;
@Schema(description = "接收速度")
private String speed;
// @Schema(description = "接收速度")
// private String speed;
}
@@ -31,8 +31,8 @@ public class SystemVO implements Serializable {
@Schema(description = "登录用户数")
private int usersNum;
@Schema(description = "硬盘:总可用空间")
private double diskSizeTotal;
@Schema(description = "硬盘:总可用空间(字节)")
private long diskSizeTotal;
@Schema(description = "系统启动时间")
private long bootTime;
@@ -46,13 +46,10 @@ public class SystemVO implements Serializable {
@Schema(description = "系统正常运行时间")
private long upTime;
@Schema(description = "进程数")
private double procNum;
private String uuid;
@Schema(description = "时间戳")
private long timeStamp;
// @Schema(description = "时间戳")
// 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.handler.DecoderHandler;
import com.tongran.agentserver.server.netty.handler.EncoderHandler;
import com.tongran.agentserver.server.netty.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,7 +60,7 @@ public class NettyTcpClient {
ChannelPipeline pipeline = ch.pipeline();
// 添加编解码器
pipeline.addLast("decoder", new DecoderHandler());
pipeline.addLast("encoder", new EncoderHandler());
pipeline.addLast("encoder", new StringEncoder());
// 添加心跳机制
pipeline.addLast("idleStateHandler",
new IdleStateHandler(0, 0, 90, TimeUnit.SECONDS));
@@ -1,11 +1,6 @@
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.AgentHandler;
import com.tongran.agentserver.server.netty.model.Message;
import com.tongran.agentserver.server.netty.model.UpMsgResponse;
import com.tongran.agentserver.utils.AssertLog;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
@@ -33,20 +28,19 @@ public class DecoderHandler extends ChannelInboundHandlerAdapter {
ByteBuf byteBuf = (ByteBuf) msg;
String messages = byteBuf.toString(CharsetUtil.UTF_8); // 指定字符集解码
AssertLog.info("<<[up]:[up-content]==>{}", messages);
boolean startsWith = messages.startsWith("agent-server:");
boolean endsWith = messages.endsWith("@tong-ran");
if(startsWith && endsWith){
JSONObject jsonObject = JSONObject.parseObject(messages);
String clientId = jsonObject.getString("clientId");
String dataType = jsonObject.getString("dataType");
AgentHandler msgHandler = agentDispatcherManager.getHandler(dataType + "&" + AgentDispatcher.VersionEnum.V1.value);
UpMsgResponse response = msgHandler.upHandle(messages,clientId);
Message agentMessage = Message.builder().build();
agentMessage.setClientId(clientId);
agentMessage.setDataType(response.getDataType());
agentMessage.setData(response.getContent());
ctx.fireChannelRead(agentMessage);//传递到下一个handler
}
// JSONObject jsonObject = JSONObject.parseObject(messages);
// String clientId = jsonObject.getString("clientId");
// String dataType = jsonObject.getString("dataType");
// AgentHandler msgHandler = agentDispatcherManager.getHandler(dataType + "&" + AgentDispatcher.VersionEnum.V1.value);
// UpMsgResponse response = msgHandler.upHandle(messages,clientId);
// if(Objects.nonNull(response)){
// Message agentMessage = Message.builder().build();
// agentMessage.setClientId(clientId);
// agentMessage.setDataType(response.getDataType());
// agentMessage.setData(response.getContent());
// String json = "agent-tcp:"+ JSON.toJSONString(agentMessage)+"@tong-ran";
// ctx.fireChannelRead(json);//传递到下一个handler
// }
byteBuf.release(); // 释放 ByteBuf 资源(重要!)
} else {
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:
file:
path: /data/agent-server/logs
path: /usr/local/tongran/logs
netty:
server:
host: 127.0.0.1
host: 172.16.15.103
port: 6610
client:
client-id: client-001
+2 -2
View File
@@ -11,11 +11,11 @@ knife4j:
# 日志配置
logging:
file:
path: /data/agent-server/logs
path: /usr/local/tongran/logs
netty:
server:
host: 127.0.0.1
host: 172.16.15.103
port: 6610
client:
client-id: client-001