新增延迟测试,允许测试指定服务器之间或指定服务器到自定义公网ip的延迟,去除服务器状态信息,升级springboot版本

This commit is contained in:
chuzhongzai 2024-08-18 19:56:52 +08:00
parent bcc123f8dc
commit 8dbfcb9a67
12 changed files with 337 additions and 193 deletions

25
pom.xml
View File

@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<version>3.1.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lion</groupId>
@ -68,12 +68,6 @@
<version>5.8.26</version>
</dependency>
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.4.5</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
@ -82,7 +76,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
<version>1.25.0</version>
</dependency>
</dependencies>
@ -100,6 +94,21 @@
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<configuration>
<imageName>snss</imageName>
<buildArgs>
<arg>--gc=G1</arg>
<arg>-H:+ReportExceptionStackTraces</arg>
<arg>--initialize-at-build-time=org.apache.commons.logging.LogFactory,org.apache.commons.logging.LogFactoryService</arg>
</buildArgs>
<metadataRepository>
<enabled>true</enabled>
</metadataRepository>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -0,0 +1,266 @@
package com.lion.snss.configuration;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.cache.decorators.FifoCache;
import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.cache.decorators.SoftCache;
import org.apache.ibatis.cache.decorators.WeakCache;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.javassist.util.proxy.ProxyFactory;
import org.apache.ibatis.javassist.util.proxy.RuntimeSupport;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl;
import org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.nologging.NoLoggingImpl;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.apache.ibatis.scripting.defaults.RawLanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
import org.springframework.beans.factory.aot.BeanRegistrationExcludeFilter;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.core.ResolvableType;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(MyBatisNativeConfiguration.MyBaitsRuntimeHintsRegistrar.class)
public class MyBatisNativeConfiguration {
@Bean
MyBatisBeanFactoryInitializationAotProcessor myBatisBeanFactoryInitializationAotProcessor() {
return new MyBatisBeanFactoryInitializationAotProcessor();
}
@Bean
static MyBatisMapperFactoryBeanPostProcessor myBatisMapperFactoryBeanPostProcessor() {
return new MyBatisMapperFactoryBeanPostProcessor();
}
static class MyBaitsRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
Stream.of(RawLanguageDriver.class,
XMLLanguageDriver.class,
RuntimeSupport.class,
ProxyFactory.class,
Slf4jImpl.class,
Log.class,
JakartaCommonsLoggingImpl.class,
Log4j2Impl.class,
Jdk14LoggingImpl.class,
StdOutImpl.class,
NoLoggingImpl.class,
SqlSessionFactory.class,
PerpetualCache.class,
FifoCache.class,
LruCache.class,
SoftCache.class,
WeakCache.class,
SqlSessionFactoryBean.class,
ArrayList.class,
HashMap.class,
TreeSet.class,
HashSet.class
).forEach(x -> hints.reflection().registerType(x, MemberCategory.values()));
Stream.of(
"org/apache/ibatis/builder/xml/*.dtd",
"org/apache/ibatis/builder/xml/*.xsd"
).forEach(hints.resources()::registerPattern);
}
}
static class MyBatisBeanFactoryInitializationAotProcessor
implements BeanFactoryInitializationAotProcessor, BeanRegistrationExcludeFilter {
private final Set<Class<?>> excludeClasses = new HashSet<>();
MyBatisBeanFactoryInitializationAotProcessor() {
excludeClasses.add(MapperScannerConfigurer.class);
}
@Override public boolean isExcludedFromAotProcessing(RegisteredBean registeredBean) {
return excludeClasses.contains(registeredBean.getBeanClass());
}
@Override
public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
String[] beanNames = beanFactory.getBeanNamesForType(MapperFactoryBean.class);
if (beanNames.length == 0) {
return null;
}
return (context, code) -> {
RuntimeHints hints = context.getRuntimeHints();
for (String beanName : beanNames) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName.substring(1));
PropertyValue mapperInterface = beanDefinition.getPropertyValues().getPropertyValue("mapperInterface");
if (mapperInterface != null && mapperInterface.getValue() != null) {
Class<?> mapperInterfaceType = (Class<?>) mapperInterface.getValue();
if (mapperInterfaceType != null) {
registerReflectionTypeIfNecessary(mapperInterfaceType, hints);
hints.proxies().registerJdkProxy(mapperInterfaceType);
hints.resources()
.registerPattern(mapperInterfaceType.getName().replace('.', '/').concat(".xml"));
registerMapperRelationships(mapperInterfaceType, hints);
}
}
}
};
}
private void registerMapperRelationships(Class<?> mapperInterfaceType, RuntimeHints hints) {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(mapperInterfaceType);
for (Method method : methods) {
if (method.getDeclaringClass() != Object.class) {
ReflectionUtils.makeAccessible(method);
registerSqlProviderTypes(method, hints, SelectProvider.class, SelectProvider::value, SelectProvider::type);
registerSqlProviderTypes(method, hints, InsertProvider.class, InsertProvider::value, InsertProvider::type);
registerSqlProviderTypes(method, hints, UpdateProvider.class, UpdateProvider::value, UpdateProvider::type);
registerSqlProviderTypes(method, hints, DeleteProvider.class, DeleteProvider::value, DeleteProvider::type);
Class<?> returnType = MyBatisMapperTypeUtils.resolveReturnClass(mapperInterfaceType, method);
registerReflectionTypeIfNecessary(returnType, hints);
MyBatisMapperTypeUtils.resolveParameterClasses(mapperInterfaceType, method)
.forEach(x -> registerReflectionTypeIfNecessary(x, hints));
}
}
}
@SafeVarargs
private <T extends Annotation> void registerSqlProviderTypes(
Method method, RuntimeHints hints, Class<T> annotationType, Function<T, Class<?>>... providerTypeResolvers) {
for (T annotation : method.getAnnotationsByType(annotationType)) {
for (Function<T, Class<?>> providerTypeResolver : providerTypeResolvers) {
registerReflectionTypeIfNecessary(providerTypeResolver.apply(annotation), hints);
}
}
}
private void registerReflectionTypeIfNecessary(Class<?> type, RuntimeHints hints) {
if (!type.isPrimitive() && !type.getName().startsWith("java")) {
hints.reflection().registerType(type, MemberCategory.values());
}
}
}
static class MyBatisMapperTypeUtils {
private MyBatisMapperTypeUtils() {
// NOP
}
static Class<?> resolveReturnClass(Class<?> mapperInterface, Method method) {
Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
return typeToClass(resolvedReturnType, method.getReturnType());
}
static Set<Class<?>> resolveParameterClasses(Class<?> mapperInterface, Method method) {
return Stream.of(TypeParameterResolver.resolveParamTypes(method, mapperInterface))
.map(x -> typeToClass(x, x instanceof Class ? (Class<?>) x : Object.class)).collect(Collectors.toSet());
}
private static Class<?> typeToClass(Type src, Class<?> fallback) {
Class<?> result = null;
if (src instanceof Class<?>) {
if (((Class<?>) src).isArray()) {
result = ((Class<?>) src).getComponentType();
} else {
result = (Class<?>) src;
}
} else if (src instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) src;
int index = (parameterizedType.getRawType() instanceof Class
&& Map.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())
&& parameterizedType.getActualTypeArguments().length > 1) ? 1 : 0;
Type actualType = parameterizedType.getActualTypeArguments()[index];
result = typeToClass(actualType, fallback);
}
if (result == null) {
result = fallback;
}
return result;
}
}
static class MyBatisMapperFactoryBeanPostProcessor implements MergedBeanDefinitionPostProcessor, BeanFactoryAware {
private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(
MyBatisMapperFactoryBeanPostProcessor.class);
private static final String MAPPER_FACTORY_BEAN = "org.mybatis.spring.mapper.MapperFactoryBean";
private ConfigurableBeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = (ConfigurableBeanFactory) beanFactory;
}
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (ClassUtils.isPresent(MAPPER_FACTORY_BEAN, this.beanFactory.getBeanClassLoader())) {
resolveMapperFactoryBeanTypeIfNecessary(beanDefinition);
}
}
private void resolveMapperFactoryBeanTypeIfNecessary(RootBeanDefinition beanDefinition) {
if (!beanDefinition.hasBeanClass() || !MapperFactoryBean.class.isAssignableFrom(beanDefinition.getBeanClass())) {
return;
}
if (beanDefinition.getResolvableType().hasUnresolvableGenerics()) {
Class<?> mapperInterface = getMapperInterface(beanDefinition);
if (mapperInterface != null) {
// Exposes a generic type information to context for prevent early initializing
beanDefinition
.setTargetType(ResolvableType.forClassWithGenerics(beanDefinition.getBeanClass(), mapperInterface));
}
}
}
private Class<?> getMapperInterface(RootBeanDefinition beanDefinition) {
try {
return (Class<?>) beanDefinition.getPropertyValues().get("mapperInterface");
}
catch (Exception e) {
LOG.debug("Fail getting mapper interface type.", e);
return null;
}
}
}
}

