初始化
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
public interface AgentService {
|
||||
void systemCollectStart(String data);
|
||||
|
||||
void systemCollectStop();
|
||||
|
||||
void switchCollectStart(String data);
|
||||
|
||||
void switchCollectStop();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.CpuVO;
|
||||
|
||||
public interface CPUService {
|
||||
CpuVO get();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.DiskVO;
|
||||
import com.tongran.agent.client.core.vo.PointVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface DiskService {
|
||||
List<DiskVO> diskList(long timestamp);
|
||||
|
||||
List<PointVO> pointList(long timestamp);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.DockerVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface DockerService {
|
||||
List<DockerVO> dockerList(long timestamp);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.MemoryVO;
|
||||
|
||||
public interface MemoryService {
|
||||
MemoryVO get();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.NetVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface NetService {
|
||||
List<NetVO> netList(long timestamp);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.SwitchBoardVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface SwitchBoardService {
|
||||
List<SwitchBoardVO> switchBoardList(long timestamp);
|
||||
|
||||
String getSwitchDataByType(String type);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.tongran.agent.client.service;
|
||||
|
||||
import com.tongran.agent.client.core.vo.SystemVO;
|
||||
|
||||
public interface SystemService {
|
||||
SystemVO get();
|
||||
|
||||
String otherSystem(String type);
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.alibaba.fastjson2.TypeReference;
|
||||
import com.tongran.agent.client.core.config.GlobalConfig;
|
||||
import com.tongran.agent.client.core.eo.CollectEO;
|
||||
import com.tongran.agent.client.scheduler.service.BusinessTasks;
|
||||
import com.tongran.agent.client.scheduler.service.DynamicTaskService;
|
||||
import com.tongran.agent.client.service.AgentService;
|
||||
import com.tongran.agent.client.utils.AgentUtil;
|
||||
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 java.util.List;
|
||||
|
||||
@Service
|
||||
public class AgentServiceImpl implements AgentService {
|
||||
|
||||
private final DynamicTaskService dynamicTaskService;
|
||||
|
||||
private final BusinessTasks businessTasks;
|
||||
|
||||
// 在注入点使用@Lazy
|
||||
@Autowired
|
||||
public AgentServiceImpl(DynamicTaskService dynamicTaskService,
|
||||
@Lazy BusinessTasks businessTasks) {
|
||||
this.dynamicTaskService = dynamicTaskService;
|
||||
this.businessTasks = businessTasks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void systemCollectStart(String data) {
|
||||
//更改全局变量
|
||||
JSONObject jsonObject = JSONObject.parseObject(data);
|
||||
if(jsonObject.containsKey("collects")){
|
||||
String collects = jsonObject.getString("collects");
|
||||
List<CollectEO> configList = JSON.parseObject(collects, new TypeReference<List<CollectEO>>() {});
|
||||
for (CollectEO c : configList) {
|
||||
String type = c.getType();
|
||||
boolean collect = c.isCollect();
|
||||
switch(type) {
|
||||
case "cpuCollect": //cpu采集
|
||||
GlobalConfig.cpuCollect = collect;
|
||||
GlobalConfig.cpuInterval = c.getInterval();
|
||||
if(collect){
|
||||
long milli = AgentUtil.getMillisToNextMinute() + 60000;
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
businessTasks::cpuTask, milli, GlobalConfig.cpuInterval*1000L);
|
||||
}
|
||||
break;
|
||||
case "vfsCollect": //挂载采集
|
||||
GlobalConfig.vfsCollect = collect;
|
||||
GlobalConfig.vfsInterval = c.getInterval();
|
||||
if(collect){
|
||||
long milli = AgentUtil.getMillisToNextMinute() + 60000;
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
businessTasks::pointTask, milli, GlobalConfig.vfsInterval*1000L);
|
||||
}
|
||||
break;
|
||||
case "netCollect": //网络采集
|
||||
GlobalConfig.netCollect = collect;
|
||||
GlobalConfig.netInterval = c.getInterval();
|
||||
if(collect){
|
||||
long milli = AgentUtil.millisecondsToNext5Minute();
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
businessTasks::netTask, milli, GlobalConfig.netInterval*1000L);
|
||||
}
|
||||
break;
|
||||
case "diskCollect": //磁盘采集
|
||||
GlobalConfig.diskCollect = collect;
|
||||
GlobalConfig.diskInterval = c.getInterval();
|
||||
if(collect){
|
||||
long milli = AgentUtil.getMillisToNextMinute() + 60000;
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
businessTasks::diskTask, milli, GlobalConfig.diskInterval*1000L);
|
||||
}
|
||||
break;
|
||||
case "dockerCollect": //docker采集
|
||||
GlobalConfig.dockerCollect = collect;
|
||||
GlobalConfig.dockerInterval = c.getInterval();
|
||||
if(collect){
|
||||
long milli = AgentUtil.getMillisToNextMinute() + 60000;
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
businessTasks::dockerTask, milli, GlobalConfig.dockerInterval*1000L);
|
||||
}
|
||||
break;
|
||||
default: //系统其他采集
|
||||
if(StringUtils.equals(type, "systemSwapSizeFreeCollect")){
|
||||
GlobalConfig.systemSwapSizeFreeCollect = collect;
|
||||
GlobalConfig.systemSwapSizeFreeInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "memoryUtilizationCollect")){
|
||||
GlobalConfig.memoryUtilizationCollect = collect;
|
||||
GlobalConfig.memoryUtilizationInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemSwapSizePercentCollect")){
|
||||
GlobalConfig.systemSwapSizePercentCollect = collect;
|
||||
GlobalConfig.systemSwapSizePercentInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "memorySizeAvailableCollect")){
|
||||
GlobalConfig.memorySizeAvailableCollect = collect;
|
||||
GlobalConfig.memorySizeAvailableInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "memorySizePercentCollect")){
|
||||
GlobalConfig.memorySizePercentCollect = collect;
|
||||
GlobalConfig.memorySizePercentInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "memorySizeTotalCollect")){
|
||||
GlobalConfig.memorySizeTotalCollect = collect;
|
||||
GlobalConfig.memorySizeTotalInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemSwOsCollect")){
|
||||
GlobalConfig.systemSwOsCollect = collect;
|
||||
GlobalConfig.systemSwOsInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemSwArchCollect")){
|
||||
GlobalConfig.systemSwArchCollect = collect;
|
||||
GlobalConfig.systemSwArchInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "kernelMaxprocCollect")){
|
||||
GlobalConfig.kernelMaxprocCollect = collect;
|
||||
GlobalConfig.kernelMaxprocInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "procNumRunCollect")){
|
||||
GlobalConfig.procNumRunCollect = collect;
|
||||
GlobalConfig.procNumRunInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemUsersNumCollect")){
|
||||
GlobalConfig.systemUsersNumCollect = collect;
|
||||
GlobalConfig.systemUsersNumInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemDiskSizeTotalCollect")){
|
||||
GlobalConfig.systemDiskSizeTotalCollect = collect;
|
||||
GlobalConfig.systemDiskSizeTotalInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemBoottimeCollect")){
|
||||
GlobalConfig.systemBoottimeCollect = collect;
|
||||
GlobalConfig.systemBoottimeInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemUnameCollect")){
|
||||
GlobalConfig.systemUnameCollect = collect;
|
||||
GlobalConfig.systemUnameInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemLocaltimeCollect")){
|
||||
GlobalConfig.systemLocaltimeCollect = collect;
|
||||
GlobalConfig.systemLocaltimeInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "systemUptimeCollect")){
|
||||
GlobalConfig.systemUptimeCollect = collect;
|
||||
GlobalConfig.systemUptimeInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "procNumCollect")){
|
||||
GlobalConfig.procNumCollect = collect;
|
||||
GlobalConfig.procNumInterval = c.getInterval();
|
||||
}
|
||||
long milli = AgentUtil.getMillisToNextMinute() + 60000;
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
() -> businessTasks.systemTask(c.getType()), milli, c.getInterval()*1000L);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void systemCollectStop() {
|
||||
String[] arr = {"cpuCollect","vfsCollect","netCollect","diskCollect","dockerCollect","systemSwapSizeFreeCollect","memoryUtilizationCollect"
|
||||
,"systemSwapSizePercentCollect","memorySizeAvailableCollect","memorySizePercentCollect","memorySizeTotalCollect","systemSwOsCollect"
|
||||
,"systemSwArchCollect","kernelMaxprocCollect","procNumRunCollect","systemUsersNumCollect","systemDiskSizeTotalCollect","systemBoottimeCollect"
|
||||
,"systemUnameCollect","systemLocaltimeCollect","systemUptimeCollect","procNumCollect"};
|
||||
for (String taskId : arr) {
|
||||
dynamicTaskService.cancelTask(taskId);
|
||||
}
|
||||
/**
|
||||
* 系统监控
|
||||
*/
|
||||
GlobalConfig.cpuCollect = false; //cpu采集
|
||||
GlobalConfig.cpuInterval = 300; //cpu采集间隔
|
||||
GlobalConfig.vfsCollect = false; //挂载采集
|
||||
GlobalConfig.vfsInterval = 300; //挂载采集间隔
|
||||
GlobalConfig.netCollect = false; //网络采集
|
||||
GlobalConfig.netInterval = 300; //网络采集间隔
|
||||
GlobalConfig.diskCollect = false; //硬盘采集
|
||||
GlobalConfig.diskInterval = 300; //硬盘采集间隔
|
||||
GlobalConfig.dockerCollect = false; //docker采集
|
||||
GlobalConfig.dockerInterval = 300; //docker采集间隔
|
||||
/**
|
||||
* 系统其他监控
|
||||
*/
|
||||
GlobalConfig.systemSwapSizeFreeCollect = false; //交换卷/文件的可用空间(字节)采集
|
||||
GlobalConfig.systemSwapSizeFreeInterval = 300; //交换卷/文件的可用空间(字节)采集间隔
|
||||
GlobalConfig.memoryUtilizationCollect = false; //内存利用率采集
|
||||
GlobalConfig.memoryUtilizationInterval = 300; //内存利用率采集间隔
|
||||
GlobalConfig.systemSwapSizePercentCollect = false; //可用交换空间百分比采集
|
||||
GlobalConfig.systemSwapSizePercentInterval = 300; //可用交换空间百分比采集间隔
|
||||
GlobalConfig.memorySizeAvailableCollect = false; //可用内存采集
|
||||
GlobalConfig.memorySizeAvailableInterval = 300; //可用内存采集间隔
|
||||
GlobalConfig.memorySizePercentCollect = false; //可用内存百分比采集
|
||||
GlobalConfig.memorySizePercentInterval = 300; //可用内存百分比采集间隔
|
||||
GlobalConfig.memorySizeTotalCollect = false; //总内存采集
|
||||
GlobalConfig.memorySizeTotalInterval = 300; //总内存采集间隔
|
||||
GlobalConfig.systemSwOsCollect = false; //操作系统采集
|
||||
GlobalConfig.systemSwOsInterval = 300; //操作系统采集间隔
|
||||
GlobalConfig.systemSwArchCollect = false; //操作系统架构采集
|
||||
GlobalConfig.systemSwArchInterval = 300; //操作系统架构采集间隔
|
||||
GlobalConfig.kernelMaxprocCollect = false; //最大进程数采集
|
||||
GlobalConfig.kernelMaxprocInterval = 300; //最大进程数采集间隔
|
||||
GlobalConfig.procNumRunCollect = false; //正在运行的进程数采集
|
||||
GlobalConfig.procNumRunInterval = 300; //正在运行的进程数采集间隔
|
||||
GlobalConfig.systemUsersNumCollect = false; //登录用户数采集
|
||||
GlobalConfig.systemUsersNumInterval = 300; //登录用户数采集间隔
|
||||
GlobalConfig.systemDiskSizeTotalCollect = false; ///硬盘总可用空间采集
|
||||
GlobalConfig.systemDiskSizeTotalInterval = 300; //硬盘总可用空间采集间隔
|
||||
GlobalConfig.systemBoottimeCollect = false; //系统启动时间采集
|
||||
GlobalConfig.systemBoottimeInterval = 300; //系统启动时间采集间隔
|
||||
GlobalConfig.systemUnameCollect = false; //系统描述采集
|
||||
GlobalConfig.systemUnameInterval = 300; //系统描述采集间隔
|
||||
GlobalConfig.systemLocaltimeCollect = false; //系统本地时间采集
|
||||
GlobalConfig.systemLocaltimeInterval = 300; //系统本地时间采集间隔
|
||||
GlobalConfig.systemUptimeCollect = false; //系统正常运行时间采集
|
||||
GlobalConfig.systemUptimeInterval = 300; //系统正常运行时间采集间隔
|
||||
GlobalConfig.procNumCollect = false; //进程数采集
|
||||
GlobalConfig.procNumInterval = 300; //进程数采集间隔
|
||||
}
|
||||
|
||||
@Override
|
||||
public void switchCollectStart(String data) {
|
||||
//更改全局变量
|
||||
JSONObject jsonObject = JSONObject.parseObject(data);
|
||||
if(jsonObject.containsKey("collects")){
|
||||
String collects = jsonObject.getString("collects");
|
||||
List<CollectEO> configList = JSON.parseObject(collects, new TypeReference<List<CollectEO>>() {});
|
||||
for (CollectEO c : configList) {
|
||||
String type = c.getType();
|
||||
boolean collect = c.isCollect();
|
||||
switch(type) {
|
||||
case "switchNetCollect": //交换机网络采集
|
||||
GlobalConfig.switchNetCollect = collect;
|
||||
GlobalConfig.switchNetInterval = c.getInterval();
|
||||
break;
|
||||
case "switchModuleCollect": //光模块采集
|
||||
GlobalConfig.switchModuleCollect = collect;
|
||||
GlobalConfig.switchModuleInterval = c.getInterval();
|
||||
break;
|
||||
case "switchMpuCollect": //MPU采集
|
||||
GlobalConfig.switchMpuCollect = collect;
|
||||
GlobalConfig.switchMpuInterval = c.getInterval();
|
||||
break;
|
||||
case "switchPwrCollect": //电源采集
|
||||
GlobalConfig.switchPwrCollect = collect;
|
||||
GlobalConfig.switchPwrInterval = c.getInterval();
|
||||
break;
|
||||
case "dockerCollect": //风扇采集
|
||||
GlobalConfig.switchFanCollect = collect;
|
||||
GlobalConfig.switchFanInterval = c.getInterval();
|
||||
break;
|
||||
default: //系统其他采集
|
||||
if(StringUtils.equals(type, "switchSysDescrCollect")){
|
||||
GlobalConfig.switchSysDescrCollect = collect;
|
||||
GlobalConfig.switchSysDescrInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchSysObjectIDCollect")){
|
||||
GlobalConfig.switchSysObjectIDCollect = collect;
|
||||
GlobalConfig.switchSysObjectIDInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchSysUpTimeCollect")){
|
||||
GlobalConfig.switchSysUpTimeCollect = collect;
|
||||
GlobalConfig.switchSysUpTimeInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchSysContactCollect")){
|
||||
GlobalConfig.switchSysContactCollect = collect;
|
||||
GlobalConfig.switchSysContactInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchSysNameCollect")){
|
||||
GlobalConfig.switchSysNameCollect = collect;
|
||||
GlobalConfig.switchSysNameInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchSysLocationCollect")){
|
||||
GlobalConfig.switchSysLocationCollect = collect;
|
||||
GlobalConfig.switchSysLocationInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchHwStackSystemMacCollect")){
|
||||
GlobalConfig.switchHwStackSystemMacCollect = collect;
|
||||
GlobalConfig.switchHwStackSystemMacInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchEntIndexCollect")){
|
||||
GlobalConfig.switchEntIndexCollect = collect;
|
||||
GlobalConfig.switchEntIndexInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchEntPhysicalNameCollect")){
|
||||
GlobalConfig.switchEntPhysicalNameCollect = collect;
|
||||
GlobalConfig.switchEntPhysicalNameInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchEntPhysicalSoftwareRevCollect")){
|
||||
GlobalConfig.switchEntPhysicalSoftwareRevCollect = collect;
|
||||
GlobalConfig.switchEntPhysicalSoftwareRevInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchHwEntityCpuUsageCollect")){
|
||||
GlobalConfig.switchHwEntityCpuUsageCollect = collect;
|
||||
GlobalConfig.switchHwEntityCpuUsageInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchHwEntityMemUsageCollect")){
|
||||
GlobalConfig.switchHwEntityMemUsageCollect = collect;
|
||||
GlobalConfig.switchHwEntityMemUsageInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchHwAveragePowerCollect")){
|
||||
GlobalConfig.switchHwAveragePowerCollect = collect;
|
||||
GlobalConfig.switchHwAveragePowerInterval = c.getInterval();
|
||||
}
|
||||
if(StringUtils.equals(type, "switchHwCurrentPowerCollect")){
|
||||
GlobalConfig.switchHwCurrentPowerCollect = collect;
|
||||
GlobalConfig.switchHwCurrentPowerInterval = c.getInterval();
|
||||
}
|
||||
break;
|
||||
}
|
||||
if(collect){
|
||||
long milli = AgentUtil.millisecondsToNext5Minute();
|
||||
dynamicTaskService.scheduleTask(c.getType(),
|
||||
() -> businessTasks.switchBoardTask(c.getType()), milli, GlobalConfig.switchNetInterval*1000L);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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)采集间隔
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.tongran.agent.client.core.vo.CpuVO;
|
||||
import com.tongran.agent.client.service.CPUService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import oshi.SystemInfo;
|
||||
import oshi.hardware.CentralProcessor;
|
||||
import oshi.hardware.HardwareAbstractionLayer;
|
||||
import oshi.software.os.OperatingSystem;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class CPUServiceImpl implements CPUService {
|
||||
|
||||
@Override
|
||||
public CpuVO get() {
|
||||
CpuVO cpuVO = CpuVO.builder().build();
|
||||
try {
|
||||
SystemInfo si = new SystemInfo();
|
||||
HardwareAbstractionLayer hal = si.getHardware();
|
||||
CentralProcessor processor = hal.getProcessor();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
System.out.println("=========================================================");
|
||||
// 1. CPU基本信息
|
||||
cpuVO.setNum(processor.getPhysicalProcessorCount()); // CUP数量
|
||||
System.out.println("=== CPU基本信息 ===");
|
||||
System.out.println("CPU型号: " + processor.getProcessorIdentifier().getName());
|
||||
System.out.println("物理核心数: " + processor.getPhysicalProcessorCount());
|
||||
System.out.println("逻辑核心数: " + processor.getLogicalProcessorCount());
|
||||
System.out.println("最大频率: " + processor.getMaxFreq() / 1_000_000.0 + " GHz");
|
||||
// 2. CPU负载信息
|
||||
System.out.println("\n=== CPU负载信息 ===");
|
||||
double[] loadAverage = processor.getSystemLoadAverage(3);
|
||||
cpuVO.setAvg1(loadAverage[0]);// CUP1分钟负载
|
||||
cpuVO.setAvg1(loadAverage[1]);// CUP5分钟负载
|
||||
cpuVO.setAvg1(loadAverage[2]);// CUP15分钟负载
|
||||
System.out.println("1分钟平均负载: " + loadAverage[0]);
|
||||
System.out.println("5分钟平均负载: " + loadAverage[1]);
|
||||
System.out.println("15分钟平均负载: " + loadAverage[2]);
|
||||
// 3. CPU使用率(需要两次采样)
|
||||
System.out.println("\n=== CPU使用率 ===");
|
||||
long[] prevTicks = processor.getSystemCpuLoadTicks();
|
||||
TimeUnit.SECONDS.sleep(1); // 等待1秒
|
||||
// 计算使用率
|
||||
double cpuUsage = processor.getSystemCpuLoadBetweenTicks(prevTicks);
|
||||
cpuVO.setUti(cpuUsage * 100); // CPU使用率
|
||||
System.out.printf("CPU 使用率: %.2f%%\n", cpuUsage * 100);
|
||||
long[] ticks = processor.getSystemCpuLoadTicks();
|
||||
long user = ticks[CentralProcessor.TickType.USER.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.USER.getIndex()];
|
||||
long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.NICE.getIndex()];
|
||||
long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
|
||||
long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
|
||||
long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
|
||||
long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
|
||||
long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
|
||||
long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] -
|
||||
prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
|
||||
long total = user + nice + sys + idle + iowait + irq + softirq + steal;
|
||||
// 4. CPU时间累计值
|
||||
System.out.println("\n=== CPU时间累计值 ===");
|
||||
long[] allTicks = processor.getSystemCpuLoadTicks();
|
||||
System.out.println("中断累计时间: " +
|
||||
(allTicks[CentralProcessor.TickType.IRQ.getIndex()] +
|
||||
allTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]));
|
||||
System.out.println("空闲累计时间: " + allTicks[CentralProcessor.TickType.IDLE.getIndex()]);
|
||||
System.out.printf("I/O等待时间(CPU等待响应时间): %.2f%%\n", 100d * iowait / total);
|
||||
System.out.println("系统累计时间: " + allTicks[CentralProcessor.TickType.SYSTEM.getIndex()]);
|
||||
long softwareTime = sys - irq - softirq;
|
||||
System.out.printf("软件相关时间(近似无响应时间): %.2f%%\n", 100d * softwareTime / total);
|
||||
System.out.println("用户进程累计时间: " + allTicks[CentralProcessor.TickType.USER.getIndex()]);
|
||||
|
||||
cpuVO.setInterrupt((allTicks[CentralProcessor.TickType.IRQ.getIndex()] +
|
||||
allTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()])); // CPU硬件中断提供服务时间
|
||||
cpuVO.setIdle(allTicks[CentralProcessor.TickType.IDLE.getIndex()]);// CPU空闲时间
|
||||
cpuVO.setIowait(100d * iowait / total);// CPU等待响应时间
|
||||
cpuVO.setSystem(allTicks[CentralProcessor.TickType.SYSTEM.getIndex()]);// CPU系统时间
|
||||
cpuVO.setNoresp(100d * softwareTime / total);// CPU软件无响应时间
|
||||
cpuVO.setUser(allTicks[CentralProcessor.TickType.USER.getIndex()]);// CPU用户进程所花费的时间
|
||||
|
||||
// 5. 系统运行时间和CPU空闲时间
|
||||
long uptime = os.getSystemUptime();
|
||||
cpuVO.setNormal(uptime);// CPU正常运行时间
|
||||
System.out.println("CPU正常运行时间: " + cpuVO.getNormal());
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return cpuVO;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.tongran.agent.client.core.vo.DiskVO;
|
||||
import com.tongran.agent.client.core.vo.PointVO;
|
||||
import com.tongran.agent.client.service.DiskService;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import oshi.SystemInfo;
|
||||
import oshi.hardware.HWDiskStore;
|
||||
import oshi.software.os.OSFileStore;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class DiskServiceImpl implements DiskService {
|
||||
@Override
|
||||
public List<DiskVO> diskList(long timestamp) {
|
||||
List<DiskVO> tempList = new ArrayList<>();
|
||||
List<DiskVO> resultList = new ArrayList<>();
|
||||
SystemInfo si = new SystemInfo();
|
||||
System.out.println("=========================================================");
|
||||
// 获取磁盘IO信息
|
||||
System.out.println("\n=== 磁盘IO信息 ===");
|
||||
for (HWDiskStore disk : si.getHardware().getDiskStores()) {
|
||||
DiskVO diskVO = DiskVO.builder().timestamp(timestamp).build();
|
||||
diskVO.setName(disk.getName());//磁盘名称
|
||||
diskVO.setSerial(disk.getSerial());//序列号
|
||||
diskVO.setTotal(disk.getSize());//磁盘大小
|
||||
diskVO.setWriteTimes(disk.getWrites());//磁盘写入次数
|
||||
diskVO.setReadTimes(disk.getReads());//磁盘读取次数
|
||||
diskVO.setWriteBytes(disk.getReadBytes());//磁盘写入字节
|
||||
diskVO.setReadBytes(disk.getWriteBytes());//磁盘读取字节
|
||||
tempList.add(diskVO);
|
||||
|
||||
System.out.println("磁盘名称: " + diskVO.getName());
|
||||
System.out.println("序列号: " + diskVO.getSerial());
|
||||
System.out.println("磁盘大小: " + diskVO.getTotal());
|
||||
System.out.println("磁盘写入次数: " + diskVO.getWriteTimes());
|
||||
System.out.println("磁盘读取次数: " + diskVO.getReadTimes());
|
||||
System.out.println("磁盘写入字节: " + diskVO.getWriteBytes());
|
||||
System.out.println("磁盘读取字节: " + diskVO.getReadBytes());
|
||||
}
|
||||
try{
|
||||
// 第一次采样
|
||||
List<HWDiskStore> disks1 = si.getHardware().getDiskStores();
|
||||
long[] readBytes1 = new long[disks1.size()];
|
||||
long[] writeBytes1 = new long[disks1.size()];
|
||||
for (int i = 0; i < disks1.size(); i++) {
|
||||
readBytes1[i] = disks1.get(i).getReadBytes();
|
||||
writeBytes1[i] = disks1.get(i).getWriteBytes();
|
||||
}
|
||||
// 等待1秒
|
||||
Thread.sleep(1000);
|
||||
// 第二次采样
|
||||
List<HWDiskStore> disks2 = si.getHardware().getDiskStores();
|
||||
for (int i = 0; i < disks2.size(); i++) {
|
||||
long readDiff = disks2.get(i).getReadBytes() - readBytes1[i];
|
||||
long writeDiff = disks2.get(i).getWriteBytes() - writeBytes1[i];
|
||||
String serial = disks2.get(i).getSerial();
|
||||
DiskVO diskVO = tempList.stream().filter(d -> StringUtils.equals(d.getSerial(),serial)).findFirst().orElse(null);
|
||||
if(Objects.nonNull(diskVO)){
|
||||
diskVO.setWriteSpeed(readDiff);//磁盘写入速率
|
||||
diskVO.setReadSpeed(writeDiff);//磁盘读取速率
|
||||
System.out.println("磁盘名称: " + diskVO.getName());
|
||||
System.out.println("磁盘写入速率: " + diskVO.getWriteSpeed());
|
||||
System.out.println("磁盘读取速率: " + diskVO.getReadSpeed());
|
||||
}
|
||||
resultList.add(diskVO);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PointVO> pointList(long timestamp) {
|
||||
List<PointVO> list = new ArrayList<>();
|
||||
SystemInfo si = new SystemInfo();
|
||||
// 获取文件系统信息
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("=== 挂载信息 ===");
|
||||
for (OSFileStore fs : si.getOperatingSystem().getFileSystem().getFileStores()) {
|
||||
long totalSpace = fs.getTotalSpace();
|
||||
long usableSpace = fs.getUsableSpace();
|
||||
long freeSpace = fs.getFreeSpace();
|
||||
double usagePercentage = totalSpace > 0 ?
|
||||
(double) (totalSpace - freeSpace) / totalSpace * 100 : 0;
|
||||
|
||||
PointVO pointVO = PointVO.builder().timestamp(timestamp).build();
|
||||
pointVO.setMount(fs.getMount());//挂载点
|
||||
pointVO.setVfsType(fs.getType());//文件系统类型
|
||||
pointVO.setVfsTotal(totalSpace);//总空间
|
||||
pointVO.setVfsFree(usableSpace);//可用空间
|
||||
pointVO.setVfsUtil(usagePercentage);//空间利用率
|
||||
list.add(pointVO);
|
||||
System.out.println("挂载点: " + pointVO.getMount());
|
||||
System.out.println("文件系统类型: " + pointVO.getVfsType());
|
||||
System.out.println("总空间: " + pointVO.getVfsTotal());
|
||||
System.out.println("可用空间: " + pointVO.getVfsFree());
|
||||
System.out.printf("空间利用率: %.2f%%\n", usagePercentage);
|
||||
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientImpl;
|
||||
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import com.tongran.agent.client.core.vo.DockerVO;
|
||||
import com.tongran.agent.client.service.DockerService;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class DockerServiceImpl implements DockerService {
|
||||
@Override
|
||||
public List<DockerVO> dockerList(long timestamp) {
|
||||
List<DockerVO> list = new ArrayList<>();
|
||||
// 配置Docker客户端
|
||||
DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withDockerHost("unix:///var/run/docker.sock")
|
||||
.withDockerTlsVerify(false) // 根据你的配置调整
|
||||
.build();
|
||||
|
||||
DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
|
||||
.dockerHost(config.getDockerHost())
|
||||
.sslConfig(config.getSSLConfig())
|
||||
.maxConnections(100)
|
||||
.connectionTimeout(Duration.ofSeconds(30))
|
||||
.responseTimeout(Duration.ofSeconds(45))
|
||||
.build();
|
||||
|
||||
DockerClient dockerClient = DockerClientImpl.getInstance(config, httpClient);
|
||||
try {
|
||||
// 获取正在运行的容器列表
|
||||
List<Container> containers = dockerClient.listContainersCmd()
|
||||
.withShowAll(false) // 只显示运行中的容器
|
||||
.exec();
|
||||
|
||||
// 打印容器信息
|
||||
System.out.println("运行中的Docker容器:");
|
||||
System.out.println("容器ID\t\t镜像\t\t状态\t\t名称");
|
||||
for (Container container : containers) {
|
||||
DockerVO dockerVO = DockerVO.builder().timestamp(timestamp).build();
|
||||
String id = container.getId().substring(0, 12); // 只显示短ID
|
||||
String image = container.getImage().length() > 15 ?
|
||||
container.getImage().substring(0, 15) + "..." : container.getImage();
|
||||
String status = container.getStatus();
|
||||
String name = container.getNames()[0].replaceFirst("/", "");
|
||||
System.out.printf("%s\t%s\t%s\t%s%n", id, image, status, name);
|
||||
dockerVO.setId(id);
|
||||
dockerVO.setName(name);
|
||||
dockerVO.setStatus(status);
|
||||
DockerVO res = dockerStats(dockerVO);
|
||||
list.add(res);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
dockerClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public DockerVO dockerStats(DockerVO dockerVO) {
|
||||
//判定目标容器 ID
|
||||
if(StringUtils.isBlank(dockerVO.getId())){
|
||||
return dockerVO;
|
||||
}
|
||||
try {
|
||||
// 执行 docker stats 命令(--no-stream 表示只输出一次)
|
||||
Process process = new ProcessBuilder(
|
||||
"docker", "stats", "--no-stream", dockerVO.getId(),
|
||||
"--format", "'table {{.ID}}\t{{.Name}}\t{{.CPUPerc}}\t{{.MemPerc}}\t{{.NetIO}}"
|
||||
).start();
|
||||
// 读取命令输出
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream())
|
||||
);
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
// 解析输出(示例输出格式):
|
||||
// "your_container_id 0.00% 0.000 CPU % 0 B / 0 B 0 packets / 0 packets"
|
||||
// 实际输出可能因 Docker 版本不同而变化,需根据实际情况调整正则表达式
|
||||
if (line.contains(dockerVO.getId())) {
|
||||
String[] parts = line.trim().split("\\s+");
|
||||
String cpuUtil = parts[3]; // cpu使用率
|
||||
String memUtil = parts[4]; // 内存使用率
|
||||
// 网络流量通常在第 4 列(接收)和第 5 列(发送),格式为 "B/s" 或 "B"
|
||||
dockerVO.setCpuUtil(cpuUtil);
|
||||
String rxRate = "0B";// 接收速率(如 "1.23kB/s")
|
||||
String txRate = "0B";// 发送速率(如 "4.56kB/s")
|
||||
//数据间有空格
|
||||
if(parts.length > 9){
|
||||
rxRate = parts[5]+parts[6];
|
||||
txRate = parts[8]+parts[9];
|
||||
}else{
|
||||
rxRate = parts[5];
|
||||
txRate = parts[7];
|
||||
|
||||
}
|
||||
// 网络流量通常在第 4 列(接收)和第 5 列(发送),格式为 "B/s" 或 "B"
|
||||
dockerVO.setCpuUtil(cpuUtil);
|
||||
dockerVO.setMemUtil(memUtil);
|
||||
dockerVO.setNetInSpeed(rxRate);
|
||||
dockerVO.setNetOutSpeed(txRate);
|
||||
|
||||
System.out.println("==================== 容器网络流量 ====================");
|
||||
System.out.println("接收速率: " + rxRate);
|
||||
System.out.println("发送速率: " + txRate);
|
||||
}
|
||||
}
|
||||
// 等待命令执行完成并获取退出码
|
||||
int exitCode = process.waitFor();
|
||||
if (exitCode != 0) {
|
||||
System.err.println("命令执行失败,退出码: " + exitCode);
|
||||
}
|
||||
reader.close();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return dockerVO;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.tongran.agent.client.core.vo.MemoryVO;
|
||||
import com.tongran.agent.client.service.MemoryService;
|
||||
import com.tongran.agent.client.utils.AgentDataUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class MemoryServiceImpl implements MemoryService {
|
||||
@Override
|
||||
public MemoryVO get() {
|
||||
MemoryVO memoryVO = MemoryVO.builder().build();
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
System.out.println("=========================================================");
|
||||
// 1. 基本内存信息
|
||||
System.out.println("=== 基本内存信息 (单位KB) ===");
|
||||
System.out.println("总内存: " + memInfo.get("MemTotal"));
|
||||
System.out.println("空闲内存: " + memInfo.get("MemFree"));
|
||||
System.out.println("可用内存: " +
|
||||
memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L)));
|
||||
memoryVO.setAvailable(memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L))); //可用内存
|
||||
memoryVO.setTotal(memInfo.get("MemTotal")); //总内存
|
||||
memoryVO.setPercent((double) memoryVO.getAvailable() / memoryVO.getTotal() * 100); //可用内存百分比
|
||||
// 3. 交换空间信息
|
||||
System.out.println("\n=== 交换空间信息 ===");
|
||||
long swapTotal = memInfo.getOrDefault("SwapTotal", 0L);
|
||||
long swapFree = memInfo.getOrDefault("SwapFree", 0L);
|
||||
System.out.println("总交换空间: " + swapTotal);
|
||||
System.out.println("空闲交换空间: " + swapFree);
|
||||
System.out.println("已用交换空间: " + (swapTotal - swapFree));
|
||||
memoryVO.setSwapSizeFree(swapFree); //交换卷/文件的可用空间(字节)
|
||||
memoryVO.setSwapSizePercent((double) swapFree / swapTotal * 100); //可用交换空间百分比
|
||||
if (swapTotal > 0) {
|
||||
System.out.printf("交换空间使用率: %.2f%%\n",
|
||||
(double)(swapTotal - swapFree) / swapTotal * 100);
|
||||
}
|
||||
// 4. 内存使用率分析
|
||||
System.out.println("\n=== 内存使用率分析 ===");
|
||||
long total = memInfo.get("MemTotal");
|
||||
long available = memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L));
|
||||
// 总内存使用率
|
||||
double totalUsage = (double)(total - available) / total * 100;
|
||||
System.out.printf("总内存使用率: %.2f%%\n", totalUsage);
|
||||
// 实际内存使用率
|
||||
long cached = memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L);
|
||||
long buffers = memInfo.getOrDefault("Buffers", 0L);
|
||||
double actualUsage = (double)(total - available - cached - buffers) / total * 100;
|
||||
System.out.printf("实际内存使用率: %.2f%%\n", actualUsage);
|
||||
memoryVO.setUntilzation(actualUsage); //内存利用率
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return memoryVO;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.tongran.agent.client.core.vo.NetVO;
|
||||
import com.tongran.agent.client.service.NetService;
|
||||
import com.tongran.agent.client.utils.AgentUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
import oshi.SystemInfo;
|
||||
import oshi.hardware.HardwareAbstractionLayer;
|
||||
import oshi.hardware.NetworkIF;
|
||||
import oshi.util.FormatUtil;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class NetServiceImpl implements NetService {
|
||||
@Override
|
||||
public List<NetVO> netList(long timestamp) {
|
||||
List<NetVO> list = new ArrayList<>();
|
||||
try {
|
||||
SystemInfo si = new SystemInfo();
|
||||
HardwareAbstractionLayer hal = si.getHardware();
|
||||
// 获取所有网络接口
|
||||
List<NetworkIF> networkIFs = hal.getNetworkIFs();
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("===== 网卡流量统计 =====");
|
||||
List<NetVO> temp = new ArrayList<>();
|
||||
for (NetworkIF net : networkIFs) {
|
||||
System.out.println("接口名称: " + net.getName()+"("+net.getDisplayName()+")");
|
||||
System.out.println("MAC地址: " + net.getMacaddr());
|
||||
System.out.print("运行状态: ");
|
||||
System.out.println(net.isConnectorPresent() ? "已连接" : "未连接");
|
||||
System.out.println("接口类型: " + AgentUtil.getInterfaceType(net));
|
||||
System.out.println("IPv4地址: " + String.join(", ", net.getIPv4addr()));
|
||||
|
||||
NetVO netVO = NetVO.builder().build();
|
||||
netVO.setName(net.getName()+"("+net.getDisplayName()+")");//网卡名称
|
||||
netVO.setMac(net.getMacaddr());//MAC
|
||||
netVO.setStatus(net.isConnectorPresent() ? "已连接" : "未连接");//运行状态
|
||||
netVO.setType(AgentUtil.getInterfaceType(net));//接口类型
|
||||
netVO.setIpV4(String.join(", ", net.getIPv4addr()));//IPv4
|
||||
Map<String, String> map = getNetworkMode(net.getName());
|
||||
if (map != null && !map.isEmpty()) {
|
||||
netVO.setSpeed(map.get("speed"));
|
||||
netVO.setDuplex(map.get("duplex"));
|
||||
}
|
||||
temp.add(netVO);
|
||||
}
|
||||
// 2. 实时带宽监控(需要两次采样)
|
||||
System.out.println("\n=== 实时带宽监控 ===");
|
||||
// 第一次采样
|
||||
for (NetworkIF net : networkIFs) {
|
||||
net.updateAttributes();
|
||||
}
|
||||
// 等待1秒
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
|
||||
// 第二次采样并计算速率
|
||||
for (NetworkIF net : networkIFs) {
|
||||
long prevBytesRecv = net.getBytesRecv();
|
||||
long prevBytesSent = net.getBytesSent();
|
||||
net.updateAttributes();
|
||||
long bytesRecv = net.getBytesRecv() - prevBytesRecv;
|
||||
long bytesSent = net.getBytesSent() - prevBytesSent;
|
||||
System.out.println("接口: " + net.getName());
|
||||
System.out.println("入站丢包: " + net.getInDrops());
|
||||
System.out.println("出站丢包: " + net.getCollisions());
|
||||
System.out.println("接收带宽: " + FormatUtil.formatBytes(bytesRecv) + "/s (" +
|
||||
bytesToMbps(bytesRecv) + " Mbps)");
|
||||
System.out.println("发送带宽: " + FormatUtil.formatBytes(bytesSent) + "/s (" +
|
||||
bytesToMbps(bytesSent) + " Mbps)");
|
||||
|
||||
NetVO netVO = temp.stream().filter(n -> n.getIpV4().equals(String.join(", ", net.getIPv4addr()))
|
||||
&& n.getMac().equals(net.getMacaddr())).findFirst().orElse(null);
|
||||
if(Objects.nonNull(netVO)){
|
||||
netVO.setInDropped(net.getInDrops());//入站丢包
|
||||
netVO.setOutDropped(net.getCollisions());//出站丢包
|
||||
netVO.setInSpeed(bytesRecv);//接收流量
|
||||
netVO.setOutSpeed(bytesSent);//发送流量
|
||||
netVO.setTimestamp(timestamp);
|
||||
list.add(netVO);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static double bytesToMbps(long bytes) {
|
||||
return bytes * 8.0 / 1_000_000; // bytes to megabits
|
||||
}
|
||||
|
||||
public static Map<String, String> getNetworkMode(String interfaceName) {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
ProcessBuilder pb = new ProcessBuilder("ethtool", interfaceName);
|
||||
pb.redirectErrorStream(true);
|
||||
try {
|
||||
Process process = pb.start();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
String line;
|
||||
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (line.contains("Speed:")) {
|
||||
result.put("speed", line.split(":")[1].trim());
|
||||
} else if (line.contains("Duplex:")) {
|
||||
result.put("duplex", line.split(":")[1].trim());
|
||||
} else if (line.contains("Auto-negotiation:")) {
|
||||
result.put("auto-negotiation", line.split(":")[1].trim());
|
||||
}
|
||||
}
|
||||
int exitCode = process.waitFor();
|
||||
if (exitCode != 0) {
|
||||
result.put("error", "ethtool command failed with exit code " + exitCode);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
result.put("error", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
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 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;
|
||||
|
||||
@Service
|
||||
public class SwitchBoardServiceImpl implements SwitchBoardService {
|
||||
@Override
|
||||
public List<SwitchBoardVO> switchBoardList(long timestamp) {
|
||||
List<SwitchBoardVO> list = new ArrayList<>();
|
||||
System.out.println("==================== 交换机流量信息 ====================");
|
||||
try {
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
|
||||
// 3. 获取交换机基本信息
|
||||
getSystemInfo(snmp, target);
|
||||
|
||||
// 4. 获取接口信息
|
||||
list = getInterfaceInfo(snmp, target, timestamp);
|
||||
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwitchDataByType(String type) {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("type",type);
|
||||
switch(type){
|
||||
case "switchNetCollect":
|
||||
json.put("value",handleSwitchNet());
|
||||
break;
|
||||
case "switchModuleCollect":
|
||||
json.put("value",handleSwitchModule());
|
||||
break;
|
||||
case "switchMpuCollect":
|
||||
json.put("value",handleSwitchMpu());
|
||||
break;
|
||||
case "switchPwrCollect":
|
||||
json.put("value",handleSwitchPwr());
|
||||
break;
|
||||
case "switchFanCollect":
|
||||
json.put("value",handleSwitchFan());
|
||||
break;
|
||||
default:
|
||||
json.put("value",handleSwitchOther(type));
|
||||
break;
|
||||
}
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
private String handleSwitchNet(){
|
||||
System.out.println("==================== 交换机网络信息 ====================");
|
||||
String result = "";
|
||||
try {
|
||||
if(GlobalConfig.SWITCH_NET_OID.isEmpty()){
|
||||
return result;
|
||||
}
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
result = getInterfaceInfoByType(snmp, target, "switchNet", GlobalConfig.SWITCH_NET_OID);
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String handleSwitchModule(){
|
||||
System.out.println("==================== 交换机光模块信息 ====================");
|
||||
String result = "";
|
||||
try {
|
||||
if(GlobalConfig.SWITCH_MODULE_OID.isEmpty()){
|
||||
return result;
|
||||
}
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
result = getInterfaceInfoByType(snmp, target, "switchModule", GlobalConfig.SWITCH_MODULE_OID);
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String handleSwitchMpu(){
|
||||
System.out.println("==================== 交换机MPU信息 ====================");
|
||||
String result = "";
|
||||
try {
|
||||
if(GlobalConfig.SWITCH_MPU_OID.isEmpty()){
|
||||
return result;
|
||||
}
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
result = getInterfaceInfoByType(snmp, target, "switchMpu", GlobalConfig.SWITCH_MPU_OID);
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String handleSwitchPwr(){
|
||||
System.out.println("==================== 交换机电源信息 ====================");
|
||||
String result = "";
|
||||
try {
|
||||
if(GlobalConfig.SWITCH_PWR_OID.isEmpty()){
|
||||
return result;
|
||||
}
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
result = getInterfaceInfoByType(snmp, target, "switchPwr", GlobalConfig.SWITCH_PWR_OID);
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String handleSwitchFan(){
|
||||
System.out.println("==================== 交换机风扇信息 ====================");
|
||||
String result = "";
|
||||
try {
|
||||
if(GlobalConfig.SWITCH_FAN_OID.isEmpty()){
|
||||
return result;
|
||||
}
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
result = getInterfaceInfoByType(snmp, target, "switchFan", GlobalConfig.SWITCH_FAN_OID);
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String handleSwitchOther(String type){
|
||||
System.out.println("==================== 交换机系统其他信息 ====================");
|
||||
String result = "";
|
||||
try {
|
||||
if(GlobalConfig.SWITCH_OTHER_OID.isEmpty()){
|
||||
return result;
|
||||
}
|
||||
// 1. 创建传输映射
|
||||
TransportMapping transport = new DefaultUdpTransportMapping();
|
||||
Snmp snmp = new Snmp(transport);
|
||||
transport.listen();
|
||||
// 2. 创建目标对象
|
||||
CommunityTarget target = new CommunityTarget();
|
||||
target.setCommunity(new OctetString(GlobalConfig.SWITCH_COMMUNITY));
|
||||
target.setAddress(GenericAddress.parse("udp:" + GlobalConfig.SWITCH_IP + "/" + GlobalConfig.SWITCH_PORT));
|
||||
target.setRetries(2);
|
||||
target.setTimeout(5000);
|
||||
target.setVersion(SnmpConstants.version2c);
|
||||
result = getInterfaceInfoByType(snmp, target, type, GlobalConfig.SWITCH_OTHER_OID);
|
||||
snmp.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void getSystemInfo(Snmp snmp, Target target) throws IOException {
|
||||
// 系统描述 OID
|
||||
String[] systemOIDs = {
|
||||
"1.3.6.1.2.1.1.1.0", // sysDescr
|
||||
"1.3.6.1.2.1.1.5.0", // sysName
|
||||
"1.3.6.1.2.1.1.6.0", // sysLocation
|
||||
"1.3.6.1.2.1.1.4.0", // sysContact
|
||||
"1.3.6.1.2.1.1.3.0" // sysUpTime
|
||||
};
|
||||
|
||||
PDU pdu = new PDU();
|
||||
for (String oid : systemOIDs) {
|
||||
pdu.add(new VariableBinding(new OID(oid)));
|
||||
}
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
ResponseEvent event = snmp.send(pdu, target);
|
||||
if (event != null && event.getResponse() != null) {
|
||||
System.out.println("\n=== 交换机基本信息 ===");
|
||||
for (VariableBinding vb : event.getResponse().getVariableBindings()) {
|
||||
System.out.printf("%-30s: %s%n",
|
||||
getOIDDescription(vb.getOid().toString()),
|
||||
vb.getVariable());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<SwitchBoardVO> getInterfaceInfo(Snmp snmp, Target target, long timestamp) throws IOException {
|
||||
// 获取接口数量
|
||||
String ifNumberOID = "1.3.6.1.2.1.2.1.0";
|
||||
PDU pdu = new PDU();
|
||||
pdu.add(new VariableBinding(new OID(ifNumberOID)));
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
ResponseEvent event = snmp.send(pdu, target);
|
||||
if (event == null || event.getResponse() == null) {
|
||||
System.err.println("无法获取接口数量");
|
||||
return null;
|
||||
}
|
||||
|
||||
int ifNumber = event.getResponse().get(0).getVariable().toInt();
|
||||
System.out.println("\n=== 接口数量: " + ifNumber + " ===");
|
||||
|
||||
// 获取每个接口的信息
|
||||
String[] ifOIDs = {
|
||||
"1.3.6.1.2.1.2.2.1.2", // ifDescr
|
||||
"1.3.6.1.2.1.2.2.1.3", // ifType
|
||||
"1.3.6.1.2.1.2.2.1.5", // ifSpeed
|
||||
"1.3.6.1.2.1.2.2.1.8", // ifOperStatus
|
||||
"1.3.6.1.2.1.31.1.1.1.6", // ifInOctets
|
||||
"1.3.6.1.2.1.31.1.1.1.10" // ifOutOctets
|
||||
// "1.3.6.1.2.1.2.2.1.10", // ifInOctets
|
||||
// "1.3.6.1.2.1.2.2.1.16" // ifOutOctets
|
||||
};
|
||||
System.out.printf("%-5s %-15s %-10s %-15s %-8s %-12s %-12s%n",
|
||||
"Index", "Name", "Type", "Speed", "Status", "InBytes", "OutBytes");
|
||||
List<SwitchBoardVO> list = new ArrayList<>();
|
||||
for (int i = 1; i <= ifNumber; i++) {
|
||||
pdu = new PDU();
|
||||
for (String baseOID : ifOIDs) {
|
||||
pdu.add(new VariableBinding(new OID(baseOID + "." + i)));
|
||||
}
|
||||
pdu.setType(PDU.GET);
|
||||
|
||||
event = snmp.send(pdu, target);
|
||||
if (event != null && event.getResponse() != null) {
|
||||
VariableBinding[] vbs = event.getResponse().getVariableBindings().toArray(new VariableBinding[0]);
|
||||
String ifName = vbs[0].getVariable().toString();
|
||||
String ifType = getInterfaceType(vbs[1].getVariable().toInt());
|
||||
String speed = formatSpeed(vbs[2].getVariable().toInt());
|
||||
String status = getOperStatus(vbs[3].getVariable().toInt());
|
||||
long inBytes = vbs[4].getVariable().toLong();
|
||||
long outBytes = vbs[5].getVariable().toLong();
|
||||
SwitchBoardVO boardVO = SwitchBoardVO.builder()
|
||||
.name(ifName)
|
||||
.switchIp(GlobalConfig.SWITCH_IP)
|
||||
.type(ifType)
|
||||
.status(status)
|
||||
.inBytes(inBytes)
|
||||
.outBytes(outBytes)
|
||||
.timestamp(timestamp)
|
||||
.build();
|
||||
list.add(boardVO);
|
||||
System.out.printf("%-5d %-15s %-10s %-15s %-8s %-12d %-12d%n",
|
||||
i, ifName, ifType, speed, status, inBytes, outBytes);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// 辅助方法
|
||||
private static String getOIDDescription(String oid) {
|
||||
switch(oid) {
|
||||
case "1.3.6.1.2.1.1.1.0": return "系统描述";
|
||||
case "1.3.6.1.2.1.1.5.0": return "系统名称";
|
||||
case "1.3.6.1.2.1.1.6.0": return "物理位置";
|
||||
case "1.3.6.1.2.1.1.4.0": return "联系人";
|
||||
case "1.3.6.1.2.1.1.3.0": return "运行时间";
|
||||
default: return oid;
|
||||
}
|
||||
}
|
||||
|
||||
private static String getInterfaceType(int type) {
|
||||
switch(type) {
|
||||
case 6: return "Ethernet";
|
||||
case 23: return "PPP";
|
||||
case 24: return "Loopback";
|
||||
case 53: return "VLAN";
|
||||
case 131: return "Tunnel";
|
||||
default: return "其他("+type+")";
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatSpeed(int speed) {
|
||||
if (speed >= 1000000000) {
|
||||
return (speed / 1000000000) + " Gbps";
|
||||
} else if (speed >= 1000000) {
|
||||
return (speed / 1000000) + " Mbps";
|
||||
} else if (speed >= 1000) {
|
||||
return (speed / 1000) + " Kbps";
|
||||
}
|
||||
return speed + " bps";
|
||||
}
|
||||
|
||||
private static String getOperStatus(int status) {
|
||||
switch(status) {
|
||||
case 1: return "Up";
|
||||
case 2: return "Down";
|
||||
case 3: return "Testing";
|
||||
case 4: return "Unknown";
|
||||
case 5: return "Dormant";
|
||||
case 6: return "NotPresent";
|
||||
case 7: return "LowerLayerDown";
|
||||
default: return "未知";
|
||||
}
|
||||
}
|
||||
|
||||
private static String getInterfaceInfoByType(Snmp snmp, Target target, String type, LinkedHashMap<String,String> oidParams) throws IOException {
|
||||
JSONObject json = new JSONObject();
|
||||
// 获取接口数量
|
||||
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 "";
|
||||
}
|
||||
int ifNumber = event.getResponse().get(0).getVariable().toInt();
|
||||
System.out.println("\n=== 接口数量: " + ifNumber + " ===");
|
||||
if(oidParams.isEmpty()){
|
||||
return "";
|
||||
}
|
||||
String[] ifOIDs = oidParams.keySet().toArray(new String[0]);
|
||||
String[] params = oidParams.values().toArray(new String[0]);
|
||||
// 获取每个接口的信息
|
||||
// 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
|
||||
// };
|
||||
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]);
|
||||
for (int m = 0; m < params.length; m++) {
|
||||
if(StringUtils.isNotBlank(type)){
|
||||
if(StringUtils.equals(params[m], type)){
|
||||
json.put(params[m],vbs[m].getVariable().toString());
|
||||
System.out.println(params[m]+":"+vbs[m].getVariable().toString());
|
||||
}
|
||||
}else{
|
||||
json.put(params[m],vbs[m].getVariable().toString());
|
||||
System.out.println(params[m]+":"+vbs[m].getVariable().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 结果封装类
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package com.tongran.agent.client.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.tongran.agent.client.core.vo.SystemVO;
|
||||
import com.tongran.agent.client.service.SystemService;
|
||||
import com.tongran.agent.client.utils.AgentDataUtil;
|
||||
import com.tongran.agent.client.utils.AgentUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
import oshi.SystemInfo;
|
||||
import oshi.hardware.CentralProcessor;
|
||||
import oshi.hardware.HardwareAbstractionLayer;
|
||||
import oshi.software.os.OperatingSystem;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class SystemServiceImpl implements SystemService {
|
||||
@Override
|
||||
public SystemVO get() {
|
||||
SystemVO systemVO = SystemVO.builder().build();
|
||||
try {
|
||||
SystemInfo si = new SystemInfo();
|
||||
HardwareAbstractionLayer hal = si.getHardware();
|
||||
CentralProcessor processor = hal.getProcessor();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
|
||||
System.out.println("=========================================================");
|
||||
// 1. 操作系统基本信息
|
||||
System.out.println("=== 操作系统信息 ===");
|
||||
systemVO.setOs(os.getFamily()); //操作系统
|
||||
systemVO.setArch(os.getVersionInfo().getVersion() + " " + os.getBitness() + "位"); //操作系统架构
|
||||
systemVO.setUuid(AgentUtil.getMotherboardUUID());
|
||||
System.out.println("操作系统: " + systemVO.getOs());
|
||||
System.out.println("操作系统架构: " + systemVO.getArch());
|
||||
System.out.println("UUID: " + AgentUtil.getMotherboardUUID());
|
||||
|
||||
// 2. 进程信息
|
||||
System.out.println("\n=== 进程信息 ===");
|
||||
long maxProcesses = getMaxProcessesLinux();
|
||||
int runningProcesses = getRunningProcessesLinux();
|
||||
System.out.println("最大进程数: " + maxProcesses);
|
||||
System.out.println("正在运行的进程数: " + runningProcesses);
|
||||
systemVO.setMaxProc(maxProcesses); //最大进程数
|
||||
systemVO.setRunProcNum(runningProcesses); //正在运行的进程数
|
||||
|
||||
// 3. 登录用户数
|
||||
System.out.println("\n=== 登录用户 ===");
|
||||
systemVO.setUsersNum(os.getSessions().size()); //登录用户数
|
||||
System.out.println("登录用户数: " + systemVO.getUsersNum());
|
||||
|
||||
// 4. 磁盘信息
|
||||
System.out.println("\n=== 磁盘信息 ===");
|
||||
systemVO.setDiskSizeTotal(diskSpace()); //硬盘:总可用空间
|
||||
systemVO.setBootTime(systemBootTime(hal.getProcessor())); //系统启动时间
|
||||
systemVO.setUname(systemDescription(si)); //系统描述
|
||||
systemVO.setLocalTime(localTime()); //系统本地时间
|
||||
systemVO.setUpTime(systemUptime(os)); //系统正常运行时间
|
||||
System.out.println("硬盘:总可用空间: " + systemVO.getDiskSizeTotal());
|
||||
System.out.println("系统启动时间: " + systemVO.getBootTime());
|
||||
System.out.println("系统描述: " + systemVO.getUname());
|
||||
System.out.println("系统本地时间: " + systemVO.getLocalTime());
|
||||
System.out.println("系统正常运行时间: " + systemVO.getUpTime());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return systemVO;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String otherSystem(String type) {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("type",type);
|
||||
switch(type){
|
||||
case "systemSwapSizeFreeCollect":
|
||||
json.put("value", String.valueOf(handleSystemSwapSizeFree()));
|
||||
break;
|
||||
case "memoryUtilizationCollect":
|
||||
json.put("value", String.valueOf(handleMemoryUtilization()));
|
||||
break;
|
||||
case "systemSwapSizePercentCollect":
|
||||
json.put("value", String.valueOf(handleSystemSwapSizePercent()));
|
||||
break;
|
||||
case "memorySizeAvailableCollect":
|
||||
json.put("value", String.valueOf(handleMemorySizeAvailable()));
|
||||
break;
|
||||
case "memorySizePercentCollect":
|
||||
json.put("value", String.valueOf(handleMemorySizePercent()));
|
||||
break;
|
||||
case "memorySizeTotalCollect":
|
||||
json.put("value", String.valueOf(handleMemorySizeTotal()));
|
||||
break;
|
||||
case "systemSwOsCollect":
|
||||
json.put("value",handleSystemSwOs());
|
||||
break;
|
||||
case "systemSwArchCollect":
|
||||
json.put("value",handleSystemSwArch());
|
||||
break;
|
||||
case "kernelMaxprocCollect":
|
||||
json.put("value", String.valueOf(handleKernelMaxproc()));
|
||||
break;
|
||||
case "procNumRunCollect":
|
||||
json.put("value", String.valueOf(handleProcNumRun()));
|
||||
break;
|
||||
case "systemUsersNumCollect":
|
||||
json.put("value", String.valueOf(handleUsersNum()));
|
||||
break;
|
||||
case "systemDiskSizeTotalCollect":
|
||||
json.put("value", String.valueOf(handleSystemDiskSizeTotal()));
|
||||
break;
|
||||
case "systemBoottimeCollect":
|
||||
json.put("value", String.valueOf(handleSystemBoottime()));
|
||||
break;
|
||||
case "systemUnameCollect":
|
||||
json.put("value",handleSystemUname());
|
||||
break;
|
||||
case "systemLocaltimeCollect":
|
||||
json.put("value",handleSystemLocaltime());
|
||||
break;
|
||||
case "systemUptimeCollect":
|
||||
json.put("value", String.valueOf(handleSystemUptime()));
|
||||
break;
|
||||
case "procNumCollect":
|
||||
json.put("value", String.valueOf(handleProcNum()));
|
||||
break;
|
||||
default:
|
||||
json.put("value",handleDefault());
|
||||
break;
|
||||
}
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
private long handleSystemSwapSizeFree(){
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
long swapFree = memInfo.getOrDefault("SwapFree", 0L);
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("交换卷/文件的可用空间(字节): " + swapFree);
|
||||
return swapFree;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
private double handleMemoryUtilization(){
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
System.out.println("=========================================================");
|
||||
long total = memInfo.get("MemTotal");
|
||||
long available = memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L));
|
||||
// 实际内存使用率
|
||||
long cached = memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L);
|
||||
long buffers = memInfo.getOrDefault("Buffers", 0L);
|
||||
double actualUsage = (double)(total - available - cached - buffers) / total * 100;
|
||||
System.out.printf("实际内存使用率: %.2f%%\n", actualUsage);
|
||||
return actualUsage;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private double handleSystemSwapSizePercent(){
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
System.out.println("=========================================================");
|
||||
long swapTotal = memInfo.getOrDefault("SwapTotal", 0L);
|
||||
long swapFree = memInfo.getOrDefault("SwapFree", 0L);
|
||||
System.out.printf("交换空间使用率: %.2f%%\n",
|
||||
(double)(swapTotal - swapFree) / swapTotal * 100);
|
||||
return (double) swapFree / swapTotal * 100;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private long handleMemorySizeAvailable(){
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("可用内存: " +
|
||||
memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L)));
|
||||
return memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private double handleMemorySizePercent(){
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
System.out.println("=========================================================");
|
||||
long available = memInfo.getOrDefault("MemAvailable",
|
||||
memInfo.get("MemFree") +
|
||||
memInfo.getOrDefault("Buffers", 0L) +
|
||||
memInfo.getOrDefault("Cached", 0L) +
|
||||
memInfo.getOrDefault("SReclaimable", 0L));
|
||||
long total = memInfo.get("MemTotal");
|
||||
System.out.println("可用内存百分比: " + (double) available / total * 100);
|
||||
return (double) available / total * 100;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private long handleMemorySizeTotal(){
|
||||
try {
|
||||
Map<String, Long> memInfo = AgentDataUtil.parseMemInfo();
|
||||
System.out.println("=========================================================");
|
||||
long total = memInfo.get("MemTotal");
|
||||
System.out.println("总内存: " + total);
|
||||
return total;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private String handleSystemSwOs(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("操作系统: " + os.getFamily());
|
||||
return os.getFamily();
|
||||
}
|
||||
|
||||
private String handleSystemSwArch(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
System.out.println("=========================================================");
|
||||
String arch = os.getVersionInfo().getVersion() + " " + os.getBitness() + "位";
|
||||
System.out.println("操作系统架构: " + arch);
|
||||
return arch;
|
||||
}
|
||||
|
||||
private long handleKernelMaxproc(){
|
||||
System.out.println("=========================================================");
|
||||
long maxProcesses = 0;
|
||||
try {
|
||||
maxProcesses = getMaxProcessesLinux();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("最大进程数: " + maxProcesses);
|
||||
return maxProcesses;
|
||||
}
|
||||
|
||||
private long handleProcNumRun(){
|
||||
System.out.println("=========================================================");
|
||||
int runningProcesses = getRunningProcessesLinux();
|
||||
System.out.println("正在运行的进程数: " + runningProcesses);
|
||||
return runningProcesses;
|
||||
}
|
||||
|
||||
private int handleUsersNum(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
System.out.println("=========================================================");
|
||||
int usersNum = os.getSessions().size();
|
||||
System.out.println("登录用户数: " + usersNum);
|
||||
return usersNum;
|
||||
}
|
||||
|
||||
private long handleSystemDiskSizeTotal(){
|
||||
System.out.println("=========================================================");
|
||||
long diskSizeTotal = diskSpace();
|
||||
System.out.println("硬盘:总可用空间: " + diskSizeTotal);
|
||||
return diskSizeTotal;
|
||||
}
|
||||
|
||||
public long handleSystemBoottime(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
HardwareAbstractionLayer hal = si.getHardware();
|
||||
long boottime = systemBootTime(hal.getProcessor());
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("系统启动时间: " + boottime);
|
||||
return boottime;
|
||||
}
|
||||
|
||||
private String handleSystemUname(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
String uname = systemDescription(si);
|
||||
System.out.println("=========================================================");
|
||||
System.out.println("系统描述: " + uname);
|
||||
return uname;
|
||||
}
|
||||
|
||||
private String handleSystemLocaltime(){
|
||||
System.out.println("=========================================================");
|
||||
String time = localTime();
|
||||
System.out.println("系统本地时间: " + time);
|
||||
return time;
|
||||
}
|
||||
|
||||
private long handleSystemUptime(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
System.out.println("=========================================================");
|
||||
long uptime = systemUptime(os);
|
||||
System.out.println("系统正常运行时间: " + uptime);
|
||||
return uptime;
|
||||
}
|
||||
|
||||
private long handleProcNum(){
|
||||
SystemInfo si = new SystemInfo();
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
System.out.println("=========================================================");
|
||||
long procNum = os.getProcessCount();
|
||||
System.out.println("进程数: " + procNum);
|
||||
return procNum;
|
||||
}
|
||||
|
||||
|
||||
private String handleDefault(){
|
||||
return "";
|
||||
}
|
||||
|
||||
// 读取 /proc/sys/kernel/pid_max 获取最大进程数
|
||||
private static long getMaxProcessesLinux() throws IOException {
|
||||
File pidMaxFile = new File("/proc/sys/kernel/pid_max");
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(pidMaxFile))) {
|
||||
String line = reader.readLine().trim();
|
||||
return Long.parseLong(line);
|
||||
}
|
||||
}
|
||||
|
||||
// 统计 /proc 下的数字目录数(每个目录对应一个进程)
|
||||
private static int getRunningProcessesLinux() {
|
||||
File procDir = new File("/proc");
|
||||
File[] files = procDir.listFiles();
|
||||
if (files == null) return 0;
|
||||
|
||||
int count = 0;
|
||||
for (File file : files) {
|
||||
if (file.isDirectory() && file.getName().matches("\\d+")) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// 获取硬盘总可用空间
|
||||
public long diskSpace() {
|
||||
long diskSizeTotal = 0;
|
||||
File[] roots = File.listRoots();
|
||||
for (File root : roots) {
|
||||
diskSizeTotal += root.getFreeSpace();
|
||||
}
|
||||
return diskSizeTotal;
|
||||
}
|
||||
|
||||
// 获取系统启动时间
|
||||
public long systemBootTime(CentralProcessor processor) {
|
||||
long[] systemCpuLoadTicks = processor.getSystemCpuLoadTicks();
|
||||
long bootTime = ManagementFactory.getRuntimeMXBean().getStartTime();
|
||||
return bootTime;
|
||||
}
|
||||
|
||||
// 获取系统描述
|
||||
public String systemDescription(SystemInfo si) {
|
||||
OperatingSystem os = si.getOperatingSystem();
|
||||
HardwareAbstractionLayer hal = si.getHardware();
|
||||
return "操作系统: " + os.toString() + ",系统版本: " + os.getVersionInfo().toString() + "" +
|
||||
",处理器: " + hal.getProcessor().getProcessorIdentifier().getName() +
|
||||
",物理内存: " + hal.getMemory().getTotal() / (1024 * 1024 * 1024) + " GB";
|
||||
}
|
||||
|
||||
// 获取系统本地时间
|
||||
public String localTime() {
|
||||
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
|
||||
// 获取系统正常运行时间
|
||||
public long systemUptime(OperatingSystem os) {
|
||||
long uptimeSeconds = os.getSystemUptime();
|
||||
return uptimeSeconds;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user