From 81622001cecc8208aa8cec86d38304b4d57a752c Mon Sep 17 00:00:00 2001 From: nagocoler Date: Fri, 1 Dec 2023 16:56:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E8=BF=90=E8=A1=8C=E6=97=B6?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E4=B8=8A=E6=8A=A5=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- itbaima-monitor-client/pom.xml | 6 +- .../example/entity/data/RuntimeDetail.java | 17 ++++ .../java/com/example/task/MonitorJobBean.java | 26 +++++ .../java/com/example/utils/MonitorUtils.java | 97 ++++++++++++++++--- .../main/java/com/example/utils/NetUtils.java | 8 ++ .../example/controller/ClientController.java | 8 ++ .../entity/vo/request/RuntimeDetailVO.java | 24 +++++ .../com/example/service/ClientService.java | 2 + .../service/impl/ClientServiceImpl.java | 13 ++- 9 files changed, 180 insertions(+), 21 deletions(-) create mode 100644 itbaima-monitor-client/src/main/java/com/example/entity/data/RuntimeDetail.java create mode 100644 itbaima-monitor-client/src/main/java/com/example/task/MonitorJobBean.java create mode 100644 itbaima-monitor-server/src/main/java/com/example/entity/vo/request/RuntimeDetailVO.java diff --git a/itbaima-monitor-client/pom.xml b/itbaima-monitor-client/pom.xml index f2ab547..901d9d3 100644 --- a/itbaima-monitor-client/pom.xml +++ b/itbaima-monitor-client/pom.xml @@ -21,6 +21,10 @@ org.springframework.boot spring-boot-starter + + org.springframework.boot + spring-boot-starter-quartz + com.alibaba.fastjson2 fastjson2 @@ -39,7 +43,7 @@ com.github.oshi oshi-core - 6.4.0 + 6.4.8 diff --git a/itbaima-monitor-client/src/main/java/com/example/entity/data/RuntimeDetail.java b/itbaima-monitor-client/src/main/java/com/example/entity/data/RuntimeDetail.java new file mode 100644 index 0000000..1980ce9 --- /dev/null +++ b/itbaima-monitor-client/src/main/java/com/example/entity/data/RuntimeDetail.java @@ -0,0 +1,17 @@ +package com.example.entity.data; + +import lombok.Data; +import lombok.experimental.Accessors; + +@Data +@Accessors(chain = true) +public class RuntimeDetail { + long timestamp; + double cpuUsage; + double memoryUsage; + double diskUsage; + double networkUpload; + double networkDownload; + double diskRead; + double diskWrite; +} diff --git a/itbaima-monitor-client/src/main/java/com/example/task/MonitorJobBean.java b/itbaima-monitor-client/src/main/java/com/example/task/MonitorJobBean.java new file mode 100644 index 0000000..90baae9 --- /dev/null +++ b/itbaima-monitor-client/src/main/java/com/example/task/MonitorJobBean.java @@ -0,0 +1,26 @@ +package com.example.task; + +import com.example.entity.data.RuntimeDetail; +import com.example.utils.MonitorUtils; +import com.example.utils.NetUtils; +import jakarta.annotation.Resource; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.springframework.scheduling.quartz.QuartzJobBean; +import org.springframework.stereotype.Component; + +@Component +public class MonitorJobBean extends QuartzJobBean { + + @Resource + MonitorUtils monitor; + + @Resource + NetUtils net; + + @Override + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + RuntimeDetail runtimeDetail = monitor.monitorRuntimeData(); + net.updateRuntimeDetails(runtimeDetail); + } +} diff --git a/itbaima-monitor-client/src/main/java/com/example/utils/MonitorUtils.java b/itbaima-monitor-client/src/main/java/com/example/utils/MonitorUtils.java index 6e303ef..dff8756 100644 --- a/itbaima-monitor-client/src/main/java/com/example/utils/MonitorUtils.java +++ b/itbaima-monitor-client/src/main/java/com/example/utils/MonitorUtils.java @@ -1,16 +1,22 @@ package com.example.utils; import com.example.entity.data.BaseDetail; +import com.example.entity.data.RuntimeDetail; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import oshi.SystemInfo; +import oshi.hardware.CentralProcessor; import oshi.hardware.HWDiskStore; import oshi.hardware.HardwareAbstractionLayer; import oshi.hardware.NetworkIF; import oshi.software.os.OperatingSystem; +import java.io.File; import java.io.IOException; import java.net.NetworkInterface; +import java.util.Arrays; +import java.util.Date; +import java.util.Objects; import java.util.Properties; @Slf4j @@ -20,36 +26,95 @@ public class MonitorUtils { private final SystemInfo info = new SystemInfo(); private final Properties properties = System.getProperties(); + public RuntimeDetail monitorRuntimeData() { + double statisticTime = 0.5; + try { + HardwareAbstractionLayer hardware = info.getHardware(); + NetworkIF networkInterface = Objects.requireNonNull(this.findNetworkInterface(hardware)); + CentralProcessor processor = hardware.getProcessor(); + //开始读取各种运行时信息 + double upload = networkInterface.getBytesSent(), download = networkInterface.getBytesRecv(); + double read = hardware.getDiskStores().stream().mapToLong(HWDiskStore::getReadBytes).sum(); + double write = hardware.getDiskStores().stream().mapToLong(HWDiskStore::getWriteBytes).sum(); + long[] ticks = processor.getSystemCpuLoadTicks(); + Thread.sleep((long) (statisticTime * 1000)); + networkInterface = Objects.requireNonNull(this.findNetworkInterface(hardware)); + upload = (networkInterface.getBytesSent() - upload) / statisticTime; + download = (networkInterface.getBytesRecv() - download) / statisticTime; + read = (hardware.getDiskStores().stream().mapToLong(HWDiskStore::getReadBytes).sum() - read) / statisticTime; + write = (hardware.getDiskStores().stream().mapToLong(HWDiskStore::getWriteBytes).sum() - write) / statisticTime; + double memory = (hardware.getMemory().getTotal() - hardware.getMemory().getAvailable()) / 1024.0 / 1024 / 1024; + double disk = Arrays.stream(File.listRoots()) + .mapToLong(file -> file.getTotalSpace() - file.getFreeSpace()).sum() / 1024.0 / 1024 / 1024; + return new RuntimeDetail() + .setCpuUsage(this.calculateCpuUsage(processor, ticks)) + .setMemoryUsage(memory) + .setDiskUsage(disk) + .setNetworkUpload(upload / 1024) + .setNetworkDownload(download / 1024) + .setDiskRead(read / 1024 / 1024) + .setDiskWrite(write / 1024 / 1024) + .setTimestamp(new Date().getTime()); + }catch (Exception e) { + log.error("读取运行时数据时出现问题", e); + } + return null; + } + public BaseDetail monitorBaseData() { OperatingSystem os = info.getOperatingSystem(); HardwareAbstractionLayer hardware = info.getHardware(); double memory = hardware.getMemory().getTotal() / 1024.0 / 1024 / 1024; - double diskSize = hardware.getDiskStores().stream().mapToLong(HWDiskStore::getSize).sum() / 1024.0 / 1024 / 1024; + double diskSize = Arrays.stream(File.listRoots()).mapToLong(File::getTotalSpace).sum() / 1024.0 / 1024 / 1024; + String ip = Objects.requireNonNull(this.findNetworkInterface(hardware)).getIPv4addr()[0]; + return new BaseDetail() + .setOsBit(os.getBitness()) + .setOsArch(properties.getProperty("os.arch")) + .setOsVersion(os.getVersionInfo().getVersion()) + .setOsName(os.getFamily()) + .setCpuName(hardware.getProcessor().getProcessorIdentifier().getName()) + .setCpuCore(hardware.getProcessor().getLogicalProcessorCount()) + .setMemory(memory) + .setDisk(diskSize) + .setIp(ip); + } + + private NetworkIF findNetworkInterface(HardwareAbstractionLayer hardware) { try { - String ip = null; for (NetworkIF network : hardware.getNetworkIFs()) { String[] iPv4addr = network.getIPv4addr(); NetworkInterface ni = network.queryNetworkInterface(); if(!ni.isLoopback() && !ni.isPointToPoint() && ni.isUp() && !ni.isVirtual() && (ni.getName().startsWith("eth") || ni.getName().startsWith("en")) && iPv4addr.length > 0) { - ip = network.getIPv4addr()[0]; - break; + return network; } } - return new BaseDetail() - .setOsBit(os.getBitness()) - .setOsArch(properties.getProperty("os.arch")) - .setOsVersion(os.getVersionInfo().getVersion()) - .setOsName(os.getFamily()) - .setCpuName(hardware.getProcessor().getProcessorIdentifier().getName()) - .setCpuCore(hardware.getProcessor().getLogicalProcessorCount()) - .setMemory(memory) - .setDisk(diskSize) - .setIp(ip); } catch (IOException e) { - log.error("读取系统基本信息时出错", e); - return null; + log.error("读取网络接口信息时出错", e); } + return null; + } + + private double calculateCpuUsage(CentralProcessor processor, long[] prevTicks) { + long[] ticks = processor.getSystemCpuLoadTicks(); + long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] + - prevTicks[CentralProcessor.TickType.NICE.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 cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] + - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; + long cUser = ticks[CentralProcessor.TickType.USER.getIndex()] + - prevTicks[CentralProcessor.TickType.USER.getIndex()]; + long ioWait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] + - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; + long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] + - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; + long totalCpu = cUser + nice + cSys + idle + ioWait + irq + softIrq + steal; + return (cSys + cUser) * 1.0 / totalCpu; } } diff --git a/itbaima-monitor-client/src/main/java/com/example/utils/NetUtils.java b/itbaima-monitor-client/src/main/java/com/example/utils/NetUtils.java index 8b48343..7d0fa1c 100644 --- a/itbaima-monitor-client/src/main/java/com/example/utils/NetUtils.java +++ b/itbaima-monitor-client/src/main/java/com/example/utils/NetUtils.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson2.JSONObject; import com.example.entity.ConnectionConfig; import com.example.entity.Response; import com.example.entity.data.BaseDetail; +import com.example.entity.data.RuntimeDetail; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Lazy; @@ -44,6 +45,13 @@ public class NetUtils { } } + public void updateRuntimeDetails(RuntimeDetail detail) { + Response response = this.doPost("/runtime", detail); + if(!response.success()) { + log.warn("更新运行时状态时,接收到服务端的异常响应内容: {}", response.getMessage()); + } + } + private Response doPost(String url, Object data) { try { String rawData = JSONObject.from(data).toJSONString(); diff --git a/itbaima-monitor-server/src/main/java/com/example/controller/ClientController.java b/itbaima-monitor-server/src/main/java/com/example/controller/ClientController.java index 3590f32..2c133a0 100644 --- a/itbaima-monitor-server/src/main/java/com/example/controller/ClientController.java +++ b/itbaima-monitor-server/src/main/java/com/example/controller/ClientController.java @@ -3,6 +3,7 @@ package com.example.controller; import com.example.entity.RestBean; import com.example.entity.dto.Client; import com.example.entity.vo.request.ClientDetailVO; +import com.example.entity.vo.request.RuntimeDetailVO; import com.example.service.ClientService; import com.example.utils.Const; import jakarta.annotation.Resource; @@ -28,4 +29,11 @@ public class ClientController { service.updateClientDetail(vo, client); return RestBean.success(); } + + @PostMapping("/runtime") + public RestBean updateRuntimeDetails(@RequestAttribute(Const.ATTR_CLIENT) Client client, + @RequestBody @Valid RuntimeDetailVO vo) { + service.updateRuntimeDetail(vo, client); + return RestBean.success(); + } } diff --git a/itbaima-monitor-server/src/main/java/com/example/entity/vo/request/RuntimeDetailVO.java b/itbaima-monitor-server/src/main/java/com/example/entity/vo/request/RuntimeDetailVO.java new file mode 100644 index 0000000..d90f292 --- /dev/null +++ b/itbaima-monitor-server/src/main/java/com/example/entity/vo/request/RuntimeDetailVO.java @@ -0,0 +1,24 @@ +package com.example.entity.vo.request; + +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +@Data +public class RuntimeDetailVO { + @NotNull + long timestamp; + @NotNull + double cpuUsage; + @NotNull + double memoryUsage; + @NotNull + double diskUsage; + @NotNull + double networkUpload; + @NotNull + double networkDownload; + @NotNull + double diskRead; + @NotNull + double diskWrite; +} diff --git a/itbaima-monitor-server/src/main/java/com/example/service/ClientService.java b/itbaima-monitor-server/src/main/java/com/example/service/ClientService.java index 9ae3763..6892308 100644 --- a/itbaima-monitor-server/src/main/java/com/example/service/ClientService.java +++ b/itbaima-monitor-server/src/main/java/com/example/service/ClientService.java @@ -3,6 +3,7 @@ package com.example.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.entity.dto.Client; import com.example.entity.vo.request.ClientDetailVO; +import com.example.entity.vo.request.RuntimeDetailVO; public interface ClientService extends IService { String registerToken(); @@ -10,4 +11,5 @@ public interface ClientService extends IService { Client findClient(Integer id); boolean verifyAndRegister(String token); void updateClientDetail(ClientDetailVO vo, Client client); + void updateRuntimeDetail(RuntimeDetailVO vo, Client client); } diff --git a/itbaima-monitor-server/src/main/java/com/example/service/impl/ClientServiceImpl.java b/itbaima-monitor-server/src/main/java/com/example/service/impl/ClientServiceImpl.java index d3c5577..7b0e74c 100644 --- a/itbaima-monitor-server/src/main/java/com/example/service/impl/ClientServiceImpl.java +++ b/itbaima-monitor-server/src/main/java/com/example/service/impl/ClientServiceImpl.java @@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.entity.dto.Client; import com.example.entity.dto.ClientDetail; import com.example.entity.vo.request.ClientDetailVO; +import com.example.entity.vo.request.RuntimeDetailVO; import com.example.mapper.ClientDetailMapper; import com.example.mapper.ClientMapper; import com.example.service.ClientService; @@ -14,10 +15,7 @@ import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import java.security.SecureRandom; -import java.util.Date; -import java.util.HashMap; -import java.util.Objects; -import java.util.Random; +import java.util.*; @Slf4j @Service @@ -78,6 +76,13 @@ public class ClientServiceImpl extends ServiceImpl impleme } } + private Map test = new HashMap<>(); + + @Override + public void updateRuntimeDetail(RuntimeDetailVO vo, Client client) { + test.put(client, vo); + } + private void addClientCache(Client client) { clientIdCache.put(client.getId(), client); clientTokenCache.put(client.getToken(), client);