init project

This commit is contained in:
wangwei
2024-01-05 15:15:36 +08:00
parent 6a27a9c3a9
commit 30a0884811
18 changed files with 992 additions and 92 deletions

34
.gitignore vendored Normal file
View File

@@ -0,0 +1,34 @@
/target/
!.mvn/wrapper/maven-wrapper.jar
.DS_Store
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
/logs/
/config/nacos
!/config/nacos/config/fixed-127.0.0.1_8848-tsg_nacos
!/config/nacos/config/fixed-127.0.0.1_8848-cn_nacos
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### Jrebel ###
rebel*.xml

39
.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,39 @@
stages:
- build
- clean
- deploy
build:
stage: build
script:
- echo 'exec mvn clean package'
- echo 'tag:' $CI_COMMIT_TAG
- mvn clean package -Dmaven.test.skip=true
only:
- tags
tags:
- galaxy
clean:
stage: clean
script:
- echo 'build job fail, exec mvn clean'
- echo 'tag:' $CI_COMMIT_TAG
- mvn clean
when: on_failure
only:
- tags
tags:
- galaxy
deploy:
stage: deploy
script:
- echo 'exec mvn package & docker build'
- echo 'tag:' $CI_COMMIT_TAG
- mvn clean package -Dmaven.test.skip=true docker:build -DdockerImageTags=$CI_COMMIT_TAG
when: on_success
only:
- tags
tags:
- galaxy

View File

@@ -1,92 +0,0 @@
# cn-object-scheduler
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://git.mesalab.cn/wangwei/cn-object-scheduler.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://git.mesalab.cn/wangwei/cn-object-scheduler/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

44
config/application.yml Normal file
View File

@@ -0,0 +1,44 @@
server:
port: 9999
spring:
application:
name: cn-object-scheduler
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.44.53:3306/cn_api?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=UTC&failOverReadOnly=false&connectTimeout=10000&socketTimeout=30000
username: root
password: 111111
tsg:
system:
url: http://192.168.44.3:80
username: wangwei
password: ImlUl8/Hdt0MaS1LEnyuCg==
token: aa2bdec5518ad131f71944b13ce5c298&1&
httpTimeout: 3600000
object:
ip:
#指定排除的IP. 1.如果没有可不写值2.若有多个用英文逗号,分隔如: 127.0.0.1,127.0.0.23.可适用IP段匹配127.*
excludeValue: 0.0.0.0,255.255.255.255,127.*,8.8.8.8,1.1.1.1
cyberghostvpn_serverip:
id: 1309738
name: cn_vpn_ip_learning
update:
cron: 0 0/1 * * * ?
enable: true
sql: SELECT addr_format AS addrFormat, ip1 AS ip1, ip2 AS ip2 FROM cn_vpn_learning_ip WHERE knowledge_id = 10
delete:
cron: 0 0/1 * * * ?
enable: true
offsetSecond: -600
fqdn:
cyberghostvpn_servername:
id: 1309740
name: cn_vpn_ip_learning
update:
cron: 35 0/1 * * * ?
enable: true
sql: SELECT domain AS domain FROM cn_vpn_learning_domain WHERE knowledge_id = 10
delete:
cron: 0 0/1 * * * ?
enable: true
offsetSecond: -600

69
config/logback-spring.xml Normal file
View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<property name="log.path" value="log/${springAppName}"/>
<property name="log.maxHistory" value="15"/>
<property name="log.colorPattern"
value="%magenta(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%-5level) %boldCyan(${springAppName:-}) %yellow(%thread) %green(%logger) %msg%n"/>
<property name="log.pattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level ${springAppName:-} %thread %logger %msg%n"/>
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.colorPattern}</pattern>
</encoder>
</appender>
<!--输出到文件-->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/info/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<MaxHistory>${log.maxHistory}</MaxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/error.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="info">
<appender-ref ref="console"/>
<appender-ref ref="file_info"/>
<appender-ref ref="file_warn"/>
<appender-ref ref="file_error"/>
</root>
<!--<root level="debug">
<appender-ref ref="file_info"/>
<appender-ref ref="file_error"/>
</root>-->
</configuration>