View File

@ -1,18 +1,28 @@
package com.lion.snss.configuration;
import com.lion.snss.interceptor.Interceptor;
import jakarta.annotation.Resource;
import com.lion.snss.message.*;
import com.lion.snss.pojo.*;
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RegisterReflectionForBinding(classes = {AbstractMessage.class, AdjustShareMessage.class, CancelShareMessage.class, CompressFileMessage.class, ConfigMessage.class,
ConnectMessage.class, DelayTestMessage.class, DynamicConfigMessage.class, ExtractFileMessage.class, FileOperateMessage.class, FileQueryMessage.class, FileResponseMessage.class,
MoveFileRequestMessage.class, MoveFileResponseMessage.class, PairMessage.class, PairResultMessage.class, ResponseMessage.class, ShareFileMessage.class, ShareFileQueryMessage.class,
TaskCancelMessage.class, TaskStatusMessage.class, UnPairMessage.class, FileNode.class, Record.class, ShareFile.class, ShareFileDownloadRecord.class, Task.class,
User.class})
public class WebComponentConfiguration implements WebMvcConfigurer {
@Resource
Interceptor interceptor;
public WebComponentConfiguration(Interceptor interceptor) {
this.interceptor = interceptor;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")

View File

@ -1,7 +1,6 @@
package com.lion.snss.controller;
import com.lion.snss.service.FileService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
@ -11,9 +10,13 @@ import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/file")
public class FileController {
@Resource
// @Resource
FileService fileService;
public FileController(FileService fileService) {
this.fileService = fileService;
}
@GetMapping("/getFile/**")
public void getFile(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String path, String sessionId){
fileService.getFile(httpRequest, httpResponse, path, sessionId);

View File

@ -1,7 +1,6 @@
package com.lion.snss.controller;
import com.lion.snss.service.FileService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
@ -9,9 +8,13 @@ import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@Resource
// @Resource
FileService fileService;
public IndexController(FileService fileService) {
this.fileService = fileService;
}
@GetMapping("/getFileByShareCode/**")
public void getFileByShareCode(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String shareCode){
fileService.getFileByShareCode(httpRequest, httpResponse, shareCode);

View File

@ -7,7 +7,6 @@ import lombok.Data;
public class AbstractMessage {
public static final int FILE_QUERY_MESSAGE = 1;
public static final int FILE_RESPONSE_MESSAGE = 2;
public static final int STATUS_MESSAGE = 10;
public static final int MOVE_FILE_REQUEST_MESSAGE = 15;
public static final int MOVE_FILE_RESPONSE_MESSAGE = 16;
public static final int PAIR_MESSAGE = 20;

View File

@ -37,7 +37,6 @@ public class MessageCodec extends ByteToMessageCodec<AbstractMessage> {
abstractMessage = switch (type){
case AbstractMessage.FILE_QUERY_MESSAGE -> objectMapper.readValue(bytes, FileQueryMessage.class);
case AbstractMessage.FILE_RESPONSE_MESSAGE -> objectMapper.readValue(bytes, FileResponseMessage.class);
case AbstractMessage.STATUS_MESSAGE -> objectMapper.readValue(bytes, StatusMessage.class);
case AbstractMessage.MOVE_FILE_REQUEST_MESSAGE -> objectMapper.readValue(bytes, MoveFileRequestMessage.class);
case AbstractMessage.MOVE_FILE_RESPONSE_MESSAGE -> objectMapper.readValue(bytes, MoveFileResponseMessage.class);
case AbstractMessage.PAIR_MESSAGE -> objectMapper.readValue(bytes, PairMessage.class);

View File

@ -11,11 +11,6 @@ public class PairMessage extends AbstractMessage{
String domain;
String reverseProxyPrefix;
String hostname;
String system;
String cpuArch;
String cpuName;
int cpuCore;
int cpuThread;
String storagePath;
long availableSpace;
}

View File

@ -1,25 +0,0 @@
package com.lion.snss.message;
import lombok.Data;
@Data
public class StatusMessage extends AbstractMessage{
{
messageType = STATUS_MESSAGE;
}
int id;
long usedMemory;
long totalMemory;
double usedMemoryPercentage;
long usedSpace;
long totalSpace;
double usedSpacePercentage;
double[] systemLoad;
double usedCpuPercentage;
long ioRead;
long ioWrite;
long networkReceive;
long networkSend;
long systemUpTime;
long systemBootTime;
}

View File

@ -18,9 +18,7 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
@ -55,10 +53,10 @@ public class CommunicateToMainService {
EventLoop eventLoop;
@Resource
// @Resource
ShareFileMapper shareFileMapper;
@Resource
// @Resource
TaskService taskService;
ObjectMapper objectMapper = CustomUtil.objectMapper;
@ -81,7 +79,10 @@ public class CommunicateToMainService {
ScheduledExecutorService scheduledExecutorService;
public CommunicateToMainService(CustomConfigurationMapper customConfigurationMapper, Interceptor interceptor) {
public CommunicateToMainService(CustomConfigurationMapper customConfigurationMapper, Interceptor interceptor,
ShareFileMapper shareFileMapper, TaskService taskService) {
this.shareFileMapper = shareFileMapper;
this.taskService = taskService;
messageId = new AtomicInteger();
promises = new HashMap<>();
ips = new HashMap<>();
@ -136,7 +137,6 @@ public class CommunicateToMainService {
protected void initChannel(NioSocketChannel channel) {
channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(100000000, 4, 4));
channel.pipeline().addLast(new MessageCodec());
// channel.pipeline().addLast(new LoggingHandler(LogLevel.WARN));
channel.pipeline().addLast(new MyChannelInboundHandlerAdapter());
}
}).connect(ip, 7777).sync();
@ -159,7 +159,6 @@ public class CommunicateToMainService {
protected void initChannel(NioSocketChannel channel) {
channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(100000000, 4, 4));
channel.pipeline().addLast(new MessageCodec());
// channel.pipeline().addLast(new LoggingHandler(LogLevel.WARN));
channel.pipeline().addLast(new MyChannelInboundHandlerAdapter());
}
}).connect(ip, 9999).sync();
@ -174,7 +173,6 @@ public class CommunicateToMainService {
scheduledExecutorService.scheduleAtFixedRate(() -> {
if(channelFuture == null)
return;
channelFuture.channel().writeAndFlush(IoUtil.generateStatusMessage(id, storagePath));
if(!taskService.getTasks().isEmpty()){
TaskStatusMessage message = new TaskStatusMessage();
message.setTasks(new HashSet<>(taskService.getTasks().values()));
@ -934,8 +932,7 @@ public class CommunicateToMainService {
for (String path : task.getPaths()) {
File file = new File(storagePath + task.getRelativePath() + path);
if(file.isFile()){
ArchiveEntry entry = new TarArchiveEntry(file, finalPath.relativize(file.toPath()).toString());
TarArchiveEntry entry = new TarArchiveEntry(file, finalPath.relativize(file.toPath()).toString());
aos.putArchiveEntry(entry);
InputStream inputStream = Files.newInputStream(file.toPath());
byte[] buf = new byte[4096];
@ -951,7 +948,7 @@ public class CommunicateToMainService {
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
ArchiveEntry entry = new TarArchiveEntry(dir.toFile(), finalPath.relativize(dir).toString());
TarArchiveEntry entry = new TarArchiveEntry(dir.toFile(), finalPath.relativize(dir).toString());
aos.putArchiveEntry(entry);
aos.closeArchiveEntry();
return FileVisitResult.CONTINUE;
@ -959,7 +956,7 @@ public class CommunicateToMainService {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
ArchiveEntry entry = new TarArchiveEntry(file.toFile(), finalPath.relativize(file).toString());
TarArchiveEntry entry = new TarArchiveEntry(file.toFile(), finalPath.relativize(file).toString());
aos.putArchiveEntry(entry);
InputStream inputStream = Files.newInputStream(file.toFile().toPath());
byte[] buf = new byte[4096];

View File

@ -8,7 +8,6 @@ import com.lion.snss.pojo.ShareFile;
import com.lion.snss.pojo.User;
import com.lion.snss.util.IoUtil;
import com.lion.snss.util.Response;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
@ -29,20 +28,23 @@ import java.util.Objects;
public class FileService {
String storagePath;
@Resource
// @Resource
ShareFileMapper shareFileMapper;
@Resource
// @Resource
CommunicateToMainService communicateToMainService;
@Resource
// @Resource
Interceptor interceptor;
HashMap<String, Long> ipAndShareCode;
public FileService(CustomConfigurationMapper customConfigurationMapper){
public FileService(CustomConfigurationMapper customConfigurationMapper, ShareFileMapper shareFileMapper, CommunicateToMainService communicateToMainService, Interceptor interceptor){
this.communicateToMainService = communicateToMainService;
this.shareFileMapper = shareFileMapper;
this.interceptor = interceptor;
storagePath = customConfigurationMapper.selectValue(CustomConfigurationMapper.PATH);
ipAndShareCode = new HashMap<>();
}

View File

@ -3,132 +3,53 @@ package com.lion.snss.util;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import com.lion.snss.message.StatusMessage;
import com.lion.snss.message.PairMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpHeaders;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HWDiskStore;
import oshi.hardware.NetworkIF;
import oshi.software.os.OperatingSystem;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
@Data
@Slf4j
public class IoUtil {
static long ioRead;
static long ioWrite;
static long networkSend;
static long networkReceive;
static NetworkIF networkIF;
static List<HWDiskStore> diskStores;
static CpuInfo cpuInfo;
static GlobalMemory globalMemory;
static long send;
static long sendNow;
static long receive;
static long receiveNow;
static long read;
static long readNow;
static long write;
static long writeNow;
static ScheduledExecutorService thread;
@Getter
static String ip;
static {
init();
}
public static void init(){
thread = Executors.newScheduledThreadPool(1);
List<NetworkIF> networkIFs = OshiUtil.getNetworkIFs();
cpuInfo = OshiUtil.getCpuInfo();
globalMemory = OshiUtil.getMemory();
for (NetworkIF nif : networkIFs)
if (nif.getName().startsWith("eth0") || nif.getName().startsWith("ens")) {
networkIF = nif;
break;
}
if(networkIF == null)
log.error("网卡 eth0 不存在");
else{
send = networkIF.getBytesSent();
receive = networkIF.getBytesRecv();
try {
ip = getPublicIP();
}catch (IOException | URISyntaxException e){
log.info("当前机器网卡为内网ip且无法获取公网ip程序退出");
Runtime.getRuntime().exit(1);
}
diskStores = OshiUtil.getDiskStores();
for (HWDiskStore diskStore : diskStores) {
read += diskStore.getReadBytes();
write += diskStore.getWriteBytes();
}
thread.scheduleAtFixedRate(IoUtil::monitor, 0, 1, TimeUnit.SECONDS);
}
private static void monitor(){
networkIF.updateAttributes();
sendNow = networkIF.getBytesSent();
receiveNow = networkIF.getBytesRecv();
networkSend = sendNow - send;
networkReceive = receiveNow - receive;
send = sendNow;
receive = receiveNow;
writeNow = 0;
readNow = 0;
for (HWDiskStore diskStore : diskStores) {
diskStore.updateAttributes();
writeNow += diskStore.getWriteBytes();
readNow += diskStore.getReadBytes();
}
ioWrite = writeNow - write;
ioRead = readNow - read;
write = writeNow;
read = readNow;
}
public static PairMessage generatePairMessage(){
PairMessage pairMessage = new PairMessage();
String ip = networkIF.getIPv4addr()[0].split("/")[0];
String privateIPPattern = "(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)";
if(Pattern.compile(privateIPPattern).matcher(ip).find())
try {
ip = getPublicIP();
}catch (IOException | URISyntaxException e){
log.info("当前机器网卡为内网ip且无法获取公网ip程序退出");
Runtime.getRuntime().exit(1);
}
String ip;
try {
ip = getPublicIP();
}catch (IOException | URISyntaxException e){
log.info("当前机器网卡为内网ip且无法获取公网ip程序退出");
Runtime.getRuntime().exit(1);
return null;
}
pairMessage.setIp(ip);
pairMessage.setHostname(NetUtil.getLocalHostName());
OperatingSystem os = OshiUtil.getOs();
pairMessage.setSystem(os.getFamily() + " " + os.getVersionInfo().toString());
pairMessage.setCpuArch(System.getProperty("os.arch"));
CentralProcessor processor = OshiUtil.getHardware().getProcessor();
pairMessage.setCpuName(processor.getProcessorIdentifier().getName().strip());
pairMessage.setCpuCore(processor.getPhysicalProcessorCount());
pairMessage.setCpuThread(processor.getLogicalProcessorCount());
return pairMessage;
}
@ -151,41 +72,6 @@ public class IoUtil {
return json.substring(startIndex + 1, endIndex);
}
public static StatusMessage generateStatusMessage(int id, String path){
StatusMessage statusMessage = new StatusMessage();
statusMessage.setId(id);
statusMessage.setTotalMemory(globalMemory.getTotal());
statusMessage.setUsedMemory(globalMemory.getTotal() - globalMemory.getAvailable());
statusMessage.setUsedMemoryPercentage(numberFormat((double) statusMessage.getUsedMemory() / statusMessage.getTotalMemory()));
File file = new File(path);
statusMessage.setTotalSpace(file.getTotalSpace());
statusMessage.setUsedSpace(file.getTotalSpace() - file.getFreeSpace());
statusMessage.setUsedSpacePercentage(numberFormat((double) statusMessage.getUsedSpace() / statusMessage.getTotalSpace()));
statusMessage.setSystemLoad(OshiUtil.getHardware().getProcessor().getSystemLoadAverage(3));
statusMessage.setUsedCpuPercentage(numberFormat(100 - OshiUtil.getCpuInfo().getFree()));
statusMessage.setIoRead(ioRead);
statusMessage.setIoWrite(ioWrite);
statusMessage.setNetworkReceive(networkReceive);
statusMessage.setNetworkSend(networkSend);
statusMessage.setSystemUpTime(OshiUtil.getOs().getSystemUptime());
statusMessage.setSystemBootTime(OshiUtil.getOs().getSystemBootTime());
return statusMessage;
}
public static double numberFormat(double number){
if(number <= 0)
return number;
if(number < 1)
return Double.parseDouble(String.format("%.1f", number * 100));
else
return Double.parseDouble(String.format("%.1f", number));
}
public static void export(HttpServletRequest request, HttpServletResponse response, String path) {
File file = new File(path);