commit d26d79d7fdce593dd11c815bf8325dc9192c3640 Author: Mzaxd Date: Thu Mar 2 21:33:00 2023 +0800 Noodles初版提交 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..28dd153 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Project exclude paths +/Noodles-Detector/target/ + +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..3014488 --- /dev/null +++ b/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.8 + + + com.mzaxd + Noodles + 0.0.1-SNAPSHOT + Noodles + Noodles + + 1.8 + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-redis + + + com.mysql + mysql-connector-j + runtime + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + com.alibaba + fastjson + 1.2.33 + + + + io.jsonwebtoken + jjwt + 0.9.0 + + + + com.baomidou + mybatis-plus-boot-starter + 3.4.3 + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.4.6 + + + io.springfox + springfox-swagger2 + 2.9.2 + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + org.springframework.boot + spring-boot-starter-amqp + + + org.apache.commons + commons-lang3 + 3.12.0 + + + org.springframework.boot + spring-boot-starter-websocket + + + com.github.oshi + oshi-core + 5.6.1 + + + + org.springframework.boot + spring-boot-starter-aop + + + + org.lionsoul + ip2region + 2.7.0 + + + + cn.hutool + hutool-all + 5.3.7 + + + javax.mail + mail + 1.4.7 + + + + com.alibaba + easyexcel + 3.2.1 + + + + + com.jcraft + jsch + 0.1.55 + + + + ch.ethz.ganymed + ganymed-ssh2 + 262 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/src/main/java/com/mzaxd/noodles/NoodlesApplication.java b/src/main/java/com/mzaxd/noodles/NoodlesApplication.java new file mode 100644 index 0000000..814a90f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/NoodlesApplication.java @@ -0,0 +1,21 @@ +package com.mzaxd.noodles; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * @author root + */ +@SpringBootApplication +@EnableScheduling +@MapperScan("com.mzaxd.noodles.mapper") +public class NoodlesApplication { + + public static void main(String[] args) { + SpringApplication.run(NoodlesApplication.class, args); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/annotation/SysLog.java b/src/main/java/com/mzaxd/noodles/annotation/SysLog.java new file mode 100644 index 0000000..b327858 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/annotation/SysLog.java @@ -0,0 +1,16 @@ +package com.mzaxd.noodles.annotation; + +import com.mzaxd.noodles.enums.OperationEnum; + +import java.lang.annotation.*; + +/** + * 操作日志注解 + * @author 13439 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface SysLog { + OperationEnum operation(); +} diff --git a/src/main/java/com/mzaxd/noodles/aspect/SysLogAspect.java b/src/main/java/com/mzaxd/noodles/aspect/SysLogAspect.java new file mode 100644 index 0000000..56c0e88 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/aspect/SysLogAspect.java @@ -0,0 +1,68 @@ +package com.mzaxd.noodles.aspect; + +import com.alibaba.fastjson.JSON; +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.entity.AuditLog; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.AuditLogService; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.lang.reflect.Method; +import java.time.LocalDateTime; + +/** + * @author 13439 + */ +@Component +@Aspect +public class SysLogAspect { + + @Resource + private AuditLogService auditLogService; + + @Pointcut("@annotation(com.mzaxd.noodles.annotation.SysLog)") + public void logPointCut() { + + } + + //方法执行前后都操作 + @Around("logPointCut()") + public Object around(ProceedingJoinPoint point) throws Throwable { + //执行方法 + Object result = point.proceed(); + //保存日志 + saveSysLog(point); + return result; + } + + private void saveSysLog(ProceedingJoinPoint joinPoint) { + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + + AuditLog log = new AuditLog(); + SysLog syslog = method.getAnnotation(SysLog.class); + if (syslog != null) { + //注解上的描述 + log.setOperation(syslog.operation().getOperation()); + log.setOperationType(syslog.operation().getOperationType()); + } + + //请求的参数 + Object[] args = joinPoint.getArgs(); + try { + String params = JSON.toJSONString(args); + log.setParam(params); + } catch (Exception e) { + e.printStackTrace(); + } + + //保存系统日志 + auditLogService.save(log); + } +} diff --git a/src/main/java/com/mzaxd/noodles/config/FastJsonRedisSerializer.java b/src/main/java/com/mzaxd/noodles/config/FastJsonRedisSerializer.java new file mode 100644 index 0000000..60ea8eb --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/FastJsonRedisSerializer.java @@ -0,0 +1,55 @@ +package com.mzaxd.noodles.config; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.type.TypeFactory; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; + +import java.nio.charset.Charset; + +/** + * Redis使用FastJson序列化 + * + * @author sg + */ +public class FastJsonRedisSerializer implements RedisSerializer { + + public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + + private Class clazz; + + static { + ParserConfig.getGlobalInstance().setAutoTypeSupport(true); + } + + public FastJsonRedisSerializer(Class clazz) { + super(); + this.clazz = clazz; + } + + @Override + public byte[] serialize(T t) throws SerializationException { + if (t == null) { + return new byte[0]; + } + return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); + } + + @Override + public T deserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length <= 0) { + return null; + } + String str = new String(bytes, DEFAULT_CHARSET); + + return JSON.parseObject(str, clazz); + } + + + protected JavaType getJavaType(Class clazz) { + return TypeFactory.defaultInstance().constructType(clazz); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/config/MyBatisPlusConfig.java b/src/main/java/com/mzaxd/noodles/config/MyBatisPlusConfig.java new file mode 100644 index 0000000..3904253 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/MyBatisPlusConfig.java @@ -0,0 +1,26 @@ +package com.mzaxd.noodles.config; + +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author root + */ +@Configuration +public class MyBatisPlusConfig { + /** + * 新版 + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); + //分页插件 + mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); + //乐观锁插件 + mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + return mybatisPlusInterceptor; + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/config/RabbitMqConfig.java b/src/main/java/com/mzaxd/noodles/config/RabbitMqConfig.java new file mode 100644 index 0000000..6ec3ff4 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/RabbitMqConfig.java @@ -0,0 +1,54 @@ +package com.mzaxd.noodles.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mzaxd.noodles.constant.RabbitMqConstant; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; +import org.springframework.amqp.support.converter.MessageConverter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Mzaxd + * @since 2023-02-06 12:51 + */ +@Configuration +public class RabbitMqConfig { + + @Bean + public Queue rabbitmqDemoDirectQueue() { + /** + * 1、name: 队列名称 + * 2、durable: 是否持久化 + * 3、exclusive: 是否独享、排外的。如果设置为true,定义为排他队列。则只有创建者可以使用此队列。也就是private私有的。 + * 4、autoDelete: 是否自动删除。也就是临时队列。当最后一个消费者断开连接后,会自动删除。 + * */ + return new Queue(RabbitMqConstant.DYNAMIC_DATA_TOPIC, true, false, false); + } + + @Bean + public DirectExchange rabbitmqDemoDirectExchange() { + //Direct交换机 + return new DirectExchange(RabbitMqConstant.DYNAMIC_DATA_EXCHANGE, true, false); + } + + @Bean + public Binding bindDirect() { + //链式写法,绑定交换机和队列,并设置匹配键 + return BindingBuilder + //绑定队列 + .bind(rabbitmqDemoDirectQueue()) + //到交换机 + .to(rabbitmqDemoDirectExchange()) + //并设置匹配键 + .with(RabbitMqConstant.DYNAMIC_DATA_ROUTING); + } + + @Bean + public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) { + return new Jackson2JsonMessageConverter(objectMapper); + } +} diff --git a/src/main/java/com/mzaxd/noodles/config/RedisConfig.java b/src/main/java/com/mzaxd/noodles/config/RedisConfig.java new file mode 100644 index 0000000..26f8b16 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/RedisConfig.java @@ -0,0 +1,31 @@ +package com.mzaxd.noodles.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@Configuration +public class RedisConfig { + + @Bean + @SuppressWarnings(value = {"unchecked", "rawtypes"}) + public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + + FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class); + + // 使用StringRedisSerializer来序列化和反序列化redis的key值 + template.setKeySerializer(new StringRedisSerializer()); + template.setValueSerializer(serializer); + + // Hash的key也采用StringRedisSerializer的序列化方式 + template.setHashKeySerializer(new StringRedisSerializer()); + template.setHashValueSerializer(serializer); + + template.afterPropertiesSet(); + return template; + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/config/RestTemplateConfig.java b/src/main/java/com/mzaxd/noodles/config/RestTemplateConfig.java new file mode 100644 index 0000000..1e4c4d6 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/RestTemplateConfig.java @@ -0,0 +1,30 @@ +package com.mzaxd.noodles.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +/** + * @author root + */ +@Configuration +public class RestTemplateConfig { + + @Bean + public RestTemplate restTemplate(ClientHttpRequestFactory factory){ + return new RestTemplate(factory); + } + + @Bean + public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + //单位为ms + factory.setReadTimeout(5000); + //单位为ms + factory.setConnectTimeout(5000); + return factory; + } + +} diff --git a/src/main/java/com/mzaxd/noodles/config/SecurityConfig.java b/src/main/java/com/mzaxd/noodles/config/SecurityConfig.java new file mode 100644 index 0000000..13e1fac --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/SecurityConfig.java @@ -0,0 +1,72 @@ +package com.mzaxd.noodles.config; + +import com.mzaxd.noodles.filter.JwtAuthenticationTokenFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +import javax.annotation.Resource; + +/** + * @author root + */ +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Bean + public PasswordEncoder passwordEncoder(){ + return new BCryptPasswordEncoder(); + } + + @Resource + private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; + + @Resource + private AuthenticationEntryPoint authenticationEntryPoint; + + @Resource + private AccessDeniedHandler accessDeniedHandler; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + //关闭csrf + .csrf().disable() + //不通过Session获取SecurityContext + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + // 对于登录接口 允许匿名访问 + .antMatchers("/auth/login").permitAll() + .antMatchers("/ws/**").permitAll() + .antMatchers("/system/isFirstUse").permitAll() + // 除上面外的所有请求全部需要鉴权认证 + .anyRequest().authenticated(); + + http.exceptionHandling() + .authenticationEntryPoint(authenticationEntryPoint) + .accessDeniedHandler(accessDeniedHandler); + + + http.logout().disable(); + + http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); + //允许跨域 + http.cors(); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } +} diff --git a/src/main/java/com/mzaxd/noodles/config/SwaggerConfig.java b/src/main/java/com/mzaxd/noodles/config/SwaggerConfig.java new file mode 100644 index 0000000..0c8f582 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/SwaggerConfig.java @@ -0,0 +1,34 @@ +package com.mzaxd.noodles.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +/** + * @author root + */ +@Configuration +public class SwaggerConfig { + @Bean + public Docket customDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.mzaxd.controller")) + .build(); + } + private ApiInfo apiInfo() { + Contact contact = new Contact("一个人的团队", "http://www.my.com", "my@my.com"); + return new ApiInfoBuilder() + .title("文档标题") + .description("文档描述") + .contact(contact) // 联系方式 + .version("1.0.0") // 版本 + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/config/WebConfig.java b/src/main/java/com/mzaxd/noodles/config/WebConfig.java new file mode 100644 index 0000000..f0a8d92 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/WebConfig.java @@ -0,0 +1,59 @@ +package com.mzaxd.noodles.config; + +import com.alibaba.fastjson.serializer.SerializeConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.alibaba.fastjson.serializer.ToStringSerializer; +import com.alibaba.fastjson.support.config.FastJsonConfig; +import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +/** + * @author Mzaxd + */ +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + // 设置允许跨域的路径 + registry.addMapping("/**") + // 设置允许跨域请求的域名 + .allowedOriginPatterns("*") + // 是否允许cookie + .allowCredentials(true) + // 设置允许的请求方式 + .allowedMethods("GET", "POST", "DELETE", "PUT") + // 设置允许的header属性 + .allowedHeaders("*") + // 跨域允许时间 + .maxAge(3600); + } + + @Bean + public HttpMessageConverter fastJsonHttpMessageConverters() { + //1.需要定义一个Convert转换消息的对象 + FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); + FastJsonConfig fastJsonConfig = new FastJsonConfig(); + fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); + fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); + + SerializeConfig.globalInstance.put(Long.class, ToStringSerializer.instance); + + fastJsonConfig.setSerializeConfig(SerializeConfig.globalInstance); + fastConverter.setFastJsonConfig(fastJsonConfig); + HttpMessageConverter converter = fastConverter; + return converter; + } + + @Override + public void configureMessageConverters(List> converters) { + converters.add(fastJsonHttpMessageConverters()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/config/WebSocketConfig.java b/src/main/java/com/mzaxd/noodles/config/WebSocketConfig.java new file mode 100644 index 0000000..8f85a3e --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/config/WebSocketConfig.java @@ -0,0 +1,34 @@ +package com.mzaxd.noodles.config; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.web.servlet.ServletContextInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.server.standard.ServerEndpointExporter; +import org.springframework.web.util.WebAppRootListener; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; + +/** + * @author Mzaxd + * @since 2023-02-05 15:35 + */ +@Configuration +@ComponentScan +@EnableAutoConfiguration +public class WebSocketConfig implements ServletContextInitializer { + + @Bean + public ServerEndpointExporter serverEndpointExporter() { + return new ServerEndpointExporter(); + } + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + servletContext.addListener(WebAppRootListener.class); + servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize","52428800"); + servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize","52428800"); + } +} diff --git a/src/main/java/com/mzaxd/noodles/constant/OsConstant.java b/src/main/java/com/mzaxd/noodles/constant/OsConstant.java new file mode 100644 index 0000000..70796f8 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/constant/OsConstant.java @@ -0,0 +1,13 @@ +package com.mzaxd.noodles.constant; + +/** + * @author Mzaxd + * @since 2023-02-05 11:38 + */ +public class OsConstant { + + /** + * 操作系统为Linux + */ + public static final String LINUX = "linux"; +} diff --git a/src/main/java/com/mzaxd/noodles/constant/RabbitMqConstant.java b/src/main/java/com/mzaxd/noodles/constant/RabbitMqConstant.java new file mode 100644 index 0000000..56e14af --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/constant/RabbitMqConstant.java @@ -0,0 +1,22 @@ +package com.mzaxd.noodles.constant; + +/** + * @author root + */ +public class RabbitMqConstant { + + /** + * RabbitMQ的队列主题名称 + */ + public static final String DYNAMIC_DATA_TOPIC = "DynamicDataTopic"; + + /** + * RabbitMQ的direct交换机名称 + */ + public static final String DYNAMIC_DATA_EXCHANGE = "DynamicDataExchange"; + + /** + * RabbitMQ的direct交换机和队列绑定的匹配键 DirectRouting + */ + public static final String DYNAMIC_DATA_ROUTING = "DynamicDataRouting"; +} diff --git a/src/main/java/com/mzaxd/noodles/constant/RedisConstant.java b/src/main/java/com/mzaxd/noodles/constant/RedisConstant.java new file mode 100644 index 0000000..13f3592 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/constant/RedisConstant.java @@ -0,0 +1,43 @@ +package com.mzaxd.noodles.constant; + +/** + * @author root + */ +public class RedisConstant { + + /** + * Redis Key + * + * @author mzaxd + * @date 2/7/23 12:59 PM + * @param null + */ + public static final String DYNAMIC_DATA = "dynamicData:"; + + /** + * Redis Key + * + * @author mzaxd + * @date 2/7/23 12:59 PM + * @param null + */ + public static final String NOTIFY_CONTAINER_IDS = "notify:containerIds"; + + /** + * Redis Key + * + * @author mzaxd + * @date 2/7/23 12:59 PM + * @param null + */ + public static final String NOTIFY_HOST_IDS = "notify:hostIds"; + + /** + * Redis Key + * + * @author mzaxd + * @date 2/7/23 12:59 PM + * @param null + */ + public static final String NOTIFY_VM_IDS = "notify:vmIds"; +} diff --git a/src/main/java/com/mzaxd/noodles/constant/SystemConstant.java b/src/main/java/com/mzaxd/noodles/constant/SystemConstant.java new file mode 100644 index 0000000..2962ad6 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/constant/SystemConstant.java @@ -0,0 +1,160 @@ +package com.mzaxd.noodles.constant; + +/** + * @author root + */ +public class SystemConstant { + + /** + * 宿主机id等于0表示没有宿主机,即物理机 + */ + public static final Integer PHYSICAL_MACHINE = 0; + + /** + * 主机在线 + */ + public static final Integer HOST_MACHINE_STATE_ONLINE = 0; + + /** + * 主机离线 + */ + public static final Integer HOST_MACHINE_STATE_OFFLINE = 1; + + /** + * 主机睡眠 + */ + public static final Integer HOST_MACHINE_STATE_SLEEP = 2; + + /** + * 主机状态未知 + */ + public static final Integer HOST_MACHINE_STATE_UNKNOWN = 3; + + /** + * 物理机 host_machine_id 是 0 + */ + public static final Long HOST_MACHINE_ID_HOST = 0L; + + /** + * 成功id + */ + public static final Integer SUCCESS_CODE = 200; + + /** + * 容器正在运行 + */ + public static final Integer CONTAINER_STATE_RUNNING = 0; + + /** + * 容器停止 + */ + public static final Integer CONTAINER_STATE_EXITED = 1; + + /** + * 容器暂停 + */ + public static final Integer CONTAINER_STATE_PAUSED = 2; + + /** + * 容器状态未知 + */ + public static final Integer CONTAINER_STATE_UNKNOWN = 3; + + /** + * 正常状态(非第一次使用) 通用常量 + */ + public static final Integer NORMAL_STATE = 1; + + /** + * 日志类型为用户 + */ + public static final String LOG_USER = "用户"; + + /** + * 提醒方式-不提醒 + */ + public static final Integer NOTIFY_NO = 0; + + /** + * 提醒方式-浏览器 + */ + public static final Integer NOTIFY_BROWSER = 1; + + /** + * 提醒方式-邮件 + */ + public static final Integer NOTIFY_EMAIL = 2; + + /** + * 提醒方式-浏览器和邮件 + */ + public static final Integer NOTIFY_BROWSER_EMAIL = 3; + + /** + * 通知类型 掉线 + */ + public static final Integer OFFLINE_NOTIFICATION = 0; + + /** + * 通知类型 统计 + */ + public static final Integer STATISTICS_NOTIFICATION = 1; + + /** + * 未处理的通知 + */ + public static final Integer NOTIFICATION_NOT_AFFIRM = 0; + + /** + * 已处理的通知 + */ + public static final Integer NOTIFICATION_AFFIRM = 1; + + /** + * 前端页面通知提醒页面对应的tab + */ + public static final Integer FRONTEND_NOTIFICATION_NOT_AFFIRM = 0; + + /** + * 前端页面通知提醒页面对应的tab + */ + public static final Integer FRONTEND_NOTIFICATION_AFFIRM = 1; + + /** + * 前端页面通知提醒页面对应的tab + */ + public static final Integer FRONTEND_NOTIFICATION_ALL = 2; + + /** + * 前端页面通知提醒页面对应的tab + */ + public static final Integer FRONTEND_NOTIFICATION_TYPE_OFFLINE = 3; + + /** + * 前端页面通知提醒页面对应的tab + */ + public static final Integer FRONTEND_NOTIFICATION_TYPE_STATISTICS = 4; + + /** + * 通知实例类型 无 + */ + public static final Integer INSTANCETYPE_NONE = 0; + + /** + * 通知实例类型 物理机 + */ + public static final Integer INSTANCETYPE_HOST = 1; + + /** + * 通知实例类型 虚拟机 + */ + public static final Integer INSTANCETYPE_VM = 2; + + /** + * 通知实例类型 容器 + */ + public static final Integer INSTANCETYPE_CONTAINER = 3; + + + +} diff --git a/src/main/java/com/mzaxd/noodles/constant/UrlConstant.java b/src/main/java/com/mzaxd/noodles/constant/UrlConstant.java new file mode 100644 index 0000000..d18ab62 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/constant/UrlConstant.java @@ -0,0 +1,57 @@ +package com.mzaxd.noodles.constant; + +/** + * @author root + */ +public class UrlConstant { + + /** + * isTrueUrl判断地址是否有效的链接 + */ + public static final String DETECTOR_IS_TRUE_URL = "/isTrueUrl"; + + /** + * 获取远程主机信息链接 + */ + public static final String DETECTOR_GET_INFO = "/getInfo"; + + /** + * 获取远程主机信息链接 + */ + public static final String DETECTOR_GET_DISK_INFO = "/getDiskInfo"; + + /** + * 获取远程主机信息链接 + */ + public static final String DETECTOR_GET_NETWORK_IF_INFO = "/getNetworkIfInfo"; + + /** + * 获取探测器uuid + */ + public static final String DETECTOR_GET_DETECTOR_ID = "/getDetectorID"; + + /** + * 通知探测器开始发送动态数据 + */ + public static final String DETECTOR_START_SEND_DYNAMIC_DATA = "/startSendDynamicDataFromMq"; + + /** + * 通知探测器停止发送动态数据 + */ + public static final String DETECTOR_STOP_SEND_DYNAMIC_DATA = "/stopSendDynamicDataFromMq"; + + /** + * 协议 + */ + public static final String PROTOCOL = "protocol"; + + /** + * ip + */ + public static final String IP = "IP"; + + /** + * 端口号 + */ + public static final String PORT = "port"; +} diff --git a/src/main/java/com/mzaxd/noodles/controller/AuthController.java b/src/main/java/com/mzaxd/noodles/controller/AuthController.java new file mode 100644 index 0000000..4df1e85 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/AuthController.java @@ -0,0 +1,43 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.User; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.LoginService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +/** + * @author root + */ +@RestController +@RequestMapping("/auth") +public class AuthController { + + @Resource + private LoginService loginService; + + @PostMapping("/login") + public ResponseResult login(@RequestBody User user) { + return loginService.login(user); + } + + @SysLog(operation = OperationEnum.USER_FIRST_USE) + @PostMapping("/updateAccount") + public ResponseResult updateAccount(@RequestBody User user) { + return loginService.updateAccount(user); + } + + @PostMapping("/logout") + public ResponseResult logout() { + return loginService.logout(); + } + + @GetMapping("/deleteAccount") + public ResponseResult deleteAccount() { + return loginService.deleteAccount(); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/ContainerController.java b/src/main/java/com/mzaxd/noodles/controller/ContainerController.java new file mode 100644 index 0000000..685d290 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/ContainerController.java @@ -0,0 +1,79 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.vo.ContainerVo; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.ContainerService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author root + */ +@RestController +@RequestMapping("/container") +public class ContainerController { + + @Resource + private ContainerService containerService; + + @GetMapping("/containerList/summaryStatistics") + public ResponseResult containerListSummaryStatistics() { + return containerService.containerListSummaryStatistics(); + } + + @GetMapping("/containerList") + public ResponseResult containerListWithCondition( + @RequestParam(value = "q", required = false) String nameLike, + @RequestParam(value = "selectedHost", required = false) List selectedHost, + @RequestParam(value = "selectedStatus", required = false) List selectedStatus, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return containerService.containerListWithCondition(nameLike, selectedHost, selectedStatus, perPage, currentPage); + } + + @GetMapping("/allHost") + public ResponseResult hostDrawer() { + return containerService.getAllHost(); + } + + @SysLog(operation = OperationEnum.CONTAINER_DELETE) + @DeleteMapping("/delete/{id}") + public ResponseResult deleteContainer(@PathVariable("id") Integer id) { + return containerService.deleteContainerById(id); + } + + @SysLog(operation = OperationEnum.CONTAINER_ADD) + @PostMapping("/addContainer") + public ResponseResult addContainer(@RequestBody Map container) { + return containerService.addContainer(container.get("container")); + } + + @GetMapping("/{id}") + public ResponseResult getContainer(@PathVariable("id") Integer id) { + return containerService.getContainer(id); + } + @SysLog(operation = OperationEnum.CONTAINER_UPDATE) + @PostMapping("/updateContainer") + public ResponseResult updateVm(@RequestBody Map container) { + return containerService.updateContainer(container.get("container")); + } + + @GetMapping("/allContainer") + public ResponseResult allContainer() { + return containerService.getAllContainer(); + } + + @GetMapping("/associatedContainers") + public ResponseResult getAssociatedContainers( + @RequestParam("hostId") Integer hostId, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return containerService.getAssociatedContainers(hostId, perPage, currentPage); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/DashboardController.java b/src/main/java/com/mzaxd/noodles/controller/DashboardController.java new file mode 100644 index 0000000..967a6aa --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/DashboardController.java @@ -0,0 +1,55 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.service.DashboardService; +import com.mzaxd.noodles.service.EveryDayDataService; +import com.mzaxd.noodles.service.HostDetectorService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ + +@RestController +@RequestMapping("/dashboard") +public class DashboardController { + + @Resource + private HostDetectorService detectorService; + + @Resource + private EveryDayDataService everyDayDataService; + + @Resource + private DashboardService dashboardService; + + @GetMapping("/getMemInfo") + public ResponseResult getMemInfo() { + return detectorService.getMemInfo(); + } + + @GetMapping("/getAuditLogCountYesterday") + public ResponseResult getAuditLogCountYesterday() { + return everyDayDataService.getAuditLogCountYesterday(); + } + + @GetMapping("/getInstancesHistory") + public ResponseResult getInstancesHistory() { + return everyDayDataService.getInstancesHistory(); + } + + @GetMapping("/getInstancesRealTimeData") + public ResponseResult getInstancesRealTimeData() { + return dashboardService.getInstancesRealTimeData(); + } + + @GetMapping("/getRecentConsoleList") + public ResponseResult getRecentConsoleList() { + return dashboardService.getRecentConsoleList(); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/DetectorController.java b/src/main/java/com/mzaxd/noodles/controller/DetectorController.java new file mode 100644 index 0000000..6bdbe77 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/DetectorController.java @@ -0,0 +1,30 @@ +package com.mzaxd.noodles.controller; + + +import com.mzaxd.noodles.constant.UrlConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.service.HostDetectorService; +import com.mzaxd.noodles.util.UrlUtil; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * @author root + */ +@RestController +@RequestMapping("/detector") +public class DetectorController { + + @Resource + private HostDetectorService hostDetectorService; + + @GetMapping("/isValidUrl/{protocol}/{ip}/{port}") + public ResponseResult isValidUrl(@PathVariable String protocol,@PathVariable String ip, @PathVariable String port) { + return hostDetectorService.isValidUrl(protocol,ip,port); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/HostController.java b/src/main/java/com/mzaxd/noodles/controller/HostController.java new file mode 100644 index 0000000..59bc70d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/HostController.java @@ -0,0 +1,140 @@ +package com.mzaxd.noodles.controller; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.fastjson.JSON; +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.domain.vo.HostVo; +import com.mzaxd.noodles.domain.vo.VmVo; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.HostMachineService; +import com.mzaxd.noodles.util.WebUtils; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; + +/** + * @author root + */ +@RestController +@RequestMapping("/host") +public class HostController { + + @Resource + private HostMachineService hostMachineService; + + @GetMapping("/drawer") + public ResponseResult hostDrawer() { + return hostMachineService.getHostDrawer(); + } + + @GetMapping("/vmList") + public ResponseResult vmListWithCondition( + @RequestParam(value = "q", required = false) String nameLike, + @RequestParam(value = "selectedKernel", required = false) List selectedKernel, + @RequestParam(value = "selectedHost", required = false) List selectedHost, + @RequestParam(value = "selectedStatus", required = false) List selectedStatus, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return hostMachineService.vmListWithCondition(nameLike, selectedKernel, selectedHost, selectedStatus, perPage, currentPage); + } + + @GetMapping("/vmList/summaryStatistics") + public ResponseResult vmListSummaryStatistics() { + return hostMachineService.vmListSummaryStatistics(); + } + + @SysLog(operation = OperationEnum.VM_ADD) + @PostMapping("/addVm") + public ResponseResult addVm(@RequestBody Map vmVo) { + return hostMachineService.addVm(vmVo.get("vm")); + } + + @SysLog(operation = OperationEnum.VM_UPDATE) + @PostMapping("/updateVm") + public ResponseResult updateVm(@RequestBody Map vmVo) { + return hostMachineService.updateVm(vmVo.get("vm")); + } + + @SysLog(operation = OperationEnum.VM_DELETE) + @DeleteMapping("/deleteVm/{id}") + public ResponseResult deleteVm(@PathVariable("id") Integer id) { + return hostMachineService.deleteVmById(id); + } + + @SysLog(operation = OperationEnum.HOST_DELETE) + @DeleteMapping("/deleteHost/{id}") + public ResponseResult deleteHost(@PathVariable("id") Integer id) { + return hostMachineService.deleteHostById(id); + } + + @GetMapping("/vm/{id}") + public ResponseResult getVmById(@PathVariable("id") Integer id) { + return hostMachineService.getVmById(id); + } + + @SysLog(operation = OperationEnum.HOST_UPDATE) + @PostMapping("/updateHost") + public ResponseResult updateHost(@RequestBody Map hostVo) { + return hostMachineService.updateHost(hostVo.get("host")); + } + + @GetMapping("/host/{id}") + public ResponseResult getHostById(@PathVariable("id") Integer id) { + return hostMachineService.getHostById(id); + } + + @GetMapping("/hostList") + public ResponseResult vmListWithCondition( + @RequestParam(value = "q", required = false) String nameLike, + @RequestParam(value = "selectedStatus", required = false) List selectedStatus, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return hostMachineService.hostListWithCondition(nameLike, selectedStatus, perPage, currentPage); + } + + @SysLog(operation = OperationEnum.HOST_ADD) + @PostMapping("/addHost") + public ResponseResult addHost(@RequestBody Map hostVo) { + return hostMachineService.addHost(hostVo.get("host")); + } + + @GetMapping("/hostDetail/{id}") + public ResponseResult getHostDetail(@PathVariable("id") Integer id) { + return hostMachineService.getHostDetail(id); + } + + @GetMapping("/associatedVms") + public ResponseResult getAssociatedVms( + @RequestParam("hostId") Integer hostId, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return hostMachineService.getAssociatedVms(hostId, perPage, currentPage); + } + + @GetMapping("/associatedDisks/{id}") + public ResponseResult getAssociatedDisks(@PathVariable("id") Integer id){ + return hostMachineService.getAssociatedDisks(id); + } + + @GetMapping("/associatedNetworkIfs/{id}") + public ResponseResult getAssociatedNetworkIfs(@PathVariable("id") Integer id) { + return hostMachineService.getAssociatedNetworkIfs(id); + } + + @GetMapping("/startSendDynamicData/{id}") + public ResponseResult startSendDynamicData(@PathVariable("id") Integer hostId) { + return hostMachineService.startSendDynamicData(hostId); + } + + @GetMapping("/stopSendDynamicData/{id}") + public ResponseResult stopSendDynamicData(@PathVariable("id") Integer hostId) { + return hostMachineService.stopSendDynamicData(hostId); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/LogController.java b/src/main/java/com/mzaxd/noodles/controller/LogController.java new file mode 100644 index 0000000..8e81d49 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/LogController.java @@ -0,0 +1,34 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.service.AuditLogService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ +@RestController +@RequestMapping("/auditLog") +public class LogController { + + @Resource + private AuditLogService auditLogService; + + @GetMapping("/logList") + public ResponseResult getLogList(@RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return auditLogService.getLogList(perPage, currentPage); + } + + @GetMapping("/getParam/{id}") + public ResponseResult getParam(@PathVariable("id") Integer id) { + return auditLogService.getParam(id); + } + + @GetMapping("/userLog") + public ResponseResult getUserLog() { + return auditLogService.getUserLog(); + } +} diff --git a/src/main/java/com/mzaxd/noodles/controller/NotificationController.java b/src/main/java/com/mzaxd/noodles/controller/NotificationController.java new file mode 100644 index 0000000..a1865de --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/NotificationController.java @@ -0,0 +1,42 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.NotificationService; +import io.swagger.models.auth.In; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; + +/** + * @author 13439 + */ +@RestController +@RequestMapping("/notification") +public class NotificationController { + + @Resource + private NotificationService notificationService; + + @GetMapping("/notificationList") + public ResponseResult getNotificationList( + @RequestParam(value = "tab", required = false) Integer tab, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return notificationService.getNotificationList(tab, perPage, currentPage); + } + + @SysLog(operation = OperationEnum.NOTIFICATION_AFFIRM) + @PutMapping("/{id}") + public ResponseResult affirmNotification(@PathVariable("id") Long id) { + return notificationService.affirmNotification(id); + } + + @GetMapping("/count") + public ResponseResult getNotificationCount() { + return notificationService.getNotificationCount(); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/ServirController.java b/src/main/java/com/mzaxd/noodles/controller/ServirController.java new file mode 100644 index 0000000..b927576 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/ServirController.java @@ -0,0 +1,71 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.vo.SaveOrUpdateServirVo; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.ServirService; +import com.mzaxd.noodles.service.TagService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * @author 13439 + */ +@RestController +@RequestMapping("/servir") +public class ServirController { + + @Resource + private TagService tagService; + + @Resource + private ServirService servirService; + + + @GetMapping("/tags") + public ResponseResult getAllTag() { + return tagService.getAllTag(); + } + + @GetMapping("/servirList") + public ResponseResult servirListWithCondition( + @RequestParam(value = "q", required = false) String nameLike, + @RequestParam(value = "selectedTags", required = false) List selectedTags, + @RequestParam("perPage") Integer perPage, + @RequestParam("currentPage") Integer currentPage) { + return servirService.servirListWithCondition(nameLike, selectedTags, perPage, currentPage); + } + + @SysLog(operation = OperationEnum.SERVIR_ADD) + @PostMapping("/addServir") + public ResponseResult addServir(@RequestBody Map saveOrUpdateServirVoMap) { + return servirService.addServir(saveOrUpdateServirVoMap.get("servir")); + } + @SysLog(operation = OperationEnum.SERVIR_UPDATE) + @PostMapping("/updateServir") + public ResponseResult updateServir(@RequestBody Map saveOrUpdateServirVoMap) { + return servirService.updateServir(saveOrUpdateServirVoMap.get("servir")); + } + + @SysLog(operation = OperationEnum.SERVIR_DELETE) + @DeleteMapping("/deleteServir/{id}") + public ResponseResult deleteServir(@PathVariable("id") Integer id) { + return servirService.deleteServirById(id); + } + + @GetMapping("/{id}") + public ResponseResult getServirDataById(@PathVariable("id") Integer id) { + return servirService.getServirById(id); + } + + @GetMapping("/getRemark/{id}") + public ResponseResult getRemarkById(@PathVariable("id") Integer id) { + return servirService.getRemarkById(id); + } + + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/SettingController.java b/src/main/java/com/mzaxd/noodles/controller/SettingController.java new file mode 100644 index 0000000..18b796b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/SettingController.java @@ -0,0 +1,50 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.vo.SmtpVo; +import com.mzaxd.noodles.domain.vo.SystemVo; +import com.mzaxd.noodles.domain.vo.TerminalVo; +import com.mzaxd.noodles.service.SystemSettingService; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ +@RestController +@RequestMapping("/setting") +public class SettingController { + + @Resource + private SystemSettingService systemSettingService; + + @GetMapping("/smtp") + public ResponseResult getSmtpSetting() { + return systemSettingService.getSmtpSetting(); + } + + @PostMapping("/smtp") + public ResponseResult saveSmtpSetting(@RequestBody SmtpVo smtpVo) { + return systemSettingService.saveSmtpSetting(smtpVo); + } + @GetMapping("/terminal") + public ResponseResult getTerminalSetting() { + return systemSettingService.getTerminalSetting(); + } + + @PostMapping("/terminal") + public ResponseResult saveTerminalSetting(@RequestBody TerminalVo terminalVo) { + return systemSettingService.saveTerminalSetting(terminalVo); + } + + @GetMapping("/system") + public ResponseResult getSystemSetting() { + return systemSettingService.getSystemSetting(); + } + + @PostMapping("/system") + public ResponseResult saveSystemSetting(@RequestBody SystemVo systemVo) { + return systemSettingService.saveSystemSetting(systemVo); + } +} diff --git a/src/main/java/com/mzaxd/noodles/controller/SshLinkController.java b/src/main/java/com/mzaxd/noodles/controller/SshLinkController.java new file mode 100644 index 0000000..3ba829b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/SshLinkController.java @@ -0,0 +1,31 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.SshLinkService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ +@RestController +@RequestMapping("/sshLink") +public class SshLinkController { + + @Resource + private SshLinkService sshLinkService; + + @SysLog(operation = OperationEnum.CONSOLE_CONNECT) + @GetMapping("/getInstanceInfo/{sshId}") + public ResponseResult getInstanceInfo(@PathVariable("sshId") Long sshId) { + return sshLinkService.getInstanceInfo(sshId); + } + + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/SystemController.java b/src/main/java/com/mzaxd/noodles/controller/SystemController.java new file mode 100644 index 0000000..9ea8538 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/SystemController.java @@ -0,0 +1,26 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.service.UserService; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ + +@RestController +@RequestMapping("/system") +public class SystemController { + + @Resource + private UserService userService; + + @RequestMapping("/isFirstUse") + private ResponseResult isFirstUse() { + return userService.isFirstUse(); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/controller/TagController.java b/src/main/java/com/mzaxd/noodles/controller/TagController.java new file mode 100644 index 0000000..396e5dd --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/TagController.java @@ -0,0 +1,25 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.service.TagService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ +@RestController +@RequestMapping("/tag") +public class TagController { + + @Resource + private TagService tagService; + + @GetMapping("/allTag") + public ResponseResult getAllTag() { + return tagService.getAllTag(); + } +} diff --git a/src/main/java/com/mzaxd/noodles/controller/UserController.java b/src/main/java/com/mzaxd/noodles/controller/UserController.java new file mode 100644 index 0000000..8d720d9 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/controller/UserController.java @@ -0,0 +1,65 @@ +package com.mzaxd.noodles.controller; + +import com.mzaxd.noodles.annotation.SysLog; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.User; +import com.mzaxd.noodles.domain.vo.UserInfoVo; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.UserService; +import com.mzaxd.noodles.util.IpUtil; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.Map; + +/** + * @author root + */ +@RestController +@RequestMapping("/user") +public class UserController { + + @Resource + private UserService userService; + + @GetMapping("/userInfo") + public ResponseResult userInfo() { + return userService.userInfo(); + } + + @PutMapping("/userInfo") + public ResponseResult updateUserInfo(@RequestBody User user) { + return userService.updateUserInfo(user); + } + + @GetMapping("/profileHeader/{id}") + public ResponseResult profileHeader(@PathVariable("id") Integer id, HttpServletRequest request) { + String ipAddr = IpUtil.getIpAddr(request); + return userService.getProfileHeader(id, ipAddr); + } + + @GetMapping("/profile") + public ResponseResult profile() { + return userService.getProfile(); + } + + @GetMapping("/{id}") + public ResponseResult getUserInfo(@PathVariable("id") Integer id) { + return userService.getUserInfo(id); + } + + @SysLog(operation = OperationEnum.USER_UPDATE_PASSWORD) + @PostMapping("/changePassword") + public ResponseResult changePassword(@RequestBody Map map) { + return userService.changePassword(map.get("password")); + } + + @SysLog(operation = OperationEnum.USER_UPDATE_USERINFO) + @PostMapping("/updateUserInfo") + public ResponseResult updateUserInfo(@RequestBody Map map) { + return userService.updateUserInfo(map.get("user")); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/ResponseResult.java b/src/main/java/com/mzaxd/noodles/domain/ResponseResult.java new file mode 100644 index 0000000..7889cd8 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/ResponseResult.java @@ -0,0 +1,131 @@ +package com.mzaxd.noodles.domain; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; + +import java.io.Serializable; + +/** + * @author Mzaxd + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ResponseResult implements Serializable { + private Integer code; + private String msg; + private T data; + + public ResponseResult() { + this.code = AppHttpCodeEnum.SUCCESS.getCode(); + this.msg = AppHttpCodeEnum.SUCCESS.getMsg(); + } + + public ResponseResult(Integer code, T data) { + this.code = code; + this.data = data; + } + + public ResponseResult(Integer code, String msg, T data) { + this.code = code; + this.msg = msg; + this.data = data; + } + + public ResponseResult(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + + public static ResponseResult errorResult(int code, String msg) { + ResponseResult result = new ResponseResult(); + return result.error(code, msg); + } + public static ResponseResult okResult() { + ResponseResult result = new ResponseResult(); + return result; + } + public static ResponseResult okResult(int code, String msg) { + ResponseResult result = new ResponseResult(); + return result.ok(code, null, msg); + } + public static ResponseResult okResult(String msg, Object data) { + ResponseResult result = setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS); + result.setMsg(msg); + if(data!=null) { + result.setData(data); + } + return result; + } + + public static ResponseResult okResult(Object data) { + ResponseResult result = setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getMsg()); + if(data!=null) { + result.setData(data); + } + return result; + } + + public static ResponseResult errorResult(AppHttpCodeEnum enums){ + return setAppHttpCodeEnum(enums,enums.getMsg()); + } + + public static ResponseResult errorResult(AppHttpCodeEnum enums, String msg){ + return setAppHttpCodeEnum(enums,msg); + } + + public static ResponseResult setAppHttpCodeEnum(AppHttpCodeEnum enums){ + return okResult(enums.getCode(),enums.getMsg()); + } + + private static ResponseResult setAppHttpCodeEnum(AppHttpCodeEnum enums, String msg){ + return okResult(enums.getCode(),msg); + } + + public ResponseResult error(Integer code, String msg) { + this.code = code; + this.msg = msg; + return this; + } + + public ResponseResult ok(Integer code, T data) { + this.code = code; + this.data = data; + return this; + } + + public ResponseResult ok(Integer code, T data, String msg) { + this.code = code; + this.data = data; + this.msg = msg; + return this; + } + + public ResponseResult ok(T data) { + this.data = data; + return this; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/AuditLog.java b/src/main/java/com/mzaxd/noodles/domain/entity/AuditLog.java new file mode 100644 index 0000000..309b839 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/AuditLog.java @@ -0,0 +1,63 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; +import java.util.Objects; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName audit_log + */ +@TableName(value ="audit_log") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +@EqualsAndHashCode(of = "param") +public class AuditLog implements Serializable { + /** + * id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 操作 + */ + private String operation; + + /** + * 操作类型(用户/容器/虚拟机/物理机/服务/系统) + */ + private String operationType; + + /** + * 请求参数 + */ + private String param; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; + +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/Container.java b/src/main/java/com/mzaxd/noodles/domain/entity/Container.java new file mode 100644 index 0000000..5ae29d1 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/Container.java @@ -0,0 +1,111 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName container + */ +@TableName(value ="container") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class Container implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 镜像名 + */ + private String imageName; + + /** + * WebUi URL + */ + private String webUi; + + /** + * 宿主机id + */ + private Long hostMachineId; + + /** + * ssh连接信息表id + */ + private Long sshId; + + /** + * 状态(0运行 1停止 2暂停 3未知) + */ + private Integer containerState; + + /** + * 提醒方式(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + /** + * 容器编号 + */ + private String containerId; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/EveryDayData.java b/src/main/java/com/mzaxd/noodles/domain/entity/EveryDayData.java new file mode 100644 index 0000000..88adf5f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/EveryDayData.java @@ -0,0 +1,108 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName every_data + */ +@TableName(value ="everyday_data") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class EveryDayData implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 主机总数 + */ + private Integer hostCount; + + /** + * 主机在线数量 + */ + private Integer hostOnlineCount; + + /** + * 主机离线数量 + */ + private Integer hostOfflineCount; + + /** + * 主机状态未知数量 + */ + private Integer hostUnknownCount; + + /** + * 虚拟机总数 + */ + private Integer vmCount; + + /** + * 虚拟机在线数量 + */ + private Integer vmOnlineCount; + + /** + * 虚拟机离线数量 + */ + private Integer vmOfflineCount; + + /** + * 虚拟机状态未知数量 + */ + private Integer vmUnknownCount; + + /** + * 容器总数 + */ + private Integer containerCount; + + /** + * 容器在线数量 + */ + private Integer containerOnlineCount; + + /** + * 容器离线数量 + */ + private Integer containerOfflineCount; + + /** + * 容器状态未知数量 + */ + private Integer containerUnknownCount; + + /** + * 服务总数 + */ + private Integer servirCount; + + /** + * 操作数 + */ + private Integer auditCount; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/HostDetector.java b/src/main/java/com/mzaxd/noodles/domain/entity/HostDetector.java new file mode 100644 index 0000000..fa6c07a --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/HostDetector.java @@ -0,0 +1,75 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * + * @author root + * @TableName host_detector + */ +@TableName(value ="host_detector") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class HostDetector implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 物理机id + */ + private Long hostMachineId; + + /** + * 探测器uuid(和机器一一绑定) + */ + private String detectorUuid; + + /** + * 探测器地址 + */ + private String detectorIpAddress; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/HostMachine.java b/src/main/java/com/mzaxd/noodles/domain/entity/HostMachine.java new file mode 100644 index 0000000..035889d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/HostMachine.java @@ -0,0 +1,116 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName host_machine + */ +@TableName(value ="host_machine") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class HostMachine implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * ssh连接信息表id + */ + private Long sshId; + + /** + * 操作系统id + */ + private Long osId; + + /** + * 管理ip地址 + */ + private String manageIp; + + /** + * 宿主机id(0代表物理机没有宿主机) + */ + private Long hostMachineId; + + /** + * 核心线程数 + */ + private Long threads; + + /** + * 内存 + */ + private Long memory; + + /** + * 状态(0在线 1离线 2睡眠 3未知) + */ + private Integer hostMachineState; + + /** + * 提醒方式(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/LoginUser.java b/src/main/java/com/mzaxd/noodles/domain/entity/LoginUser.java new file mode 100644 index 0000000..91e96fd --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/LoginUser.java @@ -0,0 +1,55 @@ +package com.mzaxd.noodles.domain.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; + +/** + * @author root + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class LoginUser implements UserDetails { + + private User user; + + @Override + public Collection getAuthorities() { + return null; + } + + @Override + public String getPassword() { + return user.getPassword(); + } + + @Override + public String getUsername() { + return user.getEmail(); + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/Notification.java b/src/main/java/com/mzaxd/noodles/domain/entity/Notification.java new file mode 100644 index 0000000..3f6b44b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/Notification.java @@ -0,0 +1,77 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @TableName notification + */ +@TableName(value ="notification") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class Notification implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 通知标题 + */ + private String title; + + /** + * 通知内容 + */ + private String content; + + /** + * 通知类型(0代表掉线通知,1代表统计通知) + */ + private Integer type; + + /** + * 可能关联的实例的类型(0代表无 1代表host 2代表vm 3代表container) + */ + private Integer instanceType; + + /** + * 可能关联的实例id + */ + private Long instanceId; + + /** + * 提醒发送方式(0不提醒 1浏览器 1邮件 3代表两者) + */ + private Integer sendType; + + /** + * 用户是否确认(0代表未确认 1代表已确认) + */ + private Integer affirm; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/Os.java b/src/main/java/com/mzaxd/noodles/domain/entity/Os.java new file mode 100644 index 0000000..6ddc8ad --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/Os.java @@ -0,0 +1,71 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * + * @author root + * @TableName os + */ +@TableName(value ="os") +@Data +@Accessors(chain = true) +public class Os implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 1代表Linux 2代表WindowsNT 3代表FreeBSD + */ + private Integer kernel; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id(0表示由系统创建) + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/Servir.java b/src/main/java/com/mzaxd/noodles/domain/entity/Servir.java new file mode 100644 index 0000000..efe9394 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/Servir.java @@ -0,0 +1,79 @@ +package com.mzaxd.noodles.domain.entity; + +import java.io.Serializable; +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName servir + */ +@TableName(value ="servir") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class Servir implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 备注 + */ + private String remark; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/ServirContainer.java b/src/main/java/com/mzaxd/noodles/domain/entity/ServirContainer.java new file mode 100644 index 0000000..37609ae --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/ServirContainer.java @@ -0,0 +1,74 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * @author 13439 + * @TableName servir_container + */ +@TableName(value ="servir_container") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ServirContainer implements Serializable { + /** + * id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 服务id + */ + private Long servirId; + + /** + * 容器id + */ + private Long containerId; + + /** + * 描述(关联方式) + */ + private String description; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/ServirHost.java b/src/main/java/com/mzaxd/noodles/domain/entity/ServirHost.java new file mode 100644 index 0000000..d3a941b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/ServirHost.java @@ -0,0 +1,76 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName servir_host + */ +@TableName(value ="servir_host") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class ServirHost implements Serializable { + /** + * id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 服务id + */ + private Long servirId; + + /** + * 服务器id(物理机、虚拟机都可以) + */ + private Long hostId; + + /** + * 描述(关联方式) + */ + private String description; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/ServirTag.java b/src/main/java/com/mzaxd/noodles/domain/entity/ServirTag.java new file mode 100644 index 0000000..65222ed --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/ServirTag.java @@ -0,0 +1,69 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * @author 13439 + * @TableName servir_tag + */ +@TableName(value ="servir_tag") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ServirTag implements Serializable { + /** + * id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 服务id + */ + private Long servirId; + + /** + * 标签id + */ + private Long tagId; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/SshLink.java b/src/main/java/com/mzaxd/noodles/domain/entity/SshLink.java new file mode 100644 index 0000000..fd3751a --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/SshLink.java @@ -0,0 +1,86 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName ssh_link + */ +@TableName(value ="ssh_link") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class SshLink implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 账号 + */ + private String host; + + /** + * 名称 + */ + private String name; + + /** + * 端口号 + */ + private Integer port; + + /** + * 密码 + */ + private String password; + + /** + * 控制台类型(bash/sh) + */ + private String consoleType; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/SystemSetting.java b/src/main/java/com/mzaxd/noodles/domain/entity/SystemSetting.java new file mode 100644 index 0000000..0699bb4 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/SystemSetting.java @@ -0,0 +1,85 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * + * @TableName system_setting + */ +@TableName(value ="system_setting") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SystemSetting implements Serializable { + /** + * id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 过期时间(1、3、7、30) + */ + private Integer logExpire; + + /** + * 检查实例状态间隔(秒) + */ + private Integer checkInstanceStatePeriod; + + /** + * ch/en + */ + private String defaultLang; + + /** + * 发送邮箱 + */ + private String serverEmail; + + /** + * 邮箱密码 + */ + private String emailPass; + + /** + * 接收邮箱 + */ + private String notificationEmail; + + /** + * 控制台渲染类型 + */ + private String rendererType; + + /** + * 字体大小 + */ + private Integer fontSize; + + /** + * 光标是否闪烁(0关1开) + */ + private Integer cursorBlink; + + /** + * 字体颜色 + */ + private String foreground; + + /** + * 背景色 + */ + private String background; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/Tag.java b/src/main/java/com/mzaxd/noodles/domain/entity/Tag.java new file mode 100644 index 0000000..8a06512 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/Tag.java @@ -0,0 +1,66 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; + +import java.io.Serializable; +import java.util.Date; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * + * @author 13439 + * @TableName tag + */ +@TableName(value ="tag") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class Tag implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/entity/User.java b/src/main/java/com/mzaxd/noodles/domain/entity/User.java new file mode 100644 index 0000000..cbe1e20 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/entity/User.java @@ -0,0 +1,86 @@ +package com.mzaxd.noodles.domain.entity; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +/** + * + * @author root + * @TableName user + */ +@TableName(value ="user") +@Data +@Accessors(chain = true) +public class User implements Serializable { + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 用户名 + */ + private String userName; + + /** + * 昵称 + */ + private String nickName; + + /** + * 邮箱 + */ + private String email; + + /** + * 密码 + */ + private String password; + + /** + * 头像 + */ + private String avatar; + + /** + * 账号状态(0代表未登陆过 1代表已经登录果) + */ + private Integer userState; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + /** + * 创建人id(0表示由系统创建) + */ + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.UPDATE) + private Date updateTime; + + /** + * 更新人id + */ + @TableField(fill = FieldFill.UPDATE) + private Long updateBy; + + /** + * 删除标志(0代表未删除,1代表已删除) + */ + private Integer delFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/domain/message/Cpu.java b/src/main/java/com/mzaxd/noodles/domain/message/Cpu.java new file mode 100644 index 0000000..a491981 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/Cpu.java @@ -0,0 +1,102 @@ +package com.mzaxd.noodles.domain.message; + +import com.mzaxd.noodledetector.util.Arith; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Mzaxd + * @since 2023-02-05 10:49 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Cpu { + + /** + * CPU型号 + */ + private String cpuName; + + /** + * CPU路数 + */ + private int physicalPackageCount; + + /** + * 核心数 + */ + private int physicalProcessorCount; + + /** + * 线程数 + */ + private int logicalProcessorCount; + + /** + * CPU主频 + */ + private long maxFreq; + + /** + * CPU Load + */ + private double cpuLoad; + + /** + * CPU总的使用率 + */ + private double total; + + /** + * CPU系统使用率 + */ + private double sys; + + /** + * CPU用户使用率 + */ + private double used; + + /** + * CPU当前等待率 + */ + private double wait; + + /** + * CPU当前空闲率 + */ + private double free; + + public double getCpuLoad() + { + return Double.parseDouble(String.format("%.1f", cpuLoad)); + } + + public double getTotal() + { + return Arith.round(Arith.mul(total, 100), 2); + } + + public double getSys() + { + return Arith.round(Arith.mul(sys / total, 100), 2); + } + + public double getUsed() + { + return Arith.round(Arith.mul(used / total, 100), 2); + } + + public double getWait() + { + return Arith.round(Arith.mul(wait / total, 100), 2); + } + + public double getFree() + { + return Arith.round(Arith.mul(free / total, 100), 2); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/message/DynamicData.java b/src/main/java/com/mzaxd/noodles/domain/message/DynamicData.java new file mode 100644 index 0000000..b65f960 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/DynamicData.java @@ -0,0 +1,73 @@ +package com.mzaxd.noodles.domain.message; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author Mzaxd + * @since 2023-02-05 18:49 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class DynamicData { + + /** + * 探测器id + */ + private String detectorId; + + /** + * CPU Load + */ + private double cpuLoad; + + /** + * CPU总的使用率 + */ + private double cpuTotal; + + /** + * CPU系统使用率 + */ + private double cpuSys; + + /** + * CPU用户使用率 + */ + private double cpuUser; + + /** + * CPU当前等待率 + */ + private double cpuWait; + + /** + * CPU当前空闲率 + */ + private double cpuFree; + + /** + * 已用内存 + */ + private double memUsed; + + /** + * 剩余内存 + */ + private double memFree; + + /** + * 上行速度 + */ + private String txPercent; + + /** + * 下行速度 + */ + private String rxPercent; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/message/Mem.java b/src/main/java/com/mzaxd/noodles/domain/message/Mem.java new file mode 100644 index 0000000..7ba2af1 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/Mem.java @@ -0,0 +1,41 @@ +package com.mzaxd.noodles.domain.message; + +/** + * @author Mzaxd + * @since 2023-02-05 10:50 + */ + +import com.mzaxd.noodledetector.util.Arith; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * 內存相关信息 + * + * @author huasheng + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Mem +{ + /** + * 内存总量 + */ + private double total; + + /** + * 已用内存 + */ + private double used; + + /** + * 剩余内存 + */ + private double free; + +} + + + diff --git a/src/main/java/com/mzaxd/noodles/domain/message/NetWork.java b/src/main/java/com/mzaxd/noodles/domain/message/NetWork.java new file mode 100644 index 0000000..b235d59 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/NetWork.java @@ -0,0 +1,60 @@ +package com.mzaxd.noodles.domain.message; + +/** + * @author Mzaxd + * @since 2023-02-05 10:52 + */ + +import lombok.Data; + +import java.util.List; + +/** + * 网速相关信息 + * + * @author huasheng + */ +@Data +public class NetWork { + + /** + * 主机ip + */ + private String hostAddress; + + /** + * hostName + */ + private String hostName; + + /** + * domainName + */ + private String domainName; + + /** + * dnsServers + */ + private List dnsServers; + + /** + * ipv4DefaultGateway + */ + private String ipv4DefaultGateway; + + /** + * ipv6DefaultGateway + */ + private String ipv6DefaultGateway; + + /** + * 上行速度 + */ + private String txPercent; + + /** + * 下行速度 + */ + private String rxPercent; +} + diff --git a/src/main/java/com/mzaxd/noodles/domain/message/Os.java b/src/main/java/com/mzaxd/noodles/domain/message/Os.java new file mode 100644 index 0000000..ff63d86 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/Os.java @@ -0,0 +1,31 @@ +package com.mzaxd.noodles.domain.message; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author Mzaxd + * @since 2023-02-05 13:29 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Os { + + /** + * 系统名 + */ + private String osName; + + /** + * 启动时间 + */ + private String booted; + + /** + * 正常运行时间 + */ + private String uptime; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/message/Server.java b/src/main/java/com/mzaxd/noodles/domain/message/Server.java new file mode 100644 index 0000000..e70cb14 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/Server.java @@ -0,0 +1,74 @@ +package com.mzaxd.noodles.domain.message; + +/** + * @author Mzaxd + * @since 2023-02-05 10:48 + */ + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import oshi.hardware.NetworkIF; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * 服务器相关信息 + * + * @author huasheng + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Server { + + private static final int OSHI_WAIT_SECOND = 1000; + /** + * 网速测速时间2s + */ + private static final int SLEEP_TIME = 2 * 1000; + + /** + * 探测器id + */ + private String detectorId; + + /** + * Os相关信息 + */ + private com.mzaxd.noodles.domain.message.Os os = new Os(); + + /** + * CPU相关信息 + */ + private Cpu cpu = new Cpu(); + + /** + * 內存相关信息 + */ + private Mem mem = new Mem(); + + /** + * 服务器相关信息 + */ + private Sys sys = new Sys(); + + /** + * 磁盘相关信息 + */ + private List sysFiles = new LinkedList(); + + /** + * 网络相关信息 + */ + private NetWork netWork = new NetWork(); + + /** + * 网络接口相关信息 + */ + private List netWorkIf = new ArrayList<>(); + +} + diff --git a/src/main/java/com/mzaxd/noodles/domain/message/Sys.java b/src/main/java/com/mzaxd/noodles/domain/message/Sys.java new file mode 100644 index 0000000..efec726 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/Sys.java @@ -0,0 +1,44 @@ +package com.mzaxd.noodles.domain.message; + +/** + * @author Mzaxd + * @since 2023-02-05 10:51 + */ + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * 系统相关信息 + * + * @author huasheng + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Sys +{ + /** + * manufacturer + */ + private String manufacturer; + + /** + * model + */ + private String model; + + /** + * serialNumber + */ + private String serialNumber; + + /** + * uuid + */ + private String uuid; +} + + + diff --git a/src/main/java/com/mzaxd/noodles/domain/message/SysFile.java b/src/main/java/com/mzaxd/noodles/domain/message/SysFile.java new file mode 100644 index 0000000..5bff942 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/message/SysFile.java @@ -0,0 +1,60 @@ +package com.mzaxd.noodles.domain.message; + +/** + * @author Mzaxd + * @since 2023-02-05 10:51 + */ + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * 系统文件相关信息 + * + * @author huasheng + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SysFile +{ + /** + * 盘符路径 + */ + private String dirName; + + /** + * 盘符类型 + */ + private String sysTypeName; + + /** + * 文件类型 + */ + private String typeName; + + /** + * 总大小 + */ + private String total; + + /** + * 剩余大小 + */ + private String free; + + /** + * 已经使用量 + */ + private String used; + + /** + * 资源的使用率 + */ + private double usage; + +} + + + diff --git a/src/main/java/com/mzaxd/noodles/domain/ssh/SshMessage.java b/src/main/java/com/mzaxd/noodles/domain/ssh/SshMessage.java new file mode 100644 index 0000000..d0c8a22 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/ssh/SshMessage.java @@ -0,0 +1,24 @@ +package com.mzaxd.noodles.domain.ssh; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 13439 + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SshMessage { + + private String op; + + private Integer cols; + + private Integer rows; + + private String data; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/ssh/SshModel.java b/src/main/java/com/mzaxd/noodles/domain/ssh/SshModel.java new file mode 100644 index 0000000..89fe568 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/ssh/SshModel.java @@ -0,0 +1,227 @@ +package com.mzaxd.noodles.domain.ssh; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.CharsetUtil; +import cn.hutool.core.util.EnumUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONArray; +import com.mzaxd.noodles.util.StringUtil; + +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.List; + +/** + * @ProjectName SshModel + * @author Administrator + * @version 1.0.0 + * @Description SshModel实体类 + * @createTime 2022/5/2 0002 15:29 + */ +public class SshModel { + + private String name; + private String host; + private Integer port; + private String user; + private String password; + /** + * 编码格式 + */ + private String charset; + + /** + * 文件目录 + */ + private String fileDirs; + + /** + * ssh 私钥 + */ + private String privateKey; + + private String connectType; + + /** + * 不允许执行的命令 + */ + private String notAllowedCommand; + + /** + * 允许编辑的后缀文件 + */ + private String allowEditSuffix; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNotAllowedCommand() { + return notAllowedCommand; + } + + public void setNotAllowedCommand(String notAllowedCommand) { + this.notAllowedCommand = notAllowedCommand; + } + + public ConnectType connectType() { + return EnumUtil.fromString(ConnectType.class, this.connectType, ConnectType.PASS); + } + + public String getConnectType() { + return connectType; + } + + public void setConnectType(String connectType) { + this.connectType = connectType; + } + + public String getPrivateKey() { + return privateKey; + } + + public void setPrivateKey(String privateKey) { + this.privateKey = privateKey; + } + + public String getFileDirs() { + return fileDirs; + } + + public void setFileDirs(String fileDirs) { + this.fileDirs = fileDirs; + } + + public List fileDirs() { + return StringUtil.jsonConvertArray(this.fileDirs, String.class); + } + + public void fileDirs(List fileDirs) { + if (fileDirs != null) { + for (int i = fileDirs.size() - 1; i >= 0; i--) { + String s = fileDirs.get(i); + fileDirs.set(i, FileUtil.normalize(s)); + } + this.fileDirs = JSONArray.toJSONString(fileDirs); + } else { + this.fileDirs = null; + } + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getCharset() { + return charset; + } + + public void setCharset(String charset) { + this.charset = charset; + } + + public Charset getCharsetT() { + Charset charset; + try { + charset = Charset.forName(this.getCharset()); + } catch (Exception e) { + charset = CharsetUtil.CHARSET_UTF_8; + } + return charset; + } + + public List allowEditSuffix() { + return StringUtil.jsonConvertArray(this.allowEditSuffix, String.class); + } + + public void allowEditSuffix(List allowEditSuffix) { + if (allowEditSuffix == null) { + this.allowEditSuffix = null; + } else { + this.allowEditSuffix = JSONArray.toJSONString(allowEditSuffix); + } + } + + public String getAllowEditSuffix() { + return allowEditSuffix; + } + + public void setAllowEditSuffix(String allowEditSuffix) { + this.allowEditSuffix = allowEditSuffix; + } + + /** + * 检查是否包含禁止命令 + * + * @param sshItem 实体 + * @param inputItem 输入的命令 + * @return false 存在禁止输入的命令 + */ + public static boolean checkInputItem(SshModel sshItem, String inputItem) { + // 检查禁止执行的命令 + String notAllowedCommand = StrUtil.emptyToDefault(sshItem.getNotAllowedCommand(), StrUtil.EMPTY).toLowerCase(); + if (StrUtil.isEmpty(notAllowedCommand)) { + return true; + } + List split = Arrays.asList(StrUtil.split(notAllowedCommand, StrUtil.COMMA)); + inputItem = inputItem.toLowerCase(); + List commands = Arrays.asList(StrUtil.split(inputItem, StrUtil.CR)); + commands.addAll(Arrays.asList(StrUtil.split(inputItem, "&"))); + for (String s : split) { + // + boolean anyMatch = commands.stream().anyMatch(item -> StrUtil.startWithAny(item, s + StrUtil.SPACE, ("&" + s + StrUtil.SPACE), StrUtil.SPACE + s + StrUtil.SPACE)); + if (anyMatch) { + return false; + } + // + anyMatch = commands.stream().anyMatch(item -> StrUtil.equals(item, s)); + if (anyMatch) { + return false; + } + } + return true; + } + + public enum ConnectType { + /** + * 账号密码 + */ + PASS, + /** + * 密钥 + */ + PUBKEY + } +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/AccountVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/AccountVo.java new file mode 100644 index 0000000..9912542 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/AccountVo.java @@ -0,0 +1,38 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AccountVo { + /** + * 主键id + */ + private Long id; + + /** + * 账号 + */ + private String account; + + /** + * 名称 + */ + private String name; + + /** + * 0代表管理员 1代表非管理员 + */ + private Integer type; + + /** + * 描述 + */ + private String description; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/AuditLogListVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/AuditLogListVo.java new file mode 100644 index 0000000..3f2974f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/AuditLogListVo.java @@ -0,0 +1,56 @@ +package com.mzaxd.noodles.domain.vo; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AuditLogListVo { + + /** + * id + */ + private Long id; + + /** + * 操作 + */ + private String operation; + + /** + * 操作类型(用户/容器/虚拟机/物理机/服务/系统) + */ + private String operationType; + + /** + * 请求参数 + */ + private String param; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 创建人id + */ + private Long createBy; + + /** + * 操作人信息 + */ + private UserInfoVo user; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ContainerSelectVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ContainerSelectVo.java new file mode 100644 index 0000000..0dc46b5 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ContainerSelectVo.java @@ -0,0 +1,35 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ContainerSelectVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ContainerVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ContainerVo.java new file mode 100644 index 0000000..142b01e --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ContainerVo.java @@ -0,0 +1,104 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class ContainerVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 镜像名 + */ + private String imageName; + + /** + * WebUi URL + */ + private String webUi; + + /** + * 宿主机id + */ + private Long hostMachineId; + + /** + * 宿主机信息 + */ + private HostMachineVo hostMachine; + + /** + * 状态(0在线 1离线 2孤立镜像) + */ + private Integer containerState; + + /** + * 容器编号 + */ + private String containerId; + + /** + * 状态(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + /** + * SSH Id + */ + private Long sshId; + + /** + * 控制台类型 + */ + private String sshType; + + /** + * SSH连接地址 + */ + private String sshHost; + + /** + * SSH连接地址端口号 + */ + private Integer sshPort; + + /** + * SSH连接用户 + */ + private String sshUser; + + /** + * SSH连接密码 + */ + private String sshPwd; + + + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineDrawerVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineDrawerVo.java new file mode 100644 index 0000000..1c5f145 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineDrawerVo.java @@ -0,0 +1,35 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class HostMachineDrawerVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineListVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineListVo.java new file mode 100644 index 0000000..d3dea9b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineListVo.java @@ -0,0 +1,86 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class HostMachineListVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 状态(0在线 1离线 2睡眠) + */ + private Integer hostMachineState; + + /** + * 探测器地址 + */ + private String detectorIpAddress; + + /** + * 操作系统id + */ + private Long osId; + + /** + * 操作系统Vo + */ + private OsVo os; + + /** + * 操作系统id + */ + private Long sshId; + + /** + * 操作系统Vo + */ + private SshLinkVo sshLink; + + /** + * 核心线程数 + */ + private Long threads; + + /** + * 内存 + */ + private Long memory; + + /** + * 管理ip地址 + */ + private String manageIp; + + /** + * 状态(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineVo.java new file mode 100644 index 0000000..fd69f7e --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/HostMachineVo.java @@ -0,0 +1,35 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class HostMachineVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/HostPanelVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/HostPanelVo.java new file mode 100644 index 0000000..6f62699 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/HostPanelVo.java @@ -0,0 +1,82 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class HostPanelVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 管理ip地址 + */ + private String manageIp; + + /** + * 协议 + */ + private String protocol; + + /** + * ip地址 + */ + private String ip; + + /** + * 端口 + */ + private String port; + + /** + * 1代表Linux 2代表WindowsNT 3代表FreeBSD + */ + private Integer osKernel; + + /** + * 状态(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + /** + * 状态(0在线 1离线 2睡眠) + */ + private Integer hostMachineState; + + /** + * 虚拟机数量 + */ + private Integer vmCount; + + /** + * 容器数量 + */ + private Integer containerCount; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/HostVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/HostVo.java new file mode 100644 index 0000000..21f50ad --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/HostVo.java @@ -0,0 +1,93 @@ +package com.mzaxd.noodles.domain.vo; + +import io.swagger.models.auth.In; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class HostVo { + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 管理ip地址 + */ + private String manageIp; + + /** + * 协议 + */ + private String protocol; + + /** + * ip地址 + */ + private String ip; + + /** + * 端口 + */ + private String port; + + /** + * 1代表Linux 2代表WindowsNT 3代表FreeBSD + */ + private Integer osKernel; + + /** + * 状态(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + /** + * 操作系统id + */ + private Long sshId; + + /** + * SSH连接地址 + */ + private String sshHost; + + /** + * SSH连接地址端口号 + */ + private Integer sshPort; + + /** + * SSH连接用户 + */ + private String sshUser; + + /** + * SSH连接密码 + */ + private String sshPwd; + +} + diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/NotificationListVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/NotificationListVo.java new file mode 100644 index 0000000..45ae383 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/NotificationListVo.java @@ -0,0 +1,77 @@ +package com.mzaxd.noodles.domain.vo; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Date; + +/** + * @author 13439 + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class NotificationListVo { + + /** + * 主键id + */ + @TableId(type = IdType.AUTO) + private Long id; + + /** + * 通知标题 + */ + private String title; + + /** + * 通知内容 + */ + private String content; + + /** + * 通知类型(0代表掉线通知,1代表统计通知) + */ + private Integer type; + + /** + * 可能关联的实例的类型(0代表无 1代表host 2代表vm 3代表container) + */ + private Integer instanceType; + + /** + * 可能关联的实例id + */ + private Long instanceId; + + /** + * 提醒发送方式(0不提醒 1浏览器 1邮件 3代表两者) + */ + private Integer sendType; + + /** + * 用户是否确认(0代表未确认 1代表已确认) + */ + private Integer affirm; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 关联的实例名称 + */ + private String instanceName; + + /** + * 关联的实例图标 + */ + private String instanceAvatar; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/OsVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/OsVo.java new file mode 100644 index 0000000..b194c68 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/OsVo.java @@ -0,0 +1,34 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OsVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 1代表Linux 2代表WindowsNT 3代表FreeBSD + */ + private Integer kernel; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ProfileHeaderVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ProfileHeaderVo.java new file mode 100644 index 0000000..ce491d1 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ProfileHeaderVo.java @@ -0,0 +1,36 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ProfileHeaderVo { + + /** + * 用户名 + */ + private String nickName; + + /** + * 头像 + */ + private String avatar; + + /** + * 登录地点 + */ + private String location; + + /** + * 账号创建时间 + */ + private Date createTime; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ProfileVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ProfileVo.java new file mode 100644 index 0000000..4a35ec5 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ProfileVo.java @@ -0,0 +1,63 @@ +package com.mzaxd.noodles.domain.vo; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ProfileVo { + + /** + * 用户名 + */ + private String userName; + + /** + * 昵称 + */ + private String nickName; + + /** + * 邮箱 + */ + private String email; + + /** + * 头像 + */ + private String avatar; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 总服务数 + */ + private Integer servirNumber; + + /** + * 总物理机数 + */ + private Integer hostNumber; + + /** + * 总虚拟机数 + */ + private Integer vmNumber; + + /** + * 总容器数 + */ + private Integer containerNumber; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/RecentConsoleListVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/RecentConsoleListVo.java new file mode 100644 index 0000000..129c701 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/RecentConsoleListVo.java @@ -0,0 +1,39 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + + +/** + * @author 13439 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +@Accessors(chain = true) +public class RecentConsoleListVo { + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * ssh连接信息表id + */ + private Long sshId; + + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/SaveOrUpdateServirVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/SaveOrUpdateServirVo.java new file mode 100644 index 0000000..f33d06b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/SaveOrUpdateServirVo.java @@ -0,0 +1,62 @@ +package com.mzaxd.noodles.domain.vo; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; +import java.util.List; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SaveOrUpdateServirVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 备注 + */ + private String remark; + + /** + * 容器id + */ + private List containerIds; + + /** + * 主机id + */ + private List hostIds; + + /** + * 标签id + */ + private List tagIds; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ServirContainerVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ServirContainerVo.java new file mode 100644 index 0000000..8d9cf7d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ServirContainerVo.java @@ -0,0 +1,40 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ServirContainerVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * WebUi URL + */ + private String webUi; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ServirHostVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ServirHostVo.java new file mode 100644 index 0000000..23add75 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ServirHostVo.java @@ -0,0 +1,42 @@ +package com.mzaxd.noodles.domain.vo; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ServirHostVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 管理ip地址 + */ + private String manageIp; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/ServirListVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/ServirListVo.java new file mode 100644 index 0000000..dffe1e6 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/ServirListVo.java @@ -0,0 +1,59 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.List; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class ServirListVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 备注 + */ + private String remark; + + /** + * 所有关联的host + */ + private List hosts; + + /** + * 所有关联的容器 + */ + private List containers; + + /** + * 所有标签 + */ + private List tags; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/SmtpVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/SmtpVo.java new file mode 100644 index 0000000..a5c3d0f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/SmtpVo.java @@ -0,0 +1,28 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SmtpVo { + /** + * 发送邮箱 + */ + private String serverEmail; + + /** + * 邮箱密码 + */ + private String emailPass; + + /** + * 接收邮箱 + */ + private String notificationEmail; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/SshLinkVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/SshLinkVo.java new file mode 100644 index 0000000..7fba0e1 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/SshLinkVo.java @@ -0,0 +1,46 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author 13439 + */ + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SshLinkVo { + + /** + * 主键id + */ + private Long id; + + /** + * 账号 + */ + private String host; + + /** + * 名称 + */ + private String name; + + /** + * 端口号 + */ + private Integer port; + + /** + * 密码 + */ + private String password; + + /** + * 控制台类型(bash/sh) + */ + private String consoleType; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/SystemVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/SystemVo.java new file mode 100644 index 0000000..24fe8be --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/SystemVo.java @@ -0,0 +1,32 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class SystemVo { + + /** + * 过期时间(1、3、7、30) + */ + private Integer logExpire; + + /** + * 检查实例状态间隔(秒) + */ + private Integer checkInstanceStatePeriod; + + /** + * ch/en + */ + private String defaultLang; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/TagVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/TagVo.java new file mode 100644 index 0000000..568db32 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/TagVo.java @@ -0,0 +1,21 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.Data; + +/** + * @author 13439 + */ + +@Data +public class TagVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/TerminalVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/TerminalVo.java new file mode 100644 index 0000000..afe533e --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/TerminalVo.java @@ -0,0 +1,41 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author 13439 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class TerminalVo { + + /** + * 控制台渲染类型 + */ + private String rendererType; + + /** + * 字体大小 + */ + private Integer fontSize; + + /** + * 光标是否闪烁(0关1开) + */ + private Integer cursorBlink; + + /** + * 字体颜色 + */ + private String foreground; + + /** + * 背景色 + */ + private String background; +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/UserInfoVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/UserInfoVo.java new file mode 100644 index 0000000..d7811c1 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/UserInfoVo.java @@ -0,0 +1,38 @@ +package com.mzaxd.noodles.domain.vo; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +/** + * @author root + */ +@Data +public class UserInfoVo { + + /** + * 主键id + */ + private Long id; + + /** + * 用户名 + */ + private String userName; + + /** + * 昵称 + */ + private String nickName; + + /** + * 头像 + */ + private String avatar; + + /** + * 邮箱 + */ + private String email; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/VirtualMachineListVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/VirtualMachineListVo.java new file mode 100644 index 0000000..c85b366 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/VirtualMachineListVo.java @@ -0,0 +1,76 @@ +package com.mzaxd.noodles.domain.vo; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class VirtualMachineListVo { + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 控制台id + */ + private Long sshId; + + /** + * 操作系统id + */ + private Long osId; + + /** + * 操作系统Vo + */ + private OsVo os; + + /** + * 管理ip地址 + */ + private String manageIp; + + /** + * 核心线程数 + */ + private Long threads; + + /** + * 内存 + */ + private Long memory; + + /** + * 状态(0在线 1离线 2睡眠) + */ + private Integer hostMachineState; + + /** + * 状态(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + +} diff --git a/src/main/java/com/mzaxd/noodles/domain/vo/VmVo.java b/src/main/java/com/mzaxd/noodles/domain/vo/VmVo.java new file mode 100644 index 0000000..c82ea5c --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/domain/vo/VmVo.java @@ -0,0 +1,94 @@ +package com.mzaxd.noodles.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +/** + * @author root + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Accessors(chain = true) +public class VmVo { + + /** + * 主键id + */ + private Long id; + + /** + * 名称 + */ + private String name; + + /** + * 描述 + */ + private String description; + + /** + * 图像 + */ + private String avatar; + + /** + * 宿主机id(0代表物理机没有宿主机) + */ + private Long hostMachineId; + + /** + * 核心线程数 + */ + private Long threads; + + /** + * 内存 + */ + private Long memory; + + /** + * 名称 + */ + private String osName; + + /** + * 管理ip地址 + */ + private String manageIp; + + /** + * 1代表Linux 2代表WindowsNT 3代表FreeBSD + */ + private Integer osKernel; + + /** + * 状态(0不提醒 1浏览器 2邮件 3浏览器&邮件) + */ + private Integer notify; + + /** + * SSH连接地址 + */ + private String sshHost; + + /** + * SSH连接地址端口号 + */ + private Integer sshPort; + + /** + * SSH连接用户 + */ + private String sshUser; + + /** + * SSH连接密码 + */ + private String sshPwd; + + + +} diff --git a/src/main/java/com/mzaxd/noodles/enums/AppHttpCodeEnum.java b/src/main/java/com/mzaxd/noodles/enums/AppHttpCodeEnum.java new file mode 100644 index 0000000..1b7f5ac --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/enums/AppHttpCodeEnum.java @@ -0,0 +1,65 @@ +package com.mzaxd.noodles.enums; + +/** + * @author Mzaxd + */ + +public enum AppHttpCodeEnum { + /** + * 操作成功通用返回信息 + */ + SUCCESS(200, "操作成功"), + + NEED_LOGIN(401, "需要登录后操作"), + + NO_OPERATOR_AUTH(403, "无权限操作"), + + SYSTEM_ERROR(500, "出现错误"), + + EMAIL_EXIST(503, "邮箱已存在"), + + LOGIN_ERROR(505, "邮箱或密码错误"), + + CONTENT_NOT_NULL(506, "评论不能为空"), + + FILE_TYPE_ERROR(507, "文件类型错误,请上传png文件"), + + USERNAME_NOT_NULL(508, "用户名不能为空"), + + PASSWORD_NOT_NULL(509, "密码不能为空"), + + NICKNAME_NOT_NULL(510, "昵称不能为空"), + + EMAIL_NOT_NULL(511, "邮箱不能为空"), + + NICKNAME_EXIST(512, "昵称已存在"), + + EXIST_ASSOCIATION_CONTAINER(513, "操作失败,存在关联的容器"), + + PORT_INVALID(514, "无效端口"), + + EXIST_ASSOCIATION_VM(513, "操作失败,存在关联的虚拟机"); + + + /** + * 统一响应码 + */ + final int code; + /** + * 响应信息 + */ + final String msg; + + AppHttpCodeEnum(int code, String errorMessage) { + this.code = code; + this.msg = errorMessage; + } + + public int getCode() { + return code; + } + + public String getMsg() { + return msg; + } +} diff --git a/src/main/java/com/mzaxd/noodles/enums/OperationEnum.java b/src/main/java/com/mzaxd/noodles/enums/OperationEnum.java new file mode 100644 index 0000000..9ea78a1 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/enums/OperationEnum.java @@ -0,0 +1,121 @@ +package com.mzaxd.noodles.enums; + +/** + * 操作日志-操作类型 + * + * @author 13439 + */ + +public enum OperationEnum { + + /** + * 新增物理机 + */ + HOST_ADD("新增物理机", "物理机"), + + /** + * 修改物理机 + */ + HOST_UPDATE("修改物理机", "物理机"), + + /** + * 删除物理机 + */ + HOST_DELETE("删除物理机", "物理机"), + + /** + * 新增虚拟机 + */ + VM_ADD("新增虚拟机", "虚拟机"), + + /** + * 修改虚拟机 + */ + VM_UPDATE("修改虚拟机", "虚拟机"), + + /** + * 删除虚拟机 + */ + VM_DELETE("删除虚拟机", "虚拟机"), + + /** + * 新增容器 + */ + CONTAINER_ADD("新增容器", "容器"), + + /** + * 修改容器 + */ + CONTAINER_UPDATE("修改容器", "容器"), + + /** + * 删除容器 + */ + CONTAINER_DELETE("删除容器", "容器"), + + /** + * 新增服务 + */ + SERVIR_ADD("新增容器", "服务"), + + /** + * 修改服务 + */ + SERVIR_UPDATE("修改容器", "服务"), + + /** + * 删除服务 + */ + SERVIR_DELETE("删除容器", "服务"), + + /** + * 第一次登录 + */ + USER_FIRST_USE("第一次登录", "用户"), + + /** + * 更改账号信息 + */ + USER_UPDATE_USERINFO("更改账号信息", "用户"), + + /** + * 更改邮箱账号 + */ + USER_UPDATE_EMAIL("更改邮箱账号", "用户"), + + /** + * 更改密码 + */ + USER_UPDATE_PASSWORD("更改密码", "用户"), + + /** + * 确认提醒 + */ + NOTIFICATION_AFFIRM("确认提醒", "提醒"), + + /** + * 确认提醒 + */ + CONSOLE_CONNECT("连接控制台", "控制台"), + + /** + * 默认操作 + */ + DEFAULT("默认操作", "默认操作类型"); + + final String operation; + final String operationType; + + OperationEnum(String operation, String operationType) { + this.operation = operation; + this.operationType = operationType; + } + + public String getOperation() { + return operation; + } + + public String getOperationType() { + return operationType; + } +} diff --git a/src/main/java/com/mzaxd/noodles/exception/SystemException.java b/src/main/java/com/mzaxd/noodles/exception/SystemException.java new file mode 100644 index 0000000..c9bb00a --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/exception/SystemException.java @@ -0,0 +1,31 @@ +package com.mzaxd.noodles.exception; + +import com.mzaxd.noodles.enums.AppHttpCodeEnum; + +/** + * + * @author mzaxd + * @date 11/27/22 3:19 AM + */ + +public class SystemException extends RuntimeException{ + + private final int code; + + private final String msg; + + public int getCode() { + return code; + } + + public String getMsg() { + return msg; + } + + public SystemException(AppHttpCodeEnum httpCodeEnum) { + super(httpCodeEnum.getMsg()); + this.code = httpCodeEnum.getCode(); + this.msg = httpCodeEnum.getMsg(); + } + +} diff --git a/src/main/java/com/mzaxd/noodles/filter/JwtAuthenticationTokenFilter.java b/src/main/java/com/mzaxd/noodles/filter/JwtAuthenticationTokenFilter.java new file mode 100644 index 0000000..8025798 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/filter/JwtAuthenticationTokenFilter.java @@ -0,0 +1,71 @@ +package com.mzaxd.noodles.filter; + +import com.alibaba.fastjson.JSON; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.LoginUser; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.util.JwtUtil; +import com.mzaxd.noodles.util.RedisCache; +import com.mzaxd.noodles.util.WebUtils; +import io.jsonwebtoken.Claims; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.annotation.Resource; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Objects; + +/** + * @author root + */ +@Component +public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { + + @Resource + private RedisCache redisCache; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + //获取请求头中的token + String token = request.getHeader("token"); + if (!StringUtils.hasText(token)) { + // 说明该接口不需要登录 直接放行 + filterChain.doFilter(request, response); + return; + } + //解析获取userId + Claims claims; + try { + claims = JwtUtil.parseJWT(token); + } catch (Exception e) { + e.printStackTrace(); + //token超时 token非法 + //响应告诉前端需要重新登录 + ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN); + WebUtils.renderString(response, JSON.toJSONString(result)); + return; + } + String userId = claims.getSubject(); + //从redis中获取用户信息 + LoginUser loginUser = redisCache.getCacheObject("login:" + userId); + //如果redis中没有用户信息 + if (Objects.isNull(loginUser)) { + //说明登录过期 需要重新登录 + ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN); + WebUtils.renderString(response, JSON.toJSONString(result)); + return; + } + //存入SecurityContextHolder + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + //放行 + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/com/mzaxd/noodles/handler/AccessDeniedHandlerImpl.java b/src/main/java/com/mzaxd/noodles/handler/AccessDeniedHandlerImpl.java new file mode 100644 index 0000000..db998c7 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/handler/AccessDeniedHandlerImpl.java @@ -0,0 +1,27 @@ +package com.mzaxd.noodles.handler; + +import com.alibaba.fastjson.JSON; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.util.WebUtils; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author root + */ +@Component +public class AccessDeniedHandlerImpl implements AccessDeniedHandler { + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws ServletException { + accessDeniedException.printStackTrace(); + ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH); + //响应给前端 + WebUtils.renderString(response, JSON.toJSONString(result)); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/handler/AuthenticationEntryPointImpl.java b/src/main/java/com/mzaxd/noodles/handler/AuthenticationEntryPointImpl.java new file mode 100644 index 0000000..bddb960 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/handler/AuthenticationEntryPointImpl.java @@ -0,0 +1,38 @@ +package com.mzaxd.noodles.handler; + +import com.alibaba.fastjson.JSON; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.util.WebUtils; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author root + */ +@Component +public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { + authException.printStackTrace(); + //InsufficientAuthenticationException + //BadCredentialsException + ResponseResult result; + if (authException instanceof BadCredentialsException) { + result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), authException.getMessage()); + } else if (authException instanceof InsufficientAuthenticationException) { + result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN); + } else { + result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), "认证或授权失败"); + } + //响应给前端 + WebUtils.renderString(response, JSON.toJSONString(result)); + } +} diff --git a/src/main/java/com/mzaxd/noodles/handler/GlobalExceptionHandler.java b/src/main/java/com/mzaxd/noodles/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..63cf1b8 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/handler/GlobalExceptionHandler.java @@ -0,0 +1,32 @@ +package com.mzaxd.noodles.handler; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.exception.SystemException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** + * @author root + */ +@RestControllerAdvice +@Slf4j +public class GlobalExceptionHandler { + + @ExceptionHandler(SystemException.class) + public ResponseResult systemExceptionHandler(SystemException e) { + //打印异常信息 + log.error("出现了异常! {}", e); + //从异常对象中获取提示信息封装返回 + return ResponseResult.errorResult(e.getCode(), e.getMsg()); + } + + @ExceptionHandler(Exception.class) + public ResponseResult exceptionHandler(Exception e) { + //打印异常信息 + log.error("出现了异常! {}", e); + //从异常对象中获取提示信息封装返回 + return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, e.getMessage()); + } +} diff --git a/src/main/java/com/mzaxd/noodles/handler/MyMetaObjectHandler.java b/src/main/java/com/mzaxd/noodles/handler/MyMetaObjectHandler.java new file mode 100644 index 0000000..d313673 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/handler/MyMetaObjectHandler.java @@ -0,0 +1,43 @@ +package com.mzaxd.noodles.handler; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import com.mzaxd.noodles.util.SecurityUtils; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * @author root + */ +@Component +public class MyMetaObjectHandler implements MetaObjectHandler { + @Override + public void insertFill(MetaObject metaObject) { + Long userId; + try { + userId = SecurityUtils.getUserId(); + } catch (Exception e) { + e.printStackTrace(); + //表示是自己创建 + userId = -1L; + } + this.setFieldValByName("createTime", new Date(), metaObject); + this.setFieldValByName("createBy",userId , metaObject); + this.setFieldValByName("updateTime", new Date(), metaObject); + this.setFieldValByName("updateBy", userId, metaObject); + } + + @Override + public void updateFill(MetaObject metaObject) { + Long userId; + try { + userId = SecurityUtils.getUserId(); + } catch (Exception e) { + //表示是自己创建 + userId = -1L; + } + this.setFieldValByName("updateTime", new Date(), metaObject); + this.setFieldValByName("updateBy", userId, metaObject); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/job/CheckInstancesStatus.java b/src/main/java/com/mzaxd/noodles/job/CheckInstancesStatus.java new file mode 100644 index 0000000..055e536 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/job/CheckInstancesStatus.java @@ -0,0 +1,171 @@ +package com.mzaxd.noodles.job; + +import cn.hutool.http.HttpException; +import cn.hutool.http.HttpRequest; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.constant.RedisConstant; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.constant.UrlConstant; +import com.mzaxd.noodles.domain.entity.Container; +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.service.*; +import com.mzaxd.noodles.util.RedisCache; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * 检测所有实例的在线状态 + * @author 13439 + */ + +@Slf4j +@Component +public class CheckInstancesStatus{ + + @Resource + private ContainerService containerService; + + @Resource + private HostMachineService hostMachineService; + + @Resource + private HostDetectorService hostDetectorService; + + @Resource + private NotificationService notificationService; + + @Resource + private RedisCache redisCache; + + /** + * 检查实例状态并且发送对应的提醒 + */ + @Scheduled(cron = "* 0/10 * * * ?") + public void checkInstancesStatus() { + //检测容器在线状态 + List containers = containerService.list(); + containers.forEach(container -> { + try { + if (!StringUtils.hasText(container.getWebUi())) { + container.setContainerState(SystemConstant.CONTAINER_STATE_UNKNOWN); + return; + } + HttpRequest.get(container.getWebUi()).setConnectionTimeout(1000).execute(true); + log.info("[实例状态检测]:与{}建立连接成功", container.getName()); + container.setContainerState(SystemConstant.CONTAINER_STATE_RUNNING); + } catch (Exception exception) { + log.info("[实例状态检测]:与{}建立连接失败,状态转为离线", container.getName()); + container.setContainerState(SystemConstant.CONTAINER_STATE_EXITED); + //判断Redis里面有没有 如果有就不需要提醒 如果没有就提醒 + Set set = redisCache.getCacheSet(RedisConstant.NOTIFY_CONTAINER_IDS); + if (Objects.nonNull(set)){ + //如果redis里面有 说明已经发送过了未check的通知 所以不需要发送 直接返回 + if (set.contains(container.getId().toString())) { + return; + } else { + //根据实例对应的提醒方式进行提醒 + if (container.getNotify().equals(SystemConstant.NOTIFY_NO)) { + return; + } else { + notificationService.sendContainerOfflineNotification(container.getId()); + } + } + } + //存入redis + set.add(container.getId().toString()); + redisCache.setCacheSet(RedisConstant.NOTIFY_CONTAINER_IDS, set); + } + }); + containerService.saveOrUpdateBatch(containers); + + //检测虚拟机在线状态 + LambdaQueryWrapper vmWrapper = new LambdaQueryWrapper<>(); + vmWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + List vms = hostMachineService.list(vmWrapper); + vms.forEach(vm -> { + try { + if (!StringUtils.hasText(vm.getManageIp())) { + vm.setHostMachineState(SystemConstant.HOST_MACHINE_STATE_UNKNOWN); + return; + } + HttpRequest.get(vm.getManageIp()).setConnectionTimeout(1000).execute(true); + log.info("[实例状态检测]:与{}建立连接成功", vm.getName()); + vm.setHostMachineState(SystemConstant.HOST_MACHINE_STATE_ONLINE); + } catch (Exception exception) { + log.info("[实例状态检测]:与{}建立连接失败,状态转为离线", vm.getName()); + vm.setHostMachineState(SystemConstant.HOST_MACHINE_STATE_OFFLINE); + //判断Redis里面有没有 如果有就不需要提醒 如果没有就提醒 + Set set = redisCache.getCacheSet(RedisConstant.NOTIFY_VM_IDS); + if (Objects.nonNull(set)){ + //如果redis里面有 说明已经发送过了未check的通知 所以不需要发送 直接返回 + if (set.contains(vm.getId().toString())) { + return; + } else { + //根据实例对应的提醒方式进行提醒 + if (vm.getNotify().equals(SystemConstant.NOTIFY_NO)) { + return; + } else { + notificationService.sendVmOfflineNotification(vm.getId()); + } + } + } + //存入redis + set.add(vm.getId().toString()); + redisCache.setCacheSet(RedisConstant.NOTIFY_VM_IDS, set); + } + }); + hostMachineService.saveOrUpdateBatch(vms); + + //检测物理机在线状态(检测物理机要用探测器的isTureUrl接口) + LambdaQueryWrapper detectorWrapper = new LambdaQueryWrapper<>(); + List hostDetectors = hostDetectorService.list(detectorWrapper); + List hostMachines = new ArrayList<>(); + hostDetectors.forEach(detector -> { + try { + HttpRequest.get(detector.getDetectorIpAddress() + UrlConstant.DETECTOR_IS_TRUE_URL).setConnectionTimeout(1000).execute(true); + HostMachine hostMachine = hostMachineService.getById(detector.getHostMachineId()); + if (Objects.nonNull(hostMachine)) { + hostMachine.setHostMachineState(SystemConstant.HOST_MACHINE_STATE_ONLINE); + hostMachines.add(hostMachine); + } + } catch (HttpException exception) { + HostMachine hostMachine = hostMachineService.getById(detector.getHostMachineId()); + if (Objects.nonNull(hostMachine)) { + hostMachine.setHostMachineState(SystemConstant.HOST_MACHINE_STATE_OFFLINE); + hostMachines.add(hostMachine); + } + //判断Redis里面有没有 如果有就不需要提醒 如果没有就提醒 + Set set = redisCache.getCacheSet(RedisConstant.NOTIFY_HOST_IDS); + if (Objects.nonNull(set)){ + //如果redis里面有 说明已经发送过了未check的通知 所以不需要发送 直接返回 + if (set.contains(hostMachine.getId().toString())) { + return; + } else { + //根据实例对应的提醒方式进行提醒 + if (hostMachine.getNotify().equals(SystemConstant.NOTIFY_NO)) { + return; + } else { + notificationService.sendHostOfflineNotification(hostMachine.getId()); + } + } + } + //存入redis + set.add(hostMachine.getId().toString()); + redisCache.setCacheSet(RedisConstant.NOTIFY_HOST_IDS, set); + } + }); + hostMachineService.saveOrUpdateBatch(hostMachines); + } +} diff --git a/src/main/java/com/mzaxd/noodles/job/EveryDayDataCollect.java b/src/main/java/com/mzaxd/noodles/job/EveryDayDataCollect.java new file mode 100644 index 0000000..1c7146f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/job/EveryDayDataCollect.java @@ -0,0 +1,85 @@ +package com.mzaxd.noodles.job; + +import cn.hutool.core.date.DateTime; +import cn.hutool.core.date.DateUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.entity.AuditLog; +import com.mzaxd.noodles.domain.entity.Container; +import com.mzaxd.noodles.domain.entity.EveryDayData; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.service.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Date; +import java.util.Map; + +/** + * @author 13439 + */ + +@Slf4j +@Component +public class EveryDayDataCollect { + + @Resource + private HostMachineService hostMachineService; + + @Resource + private ContainerService containerService; + + @Resource + private ServirService servirService; + + @Resource + private AuditLogService auditLogService; + + @Resource + private EveryDayDataService everyDayDataService; + + /** + * 每天晚上收集今日数据 + */ + @Scheduled(cron = "0 59 23 * * ?") + public void everyDayDataCollect() { + EveryDayData everyDayData = new EveryDayData(); + LambdaQueryWrapper auditLogWrapper = new LambdaQueryWrapper<>(); + Map hostStateInfo = hostMachineService.getHostStateInfo(); + Map vmStateInfo = hostMachineService.getVmStateInfo(); + Map containerStateInfo = containerService.getContainerStateInfo(); + //设置主机总数 + everyDayData.setHostCount(hostStateInfo.get("hostCount")); + //设置主机在线总数 + everyDayData.setHostOnlineCount(hostStateInfo.get("hostOnlineCount")); + //设置主机离线总数 + everyDayData.setHostOfflineCount(hostStateInfo.get("hostOfflineCount")); + //设置主机未知总数 + everyDayData.setHostUnknownCount(hostStateInfo.get("hostUnknownCount")); + //设置虚拟机总数 + everyDayData.setVmCount(vmStateInfo.get("vmCount")); + //设置虚拟机在线总数 + everyDayData.setVmOnlineCount(vmStateInfo.get("vmOnlineCount")); + //设置虚拟机离线总数 + everyDayData.setVmOfflineCount(vmStateInfo.get("vmOfflineCount")); + //设置虚拟机未知总数 + everyDayData.setVmUnknownCount(vmStateInfo.get("vmUnknownCount")); + //设置容器总数 + everyDayData.setContainerCount(containerStateInfo.get("containerCount")); + //设置容器在线总数 + everyDayData.setContainerOnlineCount(containerStateInfo.get("containerOnlineCount")); + //设置容器离线总数 + everyDayData.setContainerOfflineCount(containerStateInfo.get("containerOfflineCount")); + //设置容器未知总数 + everyDayData.setContainerUnknownCount(containerStateInfo.get("containerUnknownCount")); + //设置服务总数 + everyDayData.setServirCount(servirService.count()); + //设置操作总数 + auditLogWrapper.ge(AuditLog::getCreateTime, DateUtil.beginOfDay(DateUtil.date())); + auditLogWrapper.lt(AuditLog::getCreateTime, DateUtil.endOfDay(DateUtil.date())); + everyDayData.setAuditCount(auditLogService.count(auditLogWrapper)); + everyDayDataService.save(everyDayData); + } +} diff --git a/src/main/java/com/mzaxd/noodles/listener/RabbitDynamicDataConsumer.java b/src/main/java/com/mzaxd/noodles/listener/RabbitDynamicDataConsumer.java new file mode 100644 index 0000000..bbed4de --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/listener/RabbitDynamicDataConsumer.java @@ -0,0 +1,36 @@ +package com.mzaxd.noodles.listener; + +import com.mzaxd.noodles.constant.RabbitMqConstant; +import com.mzaxd.noodles.constant.RedisConstant; +import com.mzaxd.noodles.domain.message.DynamicData; +import com.mzaxd.noodles.util.RedisCache; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.annotation.Queue; +import org.springframework.amqp.rabbit.annotation.RabbitHandler; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * @author root + */ +@Slf4j +@Component +@RabbitListener(queuesToDeclare = @Queue(RabbitMqConstant.DYNAMIC_DATA_TOPIC)) +public class RabbitDynamicDataConsumer { + + @Resource + private RedisCache redisCache; + + @RabbitHandler + public void process(@Payload DynamicData dynamicData) { + log.info("开始消费动态数据消息"); + //将Redis中旧的数据删除 + redisCache.deleteObject(RedisConstant.DYNAMIC_DATA + dynamicData.getDetectorId()); + //将新的动态数据存入Redis + redisCache.setCacheObject(RedisConstant.DYNAMIC_DATA + dynamicData.getDetectorId(), dynamicData); + log.info("更新Redis中动态数据成功"); + } +} diff --git a/src/main/java/com/mzaxd/noodles/mapper/AuditLogMapper.java b/src/main/java/com/mzaxd/noodles/mapper/AuditLogMapper.java new file mode 100644 index 0000000..99f6b48 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/AuditLogMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.AuditLog; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【audit_log】的数据库操作Mapper +* @createDate 2023-02-13 12:19:26 +* @Entity com.mzaxd.noodles.domain.entity.AuditLog +*/ +public interface AuditLogMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/ContainerMapper.java b/src/main/java/com/mzaxd/noodles/mapper/ContainerMapper.java new file mode 100644 index 0000000..37e4443 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/ContainerMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.Container; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author root +* @description 针对表【container】的数据库操作Mapper +* @createDate 2023-02-02 06:26:00 +* @Entity com.mzaxd.noodles.domain.entity.Container +*/ +public interface ContainerMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/EveryDayDataMapper.java b/src/main/java/com/mzaxd/noodles/mapper/EveryDayDataMapper.java new file mode 100644 index 0000000..77d6383 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/EveryDayDataMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.EveryDayData; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【every_data】的数据库操作Mapper +* @createDate 2023-02-21 12:52:12 +* @Entity com.mzaxd.noodles.domain.entity.EveryDayData +*/ +public interface EveryDayDataMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/HostDetectorMapper.java b/src/main/java/com/mzaxd/noodles/mapper/HostDetectorMapper.java new file mode 100644 index 0000000..42ea251 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/HostDetectorMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author root +* @description 针对表【host_detector】的数据库操作Mapper +* @createDate 2023-02-05 13:18:46 +* @Entity com.mzaxd.noodles.domain.entity.HostDetector +*/ +public interface HostDetectorMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/HostMachineMapper.java b/src/main/java/com/mzaxd/noodles/mapper/HostMachineMapper.java new file mode 100644 index 0000000..2c8a4e7 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/HostMachineMapper.java @@ -0,0 +1,32 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import java.util.List; + +/** +* @author root +* @description 针对表【host_machine】的数据库操作Mapper +* @createDate 2023-01-30 01:24:08 +* @Entity com.mzaxd.noodles.domain.entity.HostMachine +*/ +public interface HostMachineMapper extends BaseMapper { + + /** + * 返回VMList所需的所有数据 + * + * @param nameLike + * @param selectedKernel + * @param selectedHost + * @param selectedStatus + * @param perPage + * @param currentPage + * @return + */ + List vmListWithCondition(String nameLike, List selectedKernel, List selectedHost, List selectedStatus, Integer perPage, Integer currentPage); +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/NotificationMapper.java b/src/main/java/com/mzaxd/noodles/mapper/NotificationMapper.java new file mode 100644 index 0000000..6e9ed8e --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/NotificationMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.Notification; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【notification】的数据库操作Mapper +* @createDate 2023-02-16 16:04:53 +* @Entity com.mzaxd.noodles.domain.entity.Notification +*/ +public interface NotificationMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/OsMapper.java b/src/main/java/com/mzaxd/noodles/mapper/OsMapper.java new file mode 100644 index 0000000..76a3067 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/OsMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.Os; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author root +* @description 针对表【os】的数据库操作Mapper +* @createDate 2023-01-30 13:20:28 +* @Entity com.mzaxd.noodles.domain.entity.Os +*/ +public interface OsMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/ServirContainerMapper.java b/src/main/java/com/mzaxd/noodles/mapper/ServirContainerMapper.java new file mode 100644 index 0000000..da249f2 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/ServirContainerMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.ServirContainer; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【servir_container】的数据库操作Mapper +* @createDate 2023-02-11 20:48:45 +* @Entity com.mzaxd.noodles.domain.entity.ServirContainer +*/ +public interface ServirContainerMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/ServirHostMapper.java b/src/main/java/com/mzaxd/noodles/mapper/ServirHostMapper.java new file mode 100644 index 0000000..86912fa --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/ServirHostMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.ServirHost; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【servir_host】的数据库操作Mapper +* @createDate 2023-02-11 20:48:51 +* @Entity com.mzaxd.noodles.domain.entity.ServirHost +*/ +public interface ServirHostMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/ServirMapper.java b/src/main/java/com/mzaxd/noodles/mapper/ServirMapper.java new file mode 100644 index 0000000..5ec1e16 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/ServirMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.mzaxd.noodles.domain.entity.Servir; + +/** +* @author 13439 +* @description 针对表【service】的数据库操作Mapper +* @createDate 2023-02-11 17:51:37 +* @Entity com.mzaxd.noodles.domain.entity.Service +*/ +public interface ServirMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/ServirTagMapper.java b/src/main/java/com/mzaxd/noodles/mapper/ServirTagMapper.java new file mode 100644 index 0000000..9430ae8 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/ServirTagMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.ServirTag; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【servir_tag】的数据库操作Mapper +* @createDate 2023-02-11 19:40:35 +* @Entity com.mzaxd.noodles.domain.entity.ServirTag +*/ +public interface ServirTagMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/SshLinkMapper.java b/src/main/java/com/mzaxd/noodles/mapper/SshLinkMapper.java new file mode 100644 index 0000000..472359d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/SshLinkMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.SshLink; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【ssh_link】的数据库操作Mapper +* @createDate 2023-02-24 20:30:25 +* @Entity com.mzaxd.noodles.domain.entity.SshLink +*/ +public interface SshLinkMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/SystemSettingMapper.java b/src/main/java/com/mzaxd/noodles/mapper/SystemSettingMapper.java new file mode 100644 index 0000000..1e2422a --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/SystemSettingMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.SystemSetting; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【system_setting】的数据库操作Mapper +* @createDate 2023-02-16 20:25:57 +* @Entity com.mzaxd.noodles.domain.entity.SystemSetting +*/ +public interface SystemSettingMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/TagMapper.java b/src/main/java/com/mzaxd/noodles/mapper/TagMapper.java new file mode 100644 index 0000000..a0cdd65 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/TagMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.Tag; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author 13439 +* @description 针对表【tag】的数据库操作Mapper +* @createDate 2023-02-11 18:26:12 +* @Entity com.mzaxd.noodles.domain.entity.Tag +*/ +public interface TagMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/mapper/UserMapper.java b/src/main/java/com/mzaxd/noodles/mapper/UserMapper.java new file mode 100644 index 0000000..01626f0 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/mapper/UserMapper.java @@ -0,0 +1,18 @@ +package com.mzaxd.noodles.mapper; + +import com.mzaxd.noodles.domain.entity.User; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** +* @author root +* @description 针对表【user】的数据库操作Mapper +* @createDate 2023-01-28 09:16:07 +* @Entity com.mzaxd.noodles.domain.entity.User +*/ +public interface UserMapper extends BaseMapper { + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/AuditLogService.java b/src/main/java/com/mzaxd/noodles/service/AuditLogService.java new file mode 100644 index 0000000..fd233d6 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/AuditLogService.java @@ -0,0 +1,37 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.AuditLog; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【audit_log】的数据库操作Service +* @createDate 2023-02-13 12:19:26 +*/ +public interface AuditLogService extends IService { + + /** + * 返回日志列表 + * + * @param perPage + * @param currentPage + * @return + */ + ResponseResult getLogList(Integer perPage, Integer currentPage); + + /** + * 获取参数 + * + * @param id + * @return + */ + ResponseResult getParam(Integer id); + + /** + * 获取用户日志 + * + * @return + */ + ResponseResult getUserLog(); +} diff --git a/src/main/java/com/mzaxd/noodles/service/ContainerService.java b/src/main/java/com/mzaxd/noodles/service/ContainerService.java new file mode 100644 index 0000000..829498f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/ContainerService.java @@ -0,0 +1,114 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Container; +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.vo.ContainerVo; + +import java.util.List; +import java.util.Map; + +/** +* @author root +* @description 针对表【container】的数据库操作Service +* @createDate 2023-02-02 06:26:00 +*/ +public interface ContainerService extends IService { + + /** + * 返回简要统计信息 + * + * @author mzaxd + * @date 2/2/23 6:26 AM + * @return ResponseResult + */ + ResponseResult containerListSummaryStatistics(); + + /** + * 容器列表 + * + * @author mzaxd + * @date 2/2/23 7:06 AM + * @param nameLike + * @param selectedHost + * @param selectedStatus + * @param perPage + * @param currentPage + * @return ResponseResult + */ + ResponseResult containerListWithCondition(String nameLike, List selectedHost, List selectedStatus, Integer perPage, Integer currentPage); + + /** + * 获取所有宿主机 + * + * @author mzaxd + * @date 2/2/23 9:08 AM + * @return ResponseResult + */ + ResponseResult getAllHost(); + + /** + * 根据id删除容器 + * + * @author mzaxd + * @date 2/2/23 11:07 AM + * @param id + * @return ResponseResult + */ + ResponseResult deleteContainerById(Integer id); + + /** + * 添加容器 + * + * @author mzaxd + * @date 2/2/23 12:02 PM + * @param vm + * @return ResponseResult + */ + ResponseResult addContainer(ContainerVo vm); + + /** + * 根据id获取容器 + * + * @author mzaxd + * @date 2/2/23 12:45 PM + * @param id + * @return ResponseResult + */ + ResponseResult getContainer(Integer id); + + /** + * 编辑容器 + * + * @author mzaxd + * @date 2/2/23 1:15 PM + * @param container + * @return ResponseResult + */ + ResponseResult updateContainer(ContainerVo container); + + /** + * 获取所有容器 + * + * @return + */ + ResponseResult getAllContainer(); + + /** + * 根据物理机id查找容器 + * + * @param id + * @param rowPerPage + * @param currentPage + * @return + */ + ResponseResult getAssociatedContainers(Integer id, Integer rowPerPage, Integer currentPage); + + + /** + * 获取容器状态信息 + * + * @return + */ + Map getContainerStateInfo(); +} diff --git a/src/main/java/com/mzaxd/noodles/service/DashboardService.java b/src/main/java/com/mzaxd/noodles/service/DashboardService.java new file mode 100644 index 0000000..1515cc3 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/DashboardService.java @@ -0,0 +1,22 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; + +/** + * @author 13439 + */ +public interface DashboardService { + /** + * 获取仪表台实例服务实时数据 + * + * @return + */ + ResponseResult getInstancesRealTimeData(); + + /** + * 获取最近连接过的控制台列表 + * + * @return + */ + ResponseResult getRecentConsoleList(); +} diff --git a/src/main/java/com/mzaxd/noodles/service/EveryDayDataService.java b/src/main/java/com/mzaxd/noodles/service/EveryDayDataService.java new file mode 100644 index 0000000..eb17568 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/EveryDayDataService.java @@ -0,0 +1,51 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.EveryDayData; +import com.baomidou.mybatisplus.extension.service.IService; + +import java.util.List; + +/** +* @author 13439 +* @description 针对表【every_data】的数据库操作Service +* @createDate 2023-02-21 12:52:12 +*/ +public interface EveryDayDataService extends IService { + + /** + * 返回昨日操作次数 + * + * @return + */ + ResponseResult getAuditLogCountYesterday(); + + /** + * 返回昨日实例情况 + * + * @return + */ + ResponseResult getInstancesHistory(); + + /** + * 获取昨天的每日数据 + * + * @return + */ + EveryDayData getYesterdayData(); + + /** + * 获取上周的每日数据 + * + * @return + */ + List getLastWeekData(); + + /** + * 获取前六天的每日数据 + * + * @return + */ + List getLastSixDayData(); + +} diff --git a/src/main/java/com/mzaxd/noodles/service/HostDetectorService.java b/src/main/java/com/mzaxd/noodles/service/HostDetectorService.java new file mode 100644 index 0000000..34b0c93 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/HostDetectorService.java @@ -0,0 +1,82 @@ +package com.mzaxd.noodles.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.mzaxd.noodles.domain.message.DynamicData; +import com.mzaxd.noodles.domain.message.Server; + +import java.util.List; +import java.util.Map; + +/** +* @author root +* @description 针对表【host_detector】的数据库操作Service +* @createDate 2023-02-05 13:18:46 +*/ +public interface HostDetectorService extends IService { + + /** + * 判断探测器IP是否有效 + * + * @author mzaxd + * @date 2/7/23 6:32 AM + * @param url + * @return ResponseResult + */ + boolean isValidUrl(String url); + + /** + * 获取所有在线的探测器 + * + * @author mzaxd + * @date 2/8/23 4:38 AM + * @return HostDetector + */ + List getAllALiveDetectors(); + + /** + * 返回所有探测器获取动态数据 + * + * @author mzaxd + * @date 2/8/23 6:28 AM + * @param allAliveDetector + * @return Map + */ + Map getDynamicData(List allAliveDetector); + + /** + * 指定探测器获取动态数据 + * + * @author mzaxd + * @date 2/8/23 6:28 AM + * @param detector + * @return Map + */ + Map getDynamicDataByDetector(HostDetector detector); + + /** + * 检查是否是有效探测器地址 + * + * @param protocol + * @param ip + * @param port + * @return + */ + ResponseResult isValidUrl(String protocol, String ip, String port); + + /** + * 根据url获取远程主机信息 + * + * @param url + * @return + */ + Server detectorGetInfoByUrl(String url); + + /** + * 返回内存整体使用信息 + * + * @return + */ + ResponseResult getMemInfo(); +} diff --git a/src/main/java/com/mzaxd/noodles/service/HostMachineService.java b/src/main/java/com/mzaxd/noodles/service/HostMachineService.java new file mode 100644 index 0000000..17ffa53 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/HostMachineService.java @@ -0,0 +1,200 @@ +package com.mzaxd.noodles.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.domain.vo.HostVo; +import com.mzaxd.noodles.domain.vo.VmVo; + +import java.util.List; +import java.util.Map; + +/** +* @author root +* @description 针对表【host_machine】的数据库操作Service +* @createDate 2023-01-30 01:24:08 +*/ +public interface HostMachineService extends IService { + + /** + * 返回所有host的部分数据 + * + * @author mzaxd + * @date 1/30/23 1:25 AM + * @return ResultSet + */ + ResponseResult getHostDrawer(); + + /** + * 按照一定条件返回vm的List + * + * @author mzaxd + * @date 1/30/23 10:32 AM + * @param nameLike + * @param selectedKernel + * @param selectedHost + * @param selectedStatus + * @param perPage + * @param currentPage + * @return ResponseResult + */ + ResponseResult vmListWithCondition(String nameLike, List selectedKernel, List selectedHost, List selectedStatus, Integer perPage, Integer currentPage); + + /** + * 返回VM总数和三种状态的数据 + * + * @author mzaxd + * @date 1/31/23 10:22 AM + * @return ResponseResult + */ + ResponseResult vmListSummaryStatistics(); + + /** + * 修改vm + * + * @author mzaxd + * @date 2/1/23 3:05 AM + * @param addVmVo + * @return ResponseResult + */ + ResponseResult updateVm(VmVo addVmVo); + + /** + * 根据id删除vm + * + * @author mzaxd + * @date 2/1/23 5:11 AM + * @param id + * @return ResponseResult + */ + ResponseResult deleteVmById(Integer id); + + /** + * 根据id查找vm + * + * @author mzaxd + * @date 2/1/23 10:33 AM + * @param id + * @return ResponseResult + */ + ResponseResult getVmById(Integer id); + + /** + * 添加vm + * + * @author mzaxd + * @date 2/1/23 3:05 AM + * @param vm + * @return ResponseResult + */ + ResponseResult addVm(VmVo vm); + + /** + * 按照一定条件返回物理机的List + * + * @author mzaxd + * @date 2/5/23 1:05 PM + * @param nameLike + * @param selectedStatus + * @param perPage + * @param currentPage + * @return ResponseResult + */ + ResponseResult hostListWithCondition(String nameLike, List selectedStatus, Integer perPage, Integer currentPage); + + /** + * 添加物理机 + * + * @author mzaxd + * @date 2/7/23 8:39 AM + * @param host + * @return ResponseResult + */ + ResponseResult addHost(HostVo host); + + /** + * 根据id返回Host + * + * @param id + * @return + */ + ResponseResult getHostById(Integer id); + + /** + * 修改host + * + * @param host + * @return + */ + ResponseResult updateHost(HostVo host); + + /** + * 通过id删除host + * + * @param id + * @return + */ + ResponseResult deleteHostById(Integer id); + + /** + * 获取主机详细信息 + * + * @param id + * @return + */ + ResponseResult getHostDetail(Integer id); + + /** + * 获取所有基于此ID的虚拟机 + * + * @param id + * @param perPage + * @param currentPage + * @return + */ + ResponseResult getAssociatedVms(Integer id, Integer perPage, Integer currentPage); + + /** + * 获取所有物理机的磁盘信息 + * + * @param id + * @return + */ + ResponseResult getAssociatedDisks(Integer id); + + /** + * 获取所有物理机的网络接口信息 + * + * @param id + * @return + */ + ResponseResult getAssociatedNetworkIfs(Integer id); + + /** + * 获取物理机状态信息 + * + * @return + */ + Map getHostStateInfo(); + + /** + * 获取虚拟机状态信息 + * + * @return + */ + Map getVmStateInfo(); + + /** + * 根据前端发来的hostID通知对应探测器开始发送动态数据 + * @param hostId + * @return + */ + ResponseResult startSendDynamicData(Integer hostId); + + /** + * 根据前端发来的hostID通知对应探测器停止发送动态数据 + * @param hostId + * @return + */ + ResponseResult stopSendDynamicData(Integer hostId); +} diff --git a/src/main/java/com/mzaxd/noodles/service/LoginService.java b/src/main/java/com/mzaxd/noodles/service/LoginService.java new file mode 100644 index 0000000..d2cd340 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/LoginService.java @@ -0,0 +1,45 @@ +package com.mzaxd.noodles.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.User; + +/** + * @author root + */ +public interface LoginService extends IService { + + /** + * 后台登录接口 + * + * @author mzaxd + * @date 12/4/22 1:29 PM + * @param user + * @return ResponseResult + */ + ResponseResult login(User user); + + /** + * 后台用户退出登陆 + * + * @author mzaxd + * @date 12/6/22 2:07 PM + * @return ResponseResult + */ + ResponseResult logout(); + + /** + * 首次登陆时 修改账户信息 + * + * @param user + * @return + */ + ResponseResult updateAccount(User user); + + /** + * 删除账号 + * + * @return + */ + ResponseResult deleteAccount(); +} diff --git a/src/main/java/com/mzaxd/noodles/service/NotificationService.java b/src/main/java/com/mzaxd/noodles/service/NotificationService.java new file mode 100644 index 0000000..6cbf40d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/NotificationService.java @@ -0,0 +1,55 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Notification; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【notification】的数据库操作Service +* @createDate 2023-02-16 16:04:53 +*/ +public interface NotificationService extends IService { + + /** + * 发送容器掉线通知 + * @param id + */ + void sendContainerOfflineNotification(Long id); + + /** + * 发送虚拟机掉线通知 + * @param id + */ + void sendVmOfflineNotification(Long id); + + /** + * 发送物理机掉线通知 + * @param id + */ + void sendHostOfflineNotification(Long id); + + + /** + * 提醒列表 + * @param tab + * @param perPage + * @param currentPage + * @return + */ + ResponseResult getNotificationList(Integer tab, Integer perPage, Integer currentPage); + + /** + * 获取新通知数量 + * @return + */ + ResponseResult getNotificationCount(); + + /** + * 确认提醒 + * + * @param id + * @return + */ + ResponseResult affirmNotification(Long id); +} diff --git a/src/main/java/com/mzaxd/noodles/service/OsService.java b/src/main/java/com/mzaxd/noodles/service/OsService.java new file mode 100644 index 0000000..6dc5968 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/OsService.java @@ -0,0 +1,13 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.entity.Os; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author root +* @description 针对表【os】的数据库操作Service +* @createDate 2023-01-30 13:20:28 +*/ +public interface OsService extends IService { + +} diff --git a/src/main/java/com/mzaxd/noodles/service/ServirContainerService.java b/src/main/java/com/mzaxd/noodles/service/ServirContainerService.java new file mode 100644 index 0000000..255b4ae --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/ServirContainerService.java @@ -0,0 +1,13 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.entity.ServirContainer; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【servir_container】的数据库操作Service +* @createDate 2023-02-11 20:48:45 +*/ +public interface ServirContainerService extends IService { + +} diff --git a/src/main/java/com/mzaxd/noodles/service/ServirHostService.java b/src/main/java/com/mzaxd/noodles/service/ServirHostService.java new file mode 100644 index 0000000..3b259d3 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/ServirHostService.java @@ -0,0 +1,13 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.entity.ServirHost; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【servir_host】的数据库操作Service +* @createDate 2023-02-11 20:48:51 +*/ +public interface ServirHostService extends IService { + +} diff --git a/src/main/java/com/mzaxd/noodles/service/ServirService.java b/src/main/java/com/mzaxd/noodles/service/ServirService.java new file mode 100644 index 0000000..66229df --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/ServirService.java @@ -0,0 +1,70 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Servir; +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.vo.SaveOrUpdateServirVo; +import com.mzaxd.noodles.domain.vo.ServirListVo; + +import java.util.List; + +/** +* @author 13439 +* @description 针对表【servir】的数据库操作Service +* @createDate 2023-02-11 18:00:24 +*/ +public interface ServirService extends IService { + + + /** + * 根据条件返回所有服务 + * + * @param nameLike + * @param selectedTags + * @param perPage + * @param currentPage + * @return + */ + ResponseResult servirListWithCondition(String nameLike, List selectedTags, Integer perPage, Integer currentPage); + + /** + * 添加服务 + * + * @param servir + * @return + */ + ResponseResult addServir(SaveOrUpdateServirVo servir); + + /** + * 根据id删除服务 + * + * @param id + * @return + */ + ResponseResult deleteServirById(Integer id); + + /** + * 根据id查找 + * + * @param id + * @return + */ + ResponseResult getServirById(Integer id); + + /** + * 改 + * + * @param + * @return + */ + ResponseResult updateServir(SaveOrUpdateServirVo saveOrUpdateServirVo); + + /** + * 获取备注 + * + * @param id + * @return + */ + ResponseResult getRemarkById(Integer id); + +} diff --git a/src/main/java/com/mzaxd/noodles/service/ServirTagService.java b/src/main/java/com/mzaxd/noodles/service/ServirTagService.java new file mode 100644 index 0000000..30ee5e7 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/ServirTagService.java @@ -0,0 +1,13 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.entity.ServirTag; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【servir_tag】的数据库操作Service +* @createDate 2023-02-11 19:40:35 +*/ +public interface ServirTagService extends IService { + +} diff --git a/src/main/java/com/mzaxd/noodles/service/SshLinkService.java b/src/main/java/com/mzaxd/noodles/service/SshLinkService.java new file mode 100644 index 0000000..af2e07a --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/SshLinkService.java @@ -0,0 +1,30 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.SshLink; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【ssh_link】的数据库操作Service +* @createDate 2023-02-24 20:30:25 +*/ +public interface SshLinkService extends IService { + + /** + * 根据sshId返回实例信息 + * + * @param sshId + * @return + */ + ResponseResult getInstanceInfo(Long sshId); + + + /** + * 根据sshId返回对应的Object + * + * @param sshId + * @return + */ + Object getInstanceInfoBySshId(Long sshId); +} diff --git a/src/main/java/com/mzaxd/noodles/service/SystemSettingService.java b/src/main/java/com/mzaxd/noodles/service/SystemSettingService.java new file mode 100644 index 0000000..d2bf4ee --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/SystemSettingService.java @@ -0,0 +1,62 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.SystemSetting; +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.vo.SmtpVo; +import com.mzaxd.noodles.domain.vo.SystemVo; +import com.mzaxd.noodles.domain.vo.TerminalVo; + +/** +* @author 13439 +* @description 针对表【system_setting】的数据库操作Service +* @createDate 2023-02-16 20:25:57 +*/ +public interface SystemSettingService extends IService { + + /** + * 获取SMTP服务器设置 + * + * @return + */ + ResponseResult getSmtpSetting(); + + /** + * 保存smtp设置 + * + * @param smtpVo + * @return + */ + ResponseResult saveSmtpSetting(SmtpVo smtpVo); + + /** + * 获取终端设置 + * + * @return + */ + ResponseResult getTerminalSetting(); + + /** + * 报错终端设置 + * + * @param terminalVo + * @return + */ + ResponseResult saveTerminalSetting(TerminalVo terminalVo); + + /** + * 获取系统设置 + * + * @return + */ + ResponseResult getSystemSetting(); + + + /** + * 保存系统设置 + * + * @param systemVo + * @return + */ + ResponseResult saveSystemSetting(SystemVo systemVo); +} diff --git a/src/main/java/com/mzaxd/noodles/service/TagService.java b/src/main/java/com/mzaxd/noodles/service/TagService.java new file mode 100644 index 0000000..5ffda68 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/TagService.java @@ -0,0 +1,20 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Tag; +import com.baomidou.mybatisplus.extension.service.IService; + +/** +* @author 13439 +* @description 针对表【tag】的数据库操作Service +* @createDate 2023-02-11 18:26:12 +*/ +public interface TagService extends IService { + + /** + * 获取所有tag + * + * @return + */ + ResponseResult getAllTag(); +} diff --git a/src/main/java/com/mzaxd/noodles/service/UserService.java b/src/main/java/com/mzaxd/noodles/service/UserService.java new file mode 100644 index 0000000..a500eb0 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/UserService.java @@ -0,0 +1,76 @@ +package com.mzaxd.noodles.service; + +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.User; +import com.baomidou.mybatisplus.extension.service.IService; +import com.mzaxd.noodles.domain.vo.UserInfoVo; + +/** +* @author root +* @description 针对表【user】的数据库操作Service +* @createDate 2023-01-28 09:16:07 +*/ +public interface UserService extends IService { + + /** + * 查询用户信息 + * + * @author mzaxd + * @date 1/29/23 4:16 AM + * @return ResponseResult + */ + ResponseResult userInfo(); + + /** + * 修改用户信息 + * + * @author mzaxd + * @date 1/29/23 4:16 AM + * @param user + * @return ResponseResult + */ + ResponseResult updateUserInfo(User user); + + /** + * 返回个人信息页面头部数据 + * + * @param id + * @return + */ + ResponseResult getProfileHeader(Integer id, String ip); + + /** + * 返回profile页面所需数据 + * + * @return + */ + ResponseResult getProfile(); + + /** + * 通过判断默认账户的state状态来判断是否第一次使用 + * @return + */ + ResponseResult isFirstUse(); + + /** + * 修改密码 + * @param password + * @return + */ + ResponseResult changePassword(String password); + + /** + * 通过id获取UserInfo + * + * @param id + * @return + */ + ResponseResult getUserInfo(Integer id); + + /** + * 修改账号信息 + * @param userData + * @return + */ + ResponseResult updateUserInfo(UserInfoVo userData); +} diff --git a/src/main/java/com/mzaxd/noodles/service/impl/AuditLogServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/AuditLogServiceImpl.java new file mode 100644 index 0000000..20a8a7f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/AuditLogServiceImpl.java @@ -0,0 +1,72 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.*; +import com.mzaxd.noodles.domain.vo.*; +import com.mzaxd.noodles.mapper.UserMapper; +import com.mzaxd.noodles.service.AuditLogService; +import com.mzaxd.noodles.mapper.AuditLogMapper; +import com.mzaxd.noodles.util.BeanCopyUtils; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** +* @author 13439 +* @description 针对表【audit_log】的数据库操作Service实现 +* @createDate 2023-02-13 12:19:26 +*/ +@Service +public class AuditLogServiceImpl extends ServiceImpl + implements AuditLogService{ + + @Resource + private UserMapper userMapper; + + @Override + public ResponseResult getLogList(Integer perPage, Integer currentPage) { + //分页 + PageHelper.startPage(currentPage, perPage); + LambdaQueryWrapper auditLogLambdaQueryWrapper = new LambdaQueryWrapper<>(); + auditLogLambdaQueryWrapper.orderByDesc(AuditLog::getCreateTime); + //查询 + List auditLogs = list(auditLogLambdaQueryWrapper); + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(auditLogs, perPage); + + //封装结果返回 + List auditLogListVos = BeanCopyUtils.copyBeanList(auditLogs, AuditLogListVo.class); + auditLogListVos.forEach(auditLogListVo -> { + User user = userMapper.selectById(auditLogListVo.getCreateBy()); + UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class); + auditLogListVo.setUser(userInfoVo); + }); + pageInfo.setList(auditLogListVos); + return ResponseResult.okResult(pageInfo); + } + + @Override + public ResponseResult getParam(Integer id) { + AuditLog auditLog = getById(id); + return ResponseResult.okResult(auditLog.getParam()); + } + + @Override + public ResponseResult getUserLog() { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(AuditLog::getOperationType, SystemConstant.LOG_USER); + queryWrapper.orderByDesc(AuditLog::getCreateTime); + List list = list(queryWrapper); + return ResponseResult.okResult(list); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/ContainerServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/ContainerServiceImpl.java new file mode 100644 index 0000000..0b4bdfd --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/ContainerServiceImpl.java @@ -0,0 +1,217 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.*; +import com.mzaxd.noodles.domain.entity.Container; +import com.mzaxd.noodles.domain.vo.*; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.mapper.HostMachineMapper; +import com.mzaxd.noodles.service.ContainerService; +import com.mzaxd.noodles.mapper.ContainerMapper; +import com.mzaxd.noodles.service.HostMachineService; +import com.mzaxd.noodles.service.SshLinkService; +import com.mzaxd.noodles.util.BeanCopyUtils; +import com.mzaxd.noodles.util.SshLinkUtil; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * @author root + * @description 针对表【container】的数据库操作Service实现 + * @createDate 2023-02-02 06:26:00 + */ +@Service +public class ContainerServiceImpl extends ServiceImpl + implements ContainerService { + + @Resource + private ContainerMapper containerMapper; + + @Resource + private HostMachineService hostMachineService; + + @Resource + private HostMachineMapper hostMachineMapper; + + @Resource + private SshLinkService sshLinkService; + + @Override + public ResponseResult containerListSummaryStatistics() { + //设置查询所有在线vm的条件 + LambdaQueryWrapper runningWrapper = new LambdaQueryWrapper<>(); + runningWrapper.eq(Container::getContainerState, SystemConstant.CONTAINER_STATE_RUNNING); + //设置查询所有离线vm的条件 + LambdaQueryWrapper exitedWrapper = new LambdaQueryWrapper<>(); + exitedWrapper.eq(Container::getContainerState, SystemConstant.CONTAINER_STATE_EXITED); + //设置查询所有睡眠vm的条件 + LambdaQueryWrapper pausedWrapper = new LambdaQueryWrapper<>(); + pausedWrapper.eq(Container::getContainerState, SystemConstant.CONTAINER_STATE_PAUSED); + + int total = count(); + int running = count(runningWrapper); + int exited = count(exitedWrapper); + int paused = count(pausedWrapper); + HashMap result = new HashMap<>(4); + result.put("total", total); + result.put("running", running); + result.put("exited", exited); + result.put("paused", paused); + return ResponseResult.okResult(result); + + } + + @Override + public ResponseResult containerListWithCondition(String nameLike, List selectedHost, List selectedStatus, Integer perPage, Integer currentPage) { + //设置查询条件 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.like(StringUtils.hasText(nameLike), Container::getDescription, nameLike); + wrapper.in(Objects.nonNull(selectedHost), Container::getHostMachineId, selectedHost); + wrapper.in(Objects.nonNull(selectedStatus), Container::getContainerState, selectedStatus); + //分页 + PageHelper.startPage(currentPage, perPage); + //查询 + List containers = list(wrapper); + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(containers, perPage); + + //封装结果返回 + List containerListVos = BeanCopyUtils.copyBeanList(containers, ContainerVo.class); + + containerListVos.forEach(containerListVo -> { + HostMachine hostMachine = hostMachineMapper.selectById(containerListVo.getHostMachineId()); + HostMachineVo hostMachineVo = BeanCopyUtils.copyBean(hostMachine, HostMachineVo.class); + containerListVo.setHostMachine(hostMachineVo); + }); + + pageInfo.setList(containerListVos); + return ResponseResult.okResult(pageInfo); + } + + @Override + public ResponseResult getAllHost() { + List hostMachines = hostMachineService.list(); + List hostMachineVos = BeanCopyUtils.copyBeanList(hostMachines, HostMachineVo.class); + return ResponseResult.okResult(hostMachineVos); + } + + @Override + public ResponseResult deleteContainerById(Integer id) { + if (removeById(id)) { + return ResponseResult.okResult("删除成功"); + } + return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR); + } + + @Override + public ResponseResult addContainer(ContainerVo containerVo) { + Container container = BeanCopyUtils.copyBean(containerVo, Container.class); + SshLink sshLink = new SshLink(); + if (SshLinkUtil.isContainerSshLinkParamValid(containerVo)) { + sshLink.setConsoleType(containerVo.getSshType()) + .setHost(containerVo.getSshHost()) + .setPort(containerVo.getSshPort()) + .setName(containerVo.getSshUser()) + .setPassword(containerVo.getSshPwd()); + sshLinkService.save(sshLink); + container.setSshId(sshLink.getId()); + } + save(container); + return ResponseResult.okResult(); + } + + @Override + public ResponseResult getContainer(Integer id) { + Container container = getById(id); + ContainerVo containerVo = BeanCopyUtils.copyBean(container, ContainerVo.class); + if (Objects.nonNull(getById(id).getSshId())) { + SshLink sshLink = sshLinkService.getById(container.getSshId()); + containerVo.setSshType(sshLink.getConsoleType()) + .setSshHost(sshLink.getHost()) + .setSshPort(sshLink.getPort()) + .setSshUser(sshLink.getName()) + .setSshPwd(sshLink.getPassword()); + } + return ResponseResult.okResult(containerVo); + } + + @Override + public ResponseResult updateContainer(ContainerVo containerVo) { + Container container = BeanCopyUtils.copyBean(containerVo, Container.class); + //改ssh + SshLink sshLink = null; + if (Objects.nonNull(getById(containerVo.getId()).getSshId())) { + sshLink = sshLinkService.getById(getById(containerVo.getId()).getSshId()); + } else { + sshLink = new SshLink(); + } + if (SshLinkUtil.isContainerSshLinkParamValid(containerVo)) { + sshLink.setConsoleType(containerVo.getSshType()) + .setHost(containerVo.getSshHost()) + .setPort(containerVo.getSshPort()) + .setName(containerVo.getSshUser()) + .setPassword(containerVo.getSshPwd()); + sshLinkService.saveOrUpdate(sshLink); + container.setSshId(sshLink.getId()); + } + saveOrUpdate(container); + return ResponseResult.okResult(); + } + + @Override + public ResponseResult getAllContainer() { + List containers = list(); + List containerSelectVos = BeanCopyUtils.copyBeanList(containers, ContainerSelectVo.class); + return ResponseResult.okResult(containerSelectVos); + } + + @Override + public ResponseResult getAssociatedContainers(Integer id, Integer perPage, Integer currentPage) { + LambdaQueryWrapper containerLambdaQueryWrapper = new LambdaQueryWrapper<>(); + containerLambdaQueryWrapper.eq(Container::getHostMachineId, id); + //分页 + PageHelper.startPage(currentPage, perPage); + List containers = list(containerLambdaQueryWrapper); + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(containers, perPage); + List containerVos = BeanCopyUtils.copyBeanList(containers, ContainerVo.class); + pageInfo.setList(containerVos); + return ResponseResult.okResult(pageInfo); + } + + @Override + public Map getContainerStateInfo() { + HashMap result = new HashMap<>(); + LambdaQueryWrapper containerWrapper = new LambdaQueryWrapper<>(); + //设置容器总数 + result.put("containerCount", count()); + //设置容器在线总数 + containerWrapper.eq(Container::getContainerState, SystemConstant.CONTAINER_STATE_RUNNING); + result.put("containerOnlineCount", count(containerWrapper)); + containerWrapper.clear(); + //设置容器离线总数 + containerWrapper.eq(Container::getContainerState, SystemConstant.CONTAINER_STATE_EXITED); + result.put("containerOfflineCount", count(containerWrapper)); + containerWrapper.clear(); + //设置容器未知总数 + containerWrapper.eq(Container::getContainerState, SystemConstant.CONTAINER_STATE_UNKNOWN); + result.put("containerUnknownCount", count(containerWrapper)); + containerWrapper.clear(); + return result; + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/DashboardServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/DashboardServiceImpl.java new file mode 100644 index 0000000..4bcba00 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/DashboardServiceImpl.java @@ -0,0 +1,91 @@ +package com.mzaxd.noodles.service.impl; + +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.AuditLog; +import com.mzaxd.noodles.domain.entity.EveryDayData; +import com.mzaxd.noodles.domain.vo.RecentConsoleListVo; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.enums.OperationEnum; +import com.mzaxd.noodles.service.*; +import com.mzaxd.noodles.util.BeanCopyUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * @author 13439 + */ +@Service +public class DashboardServiceImpl implements DashboardService { + + @Resource + private HostMachineService hostMachineService; + + @Resource + private ContainerServiceImpl containerService; + + @Resource + private EveryDayDataService everyDayDataService; + + @Resource + private ServirService servirService; + + @Resource + private AuditLogService auditLogService; + + @Resource + private SshLinkService sshLinkService; + + @Override + public ResponseResult getInstancesRealTimeData() { + HashMap result = new HashMap<>(); + Map hostStateInfo = hostMachineService.getHostStateInfo(); + Map vmStateInfo = hostMachineService.getVmStateInfo(); + Map containerStateInfo = containerService.getContainerStateInfo(); + List lastSixDayData = everyDayDataService.getLastSixDayData(); + List servirCountList = lastSixDayData.stream().map(EveryDayData::getServirCount).collect(Collectors.toList()); + servirCountList.add(servirService.count()); + result.put("servirCountList", servirCountList); + result.put("hostCount", hostStateInfo.get("hostCount")); + result.put("hostOnlineCount", hostStateInfo.get("hostOnlineCount")); + result.put("vmCount", vmStateInfo.get("vmCount")); + result.put("vmOnlineCount", vmStateInfo.get("vmOnlineCount")); + result.put("containerCount", containerStateInfo.get("containerCount")); + result.put("containerOnlineCount", containerStateInfo.get("containerOnlineCount")); + return ResponseResult.okResult(result); + } + + @Override + public ResponseResult getRecentConsoleList() { + LambdaQueryWrapper auditLogLambdaQueryWrapper = new LambdaQueryWrapper<>(); + auditLogLambdaQueryWrapper.eq(AuditLog::getOperation, OperationEnum.CONSOLE_CONNECT.getOperation()).orderByDesc(AuditLog::getCreateTime); + List list = auditLogService.list(auditLogLambdaQueryWrapper); + if (Objects.nonNull(list)) { + List recentConsoleListVos = list.stream() + .distinct() + .limit(7L) + .map(auditLog -> { + Long sshId = JSON.parseArray(auditLog.getParam(), Long.class).get(0); + Object instance = sshLinkService.getInstanceInfoBySshId((sshId)); + if (Objects.nonNull(instance)) { + RecentConsoleListVo recentConsoleListVo = BeanCopyUtils.copyBean(instance, RecentConsoleListVo.class); + recentConsoleListVo.setSshId(sshId); + return recentConsoleListVo; + } + return null; + }).filter(Objects::nonNull).collect(Collectors.toList()); + return ResponseResult.okResult(recentConsoleListVos); + } + return ResponseResult.okResult(); + } +} diff --git a/src/main/java/com/mzaxd/noodles/service/impl/EveryDayDataServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/EveryDayDataServiceImpl.java new file mode 100644 index 0000000..92453e5 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/EveryDayDataServiceImpl.java @@ -0,0 +1,92 @@ +package com.mzaxd.noodles.service.impl; + +import cn.hutool.core.date.DateUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.EveryDayData; +import com.mzaxd.noodles.mapper.EveryDayDataMapper; +import com.mzaxd.noodles.service.EveryDayDataService; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** +* @author 13439 +* @description 针对表【every_data】的数据库操作Service实现 +* @createDate 2023-02-21 12:52:12 +*/ +@Service +public class EveryDayDataServiceImpl extends ServiceImpl + implements EveryDayDataService { + + @Override + public ResponseResult getAuditLogCountYesterday() { + ArrayList result = new ArrayList<>(); + for (EveryDayData lastWeekDatum : getLastWeekData()) { + result.add(lastWeekDatum.getAuditCount()); + } + return ResponseResult.okResult(result); + } + + @Override + public ResponseResult getInstancesHistory() { + EveryDayData yesterdayData = getYesterdayData(); + HashMap result = new HashMap<>(); + result.put("hostCount", yesterdayData.getHostCount()); + result.put("hostOnlineCount", yesterdayData.getHostOnlineCount()); + result.put("hostOfflineCount", yesterdayData.getHostOfflineCount()); + result.put("hostUnknownCount", yesterdayData.getHostUnknownCount()); + result.put("vmCount", yesterdayData.getVmCount()); + result.put("vmOnlineCount", yesterdayData.getVmOnlineCount()); + result.put("vmOfflineCount", yesterdayData.getVmOfflineCount()); + result.put("vmUnknownCount", yesterdayData.getVmUnknownCount()); + result.put("containerCount", yesterdayData.getContainerCount()); + result.put("containerOnlineCount", yesterdayData.getContainerOnlineCount()); + result.put("containerOfflineCount", yesterdayData.getContainerOfflineCount()); + result.put("containerUnknownCount", yesterdayData.getContainerUnknownCount()); + return ResponseResult.okResult(result); + } + + private LambdaQueryWrapper getYesterdayLambdaWrapper() { + LambdaQueryWrapper everyDayDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + everyDayDataLambdaQueryWrapper.ge(EveryDayData::getCreateTime, DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -1))); + everyDayDataLambdaQueryWrapper.lt(EveryDayData::getCreateTime, DateUtil.endOfDay(DateUtil.offsetDay(DateUtil.date(), -1))); + return everyDayDataLambdaQueryWrapper; + } + + @Override + public EveryDayData getYesterdayData() { + return getOne(getYesterdayLambdaWrapper()); + } + + private LambdaQueryWrapper getLastWeekLambdaWrapper() { + LambdaQueryWrapper everyDayDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + everyDayDataLambdaQueryWrapper.ge(EveryDayData::getCreateTime, DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -7))); + everyDayDataLambdaQueryWrapper.lt(EveryDayData::getCreateTime, DateUtil.endOfDay(DateUtil.offsetDay(DateUtil.date(), -1))); + return everyDayDataLambdaQueryWrapper; + } + + @Override + public List getLastWeekData() { + return list(getLastWeekLambdaWrapper()); + } + + private LambdaQueryWrapper getLastSixDayLambdaWrapper() { + LambdaQueryWrapper everyDayDataLambdaQueryWrapper = new LambdaQueryWrapper<>(); + everyDayDataLambdaQueryWrapper.ge(EveryDayData::getCreateTime, DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -6))); + everyDayDataLambdaQueryWrapper.lt(EveryDayData::getCreateTime, DateUtil.endOfDay(DateUtil.offsetDay(DateUtil.date(), -1))); + return everyDayDataLambdaQueryWrapper; + } + + @Override + public List getLastSixDayData() { + return list(getLastSixDayLambdaWrapper()); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/HostDetectorServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/HostDetectorServiceImpl.java new file mode 100644 index 0000000..5b13d21 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/HostDetectorServiceImpl.java @@ -0,0 +1,162 @@ +package com.mzaxd.noodles.service.impl; + +import cn.hutool.core.net.NetUtil; +import cn.hutool.core.util.NumberUtil; +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.constant.RedisConstant; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.constant.UrlConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.EveryDayData; +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.domain.message.DynamicData; +import com.mzaxd.noodles.domain.message.Server; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.exception.SystemException; +import com.mzaxd.noodles.mapper.HostDetectorMapper; +import com.mzaxd.noodles.service.HostDetectorService; +import com.mzaxd.noodles.service.HostMachineService; +import com.mzaxd.noodles.util.BeanCopyUtils; +import com.mzaxd.noodles.util.RedisCache; +import com.mzaxd.noodles.util.UrlUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author root + * @description 针对表【host_detector】的数据库操作Service实现 + * @createDate 2023-02-05 13:18:46 + */ +@Slf4j +@Service +public class HostDetectorServiceImpl extends ServiceImpl + implements HostDetectorService { + + @Resource + private HostMachineService hostMachineService; + + @Resource + private RestTemplate restTemplate; + + @Resource + private RedisCache redisCache; + + @Override + public List getAllALiveDetectors() { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_ONLINE); + queryWrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + List hostMachines = hostMachineService.list(queryWrapper); + + List hostMachineIds = hostMachines.stream().map(HostMachine::getId).collect(Collectors.toList()); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.in(HostDetector::getHostMachineId, hostMachineIds); + List hostDetectors = list(wrapper); + return hostDetectors; + } + + @Override + public Map getDynamicData(List allAliveDetector) { + HashMap map = new HashMap<>(); + for (HostDetector detector : allAliveDetector) { + DynamicData dynamicData = (DynamicData) redisCache.getCacheObject(RedisConstant.DYNAMIC_DATA + detector.getDetectorUuid()); + map.put(detector.getHostMachineId(), dynamicData); + } + return map; + } + + @Override + public Map getDynamicDataByDetector(HostDetector detector) { + HashMap map = new HashMap<>(); + DynamicData dynamicData = (DynamicData) redisCache.getCacheObject(RedisConstant.DYNAMIC_DATA + detector.getDetectorUuid()); + map.put(detector.getHostMachineId(), dynamicData); + return map; + } + + @Override + public ResponseResult isValidUrl(String protocol, String ip, String port) { + if (!NetUtil.isValidPort(Integer.parseInt(port))) { + throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR); + } + String url = UrlUtil.getUrl(protocol, ip, port, UrlConstant.DETECTOR_IS_TRUE_URL); + boolean validUrl = isValidUrl(url); + if (validUrl) { + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "连接成功"); + } + return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "连接失败"); + } + + @Override + public boolean isValidUrl(String url) { + log.info("尝试连接探测器:{}", url); + ResponseResult response = restTemplate.getForObject(url, ResponseResult.class); + if (response != null && response.getCode().equals(ResponseResult.okResult().getCode())) { + log.info("连接{}成功", url); + return true; + } + return false; + } + + @Override + public Server detectorGetInfoByUrl(String url) { + ResponseResult response = restTemplate.getForObject(url, ResponseResult.class); + if (response != null && response.getCode().equals(ResponseResult.okResult().getCode())) { + log.info("获取信息成功"); + return JSON.parseObject(JSON.toJSONString(response.getData()), Server.class); + } + return null; + } + + @Override + public ResponseResult getMemInfo() { + Map result = new HashMap<>(); + //当前在线数量 + int count = 0; + //总内存大小 + int memoryTotal = 0; + //单机最高内存使用率 + Double memoryUsedMaxRate = 0.0; + //平均内存使用率 + Double memoryUsedAvgRate = 0.0; + //平均内存使用率 + Double memoryTotalUsedRate = 0.0; + //空闲内存 + Double memoryFree = 0.0; + //已使用内存 + Double memoryUsed = 0.0; + Map dynamicData = getDynamicData(getAllALiveDetectors()); + for (DynamicData data : dynamicData.values()) { + count++; + memoryFree += data.getMemFree(); + memoryUsed += data.getMemUsed(); + Double total = data.getMemFree() + data.getMemUsed(); + memoryTotal += total.intValue(); + double memoryUsedRate = memoryUsed / memoryTotal; + memoryTotalUsedRate += memoryUsedRate; + if (memoryUsedRate > memoryUsedMaxRate) { + memoryUsedMaxRate = memoryUsedRate; + } + } + memoryUsedAvgRate = memoryTotalUsedRate / count; + result.put("memoryTotal", memoryTotal); + result.put("memoryFree", memoryFree); + result.put("memoryUsed", memoryUsed); + result.put("memoryUsedMaxRate", NumberUtil.round(memoryUsedMaxRate, 4)); + result.put("memoryUsedAvgRate", NumberUtil.round(memoryUsedAvgRate, 4)); + return ResponseResult.okResult(result); + } + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/HostMachineServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/HostMachineServiceImpl.java new file mode 100644 index 0000000..c6e3aa0 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/HostMachineServiceImpl.java @@ -0,0 +1,569 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.constant.UrlConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.*; +import com.mzaxd.noodles.domain.message.Server; +import com.mzaxd.noodles.domain.vo.*; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.exception.SystemException; +import com.mzaxd.noodles.mapper.HostDetectorMapper; +import com.mzaxd.noodles.mapper.HostMachineMapper; +import com.mzaxd.noodles.mapper.OsMapper; +import com.mzaxd.noodles.mapper.SshLinkMapper; +import com.mzaxd.noodles.service.*; +import com.mzaxd.noodles.util.BeanCopyUtils; +import com.mzaxd.noodles.util.SshLinkUtil; +import com.mzaxd.noodles.util.UrlUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * @author root + * @description 针对表【host_machine】的数据库操作Service实现 + * @createDate 2023-01-30 01:24:08 + */ +@Service +@Slf4j +public class HostMachineServiceImpl extends ServiceImpl + implements HostMachineService { + + + @Resource + private RestTemplate restTemplate; + + @Lazy + @Resource + private HostDetectorService hostDetectorService; + + @Resource + private HostDetectorMapper hostDetectorMapper; + + @Resource + private HostMachineMapper hostMachineMapper; + + @Resource + private OsMapper osMapper; + + @Resource + private OsService osService; + + @Lazy + @Resource + private ContainerService containerService; + + @Resource + private SshLinkService sshLinkService; + + @Resource + private SshLinkMapper sshLinkMapper; + + @Override + public ResponseResult getHostDrawer() { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(HostMachine::getHostMachineId, SystemConstant.PHYSICAL_MACHINE); + List hostMachineList = list(wrapper); + List hostMachineDrawerVos = BeanCopyUtils.copyBeanList(hostMachineList, HostMachineDrawerVo.class); + return ResponseResult.okResult(hostMachineDrawerVos); + } + + @Override + public ResponseResult vmListWithCondition(String nameLike, List selectedKernel, List selectedHost, List selectedStatus, Integer perPage, Integer currentPage) { + //分页 + PageHelper.startPage(currentPage, perPage); + //查询 + List hostMachines = hostMachineMapper.vmListWithCondition(nameLike, selectedKernel, selectedHost, selectedStatus, perPage, currentPage); + + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(hostMachines, perPage); + + //封装结果返回 + List virtualMachineListVos = BeanCopyUtils.copyBeanList(hostMachines, VirtualMachineListVo.class); + virtualMachineListVos.forEach(virtualMachineListVo -> { + Os os = osMapper.selectById(virtualMachineListVo.getOsId()); + OsVo osVo = BeanCopyUtils.copyBean(os, OsVo.class); + virtualMachineListVo.setOs(osVo); + }); + pageInfo.setList(virtualMachineListVos); + return ResponseResult.okResult(pageInfo); + } + + @Override + public ResponseResult vmListSummaryStatistics() { + //设置查询所有vm的条件 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + //设置查询所有在线vm的条件 + LambdaQueryWrapper onlineWrapper = new LambdaQueryWrapper<>(); + onlineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_ONLINE); + onlineWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + //设置查询所有离线vm的条件 + LambdaQueryWrapper offlineWrapper = new LambdaQueryWrapper<>(); + offlineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_OFFLINE); + offlineWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + //设置查询所有睡眠vm的条件 + LambdaQueryWrapper sleepWrapper = new LambdaQueryWrapper<>(); + sleepWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_SLEEP); + sleepWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + + int total = count(wrapper); + int online = count(onlineWrapper); + int offline = count(offlineWrapper); + int sleep = count(sleepWrapper); + HashMap result = new HashMap<>(4); + result.put("total", total); + result.put("online", online); + result.put("offline", offline); + result.put("sleep", sleep); + return ResponseResult.okResult(result); + } + + @Override + @Transactional + public ResponseResult updateVm(VmVo vmVo) { + //改Os + Os os = osService.getById(getById(vmVo.getId()).getOsId()); + os.setName(vmVo.getOsName()).setKernel(vmVo.getOsKernel()).setDescription(vmVo.getOsName()); + osService.saveOrUpdate(os); + + //改SshLink + SshLink sshLink = null; + if (Objects.nonNull(getById(vmVo.getId()).getSshId())) { + sshLink = sshLinkService.getById(getById(vmVo.getId()).getSshId()); + } else { + sshLink = new SshLink(); + } + sshLink.setHost(vmVo.getSshHost()).setPort(vmVo.getSshPort()).setName(vmVo.getSshUser()).setPassword(vmVo.getSshPwd()); + sshLinkService.saveOrUpdate(sshLink); + + HostMachine vm = BeanCopyUtils.copyBean(vmVo, HostMachine.class); + vm.setSshId(sshLink.getId()); + saveOrUpdate(vm); + return ResponseResult.okResult(SystemConstant.SUCCESS_CODE, "修改成功"); + } + + @Override + @Transactional + public ResponseResult addVm(VmVo vmvo) { + HostMachine vm = BeanCopyUtils.copyBean(vmvo, HostMachine.class); + Os os = new Os(); + os.setName(vmvo.getOsName()).setKernel(vmvo.getOsKernel()); + osService.save(os); + vm.setOsId(os.getId()); + if (SshLinkUtil.isVmSshLinkParamValid(vmvo)) { + SshLink sshLink = new SshLink(); + sshLink.setHost(vmvo.getSshHost()).setPort(vmvo.getSshPort()).setName(vmvo.getSshUser()).setPassword(vmvo.getSshPwd()); + sshLinkService.save(sshLink); + vm.setSshId(sshLink.getId()); + } + save(vm); + return ResponseResult.okResult(SystemConstant.SUCCESS_CODE, "添加虚拟机成功"); + } + + @Override + @Transactional + public ResponseResult addHost(HostVo host) { + //判断是否能连上探测器 + String isValidUrl = UrlUtil.getUrl(host.getProtocol(), host.getIp(), host.getPort(), UrlConstant.DETECTOR_IS_TRUE_URL); + if (!hostDetectorService.isValidUrl(isValidUrl)) { + throw new RuntimeException("无法连接到探测器"); + } + //获取远程主机数据 + String getInfoUrl = UrlUtil.getUrl(host.getProtocol(), host.getIp(), host.getPort(), UrlConstant.DETECTOR_GET_INFO); + Server server = hostDetectorService.detectorGetInfoByUrl(getInfoUrl); + + //存储Os信息 + Os os = new Os(); + String osName = server.getOs().getOsName(); + os.setName(osName).setDescription(osName).setKernel(host.getOsKernel()); + osService.save(os); + + //把数据库其余字段的数据补上 + HostMachine hostMachine = BeanCopyUtils.copyBean(host, HostMachine.class); + hostMachine.setThreads((long) server.getCpu().getLogicalProcessorCount()); + hostMachine.setMemory((long) server.getMem().getTotal() * 1024); + hostMachine.setHostMachineId(SystemConstant.HOST_MACHINE_ID_HOST); + hostMachine.setHostMachineState(SystemConstant.HOST_MACHINE_STATE_ONLINE); + hostMachine.setOsId(os.getId()); + + + //存储控制台信息 + if (SshLinkUtil.isHostSshLinkParamValid(host)) { + SshLink sshLink = new SshLink(); + sshLink.setHost(host.getSshHost()).setPort(host.getSshPort()).setName(host.getSshUser()).setPassword(host.getSshPwd()); + sshLinkService.save(sshLink); + hostMachine.setSshId(sshLink.getId()); + } + + save(hostMachine); + //存储探测器信息 + HostDetector hostDetector = new HostDetector(); + + String getDetectorIdUrl = UrlUtil.getUrl(host.getProtocol(), host.getIp(), host.getPort(), UrlConstant.DETECTOR_GET_DETECTOR_ID); + ResponseResult response = restTemplate.getForObject(getDetectorIdUrl, ResponseResult.class); + String uuid = response.getData().toString(); + + hostDetector + .setHostMachineId(hostMachine.getId()) + .setDetectorUuid(uuid) + .setDetectorIpAddress(UrlUtil.getAddress(host.getProtocol(), host.getIp(), host.getPort())); + hostDetectorService.save(hostDetector); + + return ResponseResult.okResult(); + } + + @Override + public ResponseResult getHostById(Integer id) { + HostMachine hostMachine = getById(id); + HostVo hostVo = BeanCopyUtils.copyBean(hostMachine, HostVo.class); + Os os = osMapper.selectById(hostMachine.getOsId()); + hostVo.setOsKernel(os.getKernel()); + + if (Objects.nonNull(hostMachine.getSshId())) { + SshLink sshLink = sshLinkService.getById(hostMachine.getSshId()); + hostVo.setSshHost(sshLink.getHost()).setSshPort(sshLink.getPort()).setSshUser(sshLink.getName()).setSshPwd(sshLink.getPassword()); + } + + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(HostDetector::getHostMachineId, id); + HostDetector hostDetector = hostDetectorService.getOne(queryWrapper); + Map map = UrlUtil.resolveUrl(hostDetector.getDetectorIpAddress()); + hostVo.setProtocol(map.get(UrlConstant.PROTOCOL)); + hostVo.setIp(map.get(UrlConstant.IP)); + hostVo.setPort(map.get(UrlConstant.PORT)); + return ResponseResult.okResult(hostVo); + } + + @Override + @Transactional + public ResponseResult updateHost(HostVo host) { + //判断是否能连上探测器 + String isValidUrl = UrlUtil.getUrl(host.getProtocol(), host.getIp(), host.getPort(), UrlConstant.DETECTOR_IS_TRUE_URL); + if (!hostDetectorService.isValidUrl(isValidUrl)) { + throw new RuntimeException("无法连接到探测器"); + } + // 改探测器 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(HostDetector::getHostMachineId, host.getId()); + HostDetector hostDetector = hostDetectorService.getOne(wrapper); + //改为新的探测器地址 + hostDetector.setDetectorIpAddress(UrlUtil.getAddress(host.getProtocol(), host.getIp(), host.getPort())); + + //获取新的探测器uuid + String getDetectorIdUrl = UrlUtil.getUrl(host.getProtocol(), host.getIp(), host.getPort(), UrlConstant.DETECTOR_GET_DETECTOR_ID); + ResponseResult response = restTemplate.getForObject(getDetectorIdUrl, ResponseResult.class); + String uuid = response.getData().toString(); + hostDetector.setDetectorUuid(uuid); + hostDetectorService.saveOrUpdate(hostDetector); + + //通过新的地址获取新的数据 + String getInfoUrl = UrlUtil.getUrl(host.getProtocol(), host.getIp(), host.getPort(), UrlConstant.DETECTOR_GET_INFO); + Server server = hostDetectorService.detectorGetInfoByUrl(getInfoUrl); + + //改Os + Os os = osService.getById(getById(host.getId()).getOsId()); + String osName = server.getOs().getOsName(); + os.setKernel(host.getOsKernel()).setName(osName).setDescription(osName); + osService.saveOrUpdate(os); + + SshLink sshLink = null; + //改SshLink + if (Objects.nonNull(getById(host.getId()).getSshId())) { + sshLink = sshLinkService.getById(getById(host.getId()).getSshId()); + } else { + sshLink = new SshLink(); + } + if (SshLinkUtil.isHostSshLinkParamValid(host)) { + sshLink.setHost(host.getSshHost()).setPort(host.getSshPort()).setName(host.getSshUser()).setPassword(host.getSshPwd()); + sshLinkService.saveOrUpdate(sshLink); + } + + HostMachine hostMachine = BeanCopyUtils.copyBean(host, HostMachine.class); + hostMachine.setSshId(sshLink.getId()); + hostMachine.setThreads((long) server.getCpu().getLogicalProcessorCount()); + hostMachine.setMemory((long) server.getMem().getTotal() * 1024); + saveOrUpdate(hostMachine); + return ResponseResult.okResult(); + } + + @Override + @Transactional + public ResponseResult deleteHostById(Integer id) { + //判断是否还有其他容器关联此VM 如果有则不可以删除 + LambdaQueryWrapper containerWrapper = new LambdaQueryWrapper<>(); + containerWrapper.eq(Container::getHostMachineId, id); + List containerList = containerService.list(containerWrapper); + + if (CollectionUtils.isNotEmpty(containerList)) { + log.info("删除失败,此物理机有关联的容器"); + throw new SystemException(AppHttpCodeEnum.EXIST_ASSOCIATION_CONTAINER); + } + + //判断是否还有其他容器关联此VM 如果有则不可以删除 + LambdaQueryWrapper vmWrapper = new LambdaQueryWrapper<>(); + vmWrapper.eq(HostMachine::getHostMachineId, id); + List vmList = list(vmWrapper); + + if (CollectionUtils.isNotEmpty(vmList)) { + log.info("删除失败,此物理机有关联的虚拟机"); + throw new SystemException(AppHttpCodeEnum.EXIST_ASSOCIATION_VM); + } + //删除对应的探测器 + LambdaQueryWrapper hostDetectorWrapper = new LambdaQueryWrapper<>(); + hostDetectorWrapper.eq(HostDetector::getHostMachineId, id); + hostDetectorMapper.delete(hostDetectorWrapper); + //删除对应的os + osMapper.deleteById(getById(id).getOsId()); + //删除对应的ssh连接信息 + if (Objects.nonNull(getById(id).getSshId())) { + sshLinkMapper.deleteById(getById(id).getSshId()); + } + //删除物理机 + HostMachine hostMachine = hostMachineMapper.selectById(id); + if (Objects.nonNull(hostMachine.getOsId())) { + log.info("删除hostId为{}的host信息", id); + osMapper.deleteById(hostMachine.getOsId()); + } + log.info("删除id为{}的host", id); + hostMachineMapper.deleteById(id); + return ResponseResult.okResult(SystemConstant.SUCCESS_CODE, "删除成功"); + } + + @Override + public ResponseResult getHostDetail(Integer id) { + HostMachine hostMachine = getById(id); + HostPanelVo hostPanelVo = BeanCopyUtils.copyBean(hostMachine, HostPanelVo.class); + LambdaQueryWrapper hostDetectorLambdaQueryWrapper = new LambdaQueryWrapper<>(); + hostDetectorLambdaQueryWrapper.eq(HostDetector::getHostMachineId, id); + HostDetector hostDetector = hostDetectorService.getOne(hostDetectorLambdaQueryWrapper); + Server server = hostDetectorService.detectorGetInfoByUrl(hostDetector.getDetectorIpAddress() + UrlConstant.DETECTOR_GET_INFO); + //查虚拟机数量 + LambdaQueryWrapper vmWrapper = new LambdaQueryWrapper<>(); + vmWrapper.eq(HostMachine::getHostMachineId, id); + int vmCount = count(vmWrapper); + //查容器数量 + LambdaQueryWrapper containerWrapper = new LambdaQueryWrapper<>(); + containerWrapper.eq(Container::getHostMachineId, id); + int containerCount = containerService.count(containerWrapper); + hostPanelVo.setVmCount(vmCount).setContainerCount(containerCount); + HashMap result = new HashMap<>(); + result.put("host", hostPanelVo); + result.put("hostDetail", server); + return ResponseResult.okResult(result); + } + + @Override + public ResponseResult getAssociatedVms(Integer id, Integer perPage, Integer currentPage) { + LambdaQueryWrapper hostMachineLambdaQueryWrapper = new LambdaQueryWrapper<>(); + hostMachineLambdaQueryWrapper.eq(HostMachine::getHostMachineId, id); + //分页 + PageHelper.startPage(currentPage, perPage); + List vms = list(hostMachineLambdaQueryWrapper); + List vmList = BeanCopyUtils.copyBeanList(vms, VirtualMachineListVo.class); + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(vmList, perPage); + vmList.forEach(virtualMachineListVo -> { + Os os = osService.getById(virtualMachineListVo.getOsId()); + OsVo osVo = BeanCopyUtils.copyBean(os, OsVo.class); + virtualMachineListVo.setOs(osVo); + }); + pageInfo.setList(vmList); + return ResponseResult.okResult(pageInfo); + } + + @Override + public ResponseResult getAssociatedDisks(Integer id) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(HostDetector::getHostMachineId, id); + HostDetector hostDetector = hostDetectorService.getOne(lambdaQueryWrapper); + ResponseResult result = restTemplate.getForObject(hostDetector.getDetectorIpAddress() + UrlConstant.DETECTOR_GET_DISK_INFO, ResponseResult.class); + return ResponseResult.okResult(result.getData()); + } + + @Override + public ResponseResult getAssociatedNetworkIfs(Integer id) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(HostDetector::getHostMachineId, id); + HostDetector hostDetector = hostDetectorService.getOne(lambdaQueryWrapper); + ResponseResult result = restTemplate.getForObject(hostDetector.getDetectorIpAddress() + UrlConstant.DETECTOR_GET_NETWORK_IF_INFO, ResponseResult.class); + return ResponseResult.okResult(result.getData()); + } + + @Override + public ResponseResult hostListWithCondition(String nameLike, List selectedStatus, Integer perPage, Integer currentPage) { + //设置查询条件 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + wrapper.like(StringUtils.hasText(nameLike), HostMachine::getDescription, nameLike); + wrapper.in(Objects.nonNull(selectedStatus), HostMachine::getHostMachineState, selectedStatus); + //分页 + PageHelper.startPage(currentPage, perPage); + //查询 + List hostMachines = list(wrapper); + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(hostMachines, perPage); + //封装结果返回 + List hostMachineListVo = BeanCopyUtils.copyBeanList(hostMachines, HostMachineListVo.class); + //设置探测器ip地址 设置Os信息 + hostMachineListVo.forEach(hostMachineVo -> { + Os os = osMapper.selectById(hostMachineVo.getOsId()); + OsVo osVo = BeanCopyUtils.copyBean(os, OsVo.class); + hostMachineVo.setOs(osVo); + }); + + pageInfo.setList(hostMachineListVo); + return ResponseResult.okResult(pageInfo); + } + + @Override + public ResponseResult deleteVmById(Integer id) { + //判断是否还有其他容器关联此VM 如果有则不可以删除 + LambdaQueryWrapper containerWrapper = new LambdaQueryWrapper<>(); + containerWrapper.eq(Container::getHostMachineId, id); + List containerList = containerService.list(containerWrapper); + + if (CollectionUtils.isNotEmpty(containerList)) { + log.info("删除失败,此Vm有关联的容器"); + throw new SystemException(AppHttpCodeEnum.EXIST_ASSOCIATION_CONTAINER); + } + HostMachine hostMachine = hostMachineMapper.selectById(id); + if (Objects.nonNull(hostMachine.getOsId())) { + log.info("删除vmId为{}的Os信息", id); + osMapper.deleteById(hostMachine.getOsId()); + } + //删除对应的os + osMapper.deleteById(getById(id).getOsId()); + //删除对应的ssh连接信息 + if (Objects.nonNull(getById(id).getSshId())) { + sshLinkMapper.deleteById(getById(id).getSshId()); + } + log.info("删除id为{}的vm", id); + hostMachineMapper.deleteById(id); + return ResponseResult.okResult(SystemConstant.SUCCESS_CODE, "删除成功"); + } + + @Override + public ResponseResult getVmById(Integer id) { + HostMachine hostMachine = hostMachineMapper.selectById(id); + Os os = osMapper.selectById(hostMachine.getOsId()); + VmVo vmVo = BeanCopyUtils.copyBean(hostMachine, VmVo.class); + vmVo.setOsName(os.getName()).setOsKernel(os.getKernel()); + if (Objects.nonNull(hostMachine.getSshId())) { + SshLink sshLink = sshLinkService.getById(hostMachine.getSshId()); + vmVo.setSshHost(sshLink.getHost()).setSshPort(sshLink.getPort()).setSshUser(sshLink.getName()).setSshPwd(sshLink.getPassword()); + } + return ResponseResult.okResult(vmVo); + } + + /** + * 获取所有物理机当前在线信息 + * + * @return + */ + @Override + public Map getHostStateInfo() { + HashMap result = new HashMap<>(); + LambdaQueryWrapper hostMachineWrapper = new LambdaQueryWrapper<>(); + //设置主机总数 + hostMachineWrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + result.put("hostCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + //设置主机在线总数 + hostMachineWrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + hostMachineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_ONLINE); + result.put("hostOnlineCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + //设置主机离线总数 + hostMachineWrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + hostMachineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_OFFLINE); + result.put("hostOfflineCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + //设置主机未知总数 + hostMachineWrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + hostMachineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_UNKNOWN); + result.put("hostUnknownCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + return result; + } + + /** + * 获取所有虚拟机当前在线信息 + * + * @return + */ + @Override + public Map getVmStateInfo() { + HashMap result = new HashMap<>(); + LambdaQueryWrapper hostMachineWrapper = new LambdaQueryWrapper<>(); + //设置虚拟机总数 + hostMachineWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + result.put("vmCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + //设置虚拟机在线总数 + hostMachineWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + hostMachineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_ONLINE); + result.put("vmOnlineCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + //设置虚拟机离线总数 + hostMachineWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + hostMachineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_OFFLINE); + result.put("vmOfflineCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + //设置虚拟机未知总数 + hostMachineWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + hostMachineWrapper.eq(HostMachine::getHostMachineState, SystemConstant.HOST_MACHINE_STATE_UNKNOWN); + result.put("vmUnknownCount", count(hostMachineWrapper)); + hostMachineWrapper.clear(); + return result; + } + + @Override + public ResponseResult startSendDynamicData(Integer hostId) { + LambdaQueryWrapper hostDetectorLambdaQueryWrapper = new LambdaQueryWrapper<>(); + hostDetectorLambdaQueryWrapper.eq(HostDetector::getHostMachineId, hostId); + HostDetector hostDetector = hostDetectorService.getOne(hostDetectorLambdaQueryWrapper); + ResponseResult result = null; + try { + result = restTemplate.getForObject(hostDetector.getDetectorIpAddress() + UrlConstant.DETECTOR_START_SEND_DYNAMIC_DATA, ResponseResult.class); + } catch (Exception e) { + throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR); + } + return result; + } + + @Override + public ResponseResult stopSendDynamicData(Integer hostId) { + LambdaQueryWrapper hostDetectorLambdaQueryWrapper = new LambdaQueryWrapper<>(); + hostDetectorLambdaQueryWrapper.eq(HostDetector::getHostMachineId, hostId); + HostDetector hostDetector = hostDetectorService.getOne(hostDetectorLambdaQueryWrapper); + ResponseResult result = null; + try { + result = restTemplate.getForObject(hostDetector.getDetectorIpAddress() + UrlConstant.DETECTOR_STOP_SEND_DYNAMIC_DATA, ResponseResult.class); + } catch (Exception e) { + throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR); + } + return result; + } + + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/LoginServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/LoginServiceImpl.java new file mode 100644 index 0000000..40f6615 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/LoginServiceImpl.java @@ -0,0 +1,89 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.LoginUser; +import com.mzaxd.noodles.domain.entity.User; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.mapper.UserMapper; +import com.mzaxd.noodles.service.LoginService; +import com.mzaxd.noodles.service.UserService; +import com.mzaxd.noodles.util.JwtUtil; +import com.mzaxd.noodles.util.RedisCache; +import com.mzaxd.noodles.util.SecurityUtils; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * @author root + */ +@Service +public class LoginServiceImpl extends ServiceImpl implements LoginService { + + @Resource + private AuthenticationManager authenticationManager; + @Resource + private RedisCache redisCache; + @Resource + private PasswordEncoder passwordEncoder; + @Resource + private UserMapper userMapper; + + @Override + public ResponseResult login(User user) { + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()); + Authentication authenticate = authenticationManager.authenticate(authenticationToken); + //判断是否认证通过 + if (Objects.isNull(authenticate)) { + throw new RuntimeException("邮箱或密码错误"); + } + //获取userid 生成token + LoginUser loginUser = (LoginUser) authenticate.getPrincipal(); + String userId = loginUser.getUser().getId().toString(); + String jwt = JwtUtil.createJWT(userId); + //把用户信息存入redis + redisCache.setCacheObject("login:" + userId, loginUser); + //把token封装 返回 + Map map = new HashMap<>(); + map.put("token", jwt); + map.put("userId", userId); + return ResponseResult.okResult("登录成功", map); + } + + @Override + public ResponseResult logout() { + //获取当前登录的用户id + Long userId = SecurityUtils.getUserId(); + //删除redis中对应的值 + redisCache.deleteObject("login:" + userId); + return ResponseResult.okResult(); + } + + @Override + public ResponseResult updateAccount(User user) { + //获取当前登录的用户id + Long userId = SecurityUtils.getUserId(); + User defaultUser = getById(userId); + defaultUser.setEmail(user.getEmail()); + defaultUser.setPassword(passwordEncoder.encode(user.getPassword())); + defaultUser.setUserState(SystemConstant.NORMAL_STATE); + saveOrUpdate(defaultUser); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),"修改账号信息成功"); + } + + @Override + public ResponseResult deleteAccount() { + Long userId = SecurityUtils.getUserId(); + userMapper.deleteById(userId); + return ResponseResult.okResult(); + } +} diff --git a/src/main/java/com/mzaxd/noodles/service/impl/NotificationServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/NotificationServiceImpl.java new file mode 100644 index 0000000..7b88663 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/NotificationServiceImpl.java @@ -0,0 +1,233 @@ +package com.mzaxd.noodles.service.impl; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.extra.mail.MailUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.mzaxd.noodles.constant.RedisConstant; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Container; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.domain.entity.Notification; +import com.mzaxd.noodles.domain.vo.NotificationListVo; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.service.ContainerService; +import com.mzaxd.noodles.service.HostMachineService; +import com.mzaxd.noodles.service.NotificationService; +import com.mzaxd.noodles.mapper.NotificationMapper; +import com.mzaxd.noodles.util.BeanCopyUtils; +import com.mzaxd.noodles.util.RedisCache; +import com.mzaxd.noodles.util.SystemSettingUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.security.core.parameters.P; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * @author 13439 + * @description 针对表【notification】的数据库操作Service实现 + * @createDate 2023-02-16 16:04:53 + */ +@Service +@Slf4j +public class NotificationServiceImpl extends ServiceImpl + implements NotificationService { + + @Resource + private ContainerService containerService; + + @Resource + private HostMachineService hostMachineService; + + @Resource + private SystemSettingUtils systemSettingUtils; + + @Resource + private RedisTemplate redisTemplate; + + public void sendContainerOfflineNotification(Long id) { + Notification notification = new Notification(); + Container container = containerService.getById(id); + Integer notify = container.getNotify(); + //判断发送方式 + if (notify.equals(SystemConstant.NOTIFY_BROWSER_EMAIL) || notify.equals(SystemConstant.NOTIFY_EMAIL)) { + //发送邮件 + sendContainerOfflineEmail(id); + } + notification.setTitle("容器掉线") + .setType(SystemConstant.OFFLINE_NOTIFICATION) + .setSendType(container.getNotify()) + .setInstanceType(SystemConstant.INSTANCETYPE_CONTAINER) + .setInstanceId(id); + String content = String.format("容器[ %s ]已无法正常访问,请排查", container.getName()); + notification.setContent(content); + save(notification); + log.info("[掉线提醒]:发送浏览器提醒:{}", content); + } + + private void sendContainerOfflineEmail(Long id) { + Container container = containerService.getById(id); + String time = LocalDateTime.now().toString(); + String content = String.format("发现容器[ %s ]掉线---- %s", container.getName(), time); + MailUtil.send(systemSettingUtils.getMailAccount(), CollUtil.newArrayList(systemSettingUtils.getMailTarget()), "Noodles掉线提醒", content, false); + log.info("[掉线提醒]:发送邮件提醒:{}", content); + } + + @Override + public void sendVmOfflineNotification(Long id) { + Notification notification = new Notification(); + HostMachine vm = hostMachineService.getById(id); + Integer notify = vm.getNotify(); + //判断发送方式 + if (notify.equals(SystemConstant.NOTIFY_BROWSER_EMAIL) || notify.equals(SystemConstant.NOTIFY_EMAIL)) { + //发送邮件 + sendVmOfflineEmail(id); + } + notification.setTitle("虚拟机掉线") + .setType(SystemConstant.OFFLINE_NOTIFICATION) + .setSendType(vm.getNotify()) + .setInstanceType(SystemConstant.INSTANCETYPE_VM) + .setInstanceId(id); + String content = String.format("虚拟机[ %s ]已无法正常访问,请排查", vm.getName()); + notification.setContent(content); + save(notification); + log.info("[掉线提醒]:发送浏览器提醒:{}", content); + } + + private void sendVmOfflineEmail(Long id) { + HostMachine vm = hostMachineService.getById(id); + String time = LocalDateTime.now().toString(); + String content = String.format("发现虚拟机[ %s ]掉线---- %s", vm.getName(), time); + MailUtil.send(systemSettingUtils.getMailAccount(), CollUtil.newArrayList(systemSettingUtils.getMailTarget()), "Noodles掉线提醒", content, false); + log.info("[掉线提醒]:发送邮件提醒:{}", content); + } + + @Override + public void sendHostOfflineNotification(Long id) { + Notification notification = new Notification(); + HostMachine host = hostMachineService.getById(id); + Integer notify = host.getNotify(); + //判断发送方式 + if (notify.equals(SystemConstant.NOTIFY_BROWSER_EMAIL) || notify.equals(SystemConstant.NOTIFY_EMAIL)) { + //发送邮件 + sendHostOfflineEmail(id); + } + notification.setTitle("物理机掉线") + .setType(SystemConstant.OFFLINE_NOTIFICATION) + .setSendType(host.getNotify()) + .setInstanceType(SystemConstant.INSTANCETYPE_HOST) + .setInstanceId(id); + String content = String.format("无法连接到物理机[ %s ]的探测器,请排查", host.getName()); + notification.setContent(content); + save(notification); + log.info("[掉线提醒]:发送浏览器提醒:{}", content); + } + + @Override + public ResponseResult getNotificationList(Integer tab, Integer perPage, Integer currentPage) { + LambdaQueryWrapper notificationWrapper = new LambdaQueryWrapper<>(); + notificationWrapper.orderByDesc(Notification::getCreateTime); + List notificationList = new ArrayList<>(); + if (tab.equals(SystemConstant.FRONTEND_NOTIFICATION_NOT_AFFIRM)) { + notificationWrapper.eq(Notification::getAffirm, SystemConstant.NOTIFICATION_NOT_AFFIRM); + } + if (tab.equals(SystemConstant.FRONTEND_NOTIFICATION_AFFIRM)) { + notificationWrapper.eq(Notification::getAffirm, SystemConstant.NOTIFICATION_AFFIRM); + } + if (tab.equals(SystemConstant.FRONTEND_NOTIFICATION_ALL)) { + //分页 + PageHelper.startPage(currentPage, perPage); + notificationList = list(notificationWrapper); + PageInfo pageInfo = new PageInfo<>(notificationList, perPage); + List notificationListVos = BeanCopyUtils.copyBeanList(notificationList, NotificationListVo.class); + notificationListVos.forEach(notificationListVo -> { + Integer instanceType = notificationListVo.getInstanceType(); + //设置实例的图像、名称等信息 + if (SystemConstant.INSTANCETYPE_HOST.equals(instanceType) || SystemConstant.INSTANCETYPE_VM.equals(instanceType)) { + HostMachine hostMachine = hostMachineService.getById(notificationListVo.getInstanceId()); + notificationListVo.setInstanceName(hostMachine.getName()) + .setInstanceAvatar(hostMachine.getAvatar()); + } + if (SystemConstant.INSTANCETYPE_CONTAINER.equals(instanceType)) { + Container container = containerService.getById(notificationListVo.getInstanceId()); + notificationListVo.setInstanceName(container.getName()) + .setInstanceAvatar(container.getAvatar()); + } + }); + pageInfo.setList(notificationListVos); + return ResponseResult.okResult(pageInfo); + } + if (tab.equals(SystemConstant.FRONTEND_NOTIFICATION_TYPE_OFFLINE)) { + notificationWrapper.eq(Notification::getType, SystemConstant.OFFLINE_NOTIFICATION); + } + if (tab.equals(SystemConstant.FRONTEND_NOTIFICATION_TYPE_STATISTICS)) { + notificationWrapper.eq(Notification::getType, SystemConstant.STATISTICS_NOTIFICATION); + } + //分页 + PageHelper.startPage(currentPage, perPage); + notificationList = list(notificationWrapper); + PageInfo pageInfo = new PageInfo<>(notificationList, perPage); + List notificationListVos = BeanCopyUtils.copyBeanList(notificationList, NotificationListVo.class); + notificationListVos.forEach(notificationListVo -> { + Integer instanceType = notificationListVo.getInstanceType(); + //设置实例的图像、名称等信息 + if (SystemConstant.INSTANCETYPE_HOST.equals(instanceType) || SystemConstant.INSTANCETYPE_VM.equals(instanceType)) { + HostMachine hostMachine = hostMachineService.getById(notificationListVo.getInstanceId()); + notificationListVo.setInstanceName(hostMachine.getName()) + .setInstanceAvatar(hostMachine.getAvatar()); + } + if (SystemConstant.INSTANCETYPE_CONTAINER.equals(instanceType)) { + Container container = containerService.getById(notificationListVo.getInstanceId()); + notificationListVo.setInstanceName(container.getName()) + .setInstanceAvatar(container.getAvatar()); + } + }); + pageInfo.setList(notificationListVos); + return ResponseResult.okResult(pageInfo); + } + + @Override + public ResponseResult affirmNotification(Long id) { + Notification notification = getById(id); + if (SystemConstant.INSTANCETYPE_HOST.equals(notification.getInstanceType())) { + redisTemplate.opsForSet().remove(RedisConstant.NOTIFY_HOST_IDS, notification.getInstanceId().toString()); + } + if (SystemConstant.INSTANCETYPE_VM.equals(notification.getInstanceType())) { + redisTemplate.opsForSet().remove(RedisConstant.NOTIFY_VM_IDS, notification.getInstanceId().toString()); + } + if (SystemConstant.INSTANCETYPE_CONTAINER.equals(notification.getInstanceType())) { + redisTemplate.opsForSet().remove(RedisConstant.NOTIFY_CONTAINER_IDS, notification.getInstanceId().toString()); + } + saveOrUpdate(notification.setAffirm(SystemConstant.NOTIFICATION_AFFIRM)); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "处理完成"); + } + + @Override + public ResponseResult getNotificationCount() { + LambdaQueryWrapper notificationLambdaQueryWrapper = new LambdaQueryWrapper<>(); + notificationLambdaQueryWrapper.eq(Notification::getAffirm, SystemConstant.NOTIFICATION_NOT_AFFIRM); + return ResponseResult.okResult(count(notificationLambdaQueryWrapper)); + } + + private void sendHostOfflineEmail(Long id) { + HostMachine host = hostMachineService.getById(id); + String time = LocalDateTime.now().toString(); + String content = String.format("发现物理机[ %s ]掉线---- %s", host.getName(), time); + MailUtil.send(systemSettingUtils.getMailAccount(), CollUtil.newArrayList(systemSettingUtils.getMailTarget()), "Noodles掉线提醒", content, false); + log.info("[掉线提醒]:发送邮件提醒:{}", content); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/OsServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/OsServiceImpl.java new file mode 100644 index 0000000..eaa1024 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/OsServiceImpl.java @@ -0,0 +1,22 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.entity.Os; +import com.mzaxd.noodles.service.OsService; +import com.mzaxd.noodles.mapper.OsMapper; +import org.springframework.stereotype.Service; + +/** +* @author root +* @description 针对表【os】的数据库操作Service实现 +* @createDate 2023-01-30 13:20:28 +*/ +@Service +public class OsServiceImpl extends ServiceImpl + implements OsService{ + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/ServirContainerServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/ServirContainerServiceImpl.java new file mode 100644 index 0000000..081a07d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/ServirContainerServiceImpl.java @@ -0,0 +1,22 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.entity.ServirContainer; +import com.mzaxd.noodles.service.ServirContainerService; +import com.mzaxd.noodles.mapper.ServirContainerMapper; +import org.springframework.stereotype.Service; + +/** +* @author 13439 +* @description 针对表【servir_container】的数据库操作Service实现 +* @createDate 2023-02-11 20:48:45 +*/ +@Service +public class ServirContainerServiceImpl extends ServiceImpl + implements ServirContainerService{ + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/ServirHostServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/ServirHostServiceImpl.java new file mode 100644 index 0000000..d3813ee --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/ServirHostServiceImpl.java @@ -0,0 +1,22 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.entity.ServirHost; +import com.mzaxd.noodles.service.ServirHostService; +import com.mzaxd.noodles.mapper.ServirHostMapper; +import org.springframework.stereotype.Service; + +/** +* @author 13439 +* @description 针对表【servir_host】的数据库操作Service实现 +* @createDate 2023-02-11 20:48:51 +*/ +@Service +public class ServirHostServiceImpl extends ServiceImpl + implements ServirHostService{ + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/ServirServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/ServirServiceImpl.java new file mode 100644 index 0000000..1aae92a --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/ServirServiceImpl.java @@ -0,0 +1,291 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.*; +import com.mzaxd.noodles.domain.message.Server; +import com.mzaxd.noodles.domain.vo.*; +import com.mzaxd.noodles.mapper.ServirMapper; +import com.mzaxd.noodles.mapper.UserMapper; +import com.mzaxd.noodles.service.*; +import com.mzaxd.noodles.util.BeanCopyUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * @author root + * @description + * @createDate 2022-11-26 12:24:08 + */ +@Service +@Slf4j +public class ServirServiceImpl extends ServiceImpl implements ServirService { + + @Resource + private HostMachineService hostMachineService; + + @Resource + private ContainerService containerService; + + @Resource + private TagService tagService; + + @Resource + private ServirTagService servirTagService; + + @Resource + private ServirHostService servirHostService; + + @Resource + private ServirContainerService servirContainerService; + + @Resource + private ServirMapper servirMapper; + + @Override + public ResponseResult servirListWithCondition(String nameLike, List selectedTags, Integer perPage, Integer currentPage) { + //先查出所有选中标签的servir id + LambdaQueryWrapper servirTagLambdaQueryWrapper = new LambdaQueryWrapper<>(); + servirTagLambdaQueryWrapper.in(Objects.nonNull(selectedTags), ServirTag::getTagId, selectedTags); + List list = servirTagService.list(servirTagLambdaQueryWrapper); + List servirIds = null; + if (!CollectionUtils.isEmpty(list)) { + servirIds = list.stream().map(ServirTag::getServirId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList()); + } + + //设置查询条件 + LambdaQueryWrapper servirLambdaQueryWrapper = new LambdaQueryWrapper<>(); + servirLambdaQueryWrapper.like(StringUtils.hasText(nameLike), Servir::getDescription, nameLike); + servirLambdaQueryWrapper.in(Objects.nonNull(servirIds), Servir::getId, servirIds); + //分页 + PageHelper.startPage(currentPage, perPage); + //查询 + List servirs = list(servirLambdaQueryWrapper); + //封装分页信息 + PageInfo pageInfo = new PageInfo<>(servirs, perPage); + //封装结果返回 + List servirListVos = BeanCopyUtils.copyBeanList(servirs, ServirListVo.class); + //关联的host 关联的容器 所有标签 + servirListVos.forEach(servirListVo -> { + //关联的host + LambdaQueryWrapper servirHostWrapper = new LambdaQueryWrapper<>(); + servirHostWrapper.eq(ServirHost::getServirId, servirListVo.getId()); + List servirHosts = servirHostService.list(servirHostWrapper); + if (!CollectionUtils.isEmpty(servirHosts)) { + List hostIds = servirHosts.stream().map(ServirHost::getHostId).collect(Collectors.toList()); + LambdaQueryWrapper hostMachineWrapper = new LambdaQueryWrapper<>(); + hostMachineWrapper.in(HostMachine::getId, hostIds); + List hostMachines = hostMachineService.list(hostMachineWrapper); + servirListVo.setHosts(BeanCopyUtils.copyBeanList(hostMachines, ServirHostVo.class)); + } + //关联的容器 + LambdaQueryWrapper servirContainerWrapper = new LambdaQueryWrapper<>(); + servirContainerWrapper.eq(ServirContainer::getServirId, servirListVo.getId()); + List servirContainers = servirContainerService.list(servirContainerWrapper); + if (!CollectionUtils.isEmpty(servirContainers)) { + List containerIds = servirContainers.stream().map(ServirContainer::getContainerId).collect(Collectors.toList()); + LambdaQueryWrapper containerWrapper = new LambdaQueryWrapper<>(); + containerWrapper.in(Container::getId, containerIds); + List containers = containerService.list(containerWrapper); + servirListVo.setContainers(BeanCopyUtils.copyBeanList(containers, ServirContainerVo.class)); + } + //关联的标签 + LambdaQueryWrapper servirTagWrapper = new LambdaQueryWrapper<>(); + servirTagWrapper.eq(ServirTag::getServirId, servirListVo.getId()); + List servirTags = servirTagService.list(servirTagWrapper); + if (!CollectionUtils.isEmpty(servirTags)) { + List tagIds = servirTags.stream().map(ServirTag::getTagId).collect(Collectors.toList()); + LambdaQueryWrapper tagWrapper = new LambdaQueryWrapper<>(); + tagWrapper.in(Tag::getId, tagIds); + List tags = tagService.list(tagWrapper); + servirListVo.setTags(BeanCopyUtils.copyBeanList(tags, TagVo.class)); + } + }); + pageInfo.setList(servirListVos); + return ResponseResult.okResult(pageInfo); + } + + @Override + @Transactional + public ResponseResult addServir(SaveOrUpdateServirVo saveOrUpdateServirVo) { + Servir servir = BeanCopyUtils.copyBean(saveOrUpdateServirVo, Servir.class); + save(servir); + //关联host + if (Objects.nonNull(saveOrUpdateServirVo.getHostIds())) { + List servirHosts = saveOrUpdateServirVo.getHostIds().stream().map(id -> { + ServirHost servirHost = new ServirHost(); + servirHost.setServirId(servir.getId()); + servirHost.setHostId(Long.valueOf(id)); + return servirHost; + }).collect(Collectors.toList()); + servirHostService.saveBatch(servirHosts); + } + + //关联Container + if (Objects.nonNull(saveOrUpdateServirVo.getContainerIds())) { + List servirContainers = saveOrUpdateServirVo.getContainerIds().stream().map(id -> { + ServirContainer servirContainer = new ServirContainer(); + servirContainer.setServirId(servir.getId()); + servirContainer.setContainerId(Long.valueOf(id)); + return servirContainer; + }).collect(Collectors.toList()); + servirContainerService.saveBatch(servirContainers); + } + + //关联Tag + List servirTags = saveOrUpdateServirVo.getTagIds().stream().map(id -> { + ServirTag servirTag = new ServirTag(); + servirTag.setServirId(servir.getId()); + servirTag.setTagId(Long.valueOf(id)); + return servirTag; + }).collect(Collectors.toList()); + servirTagService.saveBatch(servirTags); + + return ResponseResult.okResult(); + } + + @Override + @Transactional + public ResponseResult updateServir(SaveOrUpdateServirVo saveOrUpdateServirVo) { + Servir servir = BeanCopyUtils.copyBean(saveOrUpdateServirVo, Servir.class); + saveOrUpdate(servir); + + if (Objects.nonNull(saveOrUpdateServirVo.getHostIds())) { + //删除所有服务关联的host + LambdaQueryWrapper servirHostWrapper = new LambdaQueryWrapper<>(); + servirHostWrapper.eq(ServirHost::getServirId, servir.getId()); + servirHostService.getBaseMapper().delete(servirHostWrapper); + //关联新的host + List servirHosts = saveOrUpdateServirVo.getHostIds().stream().map(id -> { + ServirHost servirHost = new ServirHost(); + servirHost.setServirId(servir.getId()); + servirHost.setHostId(Long.valueOf(id)); + return servirHost; + }).collect(Collectors.toList()); + servirHostService.saveBatch(servirHosts); + } + + if (Objects.nonNull(saveOrUpdateServirVo.getContainerIds())) { + //删除所有服务关联的容器 + LambdaQueryWrapper servirContainerWrapper = new LambdaQueryWrapper<>(); + servirContainerWrapper.eq(ServirContainer::getServirId, servir.getId()); + servirContainerService.getBaseMapper().delete(servirContainerWrapper); + //关联新的容器 + List servirContainers = saveOrUpdateServirVo.getContainerIds().stream().map(id -> { + ServirContainer servirContainer = new ServirContainer(); + servirContainer.setServirId(servir.getId()); + servirContainer.setContainerId(Long.valueOf(id)); + return servirContainer; + }).collect(Collectors.toList()); + servirContainerService.saveBatch(servirContainers); + } + + if (!CollectionUtils.isEmpty(saveOrUpdateServirVo.getTagIds())) { + //删除所有服务关联的标签 + LambdaQueryWrapper servirTagWrapper = new LambdaQueryWrapper<>(); + servirTagWrapper.eq(ServirTag::getServirId, servir.getId()); + servirTagService.getBaseMapper().delete(servirTagWrapper); + //关联新的标签 + List servirTags = saveOrUpdateServirVo.getTagIds().stream().map(id -> { + ServirTag servirTag = new ServirTag(); + servirTag.setServirId(servir.getId()); + servirTag.setTagId(Long.valueOf(id)); + return servirTag; + }).collect(Collectors.toList()); + servirTagService.saveBatch(servirTags); + } + return ResponseResult.okResult(); + } + + @Override + public ResponseResult getRemarkById(Integer id) { + Servir servir = getById(id); + return ResponseResult.okResult(servir.getRemark()); + } + + @Override + @Transactional + public ResponseResult deleteServirById(Integer id) { + log.info("删除id为{}的服务", id); + + //删除所有服务关联的host + LambdaQueryWrapper servirHostLambdaQueryWrapper = new LambdaQueryWrapper<>(); + servirHostLambdaQueryWrapper.eq(ServirHost::getServirId, id); + servirHostService.getBaseMapper().delete(servirHostLambdaQueryWrapper); + + //删除所有服务关联的容器 + LambdaQueryWrapper containerLambdaQueryWrapper = new LambdaQueryWrapper<>(); + containerLambdaQueryWrapper.eq(ServirContainer::getServirId, id); + servirContainerService.getBaseMapper().delete(containerLambdaQueryWrapper); + + //删除所有服务关联的标签 + LambdaQueryWrapper servirTagLambdaQueryWrapper = new LambdaQueryWrapper<>(); + servirTagLambdaQueryWrapper.eq(ServirTag::getServirId, id); + servirTagService.getBaseMapper().delete(servirTagLambdaQueryWrapper); + + //删除本体 + servirMapper.deleteById(id); + return ResponseResult.okResult(); + } + + @Override + public ResponseResult getServirById(Integer id) { + Servir servir = getById(id); + ServirListVo servirVo = BeanCopyUtils.copyBean(servir, ServirListVo.class); + + LambdaQueryWrapper servirHostWrapper = new LambdaQueryWrapper<>(); + servirHostWrapper.eq(ServirHost::getServirId, id); + List servirHosts = servirHostService.list(servirHostWrapper); + if (!CollectionUtils.isEmpty(servirHosts)) { + List hostIds = servirHosts.stream().map(ServirHost::getHostId).collect(Collectors.toList()); + LambdaQueryWrapper hostMachineWrapper = new LambdaQueryWrapper<>(); + hostMachineWrapper.in(HostMachine::getId, hostIds); + List hostMachines = hostMachineService.list(hostMachineWrapper); + servirVo.setHosts(BeanCopyUtils.copyBeanList(hostMachines, ServirHostVo.class)); + } + //关联的容器 + LambdaQueryWrapper servirContainerWrapper = new LambdaQueryWrapper<>(); + servirContainerWrapper.eq(ServirContainer::getServirId, id); + List servirContainers = servirContainerService.list(servirContainerWrapper); + if (!CollectionUtils.isEmpty(servirContainers)) { + List containerIds = servirContainers.stream().map(ServirContainer::getContainerId).collect(Collectors.toList()); + LambdaQueryWrapper containerWrapper = new LambdaQueryWrapper<>(); + containerWrapper.in(Container::getId, containerIds); + List containers = containerService.list(containerWrapper); + servirVo.setContainers(BeanCopyUtils.copyBeanList(containers, ServirContainerVo.class)); + } + //关联的标签 + LambdaQueryWrapper servirTagWrapper = new LambdaQueryWrapper<>(); + servirTagWrapper.eq(ServirTag::getServirId, id); + List servirTags = servirTagService.list(servirTagWrapper); + if (!CollectionUtils.isEmpty(servirTags)) { + List tagIds = servirTags.stream().map(ServirTag::getTagId).collect(Collectors.toList()); + LambdaQueryWrapper tagWrapper = new LambdaQueryWrapper<>(); + tagWrapper.in(Tag::getId, tagIds); + List tags = tagService.list(tagWrapper); + servirVo.setTags(BeanCopyUtils.copyBeanList(tags, TagVo.class)); + } + return ResponseResult.okResult(servirVo); + } + + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/ServirTagServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/ServirTagServiceImpl.java new file mode 100644 index 0000000..76f7969 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/ServirTagServiceImpl.java @@ -0,0 +1,22 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.entity.ServirTag; +import com.mzaxd.noodles.service.ServirTagService; +import com.mzaxd.noodles.mapper.ServirTagMapper; +import org.springframework.stereotype.Service; + +/** +* @author 13439 +* @description 针对表【servir_tag】的数据库操作Service实现 +* @createDate 2023-02-11 19:40:35 +*/ +@Service +public class ServirTagServiceImpl extends ServiceImpl + implements ServirTagService{ + +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/SshLinkServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/SshLinkServiceImpl.java new file mode 100644 index 0000000..170568f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/SshLinkServiceImpl.java @@ -0,0 +1,67 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Container; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.domain.entity.SshLink; +import com.mzaxd.noodles.domain.vo.ContainerVo; +import com.mzaxd.noodles.domain.vo.HostMachineVo; +import com.mzaxd.noodles.service.ContainerService; +import com.mzaxd.noodles.service.HostMachineService; +import com.mzaxd.noodles.service.SshLinkService; +import com.mzaxd.noodles.mapper.SshLinkMapper; +import com.mzaxd.noodles.util.BeanCopyUtils; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Objects; + +/** + * @author 13439 + * @description 针对表【ssh_link】的数据库操作Service实现 + * @createDate 2023-02-24 20:30:25 + */ +@Service +public class SshLinkServiceImpl extends ServiceImpl + implements SshLinkService { + + @Lazy + @Resource + private HostMachineService hostMachineService; + + @Lazy + @Resource + private ContainerService containerService; + + @Override + public ResponseResult getInstanceInfo(Long sshId) { + return ResponseResult.okResult(getInstanceInfoBySshId(sshId)); + } + + @Override + public Object getInstanceInfoBySshId(Long sshId) { + LambdaQueryWrapper hostMachineLambdaQueryWrapper = new LambdaQueryWrapper<>(); + hostMachineLambdaQueryWrapper.eq(HostMachine::getSshId, sshId); + HostMachine hostMachine = hostMachineService.getOne(hostMachineLambdaQueryWrapper); + if (Objects.nonNull(hostMachine)) { + HostMachineVo hostMachineVo = BeanCopyUtils.copyBean(hostMachine, HostMachineVo.class); + return hostMachineVo; + } + LambdaQueryWrapper containerLambdaQueryWrapper = new LambdaQueryWrapper<>(); + containerLambdaQueryWrapper.eq(Container::getSshId, sshId); + Container container = containerService.getOne(containerLambdaQueryWrapper); + if (Objects.nonNull(container)) { + ContainerVo containerVo = BeanCopyUtils.copyBean(container, ContainerVo.class); + return containerVo; + } + return null; + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/SystemSettingServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/SystemSettingServiceImpl.java new file mode 100644 index 0000000..e595565 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/SystemSettingServiceImpl.java @@ -0,0 +1,84 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.SystemSetting; +import com.mzaxd.noodles.domain.vo.SmtpVo; +import com.mzaxd.noodles.domain.vo.SystemVo; +import com.mzaxd.noodles.domain.vo.TerminalVo; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.service.SystemSettingService; +import com.mzaxd.noodles.mapper.SystemSettingMapper; +import com.mzaxd.noodles.util.BeanCopyUtils; +import org.springframework.stereotype.Service; + +/** +* @author 13439 +* @description 针对表【system_setting】的数据库操作Service实现 +* @createDate 2023-02-16 20:25:57 +*/ +@Service +public class SystemSettingServiceImpl extends ServiceImpl + implements SystemSettingService{ + + @Override + public ResponseResult getSmtpSetting() { + SystemSetting systemSetting = getSetting(); + SmtpVo smtpVo = BeanCopyUtils.copyBean(systemSetting, SmtpVo.class); + return ResponseResult.okResult(smtpVo); + } + + @Override + public ResponseResult saveSmtpSetting(SmtpVo smtpVo) { + SystemSetting systemSetting = getById(1); + systemSetting.setServerEmail(smtpVo.getServerEmail()); + systemSetting.setEmailPass(smtpVo.getEmailPass()); + systemSetting.setNotificationEmail(smtpVo.getNotificationEmail()); + saveOrUpdate(systemSetting); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS); + } + + @Override + public ResponseResult getTerminalSetting() { + SystemSetting systemSetting = getSetting(); + TerminalVo terminalVo = BeanCopyUtils.copyBean(systemSetting, TerminalVo.class); + return ResponseResult.okResult(terminalVo); + } + + @Override + public ResponseResult saveTerminalSetting(TerminalVo terminalVo) { + SystemSetting systemSetting = getById(1); + systemSetting.setRendererType(terminalVo.getRendererType()); + systemSetting.setFontSize(terminalVo.getFontSize()); + systemSetting.setCursorBlink(terminalVo.getCursorBlink()); + systemSetting.setForeground(terminalVo.getForeground()); + systemSetting.setBackground(terminalVo.getBackground()); + saveOrUpdate(systemSetting); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS); + } + + @Override + public ResponseResult getSystemSetting() { + SystemSetting systemSetting = getSetting(); + SystemVo systemVo = BeanCopyUtils.copyBean(systemSetting, SystemVo.class); + return ResponseResult.okResult(systemVo); + } + + @Override + public ResponseResult saveSystemSetting(SystemVo systemVo) { + SystemSetting systemSetting = getById(1); + systemSetting.setLogExpire(systemVo.getLogExpire()); + systemSetting.setDefaultLang(systemVo.getDefaultLang()); + systemSetting.setCheckInstanceStatePeriod(systemVo.getCheckInstanceStatePeriod()); + saveOrUpdate(systemSetting); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS); + } + + private SystemSetting getSetting(){ + return getById(1); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/TagServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/TagServiceImpl.java new file mode 100644 index 0000000..e177365 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/TagServiceImpl.java @@ -0,0 +1,33 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.Tag; +import com.mzaxd.noodles.domain.vo.TagVo; +import com.mzaxd.noodles.service.TagService; +import com.mzaxd.noodles.mapper.TagMapper; +import com.mzaxd.noodles.util.BeanCopyUtils; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** +* @author 13439 +* @description 针对表【tag】的数据库操作Service实现 +* @createDate 2023-02-11 18:26:12 +*/ +@Service +public class TagServiceImpl extends ServiceImpl + implements TagService{ + + @Override + public ResponseResult getAllTag() { + List tagList = list(); + List tagVos = BeanCopyUtils.copyBeanList(tagList, TagVo.class); + return ResponseResult.okResult(tagVos); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/UserDetailServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/UserDetailServiceImpl.java new file mode 100644 index 0000000..7cf49ce --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/UserDetailServiceImpl.java @@ -0,0 +1,44 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.domain.entity.LoginUser; +import com.mzaxd.noodles.domain.entity.User; +import com.mzaxd.noodles.mapper.UserMapper; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Objects; + +/** + * @author root + * @description + * @createDate 2022-11-26 12:24:08 + */ +@Service +public class UserDetailServiceImpl implements UserDetailsService { + + @Resource + private UserMapper userMapper; + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + //根据用户名查询用户信息 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(User::getEmail, email); + User user = userMapper.selectOne(wrapper); + //如果查询不到数据就通过抛出异常来给出提示 + if (Objects.isNull(user)) { + throw new RuntimeException("邮箱或密码错误"); + } + + //封装成UserDetails对象返回 + return new LoginUser(user); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/service/impl/UserServiceImpl.java b/src/main/java/com/mzaxd/noodles/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..952efe6 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/service/impl/UserServiceImpl.java @@ -0,0 +1,137 @@ +package com.mzaxd.noodles.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.ResponseResult; +import com.mzaxd.noodles.domain.entity.HostMachine; +import com.mzaxd.noodles.domain.entity.User; +import com.mzaxd.noodles.domain.vo.ProfileHeaderVo; +import com.mzaxd.noodles.domain.vo.ProfileVo; +import com.mzaxd.noodles.domain.vo.UserInfoVo; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.mapper.UserMapper; +import com.mzaxd.noodles.service.ContainerService; +import com.mzaxd.noodles.service.HostMachineService; +import com.mzaxd.noodles.service.ServirService; +import com.mzaxd.noodles.service.UserService; +import com.mzaxd.noodles.util.BeanCopyUtils; +import com.mzaxd.noodles.util.IpUtil; +import com.mzaxd.noodles.util.SecurityUtils; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.IOException; +import java.util.Objects; + +/** +* @author root +* @description 针对表【user】的数据库操作Service实现 +* @createDate 2023-01-28 09:16:07 +*/ +@Service +public class UserServiceImpl extends ServiceImpl + implements UserService{ + + @Resource + private PasswordEncoder passwordEncoder; + + @Resource + private HostMachineService hostMachineService; + + @Resource + private ContainerService containerService; + + @Resource + private ServirService servirService; + + @Override + public ResponseResult userInfo() { + //获取当前用户id + Long userId = SecurityUtils.getUserId(); + //根据id查询用户信息 + User user = getById(userId); + //将用户信息封装Vo并返回 + UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class); + return ResponseResult.okResult(userInfoVo); + } + + @Override + public ResponseResult updateUserInfo(User user) { + updateById(user); + return ResponseResult.okResult(); + } + + @Override + public ResponseResult getProfileHeader(Integer id, String ip) { + User user = getById(id); + ProfileHeaderVo profileHeaderVo = BeanCopyUtils.copyBean(user, ProfileHeaderVo.class); + try { + profileHeaderVo.setLocation(IpUtil.getRegionByIp(ip)); + } catch (Exception e) { + throw new RuntimeException(e); + } + return ResponseResult.okResult(profileHeaderVo); + } + + @Override + public ResponseResult getProfile() { + //获取当前用户id + Long userId = SecurityUtils.getUserId(); + User user = getById(userId); + ProfileVo profile = BeanCopyUtils.copyBean(user, ProfileVo.class); + //查物理机数量 + LambdaQueryWrapper hostMachineWrapper = new LambdaQueryWrapper<>(); + hostMachineWrapper.eq(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + profile.setHostNumber(hostMachineService.count(hostMachineWrapper)); + //查虚拟机数量 + LambdaQueryWrapper vmWrapper = new LambdaQueryWrapper<>(); + vmWrapper.ne(HostMachine::getHostMachineId, SystemConstant.HOST_MACHINE_ID_HOST); + profile.setVmNumber(hostMachineService.count(vmWrapper)); + //查容器数量 + profile.setContainerNumber(containerService.count()); + //查服务数量 + profile.setServirNumber(servirService.count()); + return ResponseResult.okResult(profile); + } + + @Override + public ResponseResult isFirstUse() { + User user = getById(1); + if (user.getUserState() == 0) { + return ResponseResult.okResult(true); + } else { + return ResponseResult.okResult(false); + } + } + + @Override + public ResponseResult changePassword(String password) { + Long userId = SecurityUtils.getUserId(); + User user = getById(userId); + user.setPassword(passwordEncoder.encode(password)); + saveOrUpdate(user); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "密码修改成功"); + } + + @Override + public ResponseResult getUserInfo(Integer id) { + User user = getById(id); + UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class); + return ResponseResult.okResult(userInfoVo); + } + + @Override + public ResponseResult updateUserInfo(UserInfoVo userData) { + Long userId = SecurityUtils.getUserId(); + User user = getById(userId); + user.setEmail(userData.getEmail()).setUserName(userData.getUserName()).setNickName(userData.getNickName()).setAvatar(userData.getAvatar()); + saveOrUpdate(user); + return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "账号信息修改成功"); + } +} + + + + diff --git a/src/main/java/com/mzaxd/noodles/util/Arith.java b/src/main/java/com/mzaxd/noodles/util/Arith.java new file mode 100644 index 0000000..d564418 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/Arith.java @@ -0,0 +1,118 @@ +package com.mzaxd.noodledetector.util; + +/** + * @author Mzaxd + * @since 2023-02-05 10:56 + */ +import java.math.BigDecimal; + +/** + * 由於Java的簡單類型不能夠精確的對浮點數進行運算,這個工具類提供精 確的浮點數運算,包括加減乘除和四捨五入。 + */ +public class Arith { + + // 默認除法運算精度 + private static final int DEF_DIV_SCALE = 10; + + // 這個類不能實例化 + private Arith() { + } + + /** + * 提供精確的加法運算。 + * + * @param v1 + * 被加數 + * @param v2 + * 加數 + * @return 兩個參數的和 + */ + public static double add(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.add(b2).doubleValue(); + } + + /** + * 提供精確的減法運算。 + * + * @param v1 + * 被減數 + * @param v2 + * 減數 + * @return 兩個參數的差 + */ + public static double sub(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.subtract(b2).doubleValue(); + } + + /** + * 提供精確的乘法運算。 + * + * @param v1 + * 被乘數 + * @param v2 + * 乘數 + * @return 兩個參數的積 + */ + public static double mul(double v1, double v2) { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.multiply(b2).doubleValue(); + } + + /** + * 提供(相對)精確的除法運算,當發生除不盡的情況時,精確到 小數點以後10位元,以後的數字四捨五入。 + * + * @param v1 + * 被除數 + * @param v2 + * 除數 + * @return 兩個參數的商 + */ + public static double div(double v1, double v2) { + return div(v1, v2, DEF_DIV_SCALE); + } + + /** + * 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指 定精度,以後的數字四捨五入。 + * + * @param v1 + * 被除數 + * @param v2 + * 除數 + * @param scale + * 表示表示需要精確到小數點以後幾位。 + * @return 兩個參數的商 + */ + public static double div(double v1, double v2, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * 提供精確的小數位四捨五入處理。 + * + * @param v + * 需要四捨五入的數位 + * @param scale + * 小數點後保留幾位 + * @return 四捨五入後的結果 + */ + public static double round(double v, int scale) { + if (scale < 0) { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = new BigDecimal(Double.toString(v)); + BigDecimal one = new BigDecimal("1"); + return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); + } +} diff --git a/src/main/java/com/mzaxd/noodles/util/BeanCopyUtils.java b/src/main/java/com/mzaxd/noodles/util/BeanCopyUtils.java new file mode 100644 index 0000000..ee3f12b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/BeanCopyUtils.java @@ -0,0 +1,36 @@ +package com.mzaxd.noodles.util; + +import org.springframework.beans.BeanUtils; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * @author Mzaxd + * @since 2022-11-22 15:36 + */ +public class BeanCopyUtils { + + private BeanCopyUtils() { + } + + public static V copyBean(Object source, Class clazz){ + V result = null; + //创建目标对象 + try { + result = clazz.newInstance(); + //实现属性copy + BeanUtils.copyProperties(source, result); + } catch (Exception e) { + e.printStackTrace(); + } + //返回结果 + return result; + } + + public static List copyBeanList(List list, Class clazz) { + return list.stream() + .map(o -> copyBean(o, clazz)) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/com/mzaxd/noodles/util/FormatUtil.java b/src/main/java/com/mzaxd/noodles/util/FormatUtil.java new file mode 100644 index 0000000..fd628b8 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/FormatUtil.java @@ -0,0 +1,217 @@ +package com.mzaxd.noodledetector.util; + +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; + +/** + * @author Mzaxd + * @since 2023-02-05 14:05 + */ +public class FormatUtil { + /** + * Binary prefixes, used in IEC Standard for naming bytes. + * (https://en.wikipedia.org/wiki/International_Electrotechnical_Commission) + * + * Should be used for most representations of bytes + */ + private static final long KIBI = 1L << 10; + private static final long MEBI = 1L << 20; + private static final long GIBI = 1L << 30; + private static final long TEBI = 1L << 40; + private static final long PEBI = 1L << 50; + private static final long EXBI = 1L << 60; + + /** + * Decimal prefixes, used for Hz and other metric units and for bytes by hard drive manufacturers + */ + private static final long KILO = 1_000L; + private static final long MEGA = 1_000_000L; + private static final long GIGA = 1_000_000_000L; + private static final long TERA = 1_000_000_000_000L; + private static final long PETA = 1_000_000_000_000_000L; + private static final long EXA = 1_000_000_000_000_000_000L; + + /* + * Two's complement reference: 2^64. + */ + private static final BigInteger TWOS_COMPLEMENT_REF = BigInteger.ONE.shiftLeft(64); + + /** Constant HEX_ERROR="0x%08X" */ + public static final String HEX_ERROR = "0x%08X"; + + private FormatUtil() { + } + + /** + * Format bytes into a rounded string representation using IEC standard (matches Mac/Linux). For hard drive + * capacities, use @link {@link #formatBytesDecimal(long)}. For Windows displays for KB, MB and GB, in JEDEC units, + * edit the returned string to remove the 'i' to display the (incorrect) JEDEC units. + * + * @param bytes Bytes. + * @return Rounded string representation of the byte size. + */ + public static String formatBytes(long bytes) { + if (bytes == 1L) { // bytes + return String.format("%d byte", bytes); + } else if (bytes < KIBI) { // bytes + return String.format("%d bytes", bytes); + } else if (bytes < MEBI) { // KiB + return formatUnits(bytes, KIBI, "KiB"); + } else if (bytes < GIBI) { // MiB + return formatUnits(bytes, MEBI, "MiB"); + } else if (bytes < TEBI) { // GiB + return formatUnits(bytes, GIBI, "GiB"); + } else if (bytes < PEBI) { // TiB + return formatUnits(bytes, TEBI, "TiB"); + } else if (bytes < EXBI) { // PiB + return formatUnits(bytes, PEBI, "PiB"); + } else { // EiB + return formatUnits(bytes, EXBI, "EiB"); + } + } + + /** + * Format units as exact integer or fractional decimal based on the prefix, appending the appropriate units + * + * @param value The value to format + * @param prefix The divisor of the unit multiplier + * @param unit A string representing the units + * @return A string with the value + */ + private static String formatUnits(long value, long prefix, String unit) { + if (value % prefix == 0) { + return String.format("%d %s", value / prefix, unit); + } + return String.format("%.1f %s", (double) value / prefix, unit); + } + + /** + * Format bytes into a rounded string representation using decimal SI units. These are used by hard drive + * manufacturers for capacity. Most other storage should use {@link #formatBytes(long)}. + * + * @param bytes Bytes. + * @return Rounded string representation of the byte size. + */ + public static String formatBytesDecimal(long bytes) { + if (bytes == 1L) { // bytes + return String.format("%d byte", bytes); + } else if (bytes < KILO) { // bytes + return String.format("%d bytes", bytes); + } else { + return formatValue(bytes, "B"); + } + } + + /** + * Format hertz into a string to a rounded string representation. + * + * @param hertz Hertz. + * @return Rounded string representation of the hertz size. + */ + public static String formatHertz(long hertz) { + return formatValue(hertz, "Hz"); + } + + /** + * Format arbitrary units into a string to a rounded string representation. + * + * @param value The value + * @param unit Units to append metric prefix to + * @return Rounded string representation of the value with metric prefix to extension + */ + public static String formatValue(long value, String unit) { + if (value < KILO) { + return String.format("%d %s", value, unit).trim(); + } else if (value < MEGA) { // K + return formatUnits(value, KILO, "K" + unit); + } else if (value < GIGA) { // M + return formatUnits(value, MEGA, "M" + unit); + } else if (value < TERA) { // G + return formatUnits(value, GIGA, "G" + unit); + } else if (value < PETA) { // T + return formatUnits(value, TERA, "T" + unit); + } else if (value < EXA) { // P + return formatUnits(value, PETA, "P" + unit); + } else { // E + return formatUnits(value, EXA, "E" + unit); + } + } + + /** + * Formats an elapsed time in seconds as days, hh:mm:ss. + * + * @param secs Elapsed seconds + * @return A string representation of elapsed time + */ + public static String formatElapsedSecs(long secs) { + long eTime = secs; + final long days = TimeUnit.SECONDS.toDays(eTime); + eTime -= TimeUnit.DAYS.toSeconds(days); + final long hr = TimeUnit.SECONDS.toHours(eTime); + eTime -= TimeUnit.HOURS.toSeconds(hr); + final long min = TimeUnit.SECONDS.toMinutes(eTime); + eTime -= TimeUnit.MINUTES.toSeconds(min); + final long sec = eTime; + return String.format("%d days, %02d:%02d:%02d", days, hr, min, sec); + } + + /** + * Convert unsigned int to signed long. + * + * @param x Signed int representing an unsigned integer + * @return long value of x unsigned + */ + public static long getUnsignedInt(int x) { + return x & 0x0000_0000_ffff_ffffL; + } + + /** + * Represent a 32 bit value as if it were an unsigned integer. + * + * This is a Java 7 implementation of Java 8's Integer.toUnsignedString. + * + * @param i a 32 bit value + * @return the string representation of the unsigned integer + */ + public static String toUnsignedString(int i) { + if (i >= 0) { + return Integer.toString(i); + } + return Long.toString(getUnsignedInt(i)); + } + + /** + * Represent a 64 bit value as if it were an unsigned long. + * + * This is a Java 7 implementation of Java 8's Long.toUnsignedString. + * + * @param l a 64 bit value + * @return the string representation of the unsigned long + */ + public static String toUnsignedString(long l) { + if (l >= 0) { + return Long.toString(l); + } + return BigInteger.valueOf(l).add(TWOS_COMPLEMENT_REF).toString(); + } + + /** + * Translate an integer error code to its hex notation + * + * @param errorCode The error code + * @return A string representing the error as 0x.... + */ + public static String formatError(int errorCode) { + return String.format(HEX_ERROR, errorCode); + } + + /** + * Rounds a floating point number to the nearest integer + * + * @param x the floating point number + * @return the integer + */ + public static int roundToInt(double x) { + return (int) Math.round(x); + } +} diff --git a/src/main/java/com/mzaxd/noodles/util/IpUtil.java b/src/main/java/com/mzaxd/noodles/util/IpUtil.java new file mode 100644 index 0000000..e882a63 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/IpUtil.java @@ -0,0 +1,104 @@ +package com.mzaxd.noodles.util; + +import cn.hutool.core.net.NetUtil; +import lombok.extern.slf4j.Slf4j; +import org.lionsoul.ip2region.xdb.Searcher; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * ip2region封装工具类 + * + * @author 13439 + */ + +@Slf4j +public class IpUtil { + + /** + * 获取客户端IP地址 + * + * @param request + * @return + */ + public static String getIpAddr(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + if ("0:0:0:0:0:0:0:1".equals(ip)) { + ip = "127.0.0.1"; + } + if (ip.split(",").length > 1) { + ip = ip.split(",")[0]; + } + return ip; + } + + public static String getRegionByIp(String ip) throws IOException { + if (NetUtil.isInnerIP(ip)) { + return "用户当前为内网访问"; + } + URL url = IpUtil.class.getClassLoader().getResource("ip2region.db"); + File file; + if (url != null) { + file = new File(url.getFile()); + } else { + return null; + } + if (!file.exists()) { + System.out.println("Error: Invalid ip2region.db file, filePath:" + file.getPath()); + return null; + } + String dbPath = file.getPath(); + // 1、创建 searcher 对象 + Searcher searcher = null; + try { + searcher = Searcher.newWithFileOnly(dbPath); + } catch (IOException e) { + log.error("failed to create searcher with `%s`: %s\n", dbPath, e); + return "无法识别用户地址"; + } + + // 2、查询 + try { + long sTime = System.nanoTime(); + String region = searcher.search(ip); + long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime)); + log.info("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost); + if (!StringUtils.hasText(region)) { + region = "无法识别用户地址"; + } + return region; + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 3、关闭资源 + searcher.close(); + } + return "无法识别用户地址"; + } +} diff --git a/src/main/java/com/mzaxd/noodles/util/JwtUtil.java b/src/main/java/com/mzaxd/noodles/util/JwtUtil.java new file mode 100644 index 0000000..5833b8d --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/JwtUtil.java @@ -0,0 +1,127 @@ +package com.mzaxd.noodles.util; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtBuilder; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.util.Base64; +import java.util.Date; +import java.util.UUID; + +/** + * JWT工具类 + * + * @author mzaxd + */ +public class JwtUtil { + + /** + * 有效期为一小时 + */ + public static final Long JWT_TTL = 24 * 60 * 60 * 1000L; + /** + * 设置秘钥明文 + */ + public static final String JWT_KEY = "sangeng"; + + public static String getUUID() { + return UUID.randomUUID().toString().replaceAll("-", ""); + } + + /** + * 生成jtw + * + * @param subject token中要存放的数据(json格式) + * @return + */ + public static String createJWT(String subject) { + // 设置过期时间 + JwtBuilder builder = getJwtBuilder(subject, null, getUUID()); + return builder.compact(); + } + + /** + * 生成jtw + * + * @param subject token中要存放的数据(json格式) + * @param ttlMillis token超时时间 + * @return + */ + public static String createJWT(String subject, Long ttlMillis) { + // 设置过期时间 + JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID()); + return builder.compact(); + } + + private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) { + SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; + SecretKey secretKey = generalKey(); + long nowMillis = System.currentTimeMillis(); + Date now = new Date(nowMillis); + if (ttlMillis == null) { + ttlMillis = JwtUtil.JWT_TTL; + } + long expMillis = nowMillis + ttlMillis; + Date expDate = new Date(expMillis); + return Jwts.builder() + // 唯一的ID + .setId(uuid) + // 主题 可以是JSON数据 + .setSubject(subject) + // 签发者 + .setIssuer("sg") + // 签发时间 + .setIssuedAt(now) + //使用HS256对称加密算法签名, 第二个参数为秘钥 + .signWith(signatureAlgorithm, secretKey) + .setExpiration(expDate); + } + + /** + * 创建token + * + * @param id + * @param subject + * @param ttlMillis + * @return + */ + public static String createJWT(String id, String subject, Long ttlMillis) { + // 设置过期时间 + JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id); + return builder.compact(); + } + + public static void main(String[] args) throws Exception { + String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjYWM2ZDVhZi1mNjVlLTQ0MDAtYjcxMi0zYWEwOGIyOTIwYjQiLCJzdWIiOiJzZyIsImlzcyI6InNnIiwiaWF0IjoxNjM4MTA2NzEyLCJleHAiOjE2MzgxMTAzMTJ9.JVsSbkP94wuczb4QryQbAke3ysBDIL5ou8fWsbt_ebg"; + Claims claims = parseJWT(token); + System.out.println(claims); + } + + /** + * 生成加密后的秘钥 secretKey + * + * @return + */ + public static SecretKey generalKey() { + byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY); + return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); + } + + /** + * 解析 + * + * @param jwt + * @return + * @throws Exception + */ + public static Claims parseJWT(String jwt) throws Exception { + SecretKey secretKey = generalKey(); + return Jwts.parser() + .setSigningKey(secretKey) + .parseClaimsJws(jwt) + .getBody(); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/util/RedisCache.java b/src/main/java/com/mzaxd/noodles/util/RedisCache.java new file mode 100644 index 0000000..53ba07f --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/RedisCache.java @@ -0,0 +1,255 @@ +package com.mzaxd.noodles.util; + +import org.springframework.data.redis.core.BoundSetOperations; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * @author mzaxd + */ +@SuppressWarnings(value = {"unchecked", "rawtypes"}) +@Component +public class RedisCache { + @Resource + public RedisTemplate redisTemplate; + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + */ + public void setCacheObject(final String key, final T value) { + redisTemplate.opsForValue().set(key, value); + } + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + */ + public void setCacheObject(final String key, final T value, final Integer day) { + redisTemplate.opsForValue().set(key, value, day, TimeUnit.DAYS); + } + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + * @param timeout 时间 + * @param timeUnit 时间颗粒度 + */ + public void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) { + redisTemplate.opsForValue().set(key, value, timeout, timeUnit); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout) { + return expire(key, timeout, TimeUnit.SECONDS); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @param unit 时间单位 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout, final TimeUnit unit) { + return redisTemplate.expire(key, timeout, unit); + } + + /** + * 获得缓存的基本对象。 + * + * @param key 缓存键值 + * @return 缓存键值对应的数据 + */ + public T getCacheObject(final String key) { + ValueOperations operation = redisTemplate.opsForValue(); + return operation.get(key); + } + + /** + * 获得缓存的基本对象。 + * + * @param keys 缓存键值 + * @return 缓存键值对应的数据 + */ + public List getCacheObjectList(final List keys) { + ValueOperations operation = redisTemplate.opsForValue(); + return operation.multiGet(keys); + } + + /** + * 删除单个对象 + * + * @param key + */ + public boolean deleteObject(final String key) { + return redisTemplate.delete(key); + } + + /** + * 删除集合对象 + * + * @param collection 多个对象 + * @return + */ + public long deleteObject(final Collection collection) { + return redisTemplate.delete(collection); + } + + /** + * 缓存List数据 + * + * @param key 缓存的键值 + * @param dataList 待缓存的List数据 + * @return 缓存的对象 + */ + public long setCacheList(final String key, final List dataList) { + Long count = redisTemplate.opsForList().rightPushAll(key, dataList); + return count == null ? 0 : count; + } + + /** + * 获得缓存的list对象 + * + * @param key 缓存的键值 + * @return 缓存键值对应的数据 + */ + public List getCacheList(final String key) { + return redisTemplate.opsForList().range(key, 0, -1); + } + + /** + * 缓存Set + * + * @param key 缓存键值 + * @param dataSet 缓存的数据 + * @return 缓存数据的对象 + */ + public BoundSetOperations setCacheSet(final String key, final Set dataSet) { + BoundSetOperations setOperation = redisTemplate.boundSetOps(key); + Iterator it = dataSet.iterator(); + while (it.hasNext()) { + setOperation.add(it.next()); + } + return setOperation; + } + + /** + * 获得缓存的set + * + * @param key + * @return + */ + public Set getCacheSet(final String key) { + return redisTemplate.opsForSet().members(key); + } + + /** + * 缓存Map + * + * @param key + * @param dataMap + */ + public void setCacheMap(final String key, final Map dataMap) { + if (dataMap != null) { + redisTemplate.opsForHash().putAll(key, dataMap); + } + } + + /** + * 获得缓存的Map + * + * @param key + * @return + */ + public Map getCacheMap(final String key) { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 往Hash中存入数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @param value 值 + */ + public void setCacheMapValue(final String key, final String hKey, final T value) { + redisTemplate.opsForHash().put(key, hKey, value); + } + + /** + * 获取Hash中的数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @return Hash中的对象 + */ + public T getCacheMapValue(final String key, final String hKey) { + HashOperations opsForHash = redisTemplate.opsForHash(); + return opsForHash.get(key, hKey); + } + + /** + * 删除Hash中的数据 + * + * @param key + * @param hkey + */ + public void delCacheMapValue(final String key, final String hkey) { + HashOperations hashOperations = redisTemplate.opsForHash(); + hashOperations.delete(key, hkey); + } + + /** + * 获取多个Hash中的数据 + * + * @param key Redis键 + * @param hKeys Hash键集合 + * @return Hash对象集合 + */ + public List getMultiCacheMapValue(final String key, final Collection hKeys) { + return redisTemplate.opsForHash().multiGet(key, hKeys); + } + + /** + * 获得缓存的基本对象列表 + * + * @param pattern 字符串前缀 + * @return 对象列表 + */ + public Collection keys(final String pattern) { + return redisTemplate.keys(pattern); + } + + /** + * 给键为key的hash结构的值增加v + * + * @param key + * @param hKey + * @param v + * @author mzaxd + * @date 12/4/22 1:18 AM + */ + public void incrementCacheMapValue(String key, String hKey, long v) { + redisTemplate.boundHashOps(key).increment(hKey, v); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/util/SecurityUtils.java b/src/main/java/com/mzaxd/noodles/util/SecurityUtils.java new file mode 100644 index 0000000..ea1ead5 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/SecurityUtils.java @@ -0,0 +1,34 @@ +package com.mzaxd.noodles.util; + +import com.mzaxd.noodles.domain.entity.LoginUser; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * @author root + */ +public class SecurityUtils { + + /** + * 获取用户 + **/ + public static LoginUser getLoginUser() { + return (LoginUser) getAuthentication().getPrincipal(); + } + + /** + * 获取Authentication + */ + public static Authentication getAuthentication() { + return SecurityContextHolder.getContext().getAuthentication(); + } + + public static Boolean isAdmin() { + Long id = getLoginUser().getUser().getId(); + return id != null && 1L == id; + } + + public static Long getUserId() { + return getLoginUser().getUser().getId(); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/util/SshLinkUtil.java b/src/main/java/com/mzaxd/noodles/util/SshLinkUtil.java new file mode 100644 index 0000000..1e39b51 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/SshLinkUtil.java @@ -0,0 +1,50 @@ +package com.mzaxd.noodles.util; + +import com.mzaxd.noodles.domain.vo.ContainerVo; +import com.mzaxd.noodles.domain.vo.HostVo; +import com.mzaxd.noodles.domain.vo.VmVo; +import org.springframework.util.StringUtils; + +/** + * @author 13439 + */ +public class SshLinkUtil { + + public static boolean isHostSshLinkParamValid(HostVo hostVo) { + try { + if (StringUtils.hasText(hostVo.getSshHost()) || StringUtils.hasText(hostVo.getSshUser()) || + StringUtils.hasText(hostVo.getSshPwd()) || StringUtils.hasText(hostVo.getSshPort().toString())) { + return true; + } + } catch (Exception e) { + return false; + } + return false; + } + + public static boolean isVmSshLinkParamValid(VmVo vmVo) { + try { + if (StringUtils.hasText(vmVo.getSshHost()) || StringUtils.hasText(vmVo.getSshUser()) || + StringUtils.hasText(vmVo.getSshPwd()) || StringUtils.hasText(vmVo.getSshPort().toString())) { + return true; + } + } catch (Exception e) { + return false; + } + return false; + } + + public static boolean isContainerSshLinkParamValid(ContainerVo containerVo) { + try { + if (StringUtils.hasText(containerVo.getSshHost()) || StringUtils.hasText(containerVo.getSshUser()) || + StringUtils.hasText(containerVo.getSshPwd()) || StringUtils.hasText(containerVo.getSshPort().toString())) { + return true; + } + } catch (Exception e) { + return false; + } + return false; + } + + +} diff --git a/src/main/java/com/mzaxd/noodles/util/StringUtil.java b/src/main/java/com/mzaxd/noodles/util/StringUtil.java new file mode 100644 index 0000000..4dd1de2 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/StringUtil.java @@ -0,0 +1,150 @@ +package com.mzaxd.noodles.util; + +import cn.hutool.core.date.DateField; +import cn.hutool.core.date.DateTime; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.lang.Validator; +import cn.hutool.core.util.StrUtil; +import cn.hutool.system.SystemUtil; +import com.alibaba.fastjson.JSON; + +import java.io.File; +import java.util.List; + +/** + * @ProjectName StringUtil + * @author qingfeng + * @version 1.0.0 + * @Description 方法运行参数工具 + * @createTime 2022/5/2 0002 15:29 + */ +public class StringUtil { + + /** + * 支持的压缩包格式 + */ + public static final String[] PACKAGE_EXT = new String[]{"tar.bz2", "tar.gz", "tar", "bz2", "zip", "gz"}; + + /** + * 获取启动参数 + * @param args 所有参数 + * @param name 参数名 + * @return 值 + */ + public static String getArgsValue(String[] args, String name) { + if (args == null) { + return null; + } + for (String item : args) { + item = StrUtil.trim(item); + if (item.startsWith("--" + name + "=")) { + return item.substring(name.length() + 3); + } + } + return null; + } + + /** + * id输入规则 + * + * @param value 值 + * @param min 最短 + * @param max 最长 + * @return true + */ + public static boolean isGeneral(CharSequence value, int min, int max) { + String reg = "^[a-zA-Z0-9_-]{" + min + StrUtil.COMMA + max + "}$"; + return Validator.isMatchRegex(reg, value); + } + + /** + * 删除文件开始的路径 + * + * @param file 要删除的文件 + * @param startPath 开始的路径 + * @param inName 是否返回文件名 + * @return /test/a.txt /test/ a.txt + */ + public static String delStartPath(File file, String startPath, boolean inName) { + String newWhitePath; + if (inName) { + newWhitePath = FileUtil.getAbsolutePath(file.getAbsolutePath()); + } else { + newWhitePath = FileUtil.getAbsolutePath(file.getParentFile()); + } + String itemAbsPath = FileUtil.getAbsolutePath(new File(startPath)); + itemAbsPath = FileUtil.normalize(itemAbsPath); + newWhitePath = FileUtil.normalize(newWhitePath); + String path = StrUtil.removePrefix(newWhitePath, itemAbsPath); + //newWhitePath.substring(newWhitePath.indexOf(itemAbsPath) + itemAbsPath.length()); + path = FileUtil.normalize(path); + if (path.startsWith(StrUtil.SLASH)) { + path = path.substring(1); + } + return path; + } + + /** + * 获取jdk 中的tools jar文件路径 + * + * @return file + */ + public static File getToolsJar() { + File file = new File(SystemUtil.getJavaRuntimeInfo().getHomeDir()); + return new File(file.getParentFile(), "lib/tools.jar"); + } + + /** + * 指定时间的下一个刻度 + * + * @return String + */ + public static String getNextScaleTime(String time, Long millis) { + DateTime dateTime = DateUtil.parse(time); + if (millis == null) { + millis = 30 * 1000L; + } + DateTime newTime = dateTime.offsetNew(DateField.SECOND, (int) (millis / 1000)); + return DateUtil.formatTime(newTime); + } + + /** + * json 字符串转 bean,兼容普通json和字符串包裹情况 + * + * @param jsonStr json 字符串 + * @param cls 要转为bean的类 + * @param 泛型 + * @return data + */ + public static T jsonConvert(String jsonStr, Class cls) { + if (StrUtil.isEmpty(jsonStr)) { + return null; + } + try { + return JSON.parseObject(jsonStr, cls); + } catch (Exception e) { + return JSON.parseObject(JSON.parse(jsonStr).toString(), cls); + } + } + + /** + * json 字符串转 bean,兼容普通json和字符串包裹情况 + * + * @param jsonStr json 字符串 + * @param cls 要转为bean的类 + * @param 泛型 + * @return data + */ + public static List jsonConvertArray(String jsonStr, Class cls) { + try { + if (StrUtil.isEmpty(jsonStr)) { + return null; + } + return JSON.parseArray(jsonStr, cls); + } catch (Exception e) { + Object parse = JSON.parse(jsonStr); + return JSON.parseArray(parse.toString(), cls); + } + } +} diff --git a/src/main/java/com/mzaxd/noodles/util/SystemInfoUtils.java b/src/main/java/com/mzaxd/noodles/util/SystemInfoUtils.java new file mode 100644 index 0000000..8fe8e3b --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/SystemInfoUtils.java @@ -0,0 +1,192 @@ +package com.mzaxd.noodles.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import oshi.SystemInfo; +import oshi.hardware.CentralProcessor; +import oshi.hardware.GlobalMemory; +import oshi.hardware.HardwareAbstractionLayer; +import oshi.software.os.FileSystem; +import oshi.software.os.OSFileStore; +import oshi.software.os.OperatingSystem; +import oshi.util.Util; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.DecimalFormat; +import java.util.List; +import java.util.Properties; + +/** +* 系统消息工具类 +* +**/ +public class SystemInfoUtils { + private static final int OSHI_WAIT_SECOND = 1000; + private static SystemInfo systemInfo = new SystemInfo(); + private static HardwareAbstractionLayer hardware = systemInfo.getHardware(); + private static OperatingSystem operatingSystem = systemInfo.getOperatingSystem(); + + public static JSONObject getCpuInfo() { + JSONObject cpuInfo = new JSONObject(); + CentralProcessor processor = hardware.getProcessor(); + // CPU信息 + long[] prevTicks = processor.getSystemCpuLoadTicks(); + Util.sleep(OSHI_WAIT_SECOND); + 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 user = 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 = user + nice + cSys + idle + iowait + irq + softirq + steal; + //cpu核数 + cpuInfo.put("cpuNum", processor.getLogicalProcessorCount()); + //cpu系统使用率 + cpuInfo.put("cSys", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu)); + //cpu用户使用率 + cpuInfo.put("user", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu)); + //cpu当前等待率 + cpuInfo.put("iowait", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu)); + //cpu当前使用率 + cpuInfo.put("idle", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu))); + return cpuInfo; + } + + /** + * 系统jvm信息 + */ + public static JSONObject getJvmInfo() { + JSONObject cpuInfo = new JSONObject(); + Properties props = System.getProperties(); + Runtime runtime = Runtime.getRuntime(); + long jvmTotalMemoryByte = runtime.totalMemory(); + long freeMemoryByte = runtime.freeMemory(); + //jvm总内存 + cpuInfo.put("total", formatByte(runtime.totalMemory())); + //空闲空间 + cpuInfo.put("free", formatByte(runtime.freeMemory())); + //jvm最大可申请 + cpuInfo.put("max", formatByte(runtime.maxMemory())); + //vm已使用内存 + cpuInfo.put("user", formatByte(jvmTotalMemoryByte - freeMemoryByte)); + //jvm内存使用率 + cpuInfo.put("usageRate", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte)); + //jdk版本 + cpuInfo.put("jdkVersion", props.getProperty("java.version")); + //jdk路径 + cpuInfo.put("jdkHome", props.getProperty("java.home")); + return cpuInfo; + } + + /** + * 系统内存信息 + */ + public static JSONObject getMemInfo() { + JSONObject cpuInfo = new JSONObject(); + GlobalMemory memory = systemInfo.getHardware().getMemory(); + //总内存 + long totalByte = memory.getTotal(); + //剩余 + long acaliableByte = memory.getAvailable(); + //总内存 + cpuInfo.put("total", formatByte(totalByte)); + //使用 + cpuInfo.put("used", formatByte(totalByte - acaliableByte)); + //剩余内存 + cpuInfo.put("free", formatByte(acaliableByte)); + //使用率 + cpuInfo.put("usageRate", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte)); + return cpuInfo; + } + + /** + * 系统盘符信息 + */ + public static JSONArray getSysFileInfo() { + JSONObject cpuInfo; + JSONArray sysFiles = new JSONArray(); + FileSystem fileSystem = operatingSystem.getFileSystem(); + List fsArray = fileSystem.getFileStores(); + for (OSFileStore fs : fsArray) { + cpuInfo = new JSONObject(); + //盘符路径 + cpuInfo.put("dirName", fs.getMount()); + //盘符类型 + cpuInfo.put("sysTypeName", fs.getType()); + //文件类型 + cpuInfo.put("typeName", fs.getName()); + //总大小 + cpuInfo.put("total", formatByte(fs.getTotalSpace())); + //剩余大小 + cpuInfo.put("free", formatByte(fs.getUsableSpace())); + //已经使用量 + cpuInfo.put("used", formatByte(fs.getTotalSpace() - fs.getUsableSpace())); + if (fs.getTotalSpace() == 0) { + //资源的使用率 + cpuInfo.put("usage", 0); + } else { + cpuInfo.put("usage",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace())); + } + sysFiles.add(cpuInfo); + } + return sysFiles; + } + + /** + * 系统信息 + */ + public static JSONObject getSysInfo() throws UnknownHostException { + JSONObject cpuInfo = new JSONObject(); + Properties props = System.getProperties(); + //操作系统名 + cpuInfo.put("osName", props.getProperty("os.name")); + //系统架构 + cpuInfo.put("osArch", props.getProperty("os.arch")); + //服务器名称 + cpuInfo.put("computerName", InetAddress.getLocalHost().getHostName()); + //服务器Ip + cpuInfo.put("computerIp", InetAddress.getLocalHost().getHostAddress()); + //项目路径 + cpuInfo.put("userDir", props.getProperty("user.dir")); + return cpuInfo; + } + + /** + * 所有系统信息 + */ + public static JSONObject getInfo() throws UnknownHostException { + JSONObject info = new JSONObject(); + info.put("cpuInfo", getCpuInfo()); + info.put("jvmInfo", getJvmInfo()); + info.put("memInfo", getMemInfo()); + info.put("sysInfo", getSysInfo()); + info.put("sysFileInfo", getSysFileInfo()); + return info; + } + + /** + * 单位转换 + */ + private static String formatByte(long byteNumber) { + //换算单位 + double FORMAT = 1024.0; + double kbNumber = byteNumber / FORMAT; + if (kbNumber < FORMAT) { + return new DecimalFormat("#.##KB").format(kbNumber); + } + double mbNumber = kbNumber / FORMAT; + if (mbNumber < FORMAT) { + return new DecimalFormat("#.##MB").format(mbNumber); + } + double gbNumber = mbNumber / FORMAT; + if (gbNumber < FORMAT) { + return new DecimalFormat("#.##GB").format(gbNumber); + } + double tbNumber = gbNumber / FORMAT; + return new DecimalFormat("#.##TB").format(tbNumber); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/util/SystemSettingUtils.java b/src/main/java/com/mzaxd/noodles/util/SystemSettingUtils.java new file mode 100644 index 0000000..475d423 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/SystemSettingUtils.java @@ -0,0 +1,51 @@ +package com.mzaxd.noodles.util; + +import cn.hutool.extra.mail.MailAccount; +import com.mzaxd.noodles.domain.entity.SystemSetting; +import com.mzaxd.noodles.enums.AppHttpCodeEnum; +import com.mzaxd.noodles.exception.SystemException; +import com.mzaxd.noodles.service.SystemSettingService; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; + +/** + * @author 13439 + */ +@Component +public class SystemSettingUtils { + + @Resource + private SystemSettingService systemSettingService; + + /** + * 获取邮件服务器Bean + * @return + */ + public MailAccount getMailAccount() { + //获取系统设置 + SystemSetting setting = systemSettingService.getById(1); + MailAccount account = new MailAccount(); + if (!StringUtils.hasText(setting.getEmailPass())) { + throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL); + } + account.setFrom(setting.getServerEmail()); + account.setUser(setting.getServerEmail()); + account.setPass(setting.getEmailPass()); + return account; + } + + public String getMailTarget() { + //获取系统设置 + SystemSetting setting = systemSettingService.getById(1); + //如果不配置目标邮箱的话,默认目标邮箱为服务器邮箱地址 + String target = ""; + if (StringUtils.hasText(setting.getNotificationEmail())) { + target = setting.getNotificationEmail(); + } else { + target = setting.getServerEmail(); + } + return target; + } +} diff --git a/src/main/java/com/mzaxd/noodles/util/UrlUtil.java b/src/main/java/com/mzaxd/noodles/util/UrlUtil.java new file mode 100644 index 0000000..61bef22 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/UrlUtil.java @@ -0,0 +1,37 @@ +package com.mzaxd.noodles.util; + +import com.mzaxd.noodles.constant.UrlConstant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * @author root + */ +public class UrlUtil { + + public static String getUrl(String protocol, String ip, String port, String path) { + return getAddress(protocol, ip, port) + path; + } + + public static String getAddress(String protocol, String ip, String port) { + return protocol + "://" + ip + ":" + port; + } + + public static Map resolveUrl(String url) { + HashMap result = new HashMap<>(3); + + String[] protocolAndAddress = url.split("://"); + String protocol = protocolAndAddress[0]; + String[] ipAndPort = protocolAndAddress[1].split(":"); + String ip = ipAndPort[0]; + String port = ipAndPort[1]; + result.put(UrlConstant.PROTOCOL, protocol); + result.put(UrlConstant.IP, ip); + result.put(UrlConstant.PORT, port); + return result; + } + + +} diff --git a/src/main/java/com/mzaxd/noodles/util/WebUtils.java b/src/main/java/com/mzaxd/noodles/util/WebUtils.java new file mode 100644 index 0000000..fba235e --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/util/WebUtils.java @@ -0,0 +1,37 @@ +package com.mzaxd.noodles.util; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +/** + * @author root + */ +public class WebUtils { + /** + * 将字符串渲染到客户端 + * + * @param response 渲染对象 + * @param string 待渲染的字符串 + * @return null + */ + public static void renderString(HttpServletResponse response, String string) { + try { + response.setStatus(200); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().print(string); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + public static void setDownLoadHeader(String filename, HttpServletResponse response) throws UnsupportedEncodingException { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + String fname= URLEncoder.encode(filename,"UTF-8").replaceAll("\\+", "%20"); + response.setHeader("Content-disposition","attachment; filename="+fname); + } +} \ No newline at end of file diff --git a/src/main/java/com/mzaxd/noodles/websocket/AllHostDynamicDataServer.java b/src/main/java/com/mzaxd/noodles/websocket/AllHostDynamicDataServer.java new file mode 100644 index 0000000..29cf071 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/websocket/AllHostDynamicDataServer.java @@ -0,0 +1,128 @@ +package com.mzaxd.noodles.websocket; + +import com.alibaba.fastjson.JSONObject; +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.mzaxd.noodles.domain.message.DynamicData; +import com.mzaxd.noodles.service.HostDetectorService; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author Mzaxd + * @since 2023-02-05 15:37 + */ +@Component +@ServerEndpoint("/ws/getDynamicData/") +@Slf4j +@Data +public class AllHostDynamicDataServer { + + private static HostDetectorService hostDetectorService; + + @Autowired + public void setHostDetectorService(HostDetectorService hostDetectorService) { + AllHostDynamicDataServer.hostDetectorService = hostDetectorService; + } + + /** + * 实例一个session,这个session是websocket的session + */ + private Session session; + + /** + * 存放websocket的集合(本次demo不会用到,聊天室的demo会用到) + * + * @author mzaxd + * @date 2023/2/5 15:39 + * @param null + */ + private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet<>(); + + /** + * 前端请求时一个websocket时 + * + * @param session + * @author mzaxd + * @date 2023/2/5 16:11 + */ + @OnOpen + public void onOpen(Session session) { + this.session = session; + webSocketSet.add(this); + log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size()); + + List allALiveDetectors = hostDetectorService.getAllALiveDetectors(); + + // 执行逻辑 + long initialDelay = 0; + long period = 6L; + + ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, + new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()); + executorService.scheduleAtFixedRate(() -> { + Map dynamicData = hostDetectorService.getDynamicData(allALiveDetectors); + + String message = JSONObject.toJSONString(dynamicData); + AllHostDynamicDataServer.sendMessage(message); + }, initialDelay, period, TimeUnit.SECONDS); + } + + /** + * 前端关闭时一个websocket时 + * + * @author mzaxd + * @date 2023/2/5 16:11 + */ + @OnClose + public void onClose() { + webSocketSet.remove(this); + log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size()); + } + + /** + * 前端向后端发送消息 + * + * @param message + * @author mzaxd + * @date 2023/2/5 16:12 + */ + @OnMessage + public void onMessage(String message) { + log.info("【websocket消息】收到客户端发来的消息:{}", message); + } + + /** + * 新增一个方法用于主动向客户端发送消息 + * + * @param message + * @author mzaxd + * @date 2023/2/5 16:12 + */ + public static void sendMessage(String message) { + for (AllHostDynamicDataServer webSocket : webSocketSet) { + log.info("【websocket消息】广播消息, message={}", message); + try { + webSocket.session.getBasicRemote().sendText(message); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + +} diff --git a/src/main/java/com/mzaxd/noodles/websocket/HostDynamicDataServer.java b/src/main/java/com/mzaxd/noodles/websocket/HostDynamicDataServer.java new file mode 100644 index 0000000..b36aa13 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/websocket/HostDynamicDataServer.java @@ -0,0 +1,130 @@ +package com.mzaxd.noodles.websocket; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.mzaxd.noodles.domain.message.DynamicData; +import com.mzaxd.noodles.service.HostDetectorService; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author Mzaxd + * @since 2023-02-05 15:37 + */ +@Component +@ServerEndpoint("/ws/getHostDynamicData/{hostId}") +@Slf4j +@Data +public class HostDynamicDataServer { + + private static HostDetectorService hostDetectorService; + + @Autowired + public void setHostDetectorService(HostDetectorService hostDetectorService) { + HostDynamicDataServer.hostDetectorService = hostDetectorService; + } + + /** + * 实例一个session,这个session是websocket的session + */ + private Session session; + + /** + * 存放websocket的集合(本次demo不会用到,聊天室的demo会用到) + * + * @author mzaxd + * @date 2023/2/5 15:39 + * @param null + */ + private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet<>(); + + /** + * 前端请求时一个websocket时 + * + * @param session + * @author mzaxd + * @date 2023/2/5 16:11 + */ + @OnOpen + public void onOpen(Session session, @PathParam("hostId") Integer hostId) { + this.session = session; + webSocketSet.add(this); + log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size()); + + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<>(); + lambdaQueryWrapper.eq(HostDetector::getHostMachineId, hostId); + HostDetector hostDetector = hostDetectorService.getOne(lambdaQueryWrapper); + + // 执行逻辑 + long initialDelay = 0; + long period = 6L; + + ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, + new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()); + executorService.scheduleAtFixedRate(() -> { + Map dynamicData = hostDetectorService.getDynamicDataByDetector(hostDetector); + + String message = JSONObject.toJSONString(dynamicData); + HostDynamicDataServer.sendMessage(message); + }, initialDelay, period, TimeUnit.SECONDS); + } + + /** + * 前端关闭时一个websocket时 + * + * @author mzaxd + * @date 2023/2/5 16:11 + */ + @OnClose + public void onClose() { + webSocketSet.remove(this); + log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size()); + } + + /** + * 前端向后端发送消息 + * + * @param message + * @author mzaxd + * @date 2023/2/5 16:12 + */ + @OnMessage + public void onMessage(String message) { + log.info("【websocket消息】收到客户端发来的消息:{}", message); + } + + /** + * 新增一个方法用于主动向客户端发送消息 + * + * @param message + * @author mzaxd + * @date 2023/2/5 16:12 + */ + public static void sendMessage(String message) { + for (HostDynamicDataServer webSocket : webSocketSet) { + log.info("【websocket消息】广播消息, message={}", message); + try { + webSocket.session.getBasicRemote().sendText(message); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/src/main/java/com/mzaxd/noodles/websocket/NoodlesJvmInfoServer.java b/src/main/java/com/mzaxd/noodles/websocket/NoodlesJvmInfoServer.java new file mode 100644 index 0000000..e389e77 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/websocket/NoodlesJvmInfoServer.java @@ -0,0 +1,125 @@ +package com.mzaxd.noodles.websocket; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.domain.entity.HostDetector; +import com.mzaxd.noodles.domain.message.DynamicData; +import com.mzaxd.noodles.service.HostDetectorService; +import com.mzaxd.noodles.util.SystemInfoUtils; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.concurrent.BasicThreadFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * @author Mzaxd + * @since 2023-02-05 15:37 + */ +@Component +@ServerEndpoint("/ws/getNoodlesJvmInfo") +@Slf4j +@Data +public class NoodlesJvmInfoServer { + + private static HostDetectorService hostDetectorService; + + @Autowired + public void setHostDetectorService(HostDetectorService hostDetectorService) { + NoodlesJvmInfoServer.hostDetectorService = hostDetectorService; + } + + /** + * 实例一个session,这个session是websocket的session + */ + private Session session; + + /** + * 存放websocket的集合(本次demo不会用到,聊天室的demo会用到) + * + * @author mzaxd + * @date 2023/2/5 15:39 + * @param null + */ + private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet<>(); + + /** + * 前端请求时一个websocket时 + * + * @param session + * @author mzaxd + * @date 2023/2/5 16:11 + */ + @OnOpen + public void onOpen(Session session) { + this.session = session; + webSocketSet.add(this); + log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size()); + + // 执行逻辑 + long initialDelay = 0; + long period = 5L; + + ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, + new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()); + executorService.scheduleAtFixedRate(() -> { + JSONObject jvmInfo = SystemInfoUtils.getJvmInfo(); + NoodlesJvmInfoServer.sendMessage(jvmInfo.toJSONString()); + }, initialDelay, period, TimeUnit.SECONDS); + } + + /** + * 前端关闭时一个websocket时 + * + * @author mzaxd + * @date 2023/2/5 16:11 + */ + @OnClose + public void onClose() { + webSocketSet.remove(this); + log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size()); + } + + /** + * 前端向后端发送消息 + * + * @param message + * @author mzaxd + * @date 2023/2/5 16:12 + */ + @OnMessage + public void onMessage(String message) { + log.info("【websocket消息】收到客户端发来的消息:{}", message); + } + + /** + * 新增一个方法用于主动向客户端发送消息 + * + * @param message + * @author mzaxd + * @date 2023/2/5 16:12 + */ + public static synchronized void sendMessage(String message) { + for (NoodlesJvmInfoServer webSocket : webSocketSet) { + log.info("【websocket消息】广播消息, message={}", message); + try { + webSocket.session.getBasicRemote().sendText(message); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + +} diff --git a/src/main/java/com/mzaxd/noodles/websocket/SshHandler.java b/src/main/java/com/mzaxd/noodles/websocket/SshHandler.java new file mode 100644 index 0000000..c9f4b45 --- /dev/null +++ b/src/main/java/com/mzaxd/noodles/websocket/SshHandler.java @@ -0,0 +1,287 @@ +package com.mzaxd.noodles.websocket; + +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.thread.ThreadUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.extra.ssh.ChannelType; +import cn.hutool.extra.ssh.JschUtil; +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.jcraft.jsch.ChannelShell; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import com.mzaxd.noodles.domain.entity.Container; +import com.mzaxd.noodles.domain.entity.SshLink; +import com.mzaxd.noodles.domain.ssh.SshModel; +import com.mzaxd.noodles.domain.ssh.SshMessage; +import com.mzaxd.noodles.service.ContainerService; +import com.mzaxd.noodles.service.SshLinkService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import javax.websocket.*; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * @author qingfeng + * @version 1.0.0 + * @ProjectName SshHandler + * @Description ssh 处理 + * @createTime 2022/5/2 0002 15:26 + */ +@ServerEndpoint(value = "/ws/ssh/{sshId}") +@Component +@Slf4j +public class SshHandler { + + private static SshLinkService sshLinkService; + + private static ContainerService containerService; + + @Autowired + public void setSshLinkService(SshLinkService sshLinkService) { + SshHandler.sshLinkService = sshLinkService; + } + + @Autowired + public void ContainerService(ContainerService containerService) { + SshHandler.containerService = containerService; + } + + + private static final ConcurrentHashMap HANDLER_ITEM_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>(); + + @PostConstruct + public void init() { + log.info("websocket 加载"); + } + + + private static final AtomicInteger OnlineCount = new AtomicInteger(0); + + /** + * concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。 + */ + private static CopyOnWriteArraySet sessionSet = new CopyOnWriteArraySet(); + + + /** + * 连接建立成功调用的方法 + */ + @OnOpen + public void onOpen(javax.websocket.Session session, @PathParam("sshId") Long sshId) { + sessionSet.add(session); + SshLink sshLink = sshLinkService.getById(sshId); + SshModel sshItem = new SshModel(); + sshItem.setHost(sshLink.getHost()); + sshItem.setPort(sshLink.getPort()); + sshItem.setUser(sshLink.getName()); + sshItem.setPassword(sshLink.getPassword()); + // 在线数加1 + int cnt = OnlineCount.incrementAndGet(); + log.info("有连接加入,当前连接数为:{},sessionId={}", cnt, session.getId()); + HandlerItem handlerItem = null; + try { + handlerItem = new HandlerItem(session, sshItem); + handlerItem.startRead(); + HANDLER_ITEM_CONCURRENT_HASH_MAP.put(session.getId(), handlerItem); + if (Objects.nonNull(sshLink.getConsoleType())) { + //找出docker id + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(Container::getSshId, sshId); + Container container = containerService.getOne(wrapper); + sendBinary(session,"docker exec -it " + container.getContainerId() + " /bin/" + sshLink.getConsoleType() + "\n"); + } + } catch (Exception exception) { + sendMessage(session, "连接失败,请检查连接信息是否配置正确\n"); + sessionSet.remove(session); + } + } + + /** + * 连接关闭调用的方法 + */ + @OnClose + public void onClose(javax.websocket.Session session) { + sessionSet.remove(session); + int cnt = OnlineCount.decrementAndGet(); + log.info("有连接关闭,当前连接数为:{}", cnt); + } + + /** + * 收到客户端消息后调用的方法 + * + * @param message 客户端发送过来的消息 + */ + @OnMessage + public void onMessage(String message, javax.websocket.Session session) throws Exception { + try { + if (JSONUtil.isJson(message)) { + SshMessage sshData = JSON.parseObject(message, SshMessage.class); + HandlerItem handlerItem = HANDLER_ITEM_CONCURRENT_HASH_MAP.get(session.getId()); + handlerItem.channel.setPty(true); + handlerItem.channel.setPtySize(sshData.getCols(), sshData.getRows(), 640, 480); + } else { + HandlerItem handlerItem = HANDLER_ITEM_CONCURRENT_HASH_MAP.get(session.getId()); + this.sendCommand(handlerItem, message); + } + } catch (Exception e) { + //吃掉Hutool JSONUtil产生的异常 + HandlerItem handlerItem = HANDLER_ITEM_CONCURRENT_HASH_MAP.get(session.getId()); + this.sendCommand(handlerItem, message); + } + + } + + /** + * 出现错误 + * + * @param session + * @param error + */ + @OnError + public void onError(javax.websocket.Session session, Throwable error) { + log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId()); + error.printStackTrace(); + } + + private void sendCommand(HandlerItem handlerItem, String data) throws Exception { + if (handlerItem.checkInput(data)) { + handlerItem.outputStream.write(data.getBytes()); + } else { + handlerItem.outputStream.write("没有执行相关命令权限".getBytes()); + handlerItem.outputStream.flush(); + handlerItem.outputStream.write(new byte[]{3}); + } + handlerItem.outputStream.flush(); + } + + /** + * 发送消息,实践表明,每次浏览器刷新,session会发生变化。 + * + * @param session + * @param message + */ + public static void sendMessage(javax.websocket.Session session, String message) { + try { + synchronized (session) { + session.getBasicRemote().sendText(message); + } + } catch (IOException e) { + log.error("发送消息出错:{}", e.getMessage()); + e.printStackTrace(); + } + } + + private class HandlerItem implements Runnable { + private final javax.websocket.Session session; + private final InputStream inputStream; + private final OutputStream outputStream; + private final Session openSession; + private final ChannelShell channel; + private final SshModel sshItem; + private final StringBuilder nowLineInput = new StringBuilder(); + + HandlerItem(javax.websocket.Session session, SshModel sshItem) throws IOException { + this.session = session; + this.sshItem = sshItem; + this.openSession = JschUtil.openSession(sshItem.getHost(), sshItem.getPort(), sshItem.getUser(), sshItem.getPassword()); + this.channel = (ChannelShell) JschUtil.createChannel(openSession, ChannelType.SHELL); + this.inputStream = channel.getInputStream(); + this.outputStream = channel.getOutputStream(); + } + + void startRead() throws JSchException { + this.channel.connect(); + ThreadUtil.execute(this); + } + + + /** + * 添加到命令队列 + * + * @param msg 输入 + * @return 当前待确认待所有命令 + */ + private String append(String msg) { + char[] x = msg.toCharArray(); + if (x.length == 1 && x[0] == 127) { + // 退格键 + int length = nowLineInput.length(); + if (length > 0) { + nowLineInput.delete(length - 1, length); + } + } else { + nowLineInput.append(msg); + } + return nowLineInput.toString(); + } + + public boolean checkInput(String msg) { + String allCommand = this.append(msg); + boolean refuse; + if (StrUtil.equalsAny(msg, StrUtil.CR, StrUtil.TAB)) { + String join = nowLineInput.toString(); + if (StrUtil.equals(msg, StrUtil.CR)) { + nowLineInput.setLength(0); + } + refuse = SshModel.checkInputItem(sshItem, join); + } else { + // 复制输出 + refuse = SshModel.checkInputItem(sshItem, msg); + } + return refuse; + } + + + @Override + public void run() { + try { + byte[] buffer = new byte[1024]; + int i; + //如果没有数据来,线程会一直阻塞在这个地方等待数据。 + while ((i = inputStream.read(buffer)) != -1) { + sendBinary(session, new String(Arrays.copyOfRange(buffer, 0, i), sshItem.getCharsetT())); + } + } catch (Exception e) { + if (!this.openSession.isConnected()) { + return; + } + SshHandler.this.destroy(this.session); + } + } + } + + public void destroy(javax.websocket.Session session) { + HandlerItem handlerItem = HANDLER_ITEM_CONCURRENT_HASH_MAP.get(session.getId()); + if (handlerItem != null) { + IoUtil.close(handlerItem.inputStream); + IoUtil.close(handlerItem.outputStream); + JschUtil.close(handlerItem.channel); + JschUtil.close(handlerItem.openSession); + } + IoUtil.close(session); + HANDLER_ITEM_CONCURRENT_HASH_MAP.remove(session.getId()); + } + + private static void sendBinary(javax.websocket.Session session, String msg) { + try { + System.out.println("#####:" + msg); + session.getBasicRemote().sendText(msg); + } catch (IOException e) { + + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..b2d0744 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,38 @@ +server: + port: 6081 +spring: + #MySQL配置 + datasource: + url: jdbc:mysql://192.168.1.103:3307/noodles?characterEncoding=utf-8&serverTimezone=Asia/Shanghai + username: root + password: rootroot + driver-class-name: com.mysql.cj.jdbc.Driver + servlet: + multipart: + max-file-size: 2MB + max-request-size: 5MB + #Redis配置 + redis: + host: 192.168.1.103 + database: 3 + #RabbitMq配置 + rabbitmq: + host: 192.168.1.103 + port: 5672 + username: mzaxd + password: 200712 + +mybatis-plus: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + global-config: + db-config: + logic-delete-field: delFlag + logic-delete-value: 1 + logic-not-delete-value: 0 + id-type: auto +pagehelper: + auto-dialect: on + reasonable: true + support-methods-arguments: true + page-size-zero: true \ No newline at end of file diff --git a/src/main/resources/config/mail.setting b/src/main/resources/config/mail.setting new file mode 100644 index 0000000..2b2a2d6 --- /dev/null +++ b/src/main/resources/config/mail.setting @@ -0,0 +1,16 @@ +#使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。 +startttlsEnable = true + +# 使用SSL安全连接 +sslEnable = true +# 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字 +socketFactoryClass = javax.net.ssl.SSLSocketFactory +# 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true +socketFactoryFallback = true +# 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口456 +socketFactoryPort = 465 + +# SMTP超时时长,单位毫秒,缺省值不超时 +timeout = 0 +# Socket连接超时值,单位毫秒,缺省值不超时 +connectionTimeout = 0 \ No newline at end of file diff --git a/src/main/resources/ip2region.xdb b/src/main/resources/ip2region.xdb new file mode 100644 index 0000000..c78b792 Binary files /dev/null and b/src/main/resources/ip2region.xdb differ diff --git a/src/main/resources/mapper/HostMachineMapper.xml b/src/main/resources/mapper/HostMachineMapper.xml new file mode 100644 index 0000000..9bb2f92 --- /dev/null +++ b/src/main/resources/mapper/HostMachineMapper.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + hm + . + id + ,hm.name,hm.description, + hm.avatar,hm.ssh_id,hm.os_id, + hm.manage_ip,hm.host_machine_id,hm.threads, + hm.memory,hm.host_machine_state,notify, + hm.create_time,hm.create_by,hm.update_time, + hm.update_by,hm.del_flag + + + diff --git a/src/test/java/com/mzaxd/noodles/EncodePassword.java b/src/test/java/com/mzaxd/noodles/EncodePassword.java new file mode 100644 index 0000000..53848c4 --- /dev/null +++ b/src/test/java/com/mzaxd/noodles/EncodePassword.java @@ -0,0 +1,24 @@ +package com.mzaxd.noodles; + +import com.alibaba.fastjson.JSONObject; +import com.mzaxd.noodles.util.SystemInfoUtils; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.crypto.password.PasswordEncoder; + +import javax.annotation.Resource; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class EncodePassword { + + @Resource + private PasswordEncoder passwordEncoder; + + @Test + public void test() { + String password = "200712"; + String encode = passwordEncoder.encode(password); + System.out.println(encode); + } + +} diff --git a/src/test/java/com/mzaxd/noodles/NoodlesApplicationTests.java b/src/test/java/com/mzaxd/noodles/NoodlesApplicationTests.java new file mode 100644 index 0000000..47b165e --- /dev/null +++ b/src/test/java/com/mzaxd/noodles/NoodlesApplicationTests.java @@ -0,0 +1,135 @@ +package com.mzaxd.noodles; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.date.DateUtil; +import cn.hutool.extra.mail.MailAccount; +import cn.hutool.extra.mail.MailUtil; +import cn.hutool.http.HttpException; +import cn.hutool.http.HttpRequest; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.mzaxd.noodles.constant.SystemConstant; +import com.mzaxd.noodles.domain.entity.*; +import com.mzaxd.noodles.mapper.OsMapper; +import com.mzaxd.noodles.service.*; +import com.mzaxd.noodles.util.RedisCache; +import com.mzaxd.noodles.util.SystemInfoUtils; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.scheduling.annotation.Scheduled; + +import javax.annotation.Resource; +import java.util.Map; +import java.util.Set; + +@Slf4j +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class NoodlesApplicationTests { + + @Resource + private OsMapper osMapper; + + @Resource + private RedisCache redisCache; + + @Resource + private RedisTemplate redisTemplate; + + @Resource + private SystemSettingService systemSettingService; + + @Test + void contextLoads() { + try { + HttpRequest.get("https://elizaveta.top:71/").setConnectionTimeout(1000).execute(true); + } catch (HttpException exception) { + log.info("建立连接失败"); + } + } + + @Test + void test() { + Set containerNotifyIds = redisCache.getCacheSet("ContainerNotifyIds"); + redisTemplate.boundSetOps("setKey"); + redisTemplate.boundSetOps("Notify:ContainerIds").remove(1); + containerNotifyIds.remove(1); + redisCache.setCacheSet("ContainerNotifyIds", containerNotifyIds); + } + + @Test + void emailTest() { + SystemSetting systemSetting = systemSettingService.getById(1); + MailAccount account = new MailAccount(); + account.setFrom(systemSetting.getNotificationEmail()); + account.setUser(systemSetting.getNotificationEmail()); + account.setPass(systemSetting.getEmailPass()); + MailUtil.send(account, CollUtil.newArrayList("mzaxd0712@gmail.com"),"测试5","邮件来自测试",false); + } + + @Test + public void testJVMInfo() { + JSONObject jvmInfo = SystemInfoUtils.getJvmInfo(); + System.out.println(jvmInfo); + } + + @Resource + private HostMachineService hostMachineService; + + @Resource + private ContainerService containerService; + + @Resource + private ServirService servirService; + + @Resource + private AuditLogService auditLogService; + + @Resource + private EveryDayDataService everyDayDataService; + + /** + * 每天晚上收集今日数据 + */ + @Test + public void everyDayDataCollect() { + EveryDayData everyDayData = new EveryDayData(); + LambdaQueryWrapper auditLogWrapper = new LambdaQueryWrapper<>(); + Map hostStateInfo = hostMachineService.getHostStateInfo(); + Map vmStateInfo = hostMachineService.getVmStateInfo(); + Map containerStateInfo = containerService.getContainerStateInfo(); + //设置主机总数 + everyDayData.setHostCount(hostStateInfo.get("hostCount")); + //设置主机在线总数 + everyDayData.setHostOnlineCount(hostStateInfo.get("hostOnlineCount")); + //设置主机离线总数 + everyDayData.setHostOfflineCount(hostStateInfo.get("hostOfflineCount")); + //设置主机未知总数 + everyDayData.setHostUnknownCount(hostStateInfo.get("hostUnknownCount")); + //设置虚拟机总数 + everyDayData.setVmCount(vmStateInfo.get("vmCount")); + //设置虚拟机在线总数 + everyDayData.setVmOnlineCount(vmStateInfo.get("vmOnlineCount")); + //设置虚拟机离线总数 + everyDayData.setVmOfflineCount(vmStateInfo.get("vmOfflineCount")); + //设置虚拟机未知总数 + everyDayData.setVmUnknownCount(vmStateInfo.get("vmUnknownCount")); + //设置容器总数 + everyDayData.setContainerCount(containerStateInfo.get("containerCount")); + //设置容器在线总数 + everyDayData.setContainerOnlineCount(containerStateInfo.get("containerOnlineCount")); + //设置容器离线总数 + everyDayData.setContainerOfflineCount(containerStateInfo.get("containerOfflineCount")); + //设置容器未知总数 + everyDayData.setContainerUnknownCount(containerStateInfo.get("containerUnknownCount")); + //设置服务总数 + everyDayData.setServirCount(servirService.count()); + //设置操作总数 + auditLogWrapper.ge(AuditLog::getCreateTime, DateUtil.beginOfDay(DateUtil.date())); + auditLogWrapper.lt(AuditLog::getCreateTime, DateUtil.endOfDay(DateUtil.date())); + everyDayData.setAuditCount(auditLogService.count(auditLogWrapper)); + + System.out.println(everyDayData); + } +}