12
docker/Dockerfile Normal file
View File

@@ -0,0 +1,12 @@
ARG JDK_IMAGE
FROM ${JDK_IMAGE}
MAINTAINER Galaxy
VOLUME /tmp
WORKDIR /home/tsg/galaxy/cn-object-scheduler
COPY config config
ARG JAR_FILE
COPY ${JAR_FILE} cn-object-scheduler.xjar
#dockercompose set JAVA_OPTS
ENV JAVA_OPTS=" -Xms1024m -Xmx2048m "
ENV LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar cn-object-scheduler.jar" ]

180
pom.xml Normal file
View File

@@ -0,0 +1,180 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.geedge</groupId>
<artifactId>cn-object-scheduler</artifactId>
<version>24.01</version>
<name>cn-object-scheduler</name>
<description>cn-object-scheduler</description>
<repositories>
<repository>
<id>nexus</id>
<name>Team Nexus Repository</name>
<url>http://192.168.40.153:8099/content/groups/public</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>Team Nexus Repository</name>
<url>http://192.168.40.153:8099/content/groups/public</url>
</pluginRepository>
</pluginRepositories>
<properties>
<java.version>11</java.version>
<guava.version>23.0</guava.version>
<hutool.version>5.7.7</hutool.version>
<active.record.version>4.9.01</active.record.version>
<mysql-connector-java.version>8.0.18</mysql-connector-java.version>
<starter.druid.version>1.1.22</starter.druid.version>
<docker.build>192.168.40.153</docker.build>
<docker.build.port>2375</docker.build.port>
<docker.registry>192.168.40.153</docker.registry>
<docker.registry.port>9080</docker.registry.port>
<docker.image.prefix>tsg/galaxy</docker.image.prefix>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${starter.druid.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>activerecord</artifactId>
<version>${active.record.version}</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.0.0</version>
<configuration>
<serverId>153-docker-repo</serverId>
<registryUrl>${docker.registry}:${docker.registry.port}</registryUrl>
<pushImage>true</pushImage>
<forceTags>true</forceTags>
<imageName>${docker.registry}:${docker.registry.port}/${docker.image.prefix}/${project.artifactId}
</imageName>
<dockerHost>http://${docker.build}:${docker.build.port}</dockerHost>
<dockerDirectory>docker</dockerDirectory>
<buildArgs>
<JDK_IMAGE>${docker.registry}:${docker.registry.port}/common/amazon-corretto:11.0.21.9.1
</JDK_IMAGE>
<JAR_FILE>${project.build.finalName}.jar</JAR_FILE>
</buildArgs>
<imageTags>
<imageTag>v24.01</imageTag>
</imageTags>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
<resource>
<targetPath>/config</targetPath>
<directory>config</directory>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-toolchains-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<goals>
<goal>toolchain</goal>
</goals>
</execution>
</executions>
<configuration>
<toolchains>
<jdk>
<version>11</version>
<vendor>amazon</vendor>
</jdk>
</toolchains>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>utf-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<skipTests>true</skipTests> <!-- 默认关掉单元测试-->
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,18 @@
package com.geedge;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author wangwei
*/
@SpringBootApplication
@EnableScheduling
public class CnPolicySchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(CnPolicySchedulerApplication.class, args);
}
}

View File

@@ -0,0 +1,26 @@
package com.geedge.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
* TODO
*
* @Classname ScheduledPoolConfig
* @Date 2024/1/3 14:00
* @Author wWei
*/
@Configuration
public class ScheduledPoolConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(16);
scheduler.initialize();
taskRegistrar.setScheduler(scheduler);
}
}

View File

@@ -0,0 +1,42 @@
package com.geedge.common.constant;
/**
* TODO
*
* @Classname TSG
* @Date 2024/1/4 16:11
* @Author wWei
*/
public class TsgObject {
public static final String KEY_VSYS_ID = "vsys_id";
public static final String KEY_OBJECT = "object";
public static final String KEY_CREATED_BEFORE = "created_before";
public static final String KEY_OBJECT_NAME = "name";
public static final String KEY_OBJECT_TYPE = "type";
public static final String KEY_OBJECT_MEMBER = "member";
public static final String KEY_OBJECT_MEMBER_TYPE = "type";
public static final String KEY_OBJECT_MEMBER_ITEMS = "items";
public static final String KEY_OBJECT_MEMBER_ITEMS_OP = "op";
public static final String KEY_OBJECT_MEMBER_ITEMS_IP = "ip";
public static final String KEY_OBJECT_MEMBER_ITEMS_STRING = "string";
public static final String KEY_OBJECT_MEMBER_ITEMS_STRING_PATTERNS = "patterns";
public static final String KEY_OBJECT_MEMBER_ITEMS_IP_IP_ADDRESS = "ip_address";
public static final String KEY_OBJECT_MEMBER_ITEMS_IP_PORT_RANGE = "port_range";
public static final String KEY_OBJECT_MEMBER_ITEMS_STRING_PATTERNS_KEYWORDS = "keywords";
public static final String KEY_OBJECT_MEMBER_ITEMS_IP_ADDR_TYPE = "addr_type";
public static final String KEY_OBJECT_MEMBER_ITEMS_IP_IP_RANGE = "ip_range";
public static final String KEY_OBJECT_MEMBER_ITEMS_IP_IP_CIDR = "ip_cidr";
public static final String VALUE_OBJECT_TYPE_IP = "ip";
public static final String VALUE_OBJECT_TYPE_FQDN = "fqdn";
public static final String VALUE_OBJECT_MEMBER_ITEMS_IP_PORT_RANGE = "0-65535";
public static final String VALUE_OBJECT_MEMBER_ITEMS_OP_ADD = "add";
public static final Integer VALUE_OBJECT_MEMBER_TYPE_1 = 1;
public static final Integer VALUE_VSYS_ID_1 = 1;
}

View File

@@ -0,0 +1,24 @@
package com.geedge.common.enums;
/**
* TODO
*
* @Classname addrFormat
* @Date 2024/1/3 16:26
* @Author wWei
*/
import lombok.Getter;
@Getter
public enum AddressFormat {
SINGLE("Single"),
RANGE("Range"),
CIDR("CIDR"),
;
private final String value;
AddressFormat(String value) {
this.value = value;
}
}

View File

@@ -0,0 +1,40 @@
package com.geedge.common.plugin;
import com.jfinal.plugin.druid.DruidPlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* Desc: TODO
*
* @return {@link null}
* @created by wWei
* @date 2024/1/3 18:44
*/
@Slf4j
@Component
public class ActiveRecordInit {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@PostConstruct
public void initDialect() {
DruidPlugin dp = new DruidPlugin(url, userName, password);
dp.setTestWhileIdle(true);
dp.setValidationQuery("SELECT 1");
ArpStartPlugin arp = new ArpStartPlugin(dp);
dp.start();
arp.start();
log.info("Initializing ActiveRecordPlugin Complete");
}
}

View File

@@ -0,0 +1,32 @@
package com.geedge.common.plugin;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
/**
* Desc: TODO
*
* @return {@link null}
* @created by wWei
* @date 2024/1/3 18:44
*/
public class ArpStartPlugin extends ActiveRecordPlugin {
private static final Log log = LogFactory.get();
public ArpStartPlugin(IDataSourceProvider dataSourceProvider) {
super(dataSourceProvider);
}
@Override
public boolean start() {
try {
super.start();
} catch (RuntimeException e) {
log.error("ArpStartPlugin init error:{}", e.getMessage());
}
return true;
}
}

View File

@@ -0,0 +1,128 @@
package com.geedge.common.util;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* TODO
*
* @Classname LoginTsgUtil
* @Date 2024/1/3 09:34
* @Author wWei
*/
@Slf4j
@Component
public class TsgUtil {
public static String TSG_URL;
private static String TSG_USERNAME;
private static String TSG_PASSWORD;
private static Integer httpTimeOut;
private static String TSG_TOKEN;
@Value("${tsg.system.httpTimeout}")
public void setTsgUrl(Integer timeOut) {
httpTimeOut = timeOut;
}
@Value("${tsg.system.url}")
public void setTsgUrl(String url) {
TSG_URL = url;
}
@Value("${tsg.system.username}")
private void setTsgUsername(String username) {
TSG_USERNAME = username;
}
@Value("${tsg.system.password}")
private void setTsgPassword(String password) {
TSG_PASSWORD = password;
}
@Value("${tsg.system.token}")
private void setTsgToken(String token) {
TSG_TOKEN = token;
}
public static String getToken() {
if (StrUtil.isNotEmpty(TSG_TOKEN)) {
return TSG_TOKEN;
}
String token = "";
Map<String, Object> map = Maps.newHashMap();
map.put("username", TSG_USERNAME);
map.put("password", TSG_PASSWORD);
try {
Stopwatch watch = Stopwatch.createStarted();
String response = HttpRequest.post(TSG_URL + "/v1/user/login")
.body(JSONUtil.toJsonStr(map))
.timeout(httpTimeOut)
.execute().body();
log.info("get tsg-api token, cost {} seconds", watch.elapsed(TimeUnit.SECONDS));
if (StrUtil.isBlank(response)) {
log.error("failed to get TSG system token. response: {}", response);
throw new RuntimeException("ailed to get TSG system token. response: " + response);
}
JSONObject jsonObject = JSONUtil.parseObj(response);
if (!"200".equals(jsonObject.get("code").toString())) {
log.error("failed to get TSG system token. response: {}", response);
throw new RuntimeException("ailed to get TSG system token. response: " + response);
}
token = JSONUtil.parseObj(jsonObject.get("data")).get("token").toString();
} catch (Exception e) {
log.error("failed to get TSG system token. message: {}", e.getMessage());
throw e;
}
return token;
}
public static void updateObjectById(Integer id, Map<String, Object> body) {
Stopwatch watch = Stopwatch.createStarted();
String response = HttpRequest.put(TSG_URL + "/v1/policy/object/" + id)
.header(Header.AUTHORIZATION, getToken())
.body(JSONUtil.toJsonStr(body))
.timeout(httpTimeOut)
.execute().body();
log.info("update tsg-api, cost {} seconds", watch.elapsed(TimeUnit.SECONDS));
if (StrUtil.isBlank(response)) {
log.error("update {} Object error, response: {}", id, response);
throw new RuntimeException("update " + id + " Object error, response: " + response);
}
JSONObject jsonObject = JSONUtil.parseObj(response);
if (!"200".equals(jsonObject.get("code").toString())) {
log.error("update {} Object error, response: {}", id, response);
throw new RuntimeException("update " + id + " Object error, response: " + response);
}
}
public static void deleteItemOfObjectById(Integer id, Map<String, Object> form) {
Stopwatch watch = Stopwatch.createStarted();
String response = HttpRequest.delete(TSG_URL + "/v1/policy/object/" + id + "/item")
.header(Header.AUTHORIZATION, getToken())
.form(form)
.timeout(httpTimeOut)
.execute().body();
log.info("delete tsg-api, cost {} seconds", watch.elapsed(TimeUnit.SECONDS));
if (StrUtil.isBlank(response)) {
log.error("update {} Object error, response: {}", id, response);
throw new RuntimeException("update " + id + " Object error, response: " + response);
}
JSONObject jsonObject = JSONUtil.parseObj(response);
if (!"200".equals(jsonObject.get("code").toString())) {
log.error("update {} Object error, response: {}", id, response);
throw new RuntimeException("update " + id + " Object error, response: " + response);
}
}
}

View File

@@ -0,0 +1,128 @@
package com.geedge.scheduler;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.net.MaskBit;
import cn.hutool.core.util.BooleanUtil;
import com.geedge.common.constant.TsgObject;
import com.geedge.common.enums.AddressFormat;
import com.geedge.common.util.TsgUtil;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* TODO
*
* @Classname Scheduler
* @Date 2024/1/2 11:31
* @Author wWei
*/
@Slf4j
@Component
public class FqdnScheduler {
@Value("${tsg.object.fqdn.cyberghostvpn_servername.id}")
private Integer cyberghostvpnServernameId;
@Value("${tsg.object.fqdn.cyberghostvpn_servername.name}")
private String cyberghostvpnServernameName;
@Value("${tsg.object.fqdn.cyberghostvpn_servername.update.enable}")
private Boolean cyberghostvpnServernameUpdateEnable;
@Value("${tsg.object.fqdn.cyberghostvpn_servername.update.sql}")
private String cyberghostvpnServernameSql;
@Value("${tsg.object.fqdn.cyberghostvpn_servername.delete.enable}")
private Boolean cyberghostvpnServernameDeleteEnable;
@Value("${tsg.object.fqdn.cyberghostvpn_servername.delete.offsetSecond}")
private Integer cyberghostvpnServernameOffsetSecond;
@Scheduled(cron = "${tsg.object.fqdn.cyberghostvpn_servername.update.cron}")
public void scheduledExecutorUpdate() {
executeUpdate(cyberghostvpnServernameId, cyberghostvpnServernameName, cyberghostvpnServernameUpdateEnable, cyberghostvpnServernameSql);
}
@Scheduled(cron = "${tsg.object.fqdn.cyberghostvpn_servername.delete.cron}")
public void scheduledExecutorDelete() {
executeDelete(cyberghostvpnServernameId, cyberghostvpnServernameDeleteEnable, cyberghostvpnServernameOffsetSecond);
}
private static void executeUpdate(Integer id, String name, Boolean enable, String sql) {
log.info("{}: started update task.", id);
if (BooleanUtil.isFalse(enable)) {
log.warn("{}: interrupted update task. enable: {}", id, enable);
return;
}
try {
Stopwatch watch = Stopwatch.createStarted();
List<Record> data = Db.find(sql);
log.info("{}: query knowledge base content, cost {} seconds", id, watch.elapsed(TimeUnit.SECONDS));
watch.reset().start();
List<Map<String, Object>> items = Lists.newArrayList();
for (Record record : data) {
Map<String, Object> item = Maps.newHashMap();
String domain = record.get("domain");
Map<String, Object> pattern = Maps.newHashMap();
pattern.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_STRING_PATTERNS_KEYWORDS, domain);
List<Map<String, Object>> patterns = Lists.newArrayList();
patterns.add(pattern);
Map<String, Object> str = Maps.newHashMap();
str.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_STRING_PATTERNS, patterns);
item.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_OP, TsgObject.VALUE_OBJECT_MEMBER_ITEMS_OP_ADD);
item.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_STRING, str);
items.add(item);
}
Map<String, Object> member = Maps.newHashMap();
member.put(TsgObject.KEY_OBJECT_MEMBER_TYPE, TsgObject.VALUE_OBJECT_MEMBER_TYPE_1);
member.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS, items);
Map<String, Object> obj = Maps.newHashMap();
obj.put(TsgObject.KEY_OBJECT_NAME, name);
obj.put(TsgObject.KEY_OBJECT_TYPE, TsgObject.VALUE_OBJECT_TYPE_FQDN);
obj.put(TsgObject.KEY_OBJECT_MEMBER, member);
Map<String, Object> body = Maps.newHashMap();
body.put(TsgObject.KEY_VSYS_ID, TsgObject.VALUE_VSYS_ID_1);
body.put(TsgObject.KEY_OBJECT, obj);
log.info("{}: build api params, items size: {}, cost {} seconds", id, items.size(), watch.elapsed(TimeUnit.SECONDS));
TsgUtil.updateObjectById(id, body);
} catch (Exception e) {
log.error("{}: failed to execute update task. message: {}", id, e.getMessage());
throw new RuntimeException(e);
}
}
private static void executeDelete(Integer id, Boolean enable, Integer offsetSecond) {
log.info("{}: started delete task.", id);
if (BooleanUtil.isFalse(enable)) {
log.warn("{}: interrupted delete task. enable: {}", id, enable);
return;
}
try {
DateTime dateTime = DateUtil.offsetSecond(new Date(), offsetSecond).setTimeZone(TimeZone.getTimeZone("UTC"));
String datetimeZ = DateUtil.format(dateTime, DatePattern.UTC_PATTERN);
Map<String, Object> form = Maps.newHashMap();
form.put(TsgObject.KEY_OBJECT_TYPE, TsgObject.VALUE_OBJECT_TYPE_FQDN);
form.put(TsgObject.KEY_VSYS_ID, TsgObject.VALUE_VSYS_ID_1);
form.put(TsgObject.KEY_CREATED_BEFORE, datetimeZ);
TsgUtil.deleteItemOfObjectById(id, form);
} catch (Exception e) {
log.error("{}: failed to execute delete task. message: {}", id, e.getMessage());
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,157 @@
package com.geedge.scheduler;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.net.MaskBit;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.geedge.common.constant.TsgObject;
import com.geedge.common.enums.AddressFormat;
import com.geedge.common.util.TsgUtil;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* TODO
*
* @Classname Scheduler
* @Date 2024/1/2 11:31
* @Author wWei
*/
@Slf4j
@Component
public class IpScheduler {
public static List<String> excludeList = new ArrayList<>();
@Value("${tsg.object.ip.cyberghostvpn_serverip.id}")
private Integer cyberghostvpnServeripId;
@Value("${tsg.object.ip.cyberghostvpn_serverip.name}")
private String cyberghostvpnServeripName;
@Value("${tsg.object.ip.cyberghostvpn_serverip.update.enable}")
private Boolean cyberghostvpnServeripUpdateEnable;
@Value("${tsg.object.ip.cyberghostvpn_serverip.update.sql}")
private String cyberghostvpnServeripSql;
@Value("${tsg.object.ip.cyberghostvpn_serverip.delete.enable}")
private Boolean cyberghostvpnServeripDeleteEnable;
@Value("${tsg.object.ip.cyberghostvpn_serverip.delete.offsetSecond}")
private Integer cyberghostvpnServeripOffsetSecond;
@Value("${tsg.object.ip.excludeValue}")
public void setExcludeList(String values) {
if (StrUtil.isBlank(values)) {
return;
}
excludeList = Arrays.asList(values.split(","));
}
@Scheduled(cron = "${tsg.object.ip.cyberghostvpn_serverip.update.cron}")
public void scheduledExecutorUpdate() {
executeUpdate(cyberghostvpnServeripId, cyberghostvpnServeripName, cyberghostvpnServeripUpdateEnable, cyberghostvpnServeripSql);
}
@Scheduled(cron = "${tsg.object.ip.cyberghostvpn_serverip.delete.cron}")
public void scheduledExecutorDelete() {
executeDelete(cyberghostvpnServeripId, cyberghostvpnServeripDeleteEnable, cyberghostvpnServeripOffsetSecond);
}
private static void executeUpdate(Integer id, String name, Boolean enable, String sql) {
log.info("{}: started update task.", id);
if (BooleanUtil.isFalse(enable)) {
log.warn("{}: interrupted update task. enable: {}", id, enable);
return;
}
try {
Stopwatch watch = Stopwatch.createStarted();
List<Record> data = Db.find(sql);
log.info("{}: query knowledge base content, cost {} seconds", id, watch.elapsed(TimeUnit.SECONDS));
watch.reset().start();
List<Map<String, Object>> items = Lists.newArrayList();
row:
for (Record record : data) {
Map<String, Object> item = Maps.newHashMap();
String addressFormat = record.get("addrFormat");
String ip1 = record.get("ip1");
for (String s : excludeList) {
if (s.equals(ip1)) {
continue row;
}
if (s.endsWith("*") && ip1.startsWith(s.replace("*", ""))) {
continue row;
}
}
String ip2 = record.get("ip2");
Map<String, Object> ip = Maps.newHashMap();
if (AddressFormat.CIDR.getValue().equalsIgnoreCase(addressFormat)) {
int maskBit = Integer.parseInt(ip2);
String mask = MaskBit.get(Integer.parseInt(ip2));
String beginIpStr = Ipv4Util.getBeginIpStr(ip1, maskBit);
String ipMask = Ipv4Util.formatIpBlock(beginIpStr, mask);
ip.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP_IP_CIDR, ipMask);
} else if (AddressFormat.RANGE.getValue().equalsIgnoreCase(addressFormat)) {
ip.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP_IP_RANGE, ip1 + "-" + ip2);
} else {
ip.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP_IP_ADDRESS, ip1);
}
ip.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP_PORT_RANGE, TsgObject.VALUE_OBJECT_MEMBER_ITEMS_IP_PORT_RANGE);
InetAddress inetAddress = InetAddress.getByName(ip1);
if (inetAddress instanceof Inet4Address) {
ip.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP_ADDR_TYPE, 4);
} else if (inetAddress instanceof Inet6Address) {
ip.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP_ADDR_TYPE, 6);
}
item.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_OP, TsgObject.VALUE_OBJECT_MEMBER_ITEMS_OP_ADD);
item.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS_IP, ip);
items.add(item);
}
Map<String, Object> member = Maps.newHashMap();
member.put(TsgObject.KEY_OBJECT_MEMBER_TYPE, TsgObject.VALUE_OBJECT_MEMBER_TYPE_1);
member.put(TsgObject.KEY_OBJECT_MEMBER_ITEMS, items);
Map<String, Object> obj = Maps.newHashMap();
obj.put(TsgObject.KEY_OBJECT_NAME, name);
obj.put(TsgObject.KEY_OBJECT_TYPE, TsgObject.VALUE_OBJECT_TYPE_IP);
obj.put(TsgObject.KEY_OBJECT_MEMBER, member);
Map<String, Object> body = Maps.newHashMap();
body.put(TsgObject.KEY_VSYS_ID, TsgObject.VALUE_VSYS_ID_1);
body.put(TsgObject.KEY_OBJECT, obj);
log.info("{}: build api params, items size: {}, cost {} seconds", id, items.size(), watch.elapsed(TimeUnit.SECONDS));
TsgUtil.updateObjectById(id, body);
} catch (Exception e) {
log.error("{}: failed to execute update task. message: {}", id, e.getMessage());
throw new RuntimeException(e);
}
}
private static void executeDelete(Integer id, Boolean enable, Integer offsetSecond) {
log.info("{}: started delete task.", id);
if (BooleanUtil.isFalse(enable)) {
log.warn("{}: interrupted delete task. enable: {}", id, enable);
return;
}
try {
DateTime dateTime = DateUtil.offsetSecond(new Date(), offsetSecond).setTimeZone(TimeZone.getTimeZone("UTC"));
String datetimeZ = DateUtil.format(dateTime, DatePattern.UTC_PATTERN);
Map<String, Object> form = Maps.newHashMap();
form.put(TsgObject.KEY_OBJECT_TYPE, TsgObject.VALUE_OBJECT_TYPE_IP);
form.put(TsgObject.KEY_VSYS_ID, TsgObject.VALUE_VSYS_ID_1);
form.put(TsgObject.KEY_CREATED_BEFORE, datetimeZ);
TsgUtil.deleteItemOfObjectById(id, form);
} catch (Exception e) {
log.error("{}: failed to execute delete task. message: {}", id, e.getMessage());
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,6 @@
_ _ _ _ _ _
___ _ __ ___ | |__ (_) ___ ___| |_ ___ ___| |__ ___ __| |_ _| | ___ _ __
/ __| '_ \ / _ \| '_ \| |/ _ \/ __| __| / __|/ __| '_ \ / _ \/ _` | | | | |/ _ \ '__|
| (__| | | | | (_) | |_) | | __/ (__| |_ \__ \ (__| | | | __/ (_| | |_| | | __/ |
\___|_| |_| \___/|_.__// |\___|\___|\__| |___/\___|_| |_|\___|\__,_|\__,_|_|\___|_|
|__/ springboot${spring-boot.formatted-version}

View File

@@ -0,0 +1,13 @@
package com.geedge.scheduler;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CnPolicySchedulerApplicationTests {
@Test
void contextLoads() {
}
}