feat(syslog): 完成高吞吐可靠链路与统计存储优化
- 新增接入 WAL、检查点、背压恢复及可靠分发机制,完善 Kafka 幂等发布、分区、重试、DLT 和补偿流程 - 引入规则预编译、批内快照及 JetCache/Caffeine 两级缓存,支持缓存失效广播、影子对账和执行指标 - 升级 InfluxDB V2 原始日志模型,统一接收时间与 Point 时间,支持按日 measurement、UUID 分桶及 V1/V2 双读 - 重构达梦标准化批量写入与统计链路,支持事务内直写、增量投影、幂等控制、窗口水位和日期切换 - 完善告警处理、配置校验、运行监控及测试覆盖
This commit is contained in:
Generated
-1
@@ -1 +0,0 @@
|
||||
security-xdr
|
||||
Generated
-17
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<annotationProcessing>
|
||||
<profile default="true" name="Default" enabled="true" />
|
||||
<profile name="Maven default annotation processors profile" enabled="true">
|
||||
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||
<outputRelativeToContentRoot value="true" />
|
||||
<module name="syslog-client" />
|
||||
<module name="syslog-consumer" />
|
||||
<module name="syslog-consumer-rule" />
|
||||
<module name="syslog-serve" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-13
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding">
|
||||
<file url="file://$PROJECT_DIR$" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/syslog-client" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/syslog-consumer" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/syslog-consumer-rule" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/syslog-consumer/docker_run.txt" charset="GBK" />
|
||||
<file url="file://$PROJECT_DIR$/syslog-serve" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/syslog-serve/docker_run.txt" charset="GBK" />
|
||||
<file url="PROJECT" charset="GBK" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-14
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="MavenProjectsManager">
|
||||
<option name="originalFiles">
|
||||
<list>
|
||||
<option value="$PROJECT_DIR$/pom.xml" />
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-1596
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
java=8.0.392-zulu
|
||||
@@ -1,9 +1,9 @@
|
||||
2026-05-14 08:53:15.386 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.haobang.syslog.SysjavacollectApplicationTests], using SpringBootContextLoader
|
||||
2026-05-14 08:53:15.400 [main] INFO o.s.t.c.s.AbstractContextLoader - Could not detect default resource locations for test class [com.haobang.syslog.SysjavacollectApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
|
||||
2026-05-14 08:53:15.401 [main] INFO o.s.t.c.s.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.haobang.syslog.SysjavacollectApplicationTests]: SysjavacollectApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
|
||||
2026-05-14 08:53:15.555 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.haobang.syslog.syslogClientApplication for test class com.haobang.syslog.SysjavacollectApplicationTests
|
||||
2026-05-14 08:53:15.765 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
|
||||
2026-05-14 08:53:15.782 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@748741cb, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@3e44f2a5, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@295cf707, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@1130520d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5f77d0f9, org.springframework.test.context.event.EventPublishingTestExecutionListener@463fd068, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@895e367, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@1b266842, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@7a3793c7, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@42b3b079, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@651aed93, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@4dd6fd0a]
|
||||
2026-05-14 08:53:16.222 [main] INFO c.h.s.SysjavacollectApplicationTests - Starting SysjavacollectApplicationTests using Java 1.8.0_121 on LAPTOP-ARDUR3N0 with PID 20672 (started by chenc in E:\GIT_GOSAME\ai-security-xdr\haobang-security-xdr\syslog-client)
|
||||
2026-05-14 08:53:16.223 [main] INFO c.h.s.SysjavacollectApplicationTests - No active profile set, falling back to 1 default profile: "default"
|
||||
2026-05-14 08:53:17.046 [main] INFO c.h.s.SysjavacollectApplicationTests - Started SysjavacollectApplicationTests in 1.201 seconds (JVM running for 2.913)
|
||||
2026-08-15 04:48:58.158 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.haobang.syslog.SysjavacollectApplicationTests], using SpringBootContextLoader
|
||||
2026-08-15 04:48:58.162 [main] INFO o.s.t.c.s.AbstractContextLoader - Could not detect default resource locations for test class [com.haobang.syslog.SysjavacollectApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
|
||||
2026-08-15 04:48:58.162 [main] INFO o.s.t.c.s.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.haobang.syslog.SysjavacollectApplicationTests]: SysjavacollectApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
|
||||
2026-08-15 04:48:58.225 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.haobang.syslog.syslogClientApplication for test class com.haobang.syslog.SysjavacollectApplicationTests
|
||||
2026-08-15 04:48:58.288 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
|
||||
2026-08-15 04:48:58.294 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@22f59fa, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@78fa769e, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@16612a51, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@54e041a4, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2c78324b, org.springframework.test.context.event.EventPublishingTestExecutionListener@79defdc, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@18317edc, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@4e0ae11f, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@238d68ff, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@4b86805d, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@5852c06f, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@4149c063]
|
||||
2026-08-15 04:48:58.433 [main] INFO c.h.s.SysjavacollectApplicationTests - Starting SysjavacollectApplicationTests using Java 1.8.0_392 on wangshaohongdeMacBook-Pro.local with PID 34847 (started by wangshaohong in /Users/wangshaohong/WorkSpace/fufeng/ai-security-xdr/haobang-security-dm/syslog-client)
|
||||
2026-08-15 04:48:58.434 [main] INFO c.h.s.SysjavacollectApplicationTests - No active profile set, falling back to 1 default profile: "default"
|
||||
2026-08-15 04:48:58.712 [main] INFO c.h.s.SysjavacollectApplicationTests - Started SysjavacollectApplicationTests in 0.397 seconds (JVM running for 0.904)
|
||||
|
||||
+27
-7
@@ -20,6 +20,11 @@ services:
|
||||
# 环境配置
|
||||
- SPRING_PROFILES_ACTIVE=prod
|
||||
- TZ=Asia/Shanghai
|
||||
# 全停升级且已完成增量统计 DDL/基线后,所有 rule 节点统一开启捕获。
|
||||
- STATS_INCREMENTAL_CAPTURE_ENABLED=true
|
||||
- STATS_INGRESS_METADATA_ENABLED=true
|
||||
- STATS_INCREMENTAL_READ_ENABLED=true
|
||||
- STATS_DEVICE_RECEIVE_CHANGE_CAPTURE_ENABLED=false
|
||||
# 数据库配置
|
||||
- SPRING_DATASOURCE_URL=jdbc:dm://192.168.4.99:5237
|
||||
- SPRING_DATASOURCE_USERNAME=SYSDBA
|
||||
@@ -43,13 +48,21 @@ services:
|
||||
- SPRING_REDIS_TIMEOUT=2000
|
||||
- SPRING_CACHE_REDIS_TIME-TO-LIVE=600000
|
||||
# Kafka配置
|
||||
- SPRING_KAFKA_CONSUMER_BOOTSTRAP-SERVERS=192.168.4.99:9092
|
||||
- SPRING_KAFKA_CONSUMER_GROUP-ID=agent-01-syslog-group-dm
|
||||
- SPRING_KAFKA_CONSUMER_AUTO-OFFSET-RESET=latest
|
||||
- SPRING_KAFKA_CONSUMER_ENABLE-AUTO-COMMIT=false
|
||||
- SPRING_KAFKA_CONSUMER_BOOTSTRAP_SERVERS=192.168.4.99:9092
|
||||
# 保留客户现有生产消费组名称,多节点必须完全一致,不可临时换组。
|
||||
- SPRING_KAFKA_CONSUMER_GROUP_ID=agent-01-syslog-group-dm
|
||||
- SPRING_KAFKA_CONSUMER_AUTO_OFFSET_RESET=latest
|
||||
- SPRING_KAFKA_CONSUMER_ENABLE_AUTO_COMMIT=false
|
||||
- SPRING_KAFKA_CONSUMER_TOPIC=agent-01-syslog-topic
|
||||
- SPRING_KAFKA_CONSUMER_MAX-POLL-RECORDS=1000
|
||||
- SPRING_KAFKA_LISTENER_ACK-MODE=manual
|
||||
# consumer-rule 是活跃原始日志消费节点,多实例通过同一消费组分担分区。
|
||||
- SYSLOG_RAW_CONSUMER_ENABLED=true
|
||||
# Retry/Replay 与 Raw 隔离,避免未到期重试占用实时消费线程。
|
||||
- SYSLOG_RELIABILITY_CONSUMER_GROUP_ID=agent-01-syslog-group-dm-retry
|
||||
- SYSLOG_RELIABILITY_CONSUMER_ENABLED=true
|
||||
- SYSLOG_RELIABILITY_LISTENER_CONCURRENCY=1
|
||||
- SPRING_KAFKA_CONSUMER_MAX_POLL_RECORDS=500
|
||||
- SPRING_KAFKA_CONSUMER_PROPERTIES_MAX_POLL_INTERVAL_MS=900000
|
||||
- SPRING_KAFKA_LISTENER_ACK_MODE=manual
|
||||
- SPRING_KAFKA_LISTENER_CONCURRENCY=2
|
||||
- SPRING_KAFKA_LISTENER_TYPE=batch
|
||||
# InfluxDB配置
|
||||
@@ -57,6 +70,14 @@ services:
|
||||
- INFLUXDB_TOKEN=JsUyvU8vhQEFlMM_el4Drm87fyh707IhwJNsPBucPghSdbVmdQ-UvmPcyP5NTzWxsRfEz0T51Rw4ebZUuUrmZg==
|
||||
- INFLUXDB_ORG=influxdb
|
||||
- INFLUXDB_BUCKET=yelangbucket
|
||||
- INFLUXDB_RAW_WRITE_SCHEMA=V2
|
||||
- INFLUXDB_RAW_READ_MODE=V1_V2
|
||||
- INFLUXDB_RAW_V1_BUCKET=yelangbucket
|
||||
- INFLUXDB_RAW_V2_BUCKET=yelangbucket_v2
|
||||
- INFLUXDB_RAW_UUID_BUCKET_COUNT=4096
|
||||
- INFLUXDB_RAW_LEGACY_POINT_TIME_FALLBACK_ENABLED=true
|
||||
- INFLUXDB_RAW_QUERY_MAX_ROWS=10000
|
||||
- INFLUXDB_RAW_QUERY_MAX_RESPONSE_BYTES=10485760
|
||||
- INFLUXDB_BATCH_SIZE=1000
|
||||
- INFLUXDB_FLUSH_INTERVAL=1000
|
||||
- INFLUXDB_CONNECTION_TIMEOUT=30s
|
||||
@@ -79,4 +100,3 @@ services:
|
||||
networks:
|
||||
xdr-network:
|
||||
driver: bridge
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<slf4j.version>1.7.36</slf4j.version>
|
||||
<logback.version>1.2.11</logback.version>
|
||||
<config.version>1.4.2</config.version>
|
||||
<junit.version>5.9.2</junit.version>
|
||||
<junit.jupiter.version>5.9.2</junit.jupiter.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
|
||||
@@ -26,6 +26,9 @@
|
||||
<mybatis.version>3.5.10</mybatis.version>
|
||||
<postgresql.version>42.5.4</postgresql.version>
|
||||
<pagehelper.version>1.4.6</pagehelper.version>
|
||||
<jetcache.version>2.7.8</jetcache.version>
|
||||
<caffeine.version>2.9.3</caffeine.version>
|
||||
<kryo5.version>5.5.0</kryo5.version>
|
||||
</properties>
|
||||
<description>syslog-consumer-rule</description>
|
||||
<packaging>jar</packaging>
|
||||
@@ -46,18 +49,12 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.kafka</groupId>
|
||||
<artifactId>kafka-clients</artifactId>
|
||||
<version>3.9.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.kafka</groupId>
|
||||
<artifactId>spring-kafka</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>2.0.7</version>
|
||||
</dependency>
|
||||
<!-- InfluxDB Client for Java -->
|
||||
<dependency>
|
||||
<groupId>com.influxdb</groupId>
|
||||
@@ -104,8 +101,8 @@
|
||||
<!-- 达梦数据库驱动 JDK1.8 -->
|
||||
<dependency>
|
||||
<groupId>com.dameng</groupId>
|
||||
<artifactId>DmJdbcDriver</artifactId>
|
||||
<version>8.1.4.169</version>
|
||||
<artifactId>DmJdbcDriver18</artifactId>
|
||||
<version>8.1.2.141</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
@@ -169,6 +166,26 @@
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--
|
||||
Java 8 / Spring Boot 2.7 compatible JetCache line. Keep this version fixed:
|
||||
CompiledRule itself is local-only, while rule/device enrichment source caches use BOTH.
|
||||
-->
|
||||
<dependency>
|
||||
<groupId>com.alicp.jetcache</groupId>
|
||||
<artifactId>jetcache-starter-redis-lettuce</artifactId>
|
||||
<version>${jetcache.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
<version>${caffeine.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.esotericsoftware.kryo</groupId>
|
||||
<artifactId>kryo5</artifactId>
|
||||
<version>${kryo5.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
@@ -197,7 +214,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -226,4 +243,67 @@
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>cache-it</id>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<version>1.19.8</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>1.19.8</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-cache-integration-tests</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals><goal>add-test-source</goal></goals>
|
||||
<configuration>
|
||||
<sources><source>src/cache-it/java</source></sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals><goal>integration-test</goal><goal>verify</goal></goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
</project>
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.testcontainers.containers.GenericContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
@Testcontainers
|
||||
abstract class AbstractJetCacheRedisIntegrationTest {
|
||||
@Container
|
||||
static final GenericContainer<?> REDIS = new GenericContainer<>(DockerImageName.parse("redis:7.2-alpine"))
|
||||
.withExposedPorts(6379);
|
||||
|
||||
ConfigurableApplicationContext first;
|
||||
ConfigurableApplicationContext second;
|
||||
|
||||
@BeforeEach
|
||||
void startContexts() {
|
||||
first = context();
|
||||
second = context();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void closeContexts() {
|
||||
if (second != null) second.close();
|
||||
if (first != null) first.close();
|
||||
}
|
||||
|
||||
ConfigurableApplicationContext context() {
|
||||
String uri = "redis://" + REDIS.getHost() + ':' + REDIS.getMappedPort(6379) + "/15";
|
||||
return new SpringApplicationBuilder(CacheItApplication.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("jetcache.statIntervalMinutes=0",
|
||||
"jetcache.areaInCacheName=false",
|
||||
"jetcache.penetrationProtect=true",
|
||||
"jetcache.enableMethodCache=true",
|
||||
"jetcache.local.default.type=caffeine",
|
||||
"jetcache.local.default.keyConvertor=fastjson2",
|
||||
"jetcache.remote.default.type=redis.lettuce",
|
||||
"jetcache.remote.default.keyConvertor=fastjson2",
|
||||
"jetcache.remote.default.serialPolicy=KRYO5",
|
||||
"jetcache.remote.default.broadcastChannel=xdr:norm:v1:cache-invalidate",
|
||||
"jetcache.remote.default.uri.0=" + uri)
|
||||
.run();
|
||||
}
|
||||
|
||||
CacheItApplication.CacheItFacade facade(ConfigurableApplicationContext context) {
|
||||
return context.getBean(CacheItApplication.CacheItFacade.class);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.alicp.jetcache.anno.CacheType;
|
||||
import com.alicp.jetcache.anno.Cached;
|
||||
import com.alicp.jetcache.anno.CacheInvalidate;
|
||||
import com.alicp.jetcache.anno.SerialPolicy;
|
||||
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
|
||||
import com.alicp.jetcache.anno.config.EnableMethodCache;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@EnableMethodCache(basePackages = "com.Modules.NormalData.cache")
|
||||
@EnableCreateCacheAnnotation
|
||||
class CacheItApplication {
|
||||
@Bean CacheItFacade cacheItFacade() { return new CacheItFacade(); }
|
||||
|
||||
static final class CacheItFacade {
|
||||
private final AtomicInteger loads = new AtomicInteger();
|
||||
|
||||
@Cached(name = "xdr:norm:v1:cache-it:", key = "#key", cacheType = CacheType.BOTH,
|
||||
expire = 60, localExpire = 60, timeUnit = TimeUnit.SECONDS,
|
||||
localLimit = 100, syncLocal = true, serialPolicy = SerialPolicy.KRYO5)
|
||||
public Object get(String key, Object loadedValue) {
|
||||
loads.incrementAndGet();
|
||||
return loadedValue;
|
||||
}
|
||||
|
||||
@CacheInvalidate(name = "xdr:norm:v1:cache-it:", key = "#key")
|
||||
public void invalidate(String key) { }
|
||||
|
||||
int loads() { return loads.get(); }
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class JetCacheCrossContextInvalidationIntegrationTest extends AbstractJetCacheRedisIntegrationTest {
|
||||
@Test
|
||||
void invalidationBroadcastRemovesOtherContextsLocalEntry() throws Exception {
|
||||
facade(first).get("broadcast", "before");
|
||||
assertEquals("before", facade(second).get("broadcast", "unused"));
|
||||
facade(first).invalidate("broadcast");
|
||||
Thread.sleep(300L);
|
||||
assertEquals("after", facade(second).get("broadcast", "after"));
|
||||
assertEquals(1, facade(second).loads());
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class JetCacheRedisFailureIntegrationTest extends AbstractJetCacheRedisIntegrationTest {
|
||||
@Test
|
||||
void cacheFailureDoesNotReturnAFalseNullBusinessValue() {
|
||||
REDIS.getDockerClient().pauseContainerCmd(REDIS.getContainerId()).exec();
|
||||
RuntimeException failure = null;
|
||||
Object value = null;
|
||||
try {
|
||||
value = facade(first).get("redis-down", "database-value");
|
||||
} catch (RuntimeException expected) {
|
||||
failure = expected;
|
||||
} finally {
|
||||
REDIS.getDockerClient().unpauseContainerCmd(REDIS.getContainerId()).exec();
|
||||
}
|
||||
// JetCache 2.7 may fail-open or propagate according to error handler; either path must be explicit.
|
||||
if (failure != null) {
|
||||
assertNotNull(failure.getCause());
|
||||
} else {
|
||||
assertEquals("database-value", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.RuleSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class JetCacheSerializationIntegrationTest extends AbstractJetCacheRedisIntegrationTest {
|
||||
@Test
|
||||
void immutableSnapshotRoundTripsAcrossContextsWithKryo5() {
|
||||
RuleSourceSnapshot source = new RuleSourceSnapshot(7L, Collections.singletonList(
|
||||
new RuleSource(9L, "rule", "Rule", "json", "{\"mappers\":[]}", true, "0")),
|
||||
Instant.EPOCH);
|
||||
facade(first).get("snapshot", source);
|
||||
RuleSourceSnapshot decoded = (RuleSourceSnapshot) facade(second).get("snapshot", null);
|
||||
assertEquals(7L, decoded.getDeviceId());
|
||||
assertEquals(source.getRules().get(0).getFingerprint(), decoded.getRules().get(0).getFingerprint());
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class JetCacheTwoLevelIntegrationTest extends AbstractJetCacheRedisIntegrationTest {
|
||||
@Test
|
||||
void secondContextReadsFirstContextRemoteValueThenItsOwnL1() {
|
||||
assertEquals("from-a", facade(first).get("two-level", "from-a"));
|
||||
assertEquals("from-a", facade(second).get("two-level", "from-b"));
|
||||
assertEquals("from-a", facade(second).get("two-level", "from-c"));
|
||||
assertEquals(0, facade(second).loads());
|
||||
}
|
||||
}
|
||||
+558
-99
@@ -1,8 +1,7 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import cn.hutool.core.date.DateTime;
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import com.Modules.NormalData.compiled.*;
|
||||
import com.common.entity.RuleContent.*;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import com.common.mapper.DmColumnMapper;
|
||||
@@ -11,6 +10,8 @@ import com.common.service.*;
|
||||
import com.common.util.*;
|
||||
import com.config.AppProperties;
|
||||
import com.config.KafkaConsumerProperties;
|
||||
import com.config.NormalizationOptimizationProperties;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.json.JSONObject;
|
||||
@@ -19,7 +20,15 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import com.common.entity.SyslogMessage;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* 日志标准化处理器(规则引擎模块 - Spring 管理的单例 Bean)
|
||||
@@ -27,6 +36,45 @@ import java.util.*;
|
||||
*/
|
||||
@Service
|
||||
public class LogNormalProcessor {
|
||||
|
||||
public enum ProcessingOutcome { SUCCESS, FILTERED }
|
||||
|
||||
/**
|
||||
* 一条原始日志完成规则计算后的纯结果。
|
||||
*
|
||||
* <p>这里故意只保存“应该写什么”,不负责“怎样写入达梦”。活动 Kafka 链路会先并行产生
|
||||
* 多个 {@code NormalizationResult},再由专用批写器集中提交。这样计算线程不会继续执行
|
||||
* 每行一个事务,同时旧的 {@link #process(String, String, String, LocalDateTime)} 入口仍可按
|
||||
* 单条模式兼容历史调用方。</p>
|
||||
*/
|
||||
public static final class NormalizationResult {
|
||||
private final ProcessingOutcome outcome;
|
||||
private final List<Map<String, Object>> rows;
|
||||
|
||||
private NormalizationResult(ProcessingOutcome outcome, List<Map<String, Object>> rows) {
|
||||
this.outcome = outcome;
|
||||
this.rows = Collections.unmodifiableList(new ArrayList<>(rows));
|
||||
}
|
||||
|
||||
static NormalizationResult success(List<Map<String, Object>> rows) {
|
||||
return new NormalizationResult(ProcessingOutcome.SUCCESS, rows);
|
||||
}
|
||||
|
||||
static NormalizationResult filtered() {
|
||||
return new NormalizationResult(ProcessingOutcome.FILTERED, Collections.emptyList());
|
||||
}
|
||||
|
||||
public ProcessingOutcome getOutcome() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getRows() {
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
||||
private static final ZoneId RECEIVE_TIME_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final String LEGACY_RULE_VERSION = "legacy";
|
||||
private static final Logger logger = LoggerFactory.getLogger(LogNormalProcessor.class);
|
||||
|
||||
// ==================== 依赖注入(Spring Bean,单例,线程安全)====================
|
||||
@@ -42,6 +90,12 @@ public class LogNormalProcessor {
|
||||
private final DmNormalizeRuleMapper dmNormalizeRuleMapper;
|
||||
private final KafkaConsumerProperties kafkaConsumerProperties;
|
||||
private final AppProperties appProperties;
|
||||
private final CompiledRuleCache compiledRuleCache;
|
||||
private final NormalizationOptimizationProperties optimizationProperties;
|
||||
private final NormalizationShadowComparator shadowComparator;
|
||||
private final NormalizationShadowExecutor shadowExecutor;
|
||||
private final NormalizationRuleMetrics globalMetrics;
|
||||
private final Map<String, AtomicLong> shadowLogWindows = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 请求级处理上下文 —— 每个 process() 调用创建新实例,彻底解决多线程竞态条件
|
||||
@@ -55,15 +109,25 @@ public class LogNormalProcessor {
|
||||
Map<String, String> deviceInfoMap;
|
||||
String strSyslogUUID;
|
||||
String strSyslogTopic;
|
||||
LocalDateTime fallbackFirstReceivedAt;
|
||||
LocalDateTime initialReceivedAt;
|
||||
boolean isSaveNonNormal = false;
|
||||
SyslogNonNormalMessage syslogNonNormalMessage = new SyslogNonNormalMessage();
|
||||
List<Map<String, Object>> dmNormalizeRuleList;
|
||||
List<RuleSource> dmNormalizeRuleList;
|
||||
List<Map<String, Object>> dmColumnList;
|
||||
LinkedHashMap<String, Object> OrginalColumnMap;
|
||||
int savedCount;
|
||||
int filteredCount;
|
||||
int rejectedCount;
|
||||
BatchRuleSnapshot batchRuleSnapshot;
|
||||
BatchEnrichmentContext batchEnrichmentContext;
|
||||
RuleExecutionMetrics executionMetrics;
|
||||
MessageParseContext messageParseContext;
|
||||
boolean shadowMode;
|
||||
final List<Map<String, Object>> normalizedRows = new ArrayList<>();
|
||||
}
|
||||
|
||||
// ==================== 构造器注入(Spring 自动完成)====================
|
||||
@Autowired
|
||||
public LogNormalProcessor(
|
||||
DmNormalizeRuleService dmNormalizeRuleService,
|
||||
DmColumnService dmColumnService,
|
||||
@@ -77,6 +141,56 @@ public class LogNormalProcessor {
|
||||
DmNormalizeRuleMapper dmNormalizeRuleMapper,
|
||||
KafkaConsumerProperties kafkaConsumerProperties,
|
||||
AppProperties appProperties
|
||||
) {
|
||||
this(dmNormalizeRuleService, dmColumnService, syslogNormalDataService, messageService,
|
||||
logDataFilterService, logDataCompleteService, deviceCollectTaskService,
|
||||
deviceDeviceService, dmColumnMapper, dmNormalizeRuleMapper, kafkaConsumerProperties,
|
||||
appProperties, defaultCompiledRuleCache(), new NormalizationOptimizationProperties());
|
||||
}
|
||||
|
||||
public LogNormalProcessor(
|
||||
DmNormalizeRuleService dmNormalizeRuleService,
|
||||
DmColumnService dmColumnService,
|
||||
SyslogNormalDataService syslogNormalDataService,
|
||||
SyslogNonNormalMessageService messageService,
|
||||
LogDataFilterService logDataFilterService,
|
||||
LogDataCompleteService logDataCompleteService,
|
||||
DeviceCollectTaskService deviceCollectTaskService,
|
||||
DeviceDeviceService deviceDeviceService,
|
||||
DmColumnMapper dmColumnMapper,
|
||||
DmNormalizeRuleMapper dmNormalizeRuleMapper,
|
||||
KafkaConsumerProperties kafkaConsumerProperties,
|
||||
AppProperties appProperties,
|
||||
CompiledRuleCache compiledRuleCache,
|
||||
NormalizationOptimizationProperties optimizationProperties
|
||||
) {
|
||||
this(dmNormalizeRuleService, dmColumnService, syslogNormalDataService, messageService,
|
||||
logDataFilterService, logDataCompleteService, deviceCollectTaskService,
|
||||
deviceDeviceService, dmColumnMapper, dmNormalizeRuleMapper, kafkaConsumerProperties,
|
||||
appProperties, compiledRuleCache, optimizationProperties,
|
||||
new NormalizationShadowComparator(), new NormalizationShadowExecutor(),
|
||||
new NormalizationRuleMetrics());
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public LogNormalProcessor(
|
||||
DmNormalizeRuleService dmNormalizeRuleService,
|
||||
DmColumnService dmColumnService,
|
||||
SyslogNormalDataService syslogNormalDataService,
|
||||
SyslogNonNormalMessageService messageService,
|
||||
LogDataFilterService logDataFilterService,
|
||||
LogDataCompleteService logDataCompleteService,
|
||||
DeviceCollectTaskService deviceCollectTaskService,
|
||||
DeviceDeviceService deviceDeviceService,
|
||||
DmColumnMapper dmColumnMapper,
|
||||
DmNormalizeRuleMapper dmNormalizeRuleMapper,
|
||||
KafkaConsumerProperties kafkaConsumerProperties,
|
||||
AppProperties appProperties,
|
||||
CompiledRuleCache compiledRuleCache,
|
||||
NormalizationOptimizationProperties optimizationProperties,
|
||||
NormalizationShadowComparator shadowComparator,
|
||||
NormalizationShadowExecutor shadowExecutor,
|
||||
NormalizationRuleMetrics globalMetrics
|
||||
) {
|
||||
this.dmNormalizeRuleService = dmNormalizeRuleService;
|
||||
this.dmColumnService = dmColumnService;
|
||||
@@ -90,6 +204,16 @@ public class LogNormalProcessor {
|
||||
this.dmNormalizeRuleMapper = dmNormalizeRuleMapper;
|
||||
this.kafkaConsumerProperties = kafkaConsumerProperties;
|
||||
this.appProperties = appProperties;
|
||||
this.compiledRuleCache = compiledRuleCache;
|
||||
this.optimizationProperties = optimizationProperties;
|
||||
this.shadowComparator = shadowComparator;
|
||||
this.shadowExecutor = shadowExecutor;
|
||||
this.globalMetrics = globalMetrics;
|
||||
}
|
||||
|
||||
private static CompiledRuleCache defaultCompiledRuleCache() {
|
||||
NormalizationOptimizationProperties properties = new NormalizationOptimizationProperties();
|
||||
return new CompiledRuleCache(new CompiledRuleCompiler(new ObjectMapper()), properties);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -99,15 +223,67 @@ public class LogNormalProcessor {
|
||||
* @param syslogUUID 消息UUID
|
||||
* @param syslogTopic 消息Topic(可传 null,自动使用配置值)
|
||||
*/
|
||||
public void process(String logMsg, String syslogUUID, String syslogTopic) {
|
||||
public ProcessingOutcome process(String logMsg, String syslogUUID, String syslogTopic) {
|
||||
return process(logMsg, syslogUUID, syslogTopic, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理一条日志,并显式传入 Kafka 链路已解析好的首次接收时间。
|
||||
*
|
||||
* <p>该时间会同时写入标准化表的 created_at 和 log_time。created_at 表示日志首次进入系统,
|
||||
* log_time 是现场标准化表的 RANGE 分区键。原始业务代码用本次处理时间覆盖 log_time;这里改为
|
||||
* 稳定的首次接收时间,使 Raw、Retry 和 Replay 始终进入同一日分区。设备事件时间继续由
|
||||
* collect_time_ts 保存,不与分区时间混用。</p>
|
||||
*/
|
||||
public ProcessingOutcome process(String logMsg, String syslogUUID, String syslogTopic,
|
||||
LocalDateTime fallbackFirstReceivedAt) {
|
||||
NormalizationResult result = prepare(logMsg, syslogUUID, syslogTopic, fallbackFirstReceivedAt);
|
||||
|
||||
// 兼容历史的命令行/测试入口:这些调用方没有 Kafka 批次边界,只能继续逐条落库。
|
||||
// 当前生产活跃的 SysLogProcessor 不走这里,而是调用 prepare() 后统一批写。
|
||||
for (Map<String, Object> row : result.getRows()) {
|
||||
syslogNormalDataService.insertDynamic(row);
|
||||
}
|
||||
return result.getOutcome();
|
||||
}
|
||||
|
||||
/**
|
||||
* 只执行标准化计算并返回待写入行,不在本方法中写两张标准化表。
|
||||
*
|
||||
* <p>这是批量写入的关键边界:并行线程只负责 CPU/规则计算,达梦事务由 Kafka 批次汇总后的
|
||||
* 批写器统一管理。非标日志仍沿用原有独立保存路径,不属于本次两张标准化表的改造范围。</p>
|
||||
*/
|
||||
public NormalizationResult prepare(String logMsg, String syslogUUID, String syslogTopic,
|
||||
LocalDateTime fallbackFirstReceivedAt) {
|
||||
return prepare(logMsg, syslogUUID, syslogTopic, fallbackFirstReceivedAt,
|
||||
null, new BatchEnrichmentContext(false, deviceCollectTaskService, deviceDeviceService),
|
||||
new RuleExecutionMetrics());
|
||||
}
|
||||
|
||||
/** 活动 Kafka 链路入口:显式使用当前 poll 的规则快照、补全上下文和聚合指标。 */
|
||||
public NormalizationResult prepare(String logMsg, String syslogUUID, String syslogTopic,
|
||||
LocalDateTime fallbackFirstReceivedAt,
|
||||
BatchRuleSnapshot batchRuleSnapshot,
|
||||
BatchEnrichmentContext batchEnrichmentContext,
|
||||
RuleExecutionMetrics executionMetrics) {
|
||||
// [流程节点6] 按设备加载标准化规则,完成字段解析、映射、过滤、补全和数据质量检查。
|
||||
ProcessContext ctx = new ProcessContext();
|
||||
ctx.strSyslogUUID = syslogUUID;
|
||||
ctx.strSyslogTopic = (syslogTopic != null && !syslogTopic.isEmpty())
|
||||
? syslogTopic
|
||||
: kafkaConsumerProperties.getTopic();
|
||||
ctx.fallbackFirstReceivedAt = fallbackFirstReceivedAt;
|
||||
ctx.isSaveNonNormal = false;
|
||||
ctx.syslogNonNormalMessage = new SyslogNonNormalMessage();
|
||||
ctx.batchRuleSnapshot = batchRuleSnapshot;
|
||||
ctx.batchEnrichmentContext = batchEnrichmentContext == null
|
||||
? new BatchEnrichmentContext(false, deviceCollectTaskService, deviceDeviceService)
|
||||
: batchEnrichmentContext;
|
||||
ctx.executionMetrics = executionMetrics == null ? new RuleExecutionMetrics() : executionMetrics;
|
||||
ctx.messageParseContext = new MessageParseContext(
|
||||
optimizationProperties.getMessageParseCache().isEnabled(), globalMetrics);
|
||||
|
||||
// [流程节点6.1] 拆分 Kafka 完整消息,分别得到设备元数据头和实际 Syslog 正文。
|
||||
// 解析消息
|
||||
ctx.strKafkaMessage = logMsg;
|
||||
if (!logMsg.isEmpty()) {
|
||||
@@ -120,68 +296,285 @@ public class LogNormalProcessor {
|
||||
}
|
||||
|
||||
// 执行处理
|
||||
init(ctx);
|
||||
return init(ctx);
|
||||
}
|
||||
|
||||
/** 活动 Kafka 链路使用已经解析好的 envelope,避免并行任务重复解析消息头。 */
|
||||
public NormalizationResult prepare(PreparedNormalizationInput input,
|
||||
BatchRuleSnapshot batchRuleSnapshot,
|
||||
BatchEnrichmentContext batchEnrichmentContext,
|
||||
RuleExecutionMetrics executionMetrics) {
|
||||
ProcessContext ctx = new ProcessContext();
|
||||
ctx.strSyslogUUID = input.getEventId();
|
||||
ctx.strSyslogTopic = input.getTopic() == null || input.getTopic().isEmpty()
|
||||
? kafkaConsumerProperties.getTopic() : input.getTopic();
|
||||
ctx.fallbackFirstReceivedAt = input.getReceivedAt();
|
||||
ctx.initialReceivedAt = input.getReceivedAt();
|
||||
ctx.strKafkaMessage = input.getFullMessage();
|
||||
ctx.strLogMsg = input.getSyslogBody();
|
||||
ctx.strDeviceInfo = input.getDeviceHeader();
|
||||
ctx.deviceInfoMap = input.getDeviceInfo();
|
||||
ctx.strDataType = input.getDataType();
|
||||
ctx.batchRuleSnapshot = batchRuleSnapshot;
|
||||
ctx.batchEnrichmentContext = batchEnrichmentContext == null
|
||||
? new BatchEnrichmentContext(false, deviceCollectTaskService, deviceDeviceService)
|
||||
: batchEnrichmentContext;
|
||||
ctx.executionMetrics = executionMetrics == null ? new RuleExecutionMetrics() : executionMetrics;
|
||||
ctx.messageParseContext = new MessageParseContext(
|
||||
optimizationProperties.getMessageParseCache().isEnabled(), globalMetrics);
|
||||
return init(ctx);
|
||||
}
|
||||
|
||||
public BatchRuleSnapshot captureRuleSnapshot(Set<Long> deviceIds) {
|
||||
Map<Long, List<RuleSource>> rules = new LinkedHashMap<>();
|
||||
if (deviceIds != null) {
|
||||
for (Long deviceId : deviceIds) {
|
||||
if (deviceId == null || deviceId <= 0) continue;
|
||||
rules.put(deviceId, rulesForDevice(deviceId));
|
||||
}
|
||||
}
|
||||
return new BatchRuleSnapshot(rules, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public BatchEnrichmentContext createBatchEnrichmentContext() {
|
||||
return new BatchEnrichmentContext(
|
||||
optimizationProperties.getBatchEnrichmentCache().isEnabled(),
|
||||
deviceCollectTaskService, deviceDeviceService, globalMetrics);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据处理(所有运行时状态通过 ctx 传递,线程安全)
|
||||
*/
|
||||
private void init(ProcessContext ctx) {
|
||||
Map<String, String> mapdev = SyslogParser.parseKeyValuePairs(ctx.strDeviceInfo);
|
||||
private NormalizationResult init(ProcessContext ctx) {
|
||||
// [流程节点6.2] 解析设备上下文,确定 device_id 和 data_type,作为选择标准化规则的依据。
|
||||
Map<String, String> mapdev = ctx.deviceInfoMap == null
|
||||
? SyslogParser.parseKeyValuePairs(ctx.strDeviceInfo) : ctx.deviceInfoMap;
|
||||
ctx.deviceInfoMap = mapdev;
|
||||
if (ctx.initialReceivedAt == null) {
|
||||
ctx.initialReceivedAt = resolveInitialReceivedAt(
|
||||
mapdev.get("receive_time"), ctx.fallbackFirstReceivedAt);
|
||||
}
|
||||
long deviceID = Long.parseLong(mapdev.get("device_id"));
|
||||
System.out.println("device_id:" + deviceID);
|
||||
logger.debug("标准化开始: eventId={}, deviceId={}", ctx.strSyslogUUID, deviceID);
|
||||
ctx.strDataType = mapdev.get("data_type");
|
||||
try {
|
||||
if (deviceID > 0) {
|
||||
ctx.dmNormalizeRuleList = dmNormalizeRuleService.selectByDeviceIdAuto(deviceID);
|
||||
ctx.dmNormalizeRuleList = ctx.batchRuleSnapshot == null
|
||||
? rulesForDevice(deviceID) : ctx.batchRuleSnapshot.rulesFor(deviceID);
|
||||
}
|
||||
for (int i = 0; i < ctx.dmNormalizeRuleList.size(); i++) {
|
||||
try {
|
||||
Map<String, Object> dmNormalizeRule = ctx.dmNormalizeRuleList.get(i);
|
||||
String data_type = dmNormalizeRule.get("data_type").toString();
|
||||
System.out.println("索引: " + i + ", 值: " + dmNormalizeRule);
|
||||
System.out.println("normalrule ID: " + dmNormalizeRule.get("id")
|
||||
+ ", display_name:" + dmNormalizeRule.get("display_name")
|
||||
+ " data_type:" + dmNormalizeRule.get("data_type"));
|
||||
|
||||
ctx.OrginalColumnMap = getMessageToMap(dmNormalizeRule, ctx.strLogMsg, data_type);
|
||||
if ((ctx.OrginalColumnMap == null) || (ctx.OrginalColumnMap.size() == 0)) {
|
||||
logger.error("OrginalColumnMap 对象获取为空");
|
||||
ctx.syslogNonNormalMessage.setReason("Log解析异常");
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("log解析异常,返回规则名称:"
|
||||
+ dmNormalizeRule.get("display_name") + ",OrginalColumnMap 对象获取为空");
|
||||
if (ctx.isSaveNonNormal == false)
|
||||
SaveNonNormalMessage(ctx, deviceID, DateTime.now());
|
||||
continue;
|
||||
}
|
||||
List<HashMap<String, Object>> destColumnList = getRuleContentMappers(dmNormalizeRule);
|
||||
List<HashMap<String, Object>> ruleColumnList = getNormalColumnList(ctx.OrginalColumnMap, destColumnList);
|
||||
Map<String, Object> destMap = getColumnMap(ruleColumnList);
|
||||
|
||||
// 数据处理-过滤规则
|
||||
if (logDataFilterService.evaluateFilterRule(
|
||||
dmNormalizeRule.get("rule_content").toString(), destMap))
|
||||
continue;
|
||||
|
||||
// 数据处理-补全规则
|
||||
logDataCompleteService.processDataCompletion(
|
||||
dmNormalizeRule.get("rule_content").toString(), destMap);
|
||||
SaveNormalData(ctx, deviceID, DateTime.now(), destMap,
|
||||
Long.parseLong(dmNormalizeRule.get("id").toString()),
|
||||
dmNormalizeRule.get("name").toString());
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("泛化规则处理失败:" + ex.getMessage());
|
||||
System.out.println(ex.getMessage());
|
||||
}
|
||||
if (ctx.dmNormalizeRuleList == null || ctx.dmNormalizeRuleList.isEmpty()) {
|
||||
// 原文已在进入标准化前写入 InfluxDB。设备没有绑定规则是可预期的业务终态,
|
||||
// 继续 Retry/DLT 不会凭空产生规则,只会重复消耗 Kafka、线程和日志 I/O。
|
||||
// 因此只跳过达梦标准化并允许 ACK;系统依赖和规则执行异常仍由下方异常链处理。
|
||||
return NormalizationResult.filtered();
|
||||
}
|
||||
if (optimizationProperties.getCompiledRule().isEnabled()) {
|
||||
return executeCompiled(ctx, deviceID);
|
||||
}
|
||||
NormalizationResult legacy = executeLegacy(ctx, deviceID);
|
||||
shadowCompareIfSampled(ctx, deviceID, legacy);
|
||||
return legacy;
|
||||
} catch (Exception ex) {
|
||||
logger.error("处理日志消息异常:" + ex.getMessage());
|
||||
System.out.println(ex.getMessage());
|
||||
// [SYSLOG-ALARM][NORM][已修复] 消息级异常不再转换为成功返回,确保未达终态时不会 ACK。
|
||||
logger.error("处理日志消息异常, eventId={}", ctx.strSyslogUUID, ex);
|
||||
throw ex instanceof RuntimeException ? (RuntimeException) ex
|
||||
: new IllegalStateException("标准化处理失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private NormalizationResult executeLegacy(ProcessContext ctx, long deviceId) {
|
||||
for (RuleSource source : ctx.dmNormalizeRuleList) {
|
||||
try {
|
||||
executeLegacyRule(ctx, deviceId, source);
|
||||
} catch (Exception failure) {
|
||||
logger.error("泛化规则处理失败, eventId={}, ruleId={}",
|
||||
ctx.strSyslogUUID, source.getId(), failure);
|
||||
throw new IllegalStateException("标准化规则处理失败", failure);
|
||||
}
|
||||
}
|
||||
return finish(ctx);
|
||||
}
|
||||
|
||||
private NormalizationResult executeCompiled(ProcessContext ctx, long deviceId) {
|
||||
for (RuleSource source : ctx.dmNormalizeRuleList) {
|
||||
CompiledRule rule;
|
||||
try {
|
||||
rule = compiledRuleCache.get(source, ctx.executionMetrics);
|
||||
} catch (CompiledRuleCompiler.RuleCompilationException incompatibleRule) {
|
||||
// 编译执行是兼容性优化,不能让一条历史规则阻塞整个 Kafka 批次。
|
||||
// 首次失败原因由 CompiledRuleCache 按 fingerprint 限频记录;此处只回退该规则。
|
||||
try {
|
||||
executeLegacyRule(ctx, deviceId, source);
|
||||
} catch (Exception legacyFailure) {
|
||||
logger.error("编译失败规则回退旧执行器后仍失败, eventId={}, ruleId={}",
|
||||
ctx.strSyslogUUID, source.getId(), legacyFailure);
|
||||
throw new IllegalStateException("标准化规则回退处理失败", legacyFailure);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ParsedMessage parsed = ctx.messageParseContext.parse(rule, ctx.strLogMsg, ctx.executionMetrics);
|
||||
if (parsed == null || parsed.getFields().isEmpty()) {
|
||||
rejectParsedMessage(ctx, deviceId, source);
|
||||
continue;
|
||||
}
|
||||
long mappingStarted = System.nanoTime();
|
||||
Map<String, Object> destination = rule.map(parsed);
|
||||
ctx.executionMetrics.addFieldMappingNanos(System.nanoTime() - mappingStarted);
|
||||
long filterStarted = System.nanoTime();
|
||||
if (rule.isFiltered(destination)) {
|
||||
ctx.executionMetrics.addFilterCompleteNanos(System.nanoTime() - filterStarted);
|
||||
ctx.filteredCount++;
|
||||
continue;
|
||||
}
|
||||
rule.complete(destination);
|
||||
ctx.executionMetrics.addFilterCompleteNanos(System.nanoTime() - filterStarted);
|
||||
assemble(ctx, deviceId, source, destination);
|
||||
} catch (Exception failure) {
|
||||
if (!ctx.shadowMode) {
|
||||
logger.error("编译规则处理失败, eventId={}, ruleId={}",
|
||||
ctx.strSyslogUUID, source.getId(), failure);
|
||||
}
|
||||
throw new IllegalStateException("编译标准化规则处理失败", failure);
|
||||
}
|
||||
}
|
||||
return finish(ctx);
|
||||
}
|
||||
|
||||
/** 执行单条旧格式规则,供旧主路径和编译不兼容规则的精确回退共同使用。 */
|
||||
private void executeLegacyRule(ProcessContext ctx, long deviceId, RuleSource source) {
|
||||
Map<String, Object> rule = source.asLegacyMap();
|
||||
long parseStarted = System.nanoTime();
|
||||
globalMetrics.ruleJsonParse();
|
||||
ctx.OrginalColumnMap = getMessageToMap(rule, ctx.strLogMsg, source.getDataType());
|
||||
ctx.executionMetrics.addMessageParseNanos(System.nanoTime() - parseStarted);
|
||||
if (ctx.OrginalColumnMap == null || ctx.OrginalColumnMap.isEmpty()) {
|
||||
rejectParsedMessage(ctx, deviceId, source);
|
||||
return;
|
||||
}
|
||||
long mappingStarted = System.nanoTime();
|
||||
globalMetrics.ruleJsonParse();
|
||||
List<HashMap<String, Object>> destinationColumns = getRuleContentMappers(rule);
|
||||
Map<String, Object> destination = getColumnMap(
|
||||
getNormalColumnList(ctx.OrginalColumnMap, destinationColumns));
|
||||
ctx.executionMetrics.addFieldMappingNanos(System.nanoTime() - mappingStarted);
|
||||
|
||||
long filterStarted = System.nanoTime();
|
||||
globalMetrics.ruleJsonParse();
|
||||
if (logDataFilterService.evaluateFilterRule(source.getRuleContent(), destination)) {
|
||||
ctx.executionMetrics.addFilterCompleteNanos(System.nanoTime() - filterStarted);
|
||||
ctx.filteredCount++;
|
||||
return;
|
||||
}
|
||||
globalMetrics.ruleJsonParse();
|
||||
logDataCompleteService.processDataCompletion(source.getRuleContent(), destination);
|
||||
ctx.executionMetrics.addFilterCompleteNanos(System.nanoTime() - filterStarted);
|
||||
assemble(ctx, deviceId, source, destination);
|
||||
}
|
||||
|
||||
private void assemble(ProcessContext ctx, long deviceId, RuleSource source,
|
||||
Map<String, Object> destination) {
|
||||
long started = System.nanoTime();
|
||||
ctx.normalizedRows.add(prepareNormalData(ctx, deviceId, destination,
|
||||
source.getId(), source.getName()));
|
||||
ctx.executionMetrics.addAssembleNanos(System.nanoTime() - started);
|
||||
ctx.savedCount++;
|
||||
}
|
||||
|
||||
private void rejectParsedMessage(ProcessContext ctx, long deviceId, RuleSource source) {
|
||||
ctx.syslogNonNormalMessage.setReason("Log解析异常");
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("log解析异常,返回规则名称:"
|
||||
+ source.getDisplayName() + ",OrginalColumnMap 对象获取为空");
|
||||
if (!ctx.shadowMode && !ctx.isSaveNonNormal) SaveNonNormalMessage(ctx, deviceId, DateTime.now());
|
||||
ctx.rejectedCount++;
|
||||
}
|
||||
|
||||
private NormalizationResult finish(ProcessContext ctx) {
|
||||
if (ctx.savedCount > 0) return NormalizationResult.success(ctx.normalizedRows);
|
||||
if (ctx.filteredCount > 0 && ctx.rejectedCount == 0) return NormalizationResult.filtered();
|
||||
throw new IllegalArgumentException("Syslog 未产生可用标准化结果: eventId=" + ctx.strSyslogUUID);
|
||||
}
|
||||
|
||||
private void shadowCompareIfSampled(ProcessContext ctx, long deviceId, NormalizationResult legacy) {
|
||||
NormalizationOptimizationProperties.CompiledRule config = optimizationProperties.getCompiledRule();
|
||||
if (!config.isShadowCompareEnabled()
|
||||
|| !shadowComparator.sampled(ctx.strSyslogUUID, config.getShadowSampleRate())) {
|
||||
globalMetrics.shadow("skipped");
|
||||
return;
|
||||
}
|
||||
ProcessContext shadow = shadowContext(ctx);
|
||||
Future<NormalizationResult> future;
|
||||
try {
|
||||
future = shadowExecutor.submit(() -> executeCompiled(shadow, deviceId));
|
||||
} catch (RejectedExecutionException saturated) {
|
||||
globalMetrics.shadow("skipped");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
NormalizationResult candidate = future.get(config.getShadowTimeoutMs(), TimeUnit.MILLISECONDS);
|
||||
NormalizationShadowComparator.Diff diff = shadowComparator.compare(legacy, candidate);
|
||||
ctx.executionMetrics.shadowCompared(!diff.isMatches());
|
||||
globalMetrics.shadow(diff.isMatches() ? "match" : "mismatch");
|
||||
if (!diff.isMatches() && shouldLogShadow(diff.getType())) {
|
||||
logger.warn("CompiledRule影子差异: eventHash={}, ruleId={}, type={}, fields={}",
|
||||
shadowComparator.eventHash(ctx.strSyslogUUID), firstRuleId(ctx),
|
||||
diff.getType(), diff.getFields());
|
||||
}
|
||||
} catch (TimeoutException timeout) {
|
||||
future.cancel(true);
|
||||
globalMetrics.shadow("timeout");
|
||||
if (shouldLogShadow("timeout")) {
|
||||
logger.warn("CompiledRule影子超时: eventHash={}, ruleId={}, type=timeout",
|
||||
shadowComparator.eventHash(ctx.strSyslogUUID), firstRuleId(ctx));
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
globalMetrics.shadow("error");
|
||||
if (failure instanceof InterruptedException) Thread.currentThread().interrupt();
|
||||
if (shouldLogShadow("error")) {
|
||||
logger.warn("CompiledRule影子失败: eventHash={}, ruleId={}, type=error, error={}",
|
||||
shadowComparator.eventHash(ctx.strSyslogUUID), firstRuleId(ctx),
|
||||
failure.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long firstRuleId(ProcessContext ctx) {
|
||||
return ctx.dmNormalizeRuleList == null || ctx.dmNormalizeRuleList.isEmpty()
|
||||
? -1L : ctx.dmNormalizeRuleList.get(0).getId();
|
||||
}
|
||||
|
||||
private boolean shouldLogShadow(String type) {
|
||||
long now = System.currentTimeMillis();
|
||||
AtomicLong next = shadowLogWindows.computeIfAbsent(type, ignored -> new AtomicLong());
|
||||
long current = next.get();
|
||||
return now >= current && next.compareAndSet(current, now + 60_000L);
|
||||
}
|
||||
|
||||
private ProcessContext shadowContext(ProcessContext source) {
|
||||
ProcessContext shadow = new ProcessContext();
|
||||
shadow.strLogMsg = source.strLogMsg;
|
||||
shadow.strKafkaMessage = source.strKafkaMessage;
|
||||
shadow.strDeviceInfo = source.strDeviceInfo;
|
||||
shadow.strDataType = source.strDataType;
|
||||
shadow.deviceInfoMap = source.deviceInfoMap;
|
||||
shadow.strSyslogUUID = source.strSyslogUUID;
|
||||
shadow.strSyslogTopic = source.strSyslogTopic;
|
||||
shadow.fallbackFirstReceivedAt = source.fallbackFirstReceivedAt;
|
||||
shadow.initialReceivedAt = source.initialReceivedAt;
|
||||
shadow.dmNormalizeRuleList = source.dmNormalizeRuleList;
|
||||
shadow.batchEnrichmentContext = source.batchEnrichmentContext;
|
||||
shadow.executionMetrics = new RuleExecutionMetrics();
|
||||
shadow.messageParseContext = new MessageParseContext(
|
||||
optimizationProperties.getMessageParseCache().isEnabled(), globalMetrics);
|
||||
shadow.shadowMode = true;
|
||||
return shadow;
|
||||
}
|
||||
|
||||
private List<RuleSource> rulesForDevice(long deviceId) {
|
||||
List<RuleSource> loaded = dmNormalizeRuleService.selectByDeviceIdAuto(deviceId);
|
||||
return loaded == null ? Collections.emptyList() : loaded;
|
||||
}
|
||||
|
||||
// ==================== 以下为原有业务方法 ====================
|
||||
|
||||
public Cropper_paramsType getCropperParams(Map<String, Object> dmNormalizeRule) {
|
||||
@@ -249,17 +642,11 @@ public class LogNormalProcessor {
|
||||
LinkedHashMap<String, Object> linkMap = null;
|
||||
if ("json".equals("json")) { // 默认走 json 分支,已无实例字段 strDataType
|
||||
SyslogMessage msg = SyslogParser.parse(MsgContent);
|
||||
System.out.println("解析结果-log content: " + msg.getMessage().toString());
|
||||
String complexJson = "{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\"}";
|
||||
System.out.println("complexJson content: " + complexJson);
|
||||
if ("dev".equals(appProperties.getRunEnvironment())) {
|
||||
LinkedHashMap<String, Object> flatMap = JsonParser.jsonToMap(complexJson);
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
return flatMap;
|
||||
return JsonParser.jsonToMap(complexJson);
|
||||
} else {
|
||||
LinkedHashMap<String, Object> flatMap = JsonParser.jsonToMap(msg.getMessage());
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
return flatMap;
|
||||
return JsonParser.jsonToMap(msg.getMessage());
|
||||
}
|
||||
}
|
||||
return linkMap;
|
||||
@@ -303,9 +690,7 @@ public class LogNormalProcessor {
|
||||
|
||||
public List<Map<String, Object>> getRuleList(long device_id) {
|
||||
List<Map<String, Object>> rulelst = dmNormalizeRuleService.selectByDeviceId((long) 1);
|
||||
if (rulelst != null) {
|
||||
System.out.println("rulelst: " + rulelst);
|
||||
} else {
|
||||
if (rulelst == null) {
|
||||
logger.error(" List<Map<String, Object>> rulelst is null!");
|
||||
}
|
||||
return rulelst;
|
||||
@@ -318,7 +703,6 @@ public class LogNormalProcessor {
|
||||
for (Map.Entry<String, Object> entry : orginColumnMap.entrySet()) {
|
||||
for (Map<String, Object> map : destColumnList) {
|
||||
if (map.get("origin_field").toString().equals(entry.getKey())) {
|
||||
System.out.println(map);
|
||||
Map<String, Object> normalColumMap = new LinkedHashMap<>();
|
||||
normalColumMap.put("origin_field", entry.getKey());
|
||||
normalColumMap.put("dest_field", map.get("dest_field").toString());
|
||||
@@ -343,9 +727,9 @@ public class LogNormalProcessor {
|
||||
entry.getValue().toString(), action_param.get("timezone").toString());
|
||||
normalColumMap.put("dest_field_value", longTime);
|
||||
} catch (Exception e) {
|
||||
logger.error("时间类型转换错误,源值:" + entry.getValue().toString()
|
||||
+ ",java_date_format:" + action_param.get("java_date_format").toString());
|
||||
e.printStackTrace();
|
||||
logger.warn("时间类型转换错误,源字段={}, 目标字段={}, javaDateFormat={}, 原因={}",
|
||||
entry.getKey(), map.get("dest_field"), action_param.get("java_date_format"),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
columnlist.add((HashMap<String, Object>) normalColumMap);
|
||||
@@ -379,55 +763,96 @@ public class LogNormalProcessor {
|
||||
return columnMap;
|
||||
}
|
||||
|
||||
public void SaveNormalData(ProcessContext ctx, long deviceId, DateTime logtime,
|
||||
Map<String, Object> logColumnMap,
|
||||
long normalizeRuleId, String normalizeRuleName) {
|
||||
/**
|
||||
* 补齐一条标准化结果所需的所有业务字段。
|
||||
*
|
||||
* <p>本方法不允许访问标准化表 Mapper,也不允许开启事务;它必须是“构造结果”的纯边界,
|
||||
* 否则批内并行线程仍会退化为逐条 INSERT。</p>
|
||||
*/
|
||||
private Map<String, Object> prepareNormalData(ProcessContext ctx, long deviceId,
|
||||
Map<String, Object> logColumnMap,
|
||||
long normalizeRuleId, String normalizeRuleName) {
|
||||
try {
|
||||
if (logColumnMap.isEmpty()) {
|
||||
logger.error("SaveNormalData ->logColumnMap 为空,syslogUUID:" + ctx.strSyslogUUID);
|
||||
ctx.syslogNonNormalMessage.setReason("未命中规则");
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("失败详情:logColumnMap对象字段为空");
|
||||
if (ctx.isSaveNonNormal == false)
|
||||
if (!ctx.shadowMode && !ctx.isSaveNonNormal)
|
||||
SaveNonNormalMessage(ctx, deviceId, DateTime.now());
|
||||
return;
|
||||
throw new IllegalArgumentException("标准化结果字段为空");
|
||||
}
|
||||
Map<String, Object> columnMap = logColumnMap;
|
||||
//补全采集设备信息
|
||||
CompletionDeviceInfo(columnMap, deviceId);
|
||||
//补全采集探针相关信息
|
||||
CompletionCollectTaskInfo(columnMap,ctx);
|
||||
long enrichmentStarted = System.nanoTime();
|
||||
try {
|
||||
//补全采集设备信息
|
||||
CompletionDeviceInfo(columnMap, deviceId, ctx);
|
||||
//补全采集探针相关信息
|
||||
CompletionCollectTaskInfo(columnMap,ctx);
|
||||
} finally {
|
||||
ctx.executionMetrics.addEnrichmentNanos(System.nanoTime() - enrichmentStarted);
|
||||
}
|
||||
//补全日志基础信息
|
||||
columnMap.put("device_id", deviceId);
|
||||
columnMap.put("log_time", logtime);
|
||||
columnMap.put("id", UUID.randomUUID().toString());
|
||||
// 现场两张标准化主表均按 log_time 做 RANGE 分区。原始业务代码会无条件用 DateTime.now()
|
||||
// 覆盖 log_time,其实际意图是按系统接收/处理日期分区,而不是按设备事件日期分区。
|
||||
// 这里把 log_time 和 created_at 都固定为最初 receive_time:既保持原来的分区口径,
|
||||
// 又避免 Kafka 积压、Retry/Replay 或跨日重试改变分区。设备事件时间保留在 collect_time_ts。
|
||||
applyInitialReceiveTime(columnMap, ctx.initialReceivedAt);
|
||||
// 输入字符串只用于计算固定 128 位 UUID,最终 id 仍是与旧版相同长度的 36 字符 UUID。
|
||||
// 同一 event_id + 规则 + 版本在重试/回放时生成相同 id,与稳定 log_time 组成每日本地唯一键。
|
||||
columnMap.put("id", deterministicResultId(ctx.strSyslogUUID, normalizeRuleId, LEGACY_RULE_VERSION));
|
||||
columnMap.put("normalize_rule_id", normalizeRuleId);
|
||||
columnMap.put("rule_version", LEGACY_RULE_VERSION);
|
||||
columnMap.put("normalize_rule_name", normalizeRuleName);
|
||||
columnMap.put("syslog_uuid", ctx.strSyslogUUID);
|
||||
columnMap.put("syslog_topic", ctx.strSyslogTopic);
|
||||
System.out.println("columnMap:" + columnMap);
|
||||
syslogNormalDataService.insertDynamic(columnMap);
|
||||
// [SYSLOG-ALARM][LOGIO] 逐条打印完整标准化字段会增加 stdout 锁竞争和日志 I/O,并可能输出敏感字段;
|
||||
// 建议改为阶段计数、耗时直方图和带 event_id 的采样 DEBUG 日志。
|
||||
logger.debug("标准化结果待入库: eventId={}, normalizeRuleId={}", ctx.strSyslogUUID, normalizeRuleId);
|
||||
// 返回完整动态列。目标表分流和真正的 INSERT 延迟到批写阶段执行。
|
||||
return columnMap;
|
||||
} catch (Exception e) {
|
||||
logger.error("SaveNormalData失败 ");
|
||||
ctx.syslogNonNormalMessage.setReason("入库失败");
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("入库失败,normalizeRuleName :" + normalizeRuleName
|
||||
logger.error("构造标准化结果失败, eventId={}, ruleId={}", ctx.strSyslogUUID, normalizeRuleId, e);
|
||||
ctx.syslogNonNormalMessage.setReason("标准化结果构造失败");
|
||||
ctx.syslogNonNormalMessage.setReasonDetail("标准化结果构造失败,normalizeRuleName :" + normalizeRuleName
|
||||
+ ",失败详情:" + e.getMessage());
|
||||
if (ctx.isSaveNonNormal == false)
|
||||
if (!ctx.shadowMode && !ctx.isSaveNonNormal)
|
||||
SaveNonNormalMessage(ctx, deviceId, DateTime.now());
|
||||
throw new RuntimeException("SaveNormalData 失败: " + e.getMessage(), e);
|
||||
throw new RuntimeException("构造标准化结果失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
static void applyInitialReceiveTime(Map<String, Object> columnMap, LocalDateTime initialReceivedAt) {
|
||||
columnMap.put("log_time", initialReceivedAt);
|
||||
columnMap.put("created_at", initialReceivedAt);
|
||||
}
|
||||
|
||||
static String deterministicResultId(String syslogUuid, long normalizeRuleId, String ruleVersion) {
|
||||
return UUID.nameUUIDFromBytes((syslogUuid + ":" + normalizeRuleId + ":" + ruleVersion)
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8)).toString();
|
||||
}
|
||||
|
||||
//补全采集设备信息
|
||||
public void CompletionDeviceInfo(Map<String, Object> columnMap, Long deviceID) {
|
||||
CompletionDeviceInfo(columnMap, deviceID, null);
|
||||
}
|
||||
|
||||
private void CompletionDeviceInfo(Map<String, Object> columnMap, Long deviceID, ProcessContext ctx) {
|
||||
try {
|
||||
DeviceDevice devInfo = deviceDeviceService.getByIdSafely(Long.valueOf(deviceID).intValue());
|
||||
if (devInfo != null) {
|
||||
columnMap.put("device_ip", devInfo.getIp());
|
||||
columnMap.put("device_manufacturer", devInfo.getVendor());
|
||||
columnMap.put("device_name", devInfo.getName());
|
||||
DeviceSnapshot device = ctx == null
|
||||
? DeviceSnapshot.from(deviceDeviceService.getByIdSafely(deviceID.intValue()))
|
||||
: ctx.batchEnrichmentContext.device(deviceID.intValue());
|
||||
if (device != null) {
|
||||
columnMap.put("device_ip", device.getIp());
|
||||
columnMap.put("device_manufacturer", device.getVendor());
|
||||
columnMap.put("device_name", device.getName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("CompletionDeviceInfo 失败!ID:" + deviceID);
|
||||
logger.error("CompletionDeviceInfo 失败!ID:{}", deviceID, e);
|
||||
if (ctx != null && ctx.batchEnrichmentContext.isEnabled()) {
|
||||
throw e instanceof RuntimeException ? (RuntimeException) e
|
||||
: new IllegalStateException("设备补全失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,16 +861,20 @@ public class LogNormalProcessor {
|
||||
Integer collect_id=-1;
|
||||
try {
|
||||
collect_id = Integer.parseInt(ctx.deviceInfoMap.get("device_collect_id"));
|
||||
DeviceCollectTask deviceCollectTask = deviceCollectTaskService.getById(collect_id);
|
||||
if (deviceCollectTask != null) {
|
||||
CollectTaskSnapshot collectTask = ctx.batchEnrichmentContext.collectTask(collect_id);
|
||||
if (collectTask != null) {
|
||||
columnMap.put("agent_id", collect_id);
|
||||
columnMap.put("origin_agent_id",collect_id.toString() );
|
||||
columnMap.put("probe_ip",deviceCollectTask.getDeviceIp() );
|
||||
columnMap.put("agent_name", deviceCollectTask.getTaskName());
|
||||
columnMap.put("origin_agent_name", deviceCollectTask.getTaskName());
|
||||
columnMap.put("probe_ip",collectTask.getDeviceIp() );
|
||||
columnMap.put("agent_name", collectTask.getTaskName());
|
||||
columnMap.put("origin_agent_name", collectTask.getTaskName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("CompletionCollectTaskInfo 失败!探针ID:" + collect_id);
|
||||
logger.error("CompletionCollectTaskInfo 失败!探针ID:{}", collect_id, e);
|
||||
if (ctx.batchEnrichmentContext.isEnabled()) {
|
||||
throw e instanceof RuntimeException ? (RuntimeException) e
|
||||
: new IllegalStateException("采集任务补全失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,7 +882,7 @@ public class LogNormalProcessor {
|
||||
try {
|
||||
SyslogNonNormalMessage normalMessage = new SyslogNonNormalMessage();
|
||||
Integer collect_id = Integer.parseInt(ctx.deviceInfoMap.get("device_collect_id"));
|
||||
DeviceCollectTask deviceCollectTask = deviceCollectTaskService.getById(collect_id);
|
||||
CollectTaskSnapshot collectTask = ctx.batchEnrichmentContext.collectTask(collect_id);
|
||||
normalMessage.setId(UUID.randomUUID().toString());
|
||||
normalMessage.setDeviceId((int) deviceId);
|
||||
normalMessage.setLogTime(logtime.toLocalDateTime());
|
||||
@@ -462,14 +891,17 @@ public class LogNormalProcessor {
|
||||
normalMessage.setSyslogTopic(ctx.strSyslogTopic);
|
||||
normalMessage.setSyslogUuid(ctx.strSyslogUUID);
|
||||
normalMessage.setHeaderMessage(ctx.strDeviceInfo);
|
||||
normalMessage.setReceiveTime(ctx.initialReceivedAt);
|
||||
// 非标表同样按 created_at 日分区;使用同一首次接收时间,避免重试后跑到另一天的分区。
|
||||
normalMessage.setCreatedAt(ctx.initialReceivedAt.atZone(RECEIVE_TIME_ZONE).toOffsetDateTime());
|
||||
normalMessage.setEtlNode("etlgo");
|
||||
normalMessage.setReason(ctx.syslogNonNormalMessage.getReason());
|
||||
normalMessage.setReasonDetail(ctx.syslogNonNormalMessage.getReasonDetail());
|
||||
normalMessage.setRuleResult("FAIL");
|
||||
normalMessage.setDeviceName(ctx.deviceInfoMap.get("device_name"));
|
||||
normalMessage.setCollectTaskId(collect_id);
|
||||
if (deviceCollectTask != null)
|
||||
normalMessage.setCollectTaskName(deviceCollectTask.getTaskName());
|
||||
if (collectTask != null)
|
||||
normalMessage.setCollectTaskName(collectTask.getTaskName());
|
||||
this.messageService.saveMessage(normalMessage);
|
||||
ctx.isSaveNonNormal = true;
|
||||
} catch (Exception e) {
|
||||
@@ -478,6 +910,33 @@ public class LogNormalProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/** 将接入头中的 receive_time 写入非标表;无效值保留为空,避免伪造处理时间。 */
|
||||
static LocalDateTime parseReceiveTime(String receiveTime) {
|
||||
if (receiveTime == null || receiveTime.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return IngressReceiveTimeUtil.parse(receiveTime);
|
||||
} catch (IllegalArgumentException invalidReceiveTime) {
|
||||
logger.warn("非标日志接收时间格式异常,receiveTime={}", receiveTime);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 接入头优先;旧消息缺失/格式异常时,使用 Kafka 原始记录的稳定首次接收时间。 */
|
||||
static LocalDateTime resolveInitialReceivedAt(String receiveTime, LocalDateTime fallbackFirstReceivedAt) {
|
||||
LocalDateTime parsed = parseReceiveTime(receiveTime);
|
||||
if (parsed != null) {
|
||||
return parsed;
|
||||
}
|
||||
if (fallbackFirstReceivedAt != null) {
|
||||
return fallbackFirstReceivedAt;
|
||||
}
|
||||
// 只有历史非 Kafka 调用入口才可能走到这里;活动 listener 必须显式传入稳定回退时间。
|
||||
logger.warn("日志缺失稳定首次接收时间,兼容入口回退为当前时间");
|
||||
return LocalDateTime.now(RECEIVE_TIME_ZONE);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 旧入口保留,仅用于本地测试
|
||||
}
|
||||
|
||||
+589
-103
@@ -1,12 +1,24 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import com.influx.InfluxDBClient;
|
||||
import com.Modules.NormalData.compiled.BatchEnrichmentContext;
|
||||
import com.Modules.NormalData.compiled.BatchRuleSnapshot;
|
||||
import com.Modules.NormalData.compiled.RuleExecutionMetrics;
|
||||
import com.Modules.NormalData.compiled.PreparedNormalizationInput;
|
||||
import com.common.util.SyslogParser;
|
||||
import com.common.util.IngressReceiveTimeUtil;
|
||||
import com.config.AppProperties;
|
||||
import com.config.KafkaConsumerProperties;
|
||||
import com.common.service.DmStandardizedBatchWriter;
|
||||
import com.common.service.IngressStatsProjectionWriter;
|
||||
import com.common.entity.IngressStatsEvent;
|
||||
import com.influxdb.client.domain.WritePrecision;
|
||||
import com.influxdb.client.write.Point;
|
||||
import com.influxdb.client.WriteApi;
|
||||
import com.influx.raw.InfluxRawPointFactory;
|
||||
import com.influx.raw.PointTimeResolver;
|
||||
import com.influx.raw.RawInfluxMetrics;
|
||||
import com.influx.raw.RawStorageProperties;
|
||||
import com.influx.raw.ReceiveTimeParser;
|
||||
import com.influxdb.exceptions.BadRequestException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -14,19 +26,24 @@ import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDate;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import com.common.util.Sm4Util;
|
||||
@@ -34,6 +51,10 @@ import com.common.util.Sm4Util;
|
||||
@Component
|
||||
public class SysLogProcessor {
|
||||
|
||||
private static final ZoneId RECEIVE_TIME_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter MEASUREMENT_DATE_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
@Autowired
|
||||
@Qualifier("logNormalProcessorExecutor")
|
||||
private Executor taskExecutor;
|
||||
@@ -41,7 +62,7 @@ public class SysLogProcessor {
|
||||
@Value("${app.processor.batch-size:100}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${app.processor.process-timeout-ms:30000}")
|
||||
@Value("${app.processor.process-timeout-ms:120000}")
|
||||
private long processTimeoutMs;
|
||||
|
||||
@Autowired
|
||||
@@ -53,10 +74,25 @@ public class SysLogProcessor {
|
||||
@Autowired
|
||||
private LogNormalProcessor logNormalProcessor;
|
||||
|
||||
@Autowired
|
||||
private SyslogFailureRouter failureRouter;
|
||||
|
||||
@Autowired
|
||||
private DmStandardizedBatchWriter standardizedBatchWriter;
|
||||
|
||||
@Autowired
|
||||
private IngressStatsProjectionWriter ingressStatsProjectionWriter;
|
||||
|
||||
@Autowired
|
||||
private com.influx.InfluxDBClient influxClient;
|
||||
|
||||
@Autowired private InfluxRawPointFactory rawPointFactory;
|
||||
@Autowired private PointTimeResolver pointTimeResolver;
|
||||
@Autowired private RawStorageProperties rawStorageProperties;
|
||||
@Autowired private RawInfluxMetrics rawInfluxMetrics;
|
||||
|
||||
private final AtomicInteger totalProcessed = new AtomicInteger(0);
|
||||
// [SYSLOG-ALARM][KACK][已修复-主链路停用] 历史辅助方法仍保留此计数用于兼容,但唯一活动 listener 不再用全局计数决定 ACK。
|
||||
private final AtomicInteger currentBatchCount = new AtomicInteger(0);
|
||||
|
||||
|
||||
@@ -69,7 +105,7 @@ public class SysLogProcessor {
|
||||
try {
|
||||
// 处理业务逻辑
|
||||
for (String record : records) {
|
||||
System.out.println(record);
|
||||
log.debug("兼容入口收到消息,长度={}", record == null ? 0 : record.length());
|
||||
}
|
||||
// 手动提交偏移量
|
||||
ack.acknowledge(); // 告诉Kafka这条消息已成功处理
|
||||
@@ -78,62 +114,92 @@ public class SysLogProcessor {
|
||||
}
|
||||
}
|
||||
@KafkaListener(
|
||||
// Raw 只处理实时原始日志,避免未到期 Retry 占用原始消费线程。
|
||||
id = "syslog-consumer-rule-raw",
|
||||
groupId = "${spring.kafka.consumer.group-id}",
|
||||
autoStartup = "${syslog.raw-consumer.enabled:true}",
|
||||
topics = "${spring.kafka.consumer.topic:agent-syslog-topic}",
|
||||
concurrency = "${spring.kafka.listener.concurrency}" // 多线程消费
|
||||
containerFactory = "rawKafkaListenerContainerFactory"
|
||||
)
|
||||
public void consumeAndParallelProcess(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
consumeBatch(records, ack, false, "RAW");
|
||||
}
|
||||
|
||||
@KafkaListener(
|
||||
id = "syslog-consumer-rule-retry-replay",
|
||||
groupId = "${syslog.reliability.consumer-group-id}",
|
||||
autoStartup = "${syslog.reliability.consumer.enabled:true}",
|
||||
topics = {
|
||||
"${syslog.reliability.retry-1m-topic:${spring.kafka.consumer.topic}.RETRY.1M}",
|
||||
"${syslog.reliability.retry-10m-topic:${spring.kafka.consumer.topic}.RETRY.10M}",
|
||||
"${syslog.reliability.retry-1h-topic:${spring.kafka.consumer.topic}.RETRY.1H}",
|
||||
"${syslog.reliability.replay-topic:${spring.kafka.consumer.topic}.REPLAY}"
|
||||
},
|
||||
concurrency = "${syslog.reliability.listener.concurrency:1}"
|
||||
)
|
||||
public void consumeRetryAndReplay(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
consumeBatch(records, ack, true, "RETRY_REPLAY");
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一批处理边界:原文批量写入 InfluxDB 后,有界并行执行标准化;
|
||||
* 只有整批全部到达可靠终态才提交 offset。
|
||||
*/
|
||||
private void consumeBatch(List<ConsumerRecord<String, String>> records, Acknowledgment ack,
|
||||
boolean enforceRetryDue, String lane) {
|
||||
if (records.isEmpty()) {
|
||||
ack.acknowledge();
|
||||
return;
|
||||
}
|
||||
log.info("开始处理批次消息,数量: {}", records.size());
|
||||
currentBatchCount.set(records.size());
|
||||
|
||||
try {
|
||||
List<CompletableFuture<Void>> processingFutures = new ArrayList<>();
|
||||
|
||||
// 为每条消息创建独立的处理任务
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
// 异步处理单条消息
|
||||
log.info("收到syslogmessage:"+ Sm4Util.decryptCbc(record.value(), appProperties.getSm4Key()));
|
||||
processSingleMessageAsync(record);
|
||||
} catch (Exception e) {
|
||||
log.error("处理消息失败, topic: {}, partition: {}, offset: {}",
|
||||
record.topic(), record.partition(), record.offset(), e);
|
||||
} finally {
|
||||
// 计数器递减
|
||||
if (currentBatchCount.decrementAndGet() == 0) {
|
||||
log.debug("批次所有消息处理完成");
|
||||
}
|
||||
}
|
||||
}, taskExecutor);
|
||||
|
||||
processingFutures.add(future);
|
||||
}
|
||||
|
||||
// 等待所有处理任务完成(带超时)
|
||||
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
|
||||
processingFutures.toArray(new CompletableFuture[0])
|
||||
);
|
||||
|
||||
long batchStartedAt = System.currentTimeMillis();
|
||||
long prepareStartedAt = batchStartedAt;
|
||||
BatchMetrics metrics = new BatchMetrics();
|
||||
List<PreparedMessage> preparedMessages = new ArrayList<>();
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
SyslogFailureRouter.MessageContext context = failureRouter.resolve(record);
|
||||
try {
|
||||
allFutures.get(processTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
log.info("批次处理完成,总数: {}", records.size());
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
log.warn("批次处理超时,已处理: {}/{}",
|
||||
records.size() - currentBatchCount.get(), records.size());
|
||||
if (enforceRetryDue) {
|
||||
failureRouter.ensureRetryDue(context);
|
||||
}
|
||||
preparedMessages.add(prepareMessage(record, context));
|
||||
} catch (SyslogFailureRouter.RetryNotDueException notDue) {
|
||||
throw notDue;
|
||||
} catch (Exception failure) {
|
||||
metrics.record(routeFailure(record, context, failure));
|
||||
}
|
||||
|
||||
// 提交偏移量
|
||||
ack.acknowledge();
|
||||
totalProcessed.addAndGet(records.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("消费处理异常", e);
|
||||
ack.acknowledge(); // 异常情况下也提交偏移量,避免阻塞
|
||||
}
|
||||
long prepareMs = System.currentTimeMillis() - prepareStartedAt;
|
||||
|
||||
// 入口状态是 Kafka 已可靠接收的事实。批内按设备/探针聚合,失败时禁止 ACK;重投只重复 MIN/MAX。
|
||||
int ingressGroups = ingressStatsProjectionWriter.writeBatch(ingressEvents(preparedMessages));
|
||||
|
||||
long influxStartedAt = System.currentTimeMillis();
|
||||
List<PreparedMessage> persistedMessages = persistRawBatch(preparedMessages, metrics);
|
||||
long influxMs = System.currentTimeMillis() - influxStartedAt;
|
||||
|
||||
long normalizeStartedAt = System.currentTimeMillis();
|
||||
normalizePreparedMessages(persistedMessages, metrics);
|
||||
long normalizeMs = System.currentTimeMillis() - normalizeStartedAt;
|
||||
|
||||
ack.acknowledge();
|
||||
totalProcessed.addAndGet(records.size());
|
||||
log.info("Syslog批次完成: lane={}, topicPartitions={}, records={}, prepared={}, persisted={}, "
|
||||
+ "success={}, filtered={}, retry={}, dlt={}, normalizedRows={}, dmSuccessfulRows={}, "
|
||||
+ "dmFailedMessages={}, ingressGroups={}, prepareMs={}, influxMs={}, normalizeMs={}, "
|
||||
+ "ruleComputeMs={}, ruleSnapshotMs={}, messageParseMs={}, fieldMappingMs={}, "
|
||||
+ "filterCompleteMs={}, enrichmentMs={}, ruleAssembleMs={}, compiledRuleHit={}, "
|
||||
+ "compiledRuleMiss={}, messageParseHit={}, messageParseMiss={}, deviceUnique={}, "
|
||||
+ "collectTaskUnique={}, shadowCompared={}, shadowMismatch={}, dmWriteMs={}, totalMs={}",
|
||||
lane, topicPartitions(records), records.size(), preparedMessages.size(), persistedMessages.size(),
|
||||
metrics.success.get(), metrics.filtered.get(), metrics.retry.get(), metrics.dlt.get(),
|
||||
metrics.normalizedRows.get(), metrics.dmSuccessfulRows.get(), metrics.dmFailedMessages.get(), ingressGroups,
|
||||
prepareMs, influxMs, normalizeMs, metrics.ruleComputeMs(), metrics.ruleSnapshotMs(),
|
||||
metrics.messageParseMs(), metrics.fieldMappingMs(), metrics.filterCompleteMs(),
|
||||
metrics.enrichmentMs(), metrics.ruleAssembleMs(), metrics.compiledRuleHits(),
|
||||
metrics.compiledRuleMisses(), metrics.messageParseHits(), metrics.messageParseMisses(),
|
||||
metrics.deviceUnique(), metrics.collectTaskUnique(), metrics.shadowCompared(),
|
||||
metrics.shadowDifferences(), metrics.dmWriteMs(),
|
||||
System.currentTimeMillis() - batchStartedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,6 +235,7 @@ public class SysLogProcessor {
|
||||
processMessageBatch(batch, batchIndex);
|
||||
} catch (Exception e) {
|
||||
log.error("批次处理异常, 批次: {}", batchIndex, e);
|
||||
throw new java.util.concurrent.CompletionException(e);
|
||||
}
|
||||
}, taskExecutor);
|
||||
|
||||
@@ -189,7 +256,7 @@ public class SysLogProcessor {
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("分批消费处理异常", e);
|
||||
ack.acknowledge();
|
||||
throw new IllegalStateException("分批消费失败,禁止提交 offset", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,51 +318,484 @@ public class SysLogProcessor {
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("优先级消费处理异常", e);
|
||||
ack.acknowledge();
|
||||
throw new IllegalStateException("优先级消费失败,禁止提交 offset", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步处理单条消息
|
||||
*/
|
||||
@Async("logNormalProcessorExecutor")
|
||||
public void processSingleMessageAsync(ConsumerRecord<String, String> record) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
processSingleMessage(record, failureRouter.resolve(record));
|
||||
}
|
||||
|
||||
private void processSingleMessage(ConsumerRecord<String, String> record,
|
||||
SyslogFailureRouter.MessageContext messageContext) {
|
||||
// [流程节点5] 解密 Kafka 消息,生成事件标识,保存原始事件,并把消息转交标准化处理节点。
|
||||
// [SYSLOG-ALARM][KACK][已修复] 活动 listener 同步调用本方法,已移除嵌套 @Async/Future,异常直接返回唯一 ACK 边界。
|
||||
try {
|
||||
//Message进行SM4解密
|
||||
String Sm4message=Sm4Util.decryptCbc(record.value(), appProperties.getSm4Key());
|
||||
|
||||
String sysLogUUID =getSysLogUUID();
|
||||
String strDeviceInfo= SyslogParser.substringBeforeFirstChar(Sm4message,']');
|
||||
Map<String,String> mapdev =SyslogParser.parseKeyValuePairs(strDeviceInfo);
|
||||
|
||||
// 初始化 InfluxDB 客户端
|
||||
Point point = Point.measurement("syslog_security_"+sysLogUUID.substring(0,8) )
|
||||
.addTag("device_id", mapdev.get("device_id")) // 添加设备ID标签
|
||||
.addTag("device_collect_id", mapdev.get("device_collect_id")) // 添加探针ID标签
|
||||
.addTag("uuid", sysLogUUID) //syslog uuid
|
||||
.addTag("topic", kafkaConsumerProperties.getTopic()) //kafka topic
|
||||
.addField("message", Sm4message) // 添加字段
|
||||
.addField("receive_time", mapdev.get("receive_time")) // 添加字段
|
||||
.addField("uuid", sysLogUUID)
|
||||
.time(System.currentTimeMillis(), WritePrecision.MS) ;// 毫秒级时间戳
|
||||
influxClient.writePoint(point);
|
||||
|
||||
System.out.println("influxdb wirte syslog ,value:"+ record.key());
|
||||
// 日志信息插入pg XdrHoneypot 表
|
||||
//insertSingleRecord( record.value());
|
||||
|
||||
String syslogMessage= Sm4message;
|
||||
//使用注入的 Spring Bean 进行标准化处理
|
||||
logNormalProcessor.process(syslogMessage, sysLogUUID, null);
|
||||
System.out.println("insert postgres syslog ,value:"+ record.key());
|
||||
long costTime = System.currentTimeMillis() - startTime;
|
||||
log.debug("消息处理完成, offset: {}, 耗时: {}ms", record.offset(), costTime);
|
||||
PreparedMessage message = prepareMessage(record, messageContext);
|
||||
influxClient.writePointBlocking(message.bucket, message.point);
|
||||
if (message.v2) rawInfluxMetrics.v2Points(1L);
|
||||
normalizePreparedMessage(message);
|
||||
|
||||
} catch (Exception e) {
|
||||
// [SYSLOG-ALARM][KACK][已修复] 异常继续抛给唯一 ACK 边界,由可靠路由器分类处理。
|
||||
log.error("异步处理消息失败, offset: {}", record.offset(), e);
|
||||
// 这里可以添加重试逻辑或死信队列处理
|
||||
throw new IllegalStateException("Syslog 处理失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 解密并构造原文点;此阶段不做任何 Kafka ACK。 */
|
||||
private PreparedMessage prepareMessage(ConsumerRecord<String, String> record,
|
||||
SyslogFailureRouter.MessageContext messageContext) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
// [流程节点5.1] 使用约定密钥解密 Kafka 密文,恢复设备元数据头和原始 Syslog。
|
||||
String decryptedMessage = Sm4Util.decryptCbc(messageContext.getPayload(), appProperties.getSm4Key());
|
||||
String deviceHeader = SyslogParser.substringBeforeFirstChar(decryptedMessage, ']');
|
||||
Map<String, String> deviceInfo = SyslogParser.parseKeyValuePairs(deviceHeader);
|
||||
messageContext.setDeviceId(deviceInfo.get("device_id"));
|
||||
|
||||
// [流程节点5.2] 优先使用接入端 event_id;旧消息回退到稳定 topic-partition-offset ID。
|
||||
String eventId = deviceInfo.get("event_id");
|
||||
if (eventId == null || eventId.trim().isEmpty()) {
|
||||
eventId = messageContext.getEventId();
|
||||
}
|
||||
|
||||
String receiveTime = deviceInfo.get("receive_time");
|
||||
ReceiveTimeParser.ParsedReceiveTime parsed = ReceiveTimeParser.parse(receiveTime);
|
||||
boolean headerHasPointTime = deviceInfo.containsKey("point_time_ns");
|
||||
Long envelopePointTime = messageContext.getPointTimeNs();
|
||||
Long headerPointTime = pointTimeResolver.resolve(headerHasPointTime,
|
||||
deviceInfo.get("point_time_ns"), parsed.getEpochMillis(), false);
|
||||
if (envelopePointTime != null) {
|
||||
PointTimeResolver.validate(envelopePointTime, parsed.getEpochMillis());
|
||||
if (headerPointTime != null && !headerPointTime.equals(envelopePointTime)) {
|
||||
throw new IllegalArgumentException("Retry/Replay point_time_ns 与原始 Kafka 载荷不一致");
|
||||
}
|
||||
}
|
||||
Long pointTimeNs = envelopePointTime != null ? envelopePointTime : headerPointTime;
|
||||
if (pointTimeNs == null && rawStorageProperties.getWriteSchema() == RawStorageProperties.WriteSchema.V2) {
|
||||
pointTimeNs = pointTimeResolver.resolve(false, null, parsed.getEpochMillis(), true);
|
||||
}
|
||||
messageContext.setPointTimeNs(pointTimeNs);
|
||||
String originalTopic = messageContext.getOriginalTopic();
|
||||
InfluxRawPointFactory.RawPoint rawPoint = rawPointFactory.create(eventId, decryptedMessage,
|
||||
receiveTime, deviceInfo.get("device_id"), deviceInfo.get("device_collect_id"),
|
||||
originalTopic, parsed, pointTimeNs);
|
||||
ResolvedInfluxTime influxTime = new ResolvedInfluxTime(parsed.getEpochMillis(),
|
||||
parsed.getMeasurementDate(), parsed.getLocalDateTime());
|
||||
Long deviceId = optionalLong(deviceInfo.get("device_id"));
|
||||
Long collectId = optionalLong(deviceInfo.get("device_collect_id"));
|
||||
PreparedNormalizationInput normalizationInput = new PreparedNormalizationInput(
|
||||
eventId, originalTopic, influxTime.getReceivedAt(), deviceId, collectId,
|
||||
deviceInfo.get("data_type"), SyslogParser.substringAfterFirstCloseBracket(decryptedMessage),
|
||||
decryptedMessage, deviceHeader, deviceInfo);
|
||||
return new PreparedMessage(record, messageContext, decryptedMessage, eventId, rawPoint.getPoint(),
|
||||
rawPoint.getBucket(), rawPoint.isV2(), influxTime.getReceivedAt(), deviceId, collectId,
|
||||
startTime, normalizationInput);
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次 HTTP 请求持久化当前 Kafka 批次的原文。
|
||||
* 批量请求如果因单条数据格式被 InfluxDB 拒绝,降级为逐条写入以定位坏消息;
|
||||
* 连接、超时或服务端故障则直接保留原 offset,不制造 DLT 风暴。
|
||||
*/
|
||||
private List<PreparedMessage> persistRawBatch(List<PreparedMessage> messages, BatchMetrics metrics) {
|
||||
if (messages.isEmpty()) {
|
||||
return messages;
|
||||
}
|
||||
List<Point> points = new ArrayList<>(messages.size());
|
||||
for (PreparedMessage message : messages) {
|
||||
points.add(message.point);
|
||||
}
|
||||
try {
|
||||
String targetBucket = messages.get(0).bucket;
|
||||
influxClient.writePointsBlocking(targetBucket, points);
|
||||
if (messages.get(0).v2) rawInfluxMetrics.v2Points(messages.size());
|
||||
return messages;
|
||||
} catch (BadRequestException badBatchData) {
|
||||
if (messages.get(0).v2) rawInfluxMetrics.v2FailedBatch();
|
||||
log.warn("InfluxDB 批量写入发现格式错误,降级逐条定位: batchSize={}", messages.size());
|
||||
List<PreparedMessage> persisted = new ArrayList<>(messages.size());
|
||||
for (PreparedMessage message : messages) {
|
||||
try {
|
||||
influxClient.writePointBlocking(message.bucket, message.point);
|
||||
if (message.v2) rawInfluxMetrics.v2Points(1L);
|
||||
persisted.add(message);
|
||||
} catch (Exception singleFailure) {
|
||||
metrics.record(routeFailure(message.record, message.context, singleFailure));
|
||||
}
|
||||
}
|
||||
return persisted;
|
||||
} catch (Exception dependencyFailure) {
|
||||
if (messages.get(0).v2) rawInfluxMetrics.v2FailedBatch();
|
||||
// 整批原文的持久化结果不可确认,必须让 Kafka 从原 offset 重投。
|
||||
throw new IllegalStateException("InfluxDB 批量原文写入未取得成功确认,禁止提交 offset", dependencyFailure);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 历史单条兼容入口:原文已可靠持久化后,执行标准化并立即落库。
|
||||
* 活动 Kafka 批处理链路使用 prepareNormalization(),避免在计算线程中逐条开启达梦事务。
|
||||
*/
|
||||
private SyslogFailureRouter.TerminalState normalizePreparedMessage(PreparedMessage message) {
|
||||
LogNormalProcessor.ProcessingOutcome outcome =
|
||||
logNormalProcessor.process(message.decryptedMessage, message.eventId, null, message.receivedAt);
|
||||
log.debug("消息处理完成, offset: {}, 耗时: {}ms", message.record.offset(),
|
||||
System.currentTimeMillis() - message.startTime);
|
||||
return outcome == LogNormalProcessor.ProcessingOutcome.FILTERED
|
||||
? SyslogFailureRouter.TerminalState.FILTERED
|
||||
: SyslogFailureRouter.TerminalState.SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只生成待写入的标准化结果,不在并行计算线程中访问两张达梦标准化表。
|
||||
*/
|
||||
private PreparedNormalization prepareNormalization(PreparedMessage message,
|
||||
BatchRuleSnapshot ruleSnapshot,
|
||||
BatchEnrichmentContext enrichmentContext,
|
||||
RuleExecutionMetrics executionMetrics) {
|
||||
LogNormalProcessor.NormalizationResult result = logNormalProcessor.prepare(
|
||||
message.normalizationInput, ruleSnapshot, enrichmentContext, executionMetrics);
|
||||
log.debug("消息标准化计算完成, offset: {}, rows={}, 耗时: {}ms", message.record.offset(),
|
||||
result.getRows().size(), System.currentTimeMillis() - message.startTime);
|
||||
return new PreparedNormalization(message, result, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批内有界并行标准化。任务异常必须汇总回 listener;超时或系统性失败时整批不 ACK。
|
||||
*/
|
||||
void normalizePreparedMessages(List<PreparedMessage> messages, BatchMetrics metrics) {
|
||||
if (messages.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
long snapshotStartedAt = System.nanoTime();
|
||||
Set<Long> deviceIds = new HashSet<>();
|
||||
for (PreparedMessage message : messages) {
|
||||
if (message.deviceId != null) deviceIds.add(message.deviceId);
|
||||
}
|
||||
BatchRuleSnapshot ruleSnapshot = logNormalProcessor.captureRuleSnapshot(deviceIds);
|
||||
BatchEnrichmentContext enrichmentContext = logNormalProcessor.createBatchEnrichmentContext();
|
||||
RuleExecutionMetrics executionMetrics = new RuleExecutionMetrics();
|
||||
metrics.recordRuleSnapshotMs(elapsedMillis(snapshotStartedAt));
|
||||
long ruleComputeStartedAt = System.nanoTime();
|
||||
List<CompletableFuture<PreparedNormalization>> futures = new ArrayList<>(messages.size());
|
||||
try {
|
||||
for (PreparedMessage message : messages) {
|
||||
futures.add(CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return prepareNormalization(message, ruleSnapshot, enrichmentContext, executionMetrics);
|
||||
} catch (Exception failure) {
|
||||
// 解析/规则计算失败仍按原消息可靠路由。只有取得 Retry/DLT Broker ACK,
|
||||
// 这个消息才会携带 terminalState 返回并允许原批次继续。
|
||||
return new PreparedNormalization(message, null,
|
||||
routeFailure(message.record, message.context, failure));
|
||||
}
|
||||
}, taskExecutor));
|
||||
}
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
|
||||
.get(processTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
metrics.recordRuleComputeMs(elapsedMillis(ruleComputeStartedAt));
|
||||
metrics.recordRuleExecution(executionMetrics, enrichmentContext);
|
||||
|
||||
List<DmStandardizedBatchWriter.WriteRequest<PreparedMessage>> writeRequests = new ArrayList<>();
|
||||
Set<PreparedMessage> pendingDatabaseMessages = new HashSet<>();
|
||||
for (CompletableFuture<PreparedNormalization> future : futures) {
|
||||
PreparedNormalization prepared = future.join();
|
||||
if (prepared.terminalState != null) {
|
||||
metrics.record(prepared.terminalState);
|
||||
continue;
|
||||
}
|
||||
if (prepared.result.getOutcome() == LogNormalProcessor.ProcessingOutcome.FILTERED) {
|
||||
metrics.record(SyslogFailureRouter.TerminalState.FILTERED);
|
||||
continue;
|
||||
}
|
||||
|
||||
pendingDatabaseMessages.add(prepared.message);
|
||||
for (Map<String, Object> row : prepared.result.getRows()) {
|
||||
writeRequests.add(new DmStandardizedBatchWriter.WriteRequest<>(prepared.message, row));
|
||||
}
|
||||
}
|
||||
|
||||
// 批写器只返回“可归因到具体消息”的行级失败;连接、超时、事务结果未知会直接抛出,
|
||||
// 从而让本方法退出并保留整个 Kafka 批次 offset。
|
||||
long dmWriteStartedAt = System.nanoTime();
|
||||
DmStandardizedBatchWriter.WriteReport<PreparedMessage> writeReport =
|
||||
standardizedBatchWriter.write(writeRequests);
|
||||
metrics.recordDmWriteMs(elapsedMillis(dmWriteStartedAt));
|
||||
Set<PreparedMessage> failedMessages = writeReport.getFailures().keySet();
|
||||
metrics.recordDmWrite(writeRequests.size(), writeReport.getSuccessfulRows(), failedMessages.size());
|
||||
|
||||
for (Map.Entry<PreparedMessage, RuntimeException> failure : writeReport.getFailures().entrySet()) {
|
||||
PreparedMessage message = failure.getKey();
|
||||
metrics.record(routeFailure(message.record, message.context, failure.getValue()));
|
||||
}
|
||||
for (PreparedMessage message : pendingDatabaseMessages) {
|
||||
if (!failedMessages.contains(message)) {
|
||||
metrics.record(SyslogFailureRouter.TerminalState.SUCCESS);
|
||||
}
|
||||
}
|
||||
} catch (TimeoutException timeout) {
|
||||
cancelOutstanding(futures);
|
||||
throw new IllegalStateException("标准化批次处理超时,禁止提交 offset", timeout);
|
||||
} catch (InterruptedException interrupted) {
|
||||
cancelOutstanding(futures);
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("标准化批次被中断,禁止提交 offset", interrupted);
|
||||
} catch (ExecutionException executionFailure) {
|
||||
throw new IllegalStateException("标准化批次存在未到可靠终态的消息,禁止提交 offset",
|
||||
executionFailure.getCause());
|
||||
} catch (RuntimeException submitFailure) {
|
||||
cancelOutstanding(futures);
|
||||
throw submitFailure;
|
||||
}
|
||||
}
|
||||
|
||||
private static long elapsedMillis(long startedAtNanos) {
|
||||
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAtNanos);
|
||||
}
|
||||
|
||||
private void cancelOutstanding(List<? extends CompletableFuture<?>> futures) {
|
||||
for (CompletableFuture<?> future : futures) {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry/DLT 取得 Broker ACK 才返回;系统性故障抛出以保留原 offset。 */
|
||||
private SyslogFailureRouter.TerminalState routeFailure(ConsumerRecord<String, String> record,
|
||||
SyslogFailureRouter.MessageContext context,
|
||||
Exception failure) {
|
||||
SyslogFailureRouter.TerminalState state = failureRouter.route(record, context, failure);
|
||||
if (state == SyslogFailureRouter.TerminalState.PAUSED) {
|
||||
throw new IllegalStateException("系统性依赖故障,保留原 offset 等待恢复", failure);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** 已解密、已构造原文点,但尚未提交 Kafka offset 的批内消息。 */
|
||||
static final class PreparedMessage {
|
||||
private final ConsumerRecord<String, String> record;
|
||||
private final SyslogFailureRouter.MessageContext context;
|
||||
private final String decryptedMessage;
|
||||
private final String eventId;
|
||||
private final Point point;
|
||||
private final String bucket;
|
||||
private final boolean v2;
|
||||
private final LocalDateTime receivedAt;
|
||||
private final Long deviceId;
|
||||
private final Long deviceCollectId;
|
||||
private final long startTime;
|
||||
private final PreparedNormalizationInput normalizationInput;
|
||||
|
||||
PreparedMessage(ConsumerRecord<String, String> record,
|
||||
SyslogFailureRouter.MessageContext context,
|
||||
String decryptedMessage, String eventId, Point point,
|
||||
String bucket, boolean v2,
|
||||
LocalDateTime receivedAt, Long deviceId, Long deviceCollectId, long startTime,
|
||||
PreparedNormalizationInput normalizationInput) {
|
||||
this.record = record;
|
||||
this.context = context;
|
||||
this.decryptedMessage = decryptedMessage;
|
||||
this.eventId = eventId;
|
||||
this.point = point;
|
||||
this.bucket = bucket;
|
||||
this.v2 = v2;
|
||||
// 这个时间已由接入 receive_time 或 Kafka 首次接收时间解析,Retry/Replay 不得重算为当前时间。
|
||||
this.receivedAt = receivedAt;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCollectId = deviceCollectId;
|
||||
this.startTime = startTime;
|
||||
this.normalizationInput = normalizationInput;
|
||||
}
|
||||
|
||||
/** 保留既有并行单测构造入口。 */
|
||||
PreparedMessage(ConsumerRecord<String, String> record,
|
||||
SyslogFailureRouter.MessageContext context,
|
||||
String decryptedMessage, String eventId, Point point,
|
||||
LocalDateTime receivedAt, Long deviceId, Long deviceCollectId, long startTime) {
|
||||
this(record, context, decryptedMessage, eventId, point, "yelangbucket", false,
|
||||
receivedAt, deviceId, deviceCollectId, startTime,
|
||||
legacyNormalizationInput(decryptedMessage, eventId, receivedAt, deviceId, deviceCollectId));
|
||||
}
|
||||
|
||||
private static PreparedNormalizationInput legacyNormalizationInput(
|
||||
String message, String eventId, LocalDateTime receivedAt, Long deviceId, Long collectId) {
|
||||
String header = "";
|
||||
String body = message;
|
||||
Map<String, String> info = Collections.emptyMap();
|
||||
if (message != null && message.indexOf('[') >= 0 && message.indexOf(']') > message.indexOf('[')) {
|
||||
header = SyslogParser.substringBeforeFirstChar(message, ']');
|
||||
body = SyslogParser.substringAfterFirstCloseBracket(message);
|
||||
info = SyslogParser.parseKeyValuePairs(header);
|
||||
}
|
||||
return new PreparedNormalizationInput(eventId, null, receivedAt, deviceId, collectId,
|
||||
info.get("data_type"), body,
|
||||
message, header, info);
|
||||
}
|
||||
}
|
||||
|
||||
private List<IngressStatsEvent> ingressEvents(List<PreparedMessage> messages) {
|
||||
List<IngressStatsEvent> events = new ArrayList<>(messages.size());
|
||||
for (PreparedMessage message : messages) {
|
||||
events.add(new IngressStatsEvent(message.eventId, message.deviceId,
|
||||
message.deviceCollectId, message.receivedAt));
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
private static Long optionalLong(String value) {
|
||||
if (value == null || value.trim().isEmpty()) return null;
|
||||
try { return Long.valueOf(value.trim()); }
|
||||
catch (NumberFormatException invalid) { return null; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 并行计算阶段的结果封装。result 与 terminalState 二选一:前者等待达梦批写,后者表示该消息
|
||||
* 已经被 Retry/DLT 可靠接管。使用显式对象可以避免在工作线程里提前修改批次 ACK 状态。
|
||||
*/
|
||||
private static final class PreparedNormalization {
|
||||
private final PreparedMessage message;
|
||||
private final LogNormalProcessor.NormalizationResult result;
|
||||
private final SyslogFailureRouter.TerminalState terminalState;
|
||||
|
||||
private PreparedNormalization(PreparedMessage message,
|
||||
LogNormalProcessor.NormalizationResult result,
|
||||
SyslogFailureRouter.TerminalState terminalState) {
|
||||
this.message = message;
|
||||
this.result = result;
|
||||
this.terminalState = terminalState;
|
||||
}
|
||||
}
|
||||
|
||||
/** 单批终态计数,仅用于聚合日志,不参与 ACK 决策。 */
|
||||
static final class BatchMetrics {
|
||||
private final AtomicInteger success = new AtomicInteger();
|
||||
private final AtomicInteger filtered = new AtomicInteger();
|
||||
private final AtomicInteger retry = new AtomicInteger();
|
||||
private final AtomicInteger dlt = new AtomicInteger();
|
||||
private final AtomicInteger normalizedRows = new AtomicInteger();
|
||||
private final AtomicInteger dmSuccessfulRows = new AtomicInteger();
|
||||
private final AtomicInteger dmFailedMessages = new AtomicInteger();
|
||||
private final AtomicLong ruleComputeMs = new AtomicLong();
|
||||
private final AtomicLong ruleSnapshotMs = new AtomicLong();
|
||||
private final AtomicLong dmWriteMs = new AtomicLong();
|
||||
private volatile RuleExecutionMetrics ruleExecutionMetrics = new RuleExecutionMetrics();
|
||||
private volatile int deviceUnique;
|
||||
private volatile int collectTaskUnique;
|
||||
|
||||
void record(SyslogFailureRouter.TerminalState state) {
|
||||
if (state == SyslogFailureRouter.TerminalState.SUCCESS) {
|
||||
success.incrementAndGet();
|
||||
} else if (state == SyslogFailureRouter.TerminalState.FILTERED) {
|
||||
filtered.incrementAndGet();
|
||||
} else if (state == SyslogFailureRouter.TerminalState.RETRY_PUBLISHED) {
|
||||
retry.incrementAndGet();
|
||||
} else if (state == SyslogFailureRouter.TerminalState.DLT_PUBLISHED) {
|
||||
dlt.incrementAndGet();
|
||||
} else {
|
||||
throw new IllegalStateException("未到可靠终态的消息不能计入批次完成: " + state);
|
||||
}
|
||||
}
|
||||
|
||||
int successCount() {
|
||||
return success.get();
|
||||
}
|
||||
|
||||
long ruleComputeMs() {
|
||||
return ruleComputeMs.get();
|
||||
}
|
||||
|
||||
long dmWriteMs() {
|
||||
return dmWriteMs.get();
|
||||
}
|
||||
|
||||
long ruleSnapshotMs() { return ruleSnapshotMs.get(); }
|
||||
long messageParseMs() { return ruleExecutionMetrics.getMessageParseMs(); }
|
||||
long fieldMappingMs() { return ruleExecutionMetrics.getFieldMappingMs(); }
|
||||
long filterCompleteMs() { return ruleExecutionMetrics.getFilterCompleteMs(); }
|
||||
long enrichmentMs() { return ruleExecutionMetrics.getEnrichmentMs(); }
|
||||
long ruleAssembleMs() { return ruleExecutionMetrics.getAssembleMs(); }
|
||||
long compiledRuleHits() { return ruleExecutionMetrics.getCompiledHits(); }
|
||||
long compiledRuleMisses() { return ruleExecutionMetrics.getCompiledMisses(); }
|
||||
long messageParseHits() { return ruleExecutionMetrics.getParseHits(); }
|
||||
long messageParseMisses() { return ruleExecutionMetrics.getParseMisses(); }
|
||||
long shadowCompared() { return ruleExecutionMetrics.getShadowCompared(); }
|
||||
long shadowDifferences() { return ruleExecutionMetrics.getShadowDifferences(); }
|
||||
int deviceUnique() { return deviceUnique; }
|
||||
int collectTaskUnique() { return collectTaskUnique; }
|
||||
|
||||
void recordRuleComputeMs(long elapsedMs) {
|
||||
ruleComputeMs.set(Math.max(0L, elapsedMs));
|
||||
}
|
||||
|
||||
void recordRuleSnapshotMs(long elapsedMs) {
|
||||
ruleSnapshotMs.set(Math.max(0L, elapsedMs));
|
||||
}
|
||||
|
||||
void recordRuleExecution(RuleExecutionMetrics executionMetrics,
|
||||
BatchEnrichmentContext enrichmentContext) {
|
||||
this.ruleExecutionMetrics = executionMetrics;
|
||||
if (enrichmentContext != null) {
|
||||
this.deviceUnique = enrichmentContext.deviceUniqueCount();
|
||||
this.collectTaskUnique = enrichmentContext.collectTaskUniqueCount();
|
||||
}
|
||||
}
|
||||
|
||||
void recordDmWriteMs(long elapsedMs) {
|
||||
dmWriteMs.set(Math.max(0L, elapsedMs));
|
||||
}
|
||||
|
||||
/** 仅用于批次汇总观测,不参与 ACK 判断;ACK 仍由每条消息的可靠终态决定。 */
|
||||
void recordDmWrite(int rows, int successfulRows, int failedMessages) {
|
||||
this.normalizedRows.addAndGet(rows);
|
||||
this.dmSuccessfulRows.addAndGet(successfulRows);
|
||||
this.dmFailedMessages.addAndGet(failedMessages);
|
||||
}
|
||||
}
|
||||
|
||||
private String topicPartitions(List<ConsumerRecord<String, String>> records) {
|
||||
Set<String> partitions = new HashSet<>();
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
partitions.add(record.topic() + "-" + record.partition());
|
||||
}
|
||||
return partitions.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 为 InfluxDB 选择跨 Kafka Retry/Replay 稳定的时间戳。
|
||||
* 优先使用接入端 receive_time;旧消息缺失或格式异常时,回退到首次 Kafka 接收时间。
|
||||
*/
|
||||
static ResolvedInfluxTime resolveInfluxTime(String receiveTime, Instant ignoredFallbackTime) {
|
||||
ReceiveTimeParser.ParsedReceiveTime parsed = ReceiveTimeParser.parse(receiveTime);
|
||||
return new ResolvedInfluxTime(
|
||||
parsed.getEpochMillis(), parsed.getMeasurementDate(), parsed.getLocalDateTime());
|
||||
}
|
||||
|
||||
/** InfluxDB 点的时间戳和 measurement 日期必须由同一个接收时间计算。 */
|
||||
static final class ResolvedInfluxTime {
|
||||
private final long timestampMs;
|
||||
private final String measurementDate;
|
||||
private final LocalDateTime receivedAt;
|
||||
|
||||
private ResolvedInfluxTime(long timestampMs, String measurementDate, LocalDateTime receivedAt) {
|
||||
this.timestampMs = timestampMs;
|
||||
this.measurementDate = measurementDate;
|
||||
this.receivedAt = receivedAt;
|
||||
}
|
||||
|
||||
long getTimestampMs() {
|
||||
return timestampMs;
|
||||
}
|
||||
|
||||
String getMeasurementDate() {
|
||||
return measurementDate;
|
||||
}
|
||||
|
||||
LocalDateTime getReceivedAt() {
|
||||
return receivedAt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,6 +831,7 @@ public class SysLogProcessor {
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("批次处理异常: {}", batchIndex, e);
|
||||
throw new IllegalStateException("批次处理失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,19 +899,4 @@ public class SysLogProcessor {
|
||||
public int getCurrentBatchCount() { return currentBatchCount; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日志信息UUID,格式: yyyyMMddxxxxxxxx
|
||||
* @return
|
||||
*/
|
||||
private static String getSysLogUUID ()
|
||||
{
|
||||
// 获取当前日期
|
||||
LocalDate currentDate = LocalDate.now();
|
||||
// 定义格式 (yyyyMMdd)
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
// 格式化日期
|
||||
String formattedDate = currentDate.format(formatter);
|
||||
return formattedDate +"-"+ UUID.randomUUID() ;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.common.service.DmStandardizedBatchWriter;
|
||||
import com.influxdb.exceptions.BadRequestException;
|
||||
import com.influxdb.exceptions.InfluxException;
|
||||
import lombok.Data;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.common.KafkaException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketException;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* Kafka 异常消息可靠路由器。
|
||||
*
|
||||
* <p>该组件把“业务处理失败”与“原 offset 是否允许推进”放在同一个同步边界内:
|
||||
* Retry/DLT 的 send Future 只有取得 Broker ACK 后才返回终态;发布失败或结果未知一律抛出,
|
||||
* 让原消息保持未提交。这样不会用一次异步方法调用冒充消息已经被补偿链路接管。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class SyslogFailureRouter {
|
||||
|
||||
static final String ENVELOPE_TYPE = "SYSLOG_RELIABILITY_V1";
|
||||
private static final ZoneId EVENT_ID_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter EVENT_ID_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
private final KafkaTemplate<String, String> kafkaTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Value("${syslog.reliability.retry-1m-topic:${spring.kafka.consumer.topic}.RETRY.1M}")
|
||||
private String retry1mTopic;
|
||||
@Value("${syslog.reliability.retry-10m-topic:${spring.kafka.consumer.topic}.RETRY.10M}")
|
||||
private String retry10mTopic;
|
||||
@Value("${syslog.reliability.retry-1h-topic:${spring.kafka.consumer.topic}.RETRY.1H}")
|
||||
private String retry1hTopic;
|
||||
@Value("${syslog.reliability.dlt-topic:${spring.kafka.consumer.topic}.DLT}")
|
||||
private String dltTopic;
|
||||
@Value("${syslog.reliability.publish-timeout-ms:30000}")
|
||||
private long publishTimeoutMs;
|
||||
@Value("${syslog.reliability.consumer-version:unknown}")
|
||||
private String consumerVersion;
|
||||
|
||||
public SyslogFailureRouter(KafkaTemplate<String, String> kafkaTemplate, ObjectMapper objectMapper) {
|
||||
this.kafkaTemplate = kafkaTemplate;
|
||||
// Retry/DLT 是跨服务、跨版本协议,不能复用 Redis 缓存启用了默认类型信息的 Mapper。
|
||||
// 否则消息会携带 Java 专用的 @class,且安全白名单可能拒绝 FailureEnvelope,
|
||||
// 导致重试信封被误当成原始密文再次处理。副本保留 JavaTimeModule,但关闭类型信息;
|
||||
// FailureEnvelope 上的 ignoreUnknown 同时兼容现场已经产生的带 @class 历史消息。
|
||||
this.objectMapper = objectMapper.copy();
|
||||
this.objectMapper.deactivateDefaultTyping();
|
||||
}
|
||||
|
||||
/** 解析原始、Retry 或 Replay 消息,重试时始终返回最初的加密载荷和 event_id。 */
|
||||
public MessageContext resolve(ConsumerRecord<String, String> record) {
|
||||
FailureEnvelope envelope = readEnvelope(record.value());
|
||||
if (envelope == null) {
|
||||
Instant firstReceivedAt = receivedAt(record);
|
||||
return new MessageContext(record.value(), fallbackEventId(record, firstReceivedAt),
|
||||
0, null, firstReceivedAt, record.topic(), null);
|
||||
}
|
||||
return new MessageContext(envelope.getOriginalPayload(), envelope.getEventId(),
|
||||
envelope.getAttemptCount(), envelope.getNextRetryAt(),
|
||||
envelope.getFirstReceivedAt() == null ? receivedAt(record) : envelope.getFirstReceivedAt(),
|
||||
envelope.getOriginalTopic(), envelope.getPointTimeNs());
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧 Kafka 消息没有入口 event_id 时,使用首次 Kafka 接收日期和 topic-partition-offset
|
||||
* 生成带日期前缀的稳定 ID。重投同一原始 offset 始终得到同一个值,且不会再把随机 UUID
|
||||
* 前 8 位误当作 InfluxDB measurement 日期。
|
||||
*/
|
||||
static String fallbackEventId(ConsumerRecord<String, String> record, Instant firstReceivedAt) {
|
||||
String deterministicId = UUID.nameUUIDFromBytes(
|
||||
(record.topic() + ":" + record.partition() + ":" + record.offset())
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8)
|
||||
).toString();
|
||||
String datePrefix = EVENT_ID_DATE.format(firstReceivedAt.atZone(EVENT_ID_ZONE));
|
||||
return datePrefix + "-" + deterministicId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry Topic 本身不提供延时语义。未到期时短暂退避并拒绝 ACK,避免提前执行;
|
||||
* 部署时可用支持定时投递的 Kafka 网关替换此兼容实现。
|
||||
*/
|
||||
public void ensureRetryDue(MessageContext context) {
|
||||
if (context.getNextRetryAt() == null) {
|
||||
return;
|
||||
}
|
||||
long remaining = context.getNextRetryAt().toEpochMilli() - System.currentTimeMillis();
|
||||
if (remaining <= 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(Math.min(remaining, 1000L));
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
if (Instant.now().isBefore(context.getNextRetryAt())) {
|
||||
throw new RetryNotDueException("Retry 消息尚未到达 next_retry_at");
|
||||
}
|
||||
}
|
||||
|
||||
/** 根据异常影响范围决定暂停原消息,或在 Broker ACK 后返回可提交终态。 */
|
||||
public TerminalState route(ConsumerRecord<String, String> record, MessageContext context, Throwable failure) {
|
||||
FailureCategory category = classify(failure);
|
||||
if (category == FailureCategory.SYSTEMIC) {
|
||||
// [SYSLOG-ALARM][KACK][已修复] 系统性依赖故障不倾倒 DLT,也不提交原 offset,由容器背压并等待恢复。
|
||||
return TerminalState.PAUSED;
|
||||
}
|
||||
|
||||
int nextAttempt = Math.max(0, context.getAttemptCount()) + 1;
|
||||
boolean permanent = category == FailureCategory.PERMANENT_DATA;
|
||||
boolean exhausted = nextAttempt > 3;
|
||||
String targetTopic = (permanent || exhausted) ? dltTopic : retryTopic(nextAttempt);
|
||||
Instant nextRetryAt = (permanent || exhausted) ? null : Instant.now().plusSeconds(delaySeconds(nextAttempt));
|
||||
|
||||
FailureEnvelope source = readEnvelope(record.value());
|
||||
FailureEnvelope envelope = new FailureEnvelope();
|
||||
envelope.setEnvelopeType(ENVELOPE_TYPE);
|
||||
envelope.setEventId(context.getEventId());
|
||||
envelope.setDeviceId(context.getDeviceId() != null ? context.getDeviceId()
|
||||
: (source == null ? null : source.getDeviceId()));
|
||||
envelope.setOriginalTopic(source == null ? record.topic() : source.getOriginalTopic());
|
||||
envelope.setOriginalPartition(source == null ? record.partition() : source.getOriginalPartition());
|
||||
envelope.setOriginalOffset(source == null ? record.offset() : source.getOriginalOffset());
|
||||
envelope.setCurrentTopic(record.topic());
|
||||
// [SYSLOG-ALARM][ETIME][已修复] Retry/DLT/Replay 始终携带首次 Kafka 接收时间,
|
||||
// 不在每次转投时重置,供 InfluxDB 幂等时间戳和全链路对账使用。
|
||||
envelope.setFirstReceivedAt(context.getFirstReceivedAt());
|
||||
envelope.setFailedStage(detectStage(failure));
|
||||
envelope.setErrorCode(errorCode(category));
|
||||
envelope.setErrorType(rootCause(failure).getClass().getName());
|
||||
envelope.setErrorMessage(sanitize(rootCause(failure).getMessage()));
|
||||
envelope.setAttemptCount(nextAttempt);
|
||||
envelope.setNextRetryAt(nextRetryAt);
|
||||
envelope.setRuleId(source == null ? null : source.getRuleId());
|
||||
envelope.setRuleVersion(source == null ? null : source.getRuleVersion());
|
||||
envelope.setConsumerVersion(consumerVersion);
|
||||
envelope.setOriginalPayload(context.getPayload());
|
||||
envelope.setPointTimeNs(context.getPointTimeNs());
|
||||
|
||||
publishAndAwait(targetTopic, context.getEventId(), envelope);
|
||||
TerminalState state = (permanent || exhausted)
|
||||
? TerminalState.DLT_PUBLISHED : TerminalState.RETRY_PUBLISHED;
|
||||
log.warn("异常消息已由 Kafka 可靠接管: eventId={}, state={}, target={}, errorCode={}, attempt={}",
|
||||
context.getEventId(), state, targetTopic, envelope.getErrorCode(), nextAttempt);
|
||||
return state;
|
||||
}
|
||||
|
||||
private void publishAndAwait(String topic, String key, FailureEnvelope envelope) {
|
||||
try {
|
||||
String body = objectMapper.writeValueAsString(envelope);
|
||||
// [流程节点4.3] 必须等待 Broker ACK;仅调用 send() 不构成 RETRY_PUBLISHED/DLT_PUBLISHED。
|
||||
kafkaTemplate.send(topic, key, body).get(publishTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new FailurePublishException("发布异常消息时线程被中断,原 offset 不得提交", interrupted);
|
||||
} catch (ExecutionException | TimeoutException publishFailure) {
|
||||
throw new FailurePublishException("Retry/DLT 未取得 Broker ACK,原 offset 不得提交", publishFailure);
|
||||
} catch (Exception serializationFailure) {
|
||||
throw new FailurePublishException("异常消息序列化失败,原 offset 不得提交", serializationFailure);
|
||||
}
|
||||
}
|
||||
|
||||
FailureCategory classify(Throwable failure) {
|
||||
// 批写器已经把失败范围缩小到单条并完成了达梦错误判别。必须先识别这些包装异常,
|
||||
// 不能继续让内部 SQLException 的粗粒度规则把一条永久坏数据误判成整库故障,
|
||||
// 否则该 Kafka 分区会永久停在同一 offset。
|
||||
if (containsType(failure, DmStandardizedBatchWriter.PermanentRowWriteException.class)) {
|
||||
return FailureCategory.PERMANENT_DATA;
|
||||
}
|
||||
if (containsType(failure, DmStandardizedBatchWriter.RetryableRowWriteException.class)) {
|
||||
return FailureCategory.TRANSIENT;
|
||||
}
|
||||
Throwable root = rootCause(failure);
|
||||
// InfluxDB 400 数据格式错误只影响当前消息,可直接隔离;
|
||||
// 连接、超时、5xx 等 InfluxDB 故障属于系统性依赖故障,必须保留原 offset,避免 DLT 风暴。
|
||||
if (root instanceof BadRequestException) {
|
||||
return FailureCategory.PERMANENT_DATA;
|
||||
}
|
||||
if (root instanceof InfluxException) {
|
||||
return FailureCategory.SYSTEMIC;
|
||||
}
|
||||
if (root instanceof DataAccessResourceFailureException || root instanceof SQLException
|
||||
|| root instanceof ConnectException || root instanceof KafkaException
|
||||
|| root instanceof RejectedExecutionException) {
|
||||
return FailureCategory.SYSTEMIC;
|
||||
}
|
||||
if (root instanceof SocketException || root instanceof TimeoutException) {
|
||||
return FailureCategory.TRANSIENT;
|
||||
}
|
||||
if (containsInChain(failure, "规则", "rule_content", "configuration", "配置")) {
|
||||
return FailureCategory.CONFIGURATION_RULE;
|
||||
}
|
||||
if (root instanceof IllegalArgumentException || root instanceof SecurityException) {
|
||||
return FailureCategory.PERMANENT_DATA;
|
||||
}
|
||||
return FailureCategory.UNKNOWN;
|
||||
}
|
||||
|
||||
private boolean containsType(Throwable failure, Class<? extends Throwable> expectedType) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
if (expectedType.isInstance(current)) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean containsInChain(Throwable failure, String... tokens) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
String message = String.valueOf(current.getMessage()).toLowerCase(Locale.ROOT);
|
||||
for (String token : tokens) {
|
||||
if (message.contains(token.toLowerCase(Locale.ROOT))) return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private FailureEnvelope readEnvelope(String value) {
|
||||
if (value == null || value.length() < 2 || value.charAt(0) != '{') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
FailureEnvelope envelope = objectMapper.readValue(value, FailureEnvelope.class);
|
||||
return envelope != null && ENVELOPE_TYPE.equals(envelope.getEnvelopeType()) ? envelope : null;
|
||||
} catch (Exception ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Kafka 时间戳是旧消息缺失 receive_time 时的稳定回退值。 */
|
||||
private Instant receivedAt(ConsumerRecord<String, String> record) {
|
||||
return record.timestamp() > 0 ? Instant.ofEpochMilli(record.timestamp()) : Instant.now();
|
||||
}
|
||||
|
||||
private String retryTopic(int attempt) {
|
||||
if (attempt == 1) return retry1mTopic;
|
||||
if (attempt == 2) return retry10mTopic;
|
||||
return retry1hTopic;
|
||||
}
|
||||
|
||||
private long delaySeconds(int attempt) {
|
||||
if (attempt == 1) return 60L;
|
||||
if (attempt == 2) return 600L;
|
||||
return 3600L;
|
||||
}
|
||||
|
||||
private String errorCode(FailureCategory category) {
|
||||
return "SYSLOG_" + category.name();
|
||||
}
|
||||
|
||||
private String detectStage(Throwable failure) {
|
||||
String text = (failure.getMessage() + " " + rootCause(failure).getClass().getSimpleName()).toLowerCase(Locale.ROOT);
|
||||
if (text.contains("decrypt") || text.contains("sm4") || text.contains("解密")) return "DECRYPT";
|
||||
if (text.contains("sql") || text.contains("database") || text.contains("入库")) return "DB_WRITE";
|
||||
if (text.contains("parse") || text.contains("解析")) return "PARSE";
|
||||
return "NORMALIZE";
|
||||
}
|
||||
|
||||
private Throwable rootCause(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current.getCause() != null && current.getCause() != current) current = current.getCause();
|
||||
return current;
|
||||
}
|
||||
|
||||
private String sanitize(String message) {
|
||||
if (message == null) return "unknown";
|
||||
String sanitized = message.replaceAll("(?i)(password|token|secret|key)\\s*[=:]\\s*[^,;\\s]+", "$1=***")
|
||||
.replaceAll("[\\r\\n\\t]+", " ");
|
||||
return sanitized.length() <= 2048 ? sanitized : sanitized.substring(0, 2048);
|
||||
}
|
||||
|
||||
enum FailureCategory { PERMANENT_DATA, CONFIGURATION_RULE, TRANSIENT, SYSTEMIC, UNKNOWN }
|
||||
public enum TerminalState { SUCCESS, FILTERED, RETRY_PUBLISHED, DLT_PUBLISHED, PAUSED }
|
||||
|
||||
@Data
|
||||
public static class MessageContext {
|
||||
private final String payload;
|
||||
private final String eventId;
|
||||
private final int attemptCount;
|
||||
private final Instant nextRetryAt;
|
||||
private final Instant firstReceivedAt;
|
||||
private final String originalTopic;
|
||||
private Long pointTimeNs;
|
||||
private String deviceId;
|
||||
|
||||
public MessageContext(String payload, String eventId, int attemptCount,
|
||||
Instant nextRetryAt, Instant firstReceivedAt) {
|
||||
this(payload, eventId, attemptCount, nextRetryAt, firstReceivedAt, null, null);
|
||||
}
|
||||
|
||||
public MessageContext(String payload, String eventId, int attemptCount,
|
||||
Instant nextRetryAt, Instant firstReceivedAt,
|
||||
String originalTopic, Long pointTimeNs) {
|
||||
this.payload = payload; this.eventId = eventId; this.attemptCount = attemptCount;
|
||||
this.nextRetryAt = nextRetryAt; this.firstReceivedAt = firstReceivedAt;
|
||||
this.originalTopic = originalTopic; this.pointTimeNs = pointTimeNs;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class FailureEnvelope {
|
||||
private String envelopeType;
|
||||
private String eventId;
|
||||
private String deviceId;
|
||||
private String originalTopic;
|
||||
private Integer originalPartition;
|
||||
private Long originalOffset;
|
||||
private String currentTopic;
|
||||
private Instant firstReceivedAt;
|
||||
private String failedStage;
|
||||
private String errorCode;
|
||||
private String errorType;
|
||||
private String errorMessage;
|
||||
private int attemptCount;
|
||||
private Instant nextRetryAt;
|
||||
private String ruleId;
|
||||
private String ruleVersion;
|
||||
private String consumerVersion;
|
||||
private String originalPayload;
|
||||
private Long pointTimeNs;
|
||||
}
|
||||
|
||||
public static class FailurePublishException extends RuntimeException {
|
||||
public FailurePublishException(String message, Throwable cause) { super(message, cause); }
|
||||
}
|
||||
|
||||
public static class RetryNotDueException extends RuntimeException {
|
||||
public RetryNotDueException(String message) { super(message); }
|
||||
}
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.NormalizationCacheNames;
|
||||
import com.alicp.jetcache.Cache;
|
||||
import com.alicp.jetcache.CacheConfig;
|
||||
import com.alicp.jetcache.CacheManager;
|
||||
import com.alicp.jetcache.CacheResult;
|
||||
import com.alicp.jetcache.MultiLevelCacheConfig;
|
||||
import com.alicp.jetcache.anno.CacheType;
|
||||
import com.alicp.jetcache.support.Fastjson2KeyConvertor;
|
||||
import com.alicp.jetcache.support.Kryo5ValueDecoder;
|
||||
import com.alicp.jetcache.support.Kryo5ValueEncoder;
|
||||
import com.alicp.jetcache.template.QuickConfig;
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import com.config.NormalizationOptimizationProperties;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** 新 provider:只访问 JetCache BOTH,绝不嵌套 Spring Cache 或 SafeCacheUtil。 */
|
||||
@Component
|
||||
public class JetCacheLookupProvider {
|
||||
private static final Logger log = LoggerFactory.getLogger(JetCacheLookupProvider.class);
|
||||
private final NormalizationLookupDataLoader loader;
|
||||
private final NormalizationOptimizationProperties properties;
|
||||
private final NormalizationRuleMetrics metrics;
|
||||
private final ConcurrentHashMap<Long, FutureTask<RuleSourceSnapshot>> ruleLoads = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Integer, FutureTask<DeviceDevice>> deviceLoads = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Integer, FutureTask<DeviceCollectTask>> collectTaskLoads =
|
||||
new ConcurrentHashMap<>();
|
||||
private final Set<String> loggedCacheFailures = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private final Cache<Integer, DeviceDevice> deviceCache;
|
||||
private final Cache<Integer, DeviceCollectTask> collectTaskCache;
|
||||
private final Cache<Long, RuleSourceSnapshot> rulesCache;
|
||||
|
||||
@Autowired
|
||||
public JetCacheLookupProvider(NormalizationLookupDataLoader loader,
|
||||
NormalizationOptimizationProperties properties,
|
||||
NormalizationRuleMetrics metrics,
|
||||
CacheManager cacheManager) {
|
||||
this(loader, properties, metrics,
|
||||
cacheManager.<Integer, DeviceDevice>getOrCreateCache(quickConfig(
|
||||
NormalizationCacheNames.DEVICE_BY_ID,
|
||||
properties.getEnrichmentCache().getRemoteTtlSeconds(),
|
||||
properties.getEnrichmentCache().getLocalTtlSeconds())),
|
||||
cacheManager.<Integer, DeviceCollectTask>getOrCreateCache(quickConfig(
|
||||
NormalizationCacheNames.COLLECT_TASK_BY_ID,
|
||||
properties.getEnrichmentCache().getRemoteTtlSeconds(),
|
||||
properties.getEnrichmentCache().getLocalTtlSeconds())),
|
||||
cacheManager.<Long, RuleSourceSnapshot>getOrCreateCache(quickConfig(
|
||||
NormalizationCacheNames.RULES_BY_DEVICE,
|
||||
properties.getRuleSourceCache().getRemoteTtlSeconds(),
|
||||
properties.getRuleSourceCache().getLocalTtlSeconds())));
|
||||
}
|
||||
|
||||
JetCacheLookupProvider(NormalizationLookupDataLoader loader,
|
||||
NormalizationOptimizationProperties properties,
|
||||
NormalizationRuleMetrics metrics,
|
||||
Cache<Integer, DeviceDevice> deviceCache,
|
||||
Cache<Integer, DeviceCollectTask> collectTaskCache,
|
||||
Cache<Long, RuleSourceSnapshot> rulesCache) {
|
||||
this.loader = loader;
|
||||
this.properties = properties;
|
||||
this.metrics = metrics;
|
||||
this.deviceCache = deviceCache;
|
||||
this.collectTaskCache = collectTaskCache;
|
||||
this.rulesCache = rulesCache;
|
||||
}
|
||||
|
||||
static QuickConfig quickConfig(String name, int remoteTtlSeconds, int localTtlSeconds) {
|
||||
return QuickConfig.newBuilder(name)
|
||||
.cacheType(CacheType.BOTH)
|
||||
.expire(Duration.ofSeconds(remoteTtlSeconds))
|
||||
.localExpire(Duration.ofSeconds(localTtlSeconds))
|
||||
.localLimit(10_000)
|
||||
.syncLocal(true)
|
||||
.penetrationProtect(true)
|
||||
.keyConvertor(Fastjson2KeyConvertor.INSTANCE)
|
||||
.valueEncoder(Kryo5ValueEncoder.INSTANCE)
|
||||
.valueDecoder(Kryo5ValueDecoder.INSTANCE)
|
||||
.build();
|
||||
}
|
||||
|
||||
public DeviceDevice device(Integer id) {
|
||||
DeviceDevice cached = safeGet(deviceCache, id, "device");
|
||||
if (cached != null) return cached;
|
||||
FutureTask<DeviceDevice> candidate = new FutureTask<>(() -> loader.loadDevice(id));
|
||||
FutureTask<DeviceDevice> task = deviceLoads.putIfAbsent(id, candidate);
|
||||
if (task == null) {
|
||||
task = candidate;
|
||||
metrics.enrichment("device", "load");
|
||||
} else {
|
||||
metrics.enrichment("device", "hit");
|
||||
}
|
||||
return awaitAndCache(task, deviceLoads, id, deviceCache, "device");
|
||||
}
|
||||
|
||||
public DeviceCollectTask collectTask(Integer id) {
|
||||
DeviceCollectTask cached = safeGet(collectTaskCache, id, "collect_task");
|
||||
if (cached != null) return cached;
|
||||
FutureTask<DeviceCollectTask> candidate = new FutureTask<>(() -> loader.loadCollectTask(id));
|
||||
FutureTask<DeviceCollectTask> task = collectTaskLoads.putIfAbsent(id, candidate);
|
||||
if (task == null) {
|
||||
task = candidate;
|
||||
metrics.enrichment("collect_task", "load");
|
||||
} else {
|
||||
metrics.enrichment("collect_task", "hit");
|
||||
}
|
||||
return awaitAndCache(task, collectTaskLoads, id, collectTaskCache, "collect_task");
|
||||
}
|
||||
|
||||
/** 动态 put 让空快照只存 10 秒;FutureTask 保证本 JVM 同 key 并发只访问一次达梦。 */
|
||||
public RuleSourceSnapshot rules(Long deviceId) {
|
||||
RuleSourceSnapshot cached = cachedRuleSnapshot(deviceId);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
FutureTask<RuleSourceSnapshot> candidate = new FutureTask<>(() -> loader.loadRules(deviceId));
|
||||
FutureTask<RuleSourceSnapshot> task = ruleLoads.putIfAbsent(deviceId, candidate);
|
||||
if (task == null) {
|
||||
task = candidate;
|
||||
metrics.ruleSource("load");
|
||||
} else {
|
||||
metrics.ruleSource("suppressed");
|
||||
}
|
||||
task.run();
|
||||
try {
|
||||
RuleSourceSnapshot loaded = task.get();
|
||||
int remoteTtl = loaded.isEmpty()
|
||||
? properties.getRuleSourceCache().getEmptyTtlSeconds()
|
||||
: properties.getRuleSourceCache().getRemoteTtlSeconds();
|
||||
try {
|
||||
putRuleSnapshot(deviceId, loaded, remoteTtl);
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.ruleSource("failure");
|
||||
logCacheFailure("rule-source", "put", cacheFailure);
|
||||
}
|
||||
return loaded;
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("加载设备规则快照被中断: " + deviceId, interrupted);
|
||||
} catch (ExecutionException failure) {
|
||||
metrics.ruleSource("failure");
|
||||
throw new IllegalStateException("加载设备规则快照失败: " + deviceId, failure.getCause());
|
||||
} finally {
|
||||
ruleLoads.remove(deviceId, task);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private RuleSourceSnapshot cachedRuleSnapshot(Long deviceId) {
|
||||
try {
|
||||
List<Cache<Long, RuleSourceSnapshot>> layers = cacheLayers(rulesCache);
|
||||
if (layers.size() >= 2) {
|
||||
RuleSourceSnapshot local = layers.get(0).get(deviceId);
|
||||
if (local != null) {
|
||||
metrics.ruleSource("l1_hit");
|
||||
return local;
|
||||
}
|
||||
}
|
||||
RuleSourceSnapshot value = rulesCache.get(deviceId);
|
||||
if (value != null) metrics.ruleSource("l2_hit");
|
||||
return value;
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.ruleSource("failure");
|
||||
logCacheFailure("rule-source", "get", cacheFailure);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void putRuleSnapshot(Long deviceId, RuleSourceSnapshot loaded, int remoteTtl) {
|
||||
List<Cache<Long, RuleSourceSnapshot>> layers = cacheLayers(rulesCache);
|
||||
if (layers.size() < 2) {
|
||||
putChecked(rulesCache, deviceId, loaded, remoteTtl);
|
||||
return;
|
||||
}
|
||||
int localTtl = loaded.isEmpty()
|
||||
? Math.min(properties.getRuleSourceCache().getEmptyTtlSeconds(),
|
||||
properties.getRuleSourceCache().getLocalTtlSeconds())
|
||||
: properties.getRuleSourceCache().getLocalTtlSeconds();
|
||||
putChecked(layers.get(0), deviceId, loaded, localTtl);
|
||||
putChecked(layers.get(1), deviceId, loaded, remoteTtl);
|
||||
}
|
||||
|
||||
private <T> T safeGet(Cache<Integer, T> cache, Integer id, String entity) {
|
||||
try {
|
||||
T value = cache.get(id);
|
||||
if (value != null) metrics.enrichment(entity, "hit");
|
||||
return value;
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.enrichment(entity, "failure");
|
||||
logCacheFailure(entity, "get", cacheFailure);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T awaitAndCache(FutureTask<T> task,
|
||||
ConcurrentHashMap<Integer, FutureTask<T>> flights,
|
||||
Integer id, Cache<Integer, T> cache, String entity) {
|
||||
task.run();
|
||||
try {
|
||||
T value = task.get();
|
||||
if (value != null) putEnrichment(cache, id, value, entity);
|
||||
return value;
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
metrics.enrichment(entity, "failure");
|
||||
throw new IllegalStateException(entity + " 缓存加载被中断: " + id, interrupted);
|
||||
} catch (ExecutionException failure) {
|
||||
metrics.enrichment(entity, "failure");
|
||||
throw new IllegalStateException(entity + " 缓存加载失败: " + id, failure.getCause());
|
||||
} finally {
|
||||
flights.remove(id, task);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> void putEnrichment(Cache<Integer, T> cache, Integer id, T value, String entity) {
|
||||
try {
|
||||
List<Cache<Integer, T>> layers = cacheLayers(cache);
|
||||
int localTtl = properties.getEnrichmentCache().getLocalTtlSeconds();
|
||||
int remoteTtl = properties.getEnrichmentCache().getRemoteTtlSeconds();
|
||||
if (layers.size() >= 2) {
|
||||
putChecked(layers.get(0), id, value, localTtl);
|
||||
putChecked(layers.get(1), id, value, remoteTtl);
|
||||
} else {
|
||||
putChecked(cache, id, value, remoteTtl);
|
||||
}
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
// 缓存故障降级为已成功的 mapper 事实;下次调用可以重试缓存。
|
||||
metrics.enrichment(entity, "failure");
|
||||
logCacheFailure(entity, "put", cacheFailure);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JetCache 2.7.8 的 MultiLevelCache.unwrap(MultiLevelCache.class) 会遍历子缓存,
|
||||
* 不会返回 MultiLevelCache 自身,因此必须从配置中取得分层缓存。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static <K, V> List<Cache<K, V>> cacheLayers(Cache<K, V> cache) {
|
||||
if (cache == null) return Collections.emptyList();
|
||||
CacheConfig<K, V> config = cache.config();
|
||||
if (config instanceof MultiLevelCacheConfig) {
|
||||
List<Cache<K, V>> layers = ((MultiLevelCacheConfig<K, V>) config).getCaches();
|
||||
if (layers != null && !layers.isEmpty()) return layers;
|
||||
}
|
||||
return Collections.singletonList(cache);
|
||||
}
|
||||
|
||||
private static <K, V> void putChecked(Cache<K, V> cache, K key, V value, int ttlSeconds) {
|
||||
CacheResult result = cache.PUT(key, value, ttlSeconds, TimeUnit.SECONDS);
|
||||
if (!result.isSuccess()) {
|
||||
throw new IllegalStateException("JetCache PUT 失败: code=" + result.getResultCode()
|
||||
+ ", reason=" + safeReason(result.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private void logCacheFailure(String cache, String operation, RuntimeException failure) {
|
||||
String key = cache + ':' + operation;
|
||||
if (loggedCacheFailures.add(key)) {
|
||||
log.warn("JetCache 访问失败,已降级数据库: cache={}, operation={}, error={}, reason={}",
|
||||
cache, operation, failure.getClass().getSimpleName(), safeReason(failure.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private static String safeReason(String reason) {
|
||||
if (reason == null || reason.trim().isEmpty()) return "unknown";
|
||||
String oneLine = reason.replace('\r', ' ').replace('\n', ' ').trim();
|
||||
return oneLine.length() <= 240 ? oneLine : oneLine.substring(0, 240);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 回滚 provider:每个查询只经过既有 Spring Redis Cache 一层。 */
|
||||
@Component
|
||||
public class LegacySpringCacheLookupProvider {
|
||||
private final NormalizationLookupDataLoader loader;
|
||||
|
||||
public LegacySpringCacheLookupProvider(NormalizationLookupDataLoader loader) {
|
||||
this.loader = loader;
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "device", key = "'device:id:' + #id", sync = true)
|
||||
public DeviceDevice device(Integer id) {
|
||||
return loader.loadDevice(id);
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "collectTask", key = "'id:' + #id", sync = true)
|
||||
public DeviceCollectTask collectTask(Integer id) {
|
||||
return loader.loadCollectTask(id);
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "normalizeRule", key = "'deviceId:' + #deviceId", sync = true)
|
||||
public RuleSourceSnapshot rules(Long deviceId) {
|
||||
return loader.loadRules(deviceId);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.NormalizationCacheInvalidator;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/** 同时覆盖当前活动 provider 的统一精确失效入口;单级失败不覆盖数据库提交结果。 */
|
||||
@Component
|
||||
public class NormalizationCacheInvalidationService {
|
||||
private final CacheManager springCacheManager;
|
||||
private final NormalizationCacheInvalidator jetCacheInvalidator;
|
||||
private final NormalizationRuleMetrics metrics;
|
||||
|
||||
public NormalizationCacheInvalidationService(CacheManager springCacheManager,
|
||||
NormalizationCacheInvalidator jetCacheInvalidator,
|
||||
NormalizationRuleMetrics metrics) {
|
||||
this.springCacheManager = springCacheManager;
|
||||
this.jetCacheInvalidator = jetCacheInvalidator;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
public void invalidateDevice(Integer id) {
|
||||
evictSpring("device", "device:id:" + id);
|
||||
metrics.invalidation("local");
|
||||
jetCacheInvalidator.device(id);
|
||||
metrics.invalidation("remote");
|
||||
}
|
||||
|
||||
public void invalidateCollectTask(Integer id) {
|
||||
evictSpring("collectTask", "id:" + id);
|
||||
metrics.invalidation("local");
|
||||
jetCacheInvalidator.collectTask(id);
|
||||
metrics.invalidation("remote");
|
||||
}
|
||||
|
||||
public void invalidateCollectTaskViews(Integer... deviceIds) {
|
||||
evictSpring("collectTask", "all");
|
||||
if (deviceIds == null) return;
|
||||
for (Integer deviceId : deviceIds) {
|
||||
if (deviceId != null) evictSpring("collectTask", "device:" + deviceId);
|
||||
}
|
||||
}
|
||||
|
||||
public void invalidateRulesForDevice(Long deviceId) {
|
||||
evictSpring("normalizeRule", "deviceId:" + deviceId);
|
||||
metrics.invalidation("local");
|
||||
jetCacheInvalidator.rulesForDevice(deviceId);
|
||||
metrics.invalidation("remote");
|
||||
}
|
||||
|
||||
public void invalidateRuleEntity(Long ruleId) {
|
||||
evictSpring("normalizeRule", "id:" + ruleId);
|
||||
}
|
||||
|
||||
public void invalidateRulesForDevices(Collection<Long> deviceIds) {
|
||||
if (deviceIds == null) return;
|
||||
for (Long deviceId : deviceIds) {
|
||||
if (deviceId != null) invalidateRulesForDevice(deviceId);
|
||||
}
|
||||
}
|
||||
|
||||
private void evictSpring(String cacheName, Object key) {
|
||||
Cache cache = springCacheManager.getCache(cacheName);
|
||||
if (cache != null) cache.evict(key);
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.RuleSource;
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import com.common.mapper.DeviceCollectTaskMapper;
|
||||
import com.common.mapper.DeviceDeviceMapper;
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Clob;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 三个 provider 共用的无缓存数据加载器,保证 CLOB 在 mapper 返回后立即脱离 JDBC 生命周期。 */
|
||||
@Component
|
||||
public class NormalizationLookupDataLoader {
|
||||
private final DeviceDeviceMapper deviceMapper;
|
||||
private final DeviceCollectTaskMapper collectTaskMapper;
|
||||
private final DmNormalizeRuleMapper ruleMapper;
|
||||
|
||||
public NormalizationLookupDataLoader(DeviceDeviceMapper deviceMapper,
|
||||
DeviceCollectTaskMapper collectTaskMapper,
|
||||
DmNormalizeRuleMapper ruleMapper) {
|
||||
this.deviceMapper = deviceMapper;
|
||||
this.collectTaskMapper = collectTaskMapper;
|
||||
this.ruleMapper = ruleMapper;
|
||||
}
|
||||
|
||||
public DeviceDevice loadDevice(Integer id) {
|
||||
return deviceMapper.selectById(id);
|
||||
}
|
||||
|
||||
public DeviceCollectTask loadCollectTask(Integer id) {
|
||||
return collectTaskMapper.selectById(id);
|
||||
}
|
||||
|
||||
public RuleSourceSnapshot loadRules(Long deviceId) {
|
||||
List<Map<String, Object>> rows = ruleMapper.selectByDeviceId(deviceId);
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return new RuleSourceSnapshot(deviceId, Collections.emptyList(), Instant.now());
|
||||
}
|
||||
List<RuleSource> rules = new ArrayList<>(rows.size());
|
||||
for (Map<String, Object> row : rows) {
|
||||
if (row == null) continue;
|
||||
Map<String, Object> detached = new LinkedHashMap<>(row.size());
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) {
|
||||
detached.put(entry.getKey(), detach(entry.getValue()));
|
||||
}
|
||||
rules.add(RuleSource.fromMap(detached));
|
||||
}
|
||||
return new RuleSourceSnapshot(deviceId, rules, Instant.now());
|
||||
}
|
||||
|
||||
private static Object detach(Object value) {
|
||||
if (value == null) return null;
|
||||
if (value instanceof Clob) {
|
||||
try {
|
||||
Clob clob = (Clob) value;
|
||||
long length = clob.length();
|
||||
return length == 0 ? "" : clob.getSubString(1, Math.toIntExact(length));
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException("规则 CLOB 转 String 失败", failure);
|
||||
}
|
||||
}
|
||||
if (value.getClass().getName().startsWith("dm.jdbc.")) return value.toString();
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import com.config.NormalizationOptimizationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 唯一热查询路由;一次调用严格只进入一个 provider。 */
|
||||
@Component
|
||||
public class NormalizationLookupFacade {
|
||||
private final LegacySpringCacheLookupProvider legacy;
|
||||
private final JetCacheLookupProvider jetCache;
|
||||
private final NormalizationOptimizationProperties properties;
|
||||
|
||||
public NormalizationLookupFacade(LegacySpringCacheLookupProvider legacy,
|
||||
JetCacheLookupProvider jetCache,
|
||||
NormalizationOptimizationProperties properties) {
|
||||
this.legacy = legacy;
|
||||
this.jetCache = jetCache;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public DeviceDevice device(Integer id) {
|
||||
return properties.isJetcacheEnabled() ? jetCache.device(id) : legacy.device(id);
|
||||
}
|
||||
|
||||
public DeviceCollectTask collectTask(Integer id) {
|
||||
return properties.isJetcacheEnabled() ? jetCache.collectTask(id) : legacy.collectTask(id);
|
||||
}
|
||||
|
||||
public RuleSourceSnapshot rules(Long deviceId) {
|
||||
return properties.isJetcacheEnabled() && properties.getRuleSourceCache().isEnabled()
|
||||
? jetCache.rules(deviceId) : legacy.rules(deviceId);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.CompiledRuleCache;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
|
||||
/** 只有数据库事务真正提交后才清除 raw/compiled 缓存并广播 L1 失效。 */
|
||||
@Component
|
||||
public class NormalizeRuleCacheInvalidationListener {
|
||||
private static final Logger log = LoggerFactory.getLogger(NormalizeRuleCacheInvalidationListener.class);
|
||||
|
||||
private final NormalizationCacheInvalidationService invalidationService;
|
||||
private final CompiledRuleCache compiledRuleCache;
|
||||
private final NormalizationRuleMetrics metrics;
|
||||
|
||||
public NormalizeRuleCacheInvalidationListener(NormalizationCacheInvalidationService invalidationService,
|
||||
CompiledRuleCache compiledRuleCache,
|
||||
NormalizationRuleMetrics metrics) {
|
||||
this.invalidationService = invalidationService;
|
||||
this.compiledRuleCache = compiledRuleCache;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||
public void afterCommit(NormalizeRuleChangedEvent event) {
|
||||
metrics.invalidation("after_commit");
|
||||
// 先移除跨 JVM 的规则事实,再清除本 JVM 所有历史 fingerprint 编译对象。
|
||||
for (Long deviceId : event.getDeviceIds()) {
|
||||
try {
|
||||
invalidationService.invalidateRulesForDevice(deviceId);
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.invalidation("failure");
|
||||
log.error("规则提交后 raw cache 失效失败: ruleId={}, deviceId={}, operation={}",
|
||||
event.getRuleId(), deviceId, event.getOperation(), cacheFailure);
|
||||
}
|
||||
}
|
||||
try {
|
||||
compiledRuleCache.invalidateRule(event.getRuleId());
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.invalidation("failure");
|
||||
// 数据库事实已提交;raw rules 的短 TTL 是最终一致性兜底。
|
||||
log.error("规则提交后 compiled cache 失效失败: ruleId={}, operation={}",
|
||||
event.getRuleId(), event.getOperation(), cacheFailure);
|
||||
}
|
||||
try {
|
||||
invalidationService.invalidateRuleEntity(event.getRuleId());
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
metrics.invalidation("failure");
|
||||
log.error("规则提交后实体缓存失效失败: ruleId={}", event.getRuleId(), cacheFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** 事务内发布的低敏领域事件,不携带规则正文。 */
|
||||
public final class NormalizeRuleChangedEvent {
|
||||
private final long ruleId;
|
||||
private final List<Long> deviceIds;
|
||||
private final String operation;
|
||||
|
||||
public NormalizeRuleChangedEvent(long ruleId, List<Long> deviceIds, String operation) {
|
||||
this.ruleId = ruleId;
|
||||
this.deviceIds = deviceIds == null ? Collections.emptyList()
|
||||
: Collections.unmodifiableList(new ArrayList<>(deviceIds));
|
||||
this.operation = operation;
|
||||
}
|
||||
|
||||
public long getRuleId() { return ruleId; }
|
||||
public List<Long> getDeviceIds() { return deviceIds; }
|
||||
public String getOperation() { return operation; }
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.Modules.NormalData.cache;
|
||||
|
||||
import com.Modules.NormalData.compiled.RuleSource;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** 可安全跨 JVM 缓存的设备规则事实快照,不持有 JDBC/MyBatis 对象。 */
|
||||
public final class RuleSourceSnapshot implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final long deviceId;
|
||||
private final List<RuleSource> rules;
|
||||
private final Instant loadedAt;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private RuleSourceSnapshot() {
|
||||
this(0L, Collections.emptyList(), Instant.EPOCH);
|
||||
}
|
||||
|
||||
public RuleSourceSnapshot(long deviceId, List<RuleSource> rules, Instant loadedAt) {
|
||||
this.deviceId = deviceId;
|
||||
this.rules = new ArrayList<>(rules);
|
||||
this.loadedAt = loadedAt;
|
||||
}
|
||||
|
||||
public long getDeviceId() { return deviceId; }
|
||||
public List<RuleSource> getRules() { return Collections.unmodifiableList(rules); }
|
||||
public Instant getLoadedAt() { return loadedAt; }
|
||||
public boolean isEmpty() { return rules.isEmpty(); }
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import com.common.service.DeviceCollectTaskService;
|
||||
import com.common.service.DeviceDeviceService;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.FutureTask;
|
||||
|
||||
/**
|
||||
* 批次内按 ID single-flight。FutureTask 允许缓存 null(通过 Optional)并把 loader 异常传播到 ACK 边界。
|
||||
*/
|
||||
public final class BatchEnrichmentContext {
|
||||
private final boolean enabled;
|
||||
private final DeviceCollectTaskService collectTaskService;
|
||||
private final DeviceDeviceService deviceService;
|
||||
private final NormalizationRuleMetrics metrics;
|
||||
private final ConcurrentHashMap<Integer, FutureTask<Optional<DeviceSnapshot>>> devices =
|
||||
new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<Integer, FutureTask<Optional<CollectTaskSnapshot>>> collectTasks =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
public BatchEnrichmentContext(boolean enabled, DeviceCollectTaskService collectTaskService,
|
||||
DeviceDeviceService deviceService) {
|
||||
this(enabled, collectTaskService, deviceService, null);
|
||||
}
|
||||
|
||||
public BatchEnrichmentContext(boolean enabled, DeviceCollectTaskService collectTaskService,
|
||||
DeviceDeviceService deviceService, NormalizationRuleMetrics metrics) {
|
||||
this.enabled = enabled;
|
||||
this.collectTaskService = collectTaskService;
|
||||
this.deviceService = deviceService;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
public DeviceSnapshot device(int id) {
|
||||
if (!enabled) return loadDevice(id);
|
||||
FutureTask<Optional<DeviceSnapshot>> candidate = new FutureTask<>(() ->
|
||||
Optional.ofNullable(loadDevice(id)));
|
||||
FutureTask<Optional<DeviceSnapshot>> task = devices.putIfAbsent(id, candidate);
|
||||
if (task == null) {
|
||||
task = candidate;
|
||||
metric("device", "load");
|
||||
} else {
|
||||
metric("device", "hit");
|
||||
}
|
||||
return await(task, "device", id).orElse(null);
|
||||
}
|
||||
|
||||
public CollectTaskSnapshot collectTask(int id) {
|
||||
if (!enabled) return loadCollectTask(id);
|
||||
FutureTask<Optional<CollectTaskSnapshot>> candidate = new FutureTask<>(() ->
|
||||
Optional.ofNullable(loadCollectTask(id)));
|
||||
FutureTask<Optional<CollectTaskSnapshot>> task = collectTasks.putIfAbsent(id, candidate);
|
||||
if (task == null) {
|
||||
task = candidate;
|
||||
metric("collect_task", "load");
|
||||
} else {
|
||||
metric("collect_task", "hit");
|
||||
}
|
||||
return await(task, "collectTask", id).orElse(null);
|
||||
}
|
||||
|
||||
private DeviceSnapshot loadDevice(int id) {
|
||||
try {
|
||||
DeviceDevice loaded = deviceService.getByIdSafely(id);
|
||||
return DeviceSnapshot.from(loaded);
|
||||
} catch (RuntimeException failure) {
|
||||
metric("device", "failure");
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private CollectTaskSnapshot loadCollectTask(int id) {
|
||||
try {
|
||||
DeviceCollectTask loaded = collectTaskService.getById(id);
|
||||
return CollectTaskSnapshot.from(loaded);
|
||||
} catch (RuntimeException failure) {
|
||||
metric("collect_task", "failure");
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private void metric(String entity, String outcome) {
|
||||
if (metrics != null) metrics.enrichment(entity, outcome);
|
||||
}
|
||||
|
||||
private static <T> Optional<T> await(FutureTask<Optional<T>> task, String entity, int id) {
|
||||
task.run();
|
||||
try {
|
||||
return task.get();
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException(entity + " 批次补全被中断: " + id, interrupted);
|
||||
} catch (ExecutionException failure) {
|
||||
throw new IllegalStateException(entity + " 批次补全加载失败: " + id, failure.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public int deviceUniqueCount() { return devices.size(); }
|
||||
public int collectTaskUniqueCount() { return collectTasks.size(); }
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 一个 Kafka poll 固定使用的原始规则快照。 */
|
||||
public final class BatchRuleSnapshot {
|
||||
private final Map<Long, List<RuleSource>> byDevice;
|
||||
private final long capturedAtMillis;
|
||||
|
||||
public BatchRuleSnapshot(Map<Long, List<RuleSource>> byDevice, long capturedAtMillis) {
|
||||
Map<Long, List<RuleSource>> copy = new LinkedHashMap<>();
|
||||
for (Map.Entry<Long, List<RuleSource>> entry : byDevice.entrySet()) {
|
||||
copy.put(entry.getKey(), Collections.unmodifiableList(new ArrayList<>(entry.getValue())));
|
||||
}
|
||||
this.byDevice = Collections.unmodifiableMap(copy);
|
||||
this.capturedAtMillis = capturedAtMillis;
|
||||
}
|
||||
|
||||
public List<RuleSource> rulesFor(long deviceId) {
|
||||
List<RuleSource> rules = byDevice.get(deviceId);
|
||||
return rules == null ? Collections.emptyList() : rules;
|
||||
}
|
||||
|
||||
public long getCapturedAtMillis() { return capturedAtMillis; }
|
||||
public int getDeviceCount() { return byDevice.size(); }
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
|
||||
/** 批次内不可变的采集任务补全数据。 */
|
||||
public final class CollectTaskSnapshot {
|
||||
private final String deviceIp;
|
||||
private final String taskName;
|
||||
|
||||
private CollectTaskSnapshot(String deviceIp, String taskName) {
|
||||
this.deviceIp = deviceIp;
|
||||
this.taskName = taskName;
|
||||
}
|
||||
|
||||
public static CollectTaskSnapshot from(DeviceCollectTask task) {
|
||||
return task == null ? null : new CollectTaskSnapshot(task.getDeviceIp(), task.getTaskName());
|
||||
}
|
||||
|
||||
public String getDeviceIp() { return deviceIp; }
|
||||
public String getTaskName() { return taskName; }
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class CompiledCompletion {
|
||||
private final String columnName;
|
||||
private final Object value;
|
||||
private final boolean orRelation;
|
||||
private final List<CompiledPredicate> conditions;
|
||||
|
||||
public CompiledCompletion(String columnName, Object value, boolean orRelation,
|
||||
List<CompiledPredicate> conditions) {
|
||||
this.columnName = columnName;
|
||||
this.value = value;
|
||||
this.orRelation = orRelation;
|
||||
this.conditions = Collections.unmodifiableList(new ArrayList<>(conditions));
|
||||
}
|
||||
|
||||
public boolean apply(Map<String, Object> fields) {
|
||||
if (fields.containsKey(columnName) && fields.get(columnName) != null) return false;
|
||||
boolean matches;
|
||||
if (conditions.isEmpty()) {
|
||||
matches = true;
|
||||
} else if (orRelation) {
|
||||
matches = false;
|
||||
for (CompiledPredicate condition : conditions) {
|
||||
if (condition.evaluate(fields.get(condition.getColumnName()), true)) {
|
||||
matches = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
matches = true;
|
||||
for (CompiledPredicate condition : conditions) {
|
||||
if (!condition.evaluate(fields.get(condition.getColumnName()), true)) {
|
||||
matches = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (matches) fields.put(columnName, value);
|
||||
return matches;
|
||||
}
|
||||
|
||||
public String getColumnName() { return columnName; }
|
||||
public Object getValue() { return value; }
|
||||
public boolean isOrRelation() { return orRelation; }
|
||||
public List<CompiledPredicate> getConditions() { return conditions; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CompiledCompletion{" +
|
||||
"columnName='" + columnName + '\'' +
|
||||
", value=" + value +
|
||||
", orRelation=" + orRelation +
|
||||
", conditions=" + conditions +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.common.entity.RuleContent.Cropper_paramsType;
|
||||
|
||||
/** 不可变的正文截取配置。 */
|
||||
public final class CompiledCropper {
|
||||
private final String headKey;
|
||||
private final int headOffset;
|
||||
private final String tailKey;
|
||||
private final int tailOffset;
|
||||
|
||||
public CompiledCropper(String headKey, int headOffset, String tailKey, int tailOffset) {
|
||||
this.headKey = headKey;
|
||||
this.headOffset = headOffset;
|
||||
this.tailKey = tailKey;
|
||||
this.tailOffset = tailOffset;
|
||||
}
|
||||
|
||||
public Cropper_paramsType toLegacyParams() {
|
||||
Cropper_paramsType params = new Cropper_paramsType();
|
||||
params.sethead_key(headKey);
|
||||
params.sethead_offset(headOffset);
|
||||
params.settail_key(tailKey);
|
||||
params.settail_offset(tailOffset);
|
||||
return params;
|
||||
}
|
||||
|
||||
public String getHeadKey() { return headKey; }
|
||||
public int getHeadOffset() { return headOffset; }
|
||||
public String getTailKey() { return tailKey; }
|
||||
public int getTailOffset() { return tailOffset; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CompiledCropper{" +
|
||||
"headKey='" + headKey + '\'' +
|
||||
", headOffset=" + headOffset +
|
||||
", tailKey='" + tailKey + '\'' +
|
||||
", tailOffset=" + tailOffset +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class CompiledFilterGroup {
|
||||
private final boolean orRelation;
|
||||
private final List<CompiledPredicate> predicates;
|
||||
|
||||
public CompiledFilterGroup(boolean orRelation, List<CompiledPredicate> predicates) {
|
||||
this.orRelation = orRelation;
|
||||
this.predicates = Collections.unmodifiableList(new ArrayList<>(predicates));
|
||||
}
|
||||
|
||||
public boolean matches(Map<String, Object> fields) {
|
||||
if (predicates.isEmpty()) return false;
|
||||
if (orRelation) {
|
||||
for (CompiledPredicate predicate : predicates) {
|
||||
if (predicate.evaluate(fields.get(predicate.getColumnName()), false)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
for (CompiledPredicate predicate : predicates) {
|
||||
if (!predicate.evaluate(fields.get(predicate.getColumnName()), false)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isOrRelation() { return orRelation; }
|
||||
public List<CompiledPredicate> getPredicates() { return predicates; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CompiledFilterGroup{" +
|
||||
"orRelation=" + orRelation +
|
||||
", predicates=" + predicates +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.common.util.TimeConversionUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** 单个字段映射的不可变执行计划。 */
|
||||
public final class CompiledMapper {
|
||||
public enum Action { EQUAL, MAPPING, TIME, LEGACY_NULL }
|
||||
|
||||
private final String originField;
|
||||
private final String destinationField;
|
||||
private final Action action;
|
||||
private final Map<String, Object> mapping;
|
||||
private final String timezone;
|
||||
|
||||
public CompiledMapper(String originField, String destinationField, Action action,
|
||||
Map<String, Object> mapping, String timezone) {
|
||||
this.originField = originField;
|
||||
this.destinationField = destinationField;
|
||||
this.action = action;
|
||||
this.mapping = mapping == null ? Collections.emptyMap()
|
||||
: Collections.unmodifiableMap(new LinkedHashMap<>(mapping));
|
||||
this.timezone = timezone;
|
||||
}
|
||||
|
||||
public Object map(Object sourceValue) {
|
||||
switch (action) {
|
||||
case EQUAL:
|
||||
return sanitize(sourceValue);
|
||||
case MAPPING:
|
||||
// 保持旧执行器语义:源值为 null 时规则执行失败,而不是静默映射成字符串 "null"。
|
||||
return sanitize(mapping.get(sourceValue.toString()));
|
||||
case TIME:
|
||||
try {
|
||||
return TimeConversionUtils.convertToMillis(sourceValue.toString(), timezone);
|
||||
} catch (Exception conversionFailure) {
|
||||
// 旧执行器在时间转换失败时仍写入目标字段,只是字段值为 null。
|
||||
return null;
|
||||
}
|
||||
case LEGACY_NULL:
|
||||
// 历史规则 action.type 为空时,旧执行器仍生成目标字段,但字段值保持 null。
|
||||
return null;
|
||||
default:
|
||||
throw new IllegalStateException("不支持的映射动作: " + action);
|
||||
}
|
||||
}
|
||||
|
||||
private static Object sanitize(Object value) {
|
||||
if (value instanceof String && ((String) value).contains("\u0000")) {
|
||||
return ((String) value).replace("\u0000", "");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public String getOriginField() { return originField; }
|
||||
public String getDestinationField() { return destinationField; }
|
||||
public Action getAction() { return action; }
|
||||
public Map<String, Object> getMapping() { return mapping; }
|
||||
public String getTimezone() { return timezone; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CompiledMapper{" +
|
||||
"originField='" + originField + '\'' +
|
||||
", destinationField='" + destinationField + '\'' +
|
||||
", action=" + action +
|
||||
", mapping=" + mapping +
|
||||
", timezone='" + timezone + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** 过滤和补全共用的预编译条件。 */
|
||||
public final class CompiledPredicate {
|
||||
public enum Operation { EQUAL, NOT_EQUAL, IN, ZERO_LEN, CONTAIN, REGEXP }
|
||||
|
||||
private final String columnName;
|
||||
private final Operation operation;
|
||||
private final Object value;
|
||||
private final List<Object> values;
|
||||
private final Pattern pattern;
|
||||
|
||||
public CompiledPredicate(String columnName, Operation operation, Object value,
|
||||
List<Object> values, Pattern pattern) {
|
||||
this.columnName = columnName;
|
||||
this.operation = operation;
|
||||
this.value = value;
|
||||
this.values = values == null ? Collections.emptyList()
|
||||
: Collections.unmodifiableList(new ArrayList<>(values));
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
public boolean evaluate(Object fieldValue, boolean completionSemantics) {
|
||||
String actual = fieldValue == null ? "" : fieldValue.toString();
|
||||
switch (operation) {
|
||||
case EQUAL:
|
||||
return value != null && actual.equals(value.toString());
|
||||
case NOT_EQUAL:
|
||||
// 两个旧服务对 null 的唯一差别:补全 != null 为 true,过滤为 false。
|
||||
return value == null ? completionSemantics : !actual.equals(value.toString());
|
||||
case IN:
|
||||
for (Object candidate : values) {
|
||||
if (candidate != null && actual.equals(candidate.toString())) return true;
|
||||
}
|
||||
return false;
|
||||
case ZERO_LEN:
|
||||
return value != null
|
||||
&& (!StringUtils.hasText(actual) == Boolean.parseBoolean(value.toString()));
|
||||
case CONTAIN:
|
||||
return value != null && actual.contains(value.toString());
|
||||
case REGEXP:
|
||||
return pattern != null && pattern.matcher(actual).matches();
|
||||
default:
|
||||
throw new IllegalStateException("不支持的条件操作: " + operation);
|
||||
}
|
||||
}
|
||||
|
||||
public String getColumnName() { return columnName; }
|
||||
public Operation getOperation() { return operation; }
|
||||
public Object getValue() { return value; }
|
||||
public List<Object> getValues() { return values; }
|
||||
public Pattern getPattern() { return pattern; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CompiledPredicate{" +
|
||||
"columnName='" + columnName + '\'' +
|
||||
", operation=" + operation +
|
||||
", value=" + value +
|
||||
", values=" + values +
|
||||
", pattern=" + (pattern == null ? "null" : "'" + pattern.pattern() + "'") +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.Modules.NormalData.logNormalData;
|
||||
import com.common.util.NestedJsonParserUtil;
|
||||
import com.common.util.NestedJsonUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 规则文本的一次性编译结果。该对象及其集合均不可变;消息动态数据永远不写入本对象。
|
||||
*/
|
||||
public final class CompiledRule {
|
||||
private final long ruleId;
|
||||
private final String ruleName;
|
||||
private final String displayName;
|
||||
private final String dataType;
|
||||
private final String fingerprint;
|
||||
private final CompiledCropper cropper;
|
||||
private final Map<String, List<CompiledMapper>> mapperByOriginField;
|
||||
private final List<CompiledFilterGroup> filters;
|
||||
private final List<CompiledCompletion> completions;
|
||||
private final MessageParserSignature parserSignature;
|
||||
private final String kvLeftTrim;
|
||||
private final String kvRightTrim;
|
||||
private final Pattern kvInternalPattern;
|
||||
private final Pattern kvExternalPattern;
|
||||
private final Pattern kvLeftTrimPattern;
|
||||
private final Pattern kvRightTrimPattern;
|
||||
private final Pattern separatorPattern;
|
||||
private final Pattern messageRegexPattern;
|
||||
|
||||
public CompiledRule(long ruleId, String ruleName, String displayName, String dataType,
|
||||
String fingerprint, CompiledCropper cropper,
|
||||
Map<String, List<CompiledMapper>> mapperByOriginField,
|
||||
List<CompiledFilterGroup> filters, List<CompiledCompletion> completions,
|
||||
MessageParserSignature parserSignature,
|
||||
String kvInternal, String kvExternal, String kvLeftTrim, String kvRightTrim,
|
||||
String separator, Pattern messageRegexPattern) {
|
||||
this.ruleId = ruleId;
|
||||
this.ruleName = ruleName;
|
||||
this.displayName = displayName;
|
||||
this.dataType = dataType;
|
||||
this.fingerprint = fingerprint;
|
||||
this.cropper = cropper;
|
||||
Map<String, List<CompiledMapper>> immutableIndex = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<CompiledMapper>> entry : mapperByOriginField.entrySet()) {
|
||||
immutableIndex.put(entry.getKey(), Collections.unmodifiableList(new ArrayList<>(entry.getValue())));
|
||||
}
|
||||
this.mapperByOriginField = Collections.unmodifiableMap(immutableIndex);
|
||||
this.filters = Collections.unmodifiableList(new ArrayList<>(filters));
|
||||
this.completions = Collections.unmodifiableList(new ArrayList<>(completions));
|
||||
this.parserSignature = parserSignature;
|
||||
this.kvLeftTrim = kvLeftTrim;
|
||||
this.kvRightTrim = kvRightTrim;
|
||||
this.kvInternalPattern = kvInternal == null ? null : Pattern.compile(Pattern.quote(kvInternal));
|
||||
this.kvExternalPattern = kvExternal == null ? null : Pattern.compile(Pattern.quote(kvExternal));
|
||||
this.kvLeftTrimPattern = empty(kvLeftTrim) ? null
|
||||
: Pattern.compile("^[" + Pattern.quote(kvLeftTrim) + "]+");
|
||||
this.kvRightTrimPattern = empty(kvRightTrim) ? null
|
||||
: Pattern.compile("[" + Pattern.quote(kvRightTrim) + "]+$");
|
||||
this.separatorPattern = separator == null ? null : Pattern.compile(separator);
|
||||
this.messageRegexPattern = messageRegexPattern;
|
||||
}
|
||||
|
||||
public ParsedMessage parse(String message) {
|
||||
String cropped = logNormalData.ParserMessageJsonType(message,
|
||||
cropper == null ? null : cropper.toLegacyParams());
|
||||
LinkedHashMap<String, Object> parsed;
|
||||
switch (dataType) {
|
||||
case "json":
|
||||
LinkedHashMap<String, Object> nested = NestedJsonParserUtil.safeParseJson(cropped);
|
||||
parsed = nested == null ? null : NestedJsonUtils.flattenNestedJson(nested);
|
||||
break;
|
||||
case "kv":
|
||||
parsed = parseKeyValue(cropped);
|
||||
break;
|
||||
case "sep":
|
||||
parsed = parseSeparated(cropped);
|
||||
break;
|
||||
case "regex":
|
||||
parsed = parseRegex(cropped);
|
||||
break;
|
||||
case "xml":
|
||||
parsed = new LinkedHashMap<>();
|
||||
break;
|
||||
default:
|
||||
throw new IllegalStateException("不支持的数据类型: " + dataType);
|
||||
}
|
||||
return parsed == null ? null : new ParsedMessage(parsed);
|
||||
}
|
||||
|
||||
public Map<String, Object> map(ParsedMessage message) {
|
||||
Map<String, Object> destination = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> source : message.getFields().entrySet()) {
|
||||
List<CompiledMapper> mappers = mapperByOriginField.get(source.getKey());
|
||||
if (mappers == null) continue;
|
||||
for (CompiledMapper mapper : mappers) {
|
||||
destination.put(mapper.getDestinationField(), mapper.map(source.getValue()));
|
||||
}
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
|
||||
public boolean isFiltered(Map<String, Object> destination) {
|
||||
for (CompiledFilterGroup group : filters) {
|
||||
if (group.matches(destination)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void complete(Map<String, Object> destination) {
|
||||
for (CompiledCompletion completion : completions) {
|
||||
completion.apply(destination);
|
||||
}
|
||||
}
|
||||
|
||||
private LinkedHashMap<String, Object> parseKeyValue(String text) {
|
||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||
if (empty(text)) return result;
|
||||
if (kvExternalPattern == null || kvInternalPattern == null) {
|
||||
throw new IllegalStateException("KV 规则缺少分隔参数");
|
||||
}
|
||||
String[] pairs = kvExternalPattern.split(text, 0);
|
||||
for (String pair : pairs) {
|
||||
if (empty(pair)) continue;
|
||||
String[] parts = kvInternalPattern.split(pair, 2);
|
||||
if (parts.length == 2) {
|
||||
String key = trim(parts[0].trim());
|
||||
String value = removeQuotes(trim(parts[1].trim()));
|
||||
result.put(key, value);
|
||||
} else if (parts.length == 1) {
|
||||
result.put(trim(parts[0].trim()), "");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private LinkedHashMap<String, Object> parseSeparated(String text) {
|
||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||
if (empty(text)) return result;
|
||||
if (separatorPattern == null || separatorPattern.pattern().isEmpty()) {
|
||||
result.put("1", text.trim());
|
||||
return result;
|
||||
}
|
||||
String[] values = separatorPattern.split(text, -1);
|
||||
for (int i = 0; i < values.length; i++) result.put(String.valueOf(i + 1), values[i].trim());
|
||||
return result;
|
||||
}
|
||||
|
||||
private LinkedHashMap<String, Object> parseRegex(String text) {
|
||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||
if (empty(text)) return result;
|
||||
Matcher matcher = messageRegexPattern.matcher(text);
|
||||
if (!matcher.find()) return result;
|
||||
if (matcher.groupCount() == 0) {
|
||||
result.put("1", matcher.group(0));
|
||||
} else {
|
||||
for (int i = 1; i <= matcher.groupCount(); i++) {
|
||||
String value = matcher.group(i);
|
||||
result.put(String.valueOf(i), value == null ? "" : value.trim());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String trim(String value) {
|
||||
String result = value;
|
||||
if (kvLeftTrimPattern != null) result = kvLeftTrimPattern.matcher(result).replaceAll("");
|
||||
if (kvRightTrimPattern != null) result = kvRightTrimPattern.matcher(result).replaceAll("");
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String removeQuotes(String value) {
|
||||
if (value == null || value.length() < 2) return value;
|
||||
if ((value.startsWith("\"") && value.endsWith("\""))
|
||||
|| (value.startsWith("'") && value.endsWith("'"))) {
|
||||
return value.substring(1, value.length() - 1);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static boolean empty(String value) {
|
||||
return value == null || value.trim().isEmpty();
|
||||
}
|
||||
|
||||
public long getRuleId() { return ruleId; }
|
||||
public String getRuleName() { return ruleName; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public String getDataType() { return dataType; }
|
||||
public String getFingerprint() { return fingerprint; }
|
||||
public CompiledCropper getCropper() { return cropper; }
|
||||
public Map<String, List<CompiledMapper>> getMapperByOriginField() { return mapperByOriginField; }
|
||||
public List<CompiledFilterGroup> getFilters() { return filters; }
|
||||
public List<CompiledCompletion> getCompletions() { return completions; }
|
||||
public MessageParserSignature getParserSignature() { return parserSignature; }
|
||||
public String getKvLeftTrim() { return kvLeftTrim; }
|
||||
public String getKvRightTrim() { return kvRightTrim; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CompiledRule{" +
|
||||
"ruleId=" + ruleId +
|
||||
", ruleName='" + ruleName + '\'' +
|
||||
", displayName='" + displayName + '\'' +
|
||||
", dataType='" + dataType + '\'' +
|
||||
", fingerprint='" + fingerprint + '\'' +
|
||||
", cropper=" + cropper +
|
||||
", mapperByOriginField=" + mapperByOriginField +
|
||||
", filters=" + filters +
|
||||
", completions=" + completions +
|
||||
", parserSignature=" + parserSignature +
|
||||
", kvLeftTrim='" + kvLeftTrim + '\'' +
|
||||
", kvRightTrim='" + kvRightTrim + '\'' +
|
||||
", kvInternalPattern=" + pattern(kvInternalPattern) +
|
||||
", kvExternalPattern=" + pattern(kvExternalPattern) +
|
||||
", kvLeftTrimPattern=" + pattern(kvLeftTrimPattern) +
|
||||
", kvRightTrimPattern=" + pattern(kvRightTrimPattern) +
|
||||
", separatorPattern=" + pattern(separatorPattern) +
|
||||
", messageRegexPattern=" + pattern(messageRegexPattern) +
|
||||
'}';
|
||||
}
|
||||
|
||||
private static String pattern(Pattern value) {
|
||||
return value == null ? "null" : "'" + value.pattern() + "'";
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.config.NormalizationOptimizationProperties;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Collections;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
/** JVM 本地、有界、single-flight 的编译规则缓存。 */
|
||||
@Component
|
||||
public class CompiledRuleCache {
|
||||
private static final Logger log = LoggerFactory.getLogger(CompiledRuleCache.class);
|
||||
private static final ObjectMapper DIAGNOSTIC_JSON = new ObjectMapper();
|
||||
private static final List<String> EXECUTION_RULE_FIELDS = Arrays.asList(
|
||||
"cropper_params", "kv_params", "sep", "regexp", "mappers",
|
||||
"filters_params", "complete_columns");
|
||||
|
||||
private final CompiledRuleCompiler compiler;
|
||||
private final Cache<String, CompiledRule> compiled;
|
||||
private final Cache<String, FailureRecord> failures;
|
||||
private final Cache<String, Boolean> loggedFailures;
|
||||
private final Cache<Long, Set<String>> keysByRule;
|
||||
private final NormalizationRuleMetrics metrics;
|
||||
private final boolean ruleDetailLogEnabled;
|
||||
private final LongAdder compileSuccess = new LongAdder();
|
||||
private final LongAdder compileFailure = new LongAdder();
|
||||
private final LongAdder evictions = new LongAdder();
|
||||
|
||||
public CompiledRuleCache(CompiledRuleCompiler compiler,
|
||||
NormalizationOptimizationProperties properties) {
|
||||
this(compiler, properties, new NormalizationRuleMetrics());
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public CompiledRuleCache(CompiledRuleCompiler compiler,
|
||||
NormalizationOptimizationProperties properties,
|
||||
NormalizationRuleMetrics metrics) {
|
||||
this.compiler = compiler;
|
||||
this.metrics = metrics;
|
||||
NormalizationOptimizationProperties.CompiledRule config = properties.getCompiledRule();
|
||||
this.ruleDetailLogEnabled = config.isRuleDetailLogEnabled();
|
||||
this.keysByRule = Caffeine.newBuilder()
|
||||
.maximumSize(config.getLocalLimit())
|
||||
.expireAfterAccess(config.getExpireAfterAccessMinutes(), TimeUnit.MINUTES)
|
||||
.build();
|
||||
this.compiled = Caffeine.newBuilder()
|
||||
.maximumSize(config.getLocalLimit())
|
||||
.expireAfterAccess(config.getExpireAfterAccessMinutes(), TimeUnit.MINUTES)
|
||||
.removalListener((key, value, cause) -> {
|
||||
if (cause.wasEvicted()) evictions.increment();
|
||||
if (key != null && value != null) unlink(((CompiledRule) value).getRuleId(), key.toString());
|
||||
})
|
||||
.build();
|
||||
this.failures = Caffeine.newBuilder()
|
||||
.maximumSize(Math.min(config.getLocalLimit(), 1_000))
|
||||
.expireAfterWrite(config.getFailureCacheSeconds(), TimeUnit.SECONDS)
|
||||
.build();
|
||||
this.loggedFailures = Caffeine.newBuilder()
|
||||
.maximumSize(Math.min(config.getLocalLimit(), 1_000))
|
||||
.expireAfterAccess(config.getExpireAfterAccessMinutes(), TimeUnit.MINUTES)
|
||||
.build();
|
||||
}
|
||||
|
||||
public CompiledRule get(RuleSource source, RuleExecutionMetrics metrics) {
|
||||
String key = compiler.fingerprint(source);
|
||||
CompiledRule cached = compiled.getIfPresent(key);
|
||||
if (cached != null) {
|
||||
if (metrics != null) metrics.compiledHit();
|
||||
this.metrics.compiledGet("hit");
|
||||
return cached;
|
||||
}
|
||||
if (metrics != null) metrics.compiledMiss();
|
||||
FailureRecord failed = failures.getIfPresent(key);
|
||||
if (failed != null) {
|
||||
this.metrics.compiledGet("failure_hit");
|
||||
throw failed.toException(source.getId());
|
||||
}
|
||||
this.metrics.compiledGet("miss");
|
||||
// Caffeine Cache.get 对同 key 的并发加载只执行一次,其他线程等待同一结果。
|
||||
return compiled.get(key, ignored -> {
|
||||
FailureRecord recentFailure = failures.getIfPresent(key);
|
||||
if (recentFailure != null) {
|
||||
this.metrics.compiledGet("failure_hit");
|
||||
throw recentFailure.toException(source.getId());
|
||||
}
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
this.metrics.ruleJsonParse();
|
||||
CompiledRule value = compiler.compile(source);
|
||||
keysByRule.asMap().computeIfAbsent(source.getId(), ruleId ->
|
||||
Collections.newSetFromMap(new ConcurrentHashMap<>())).add(key);
|
||||
compileSuccess.increment();
|
||||
this.metrics.compiled("success", System.nanoTime() - started);
|
||||
this.metrics.compiledCacheGauge(compiled.estimatedSize() + 1L, evictions.sum());
|
||||
if (ruleDetailLogEnabled) {
|
||||
log.info("标准化规则文本编译成功: ruleId={}, fingerprint={}, ruleText={}, compiledRule={}",
|
||||
source.getId(), shortFingerprint(key), diagnosticRuleText(source.getRuleContent()), value);
|
||||
}
|
||||
return value;
|
||||
} catch (RuntimeException failure) {
|
||||
compileFailure.increment();
|
||||
this.metrics.compiled("failure", System.nanoTime() - started);
|
||||
failures.put(key, new FailureRecord(failure));
|
||||
if (loggedFailures.asMap().putIfAbsent(key, Boolean.TRUE) == null) {
|
||||
if (ruleDetailLogEnabled) {
|
||||
log.warn("标准化规则编译失败,将对此规则使用旧执行器: ruleId={}, fingerprint={}, "
|
||||
+ "error={}, reason={}, ruleText={}", source.getId(), shortFingerprint(key),
|
||||
failure.getClass().getSimpleName(), safeReason(failure),
|
||||
diagnosticRuleText(source.getRuleContent()));
|
||||
} else {
|
||||
log.warn("标准化规则编译失败,将对此规则使用旧执行器: ruleId={}, fingerprint={}, "
|
||||
+ "error={}, reason={}", source.getId(), shortFingerprint(key),
|
||||
failure.getClass().getSimpleName(), safeReason(failure));
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void invalidateRule(long ruleId) {
|
||||
Set<String> keys = keysByRule.asMap().remove(ruleId);
|
||||
if (keys != null) compiled.invalidateAll(keys);
|
||||
for (String key : failures.asMap().keySet()) {
|
||||
if (key.startsWith(ruleId + ":")) failures.invalidate(key);
|
||||
}
|
||||
for (String key : loggedFailures.asMap().keySet()) {
|
||||
if (key.startsWith(ruleId + ":")) loggedFailures.invalidate(key);
|
||||
}
|
||||
metrics.compiledCacheGauge(compiled.estimatedSize(), evictions.sum());
|
||||
}
|
||||
|
||||
public long estimatedSize() { return compiled.estimatedSize(); }
|
||||
public long compileSuccessCount() { return compileSuccess.sum(); }
|
||||
public long compileFailureCount() { return compileFailure.sum(); }
|
||||
public long evictionCount() { return evictions.sum(); }
|
||||
|
||||
private static String shortFingerprint(String key) {
|
||||
int colon = key.indexOf(':');
|
||||
int end = Math.min(key.length(), colon < 0 ? 12 : colon + 13);
|
||||
return key.substring(0, end);
|
||||
}
|
||||
|
||||
private static String safeReason(RuntimeException failure) {
|
||||
String message = failure.getMessage();
|
||||
if (message == null || message.trim().isEmpty()) {
|
||||
return failure.getClass().getSimpleName();
|
||||
}
|
||||
String oneLine = message.replace('\r', ' ').replace('\n', ' ').trim();
|
||||
return oneLine.length() <= 240 ? oneLine : oneLine.substring(0, 240);
|
||||
}
|
||||
|
||||
static String diagnosticRuleText(String ruleText) {
|
||||
if (ruleText == null) return "null";
|
||||
try {
|
||||
JsonNode root = DIAGNOSTIC_JSON.readTree(ruleText);
|
||||
if (root == null || !root.isObject()) {
|
||||
return "<非对象规则正文,长度=" + ruleText.length() + ">";
|
||||
}
|
||||
ObjectNode diagnostic = DIAGNOSTIC_JSON.createObjectNode();
|
||||
for (String field : EXECUTION_RULE_FIELDS) {
|
||||
if (root.has(field)) diagnostic.set(field, root.get(field));
|
||||
}
|
||||
return DIAGNOSTIC_JSON.writeValueAsString(diagnostic)
|
||||
.replace("\r", "\\r").replace("\n", "\\n");
|
||||
} catch (Exception invalidJson) {
|
||||
// 无效 JSON 可能仍携带样例事件或凭据,失败时只记录长度,不回显原文。
|
||||
return "<规则正文无法安全解析,长度=" + ruleText.length() + ">";
|
||||
}
|
||||
}
|
||||
|
||||
private void unlink(long ruleId, String key) {
|
||||
Set<String> keys = keysByRule.getIfPresent(ruleId);
|
||||
if (keys == null) return;
|
||||
keys.remove(key);
|
||||
if (keys.isEmpty()) keysByRule.invalidate(ruleId);
|
||||
}
|
||||
|
||||
private static final class FailureRecord {
|
||||
private final String type;
|
||||
private final String reason;
|
||||
|
||||
private FailureRecord(RuntimeException failure) {
|
||||
this.type = failure.getClass().getSimpleName();
|
||||
this.reason = safeReason(failure);
|
||||
}
|
||||
|
||||
private RuntimeException toException(long ruleId) {
|
||||
return new CompiledRuleCompiler.RuleCompilationException(ruleId,
|
||||
"规则处于短失败缓存: " + type + ", " + reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** 将原始规则 JSON 编译成不可变执行计划;本类不访问任何外部系统。 */
|
||||
@Component
|
||||
public class CompiledRuleCompiler {
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public CompiledRuleCompiler(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public CompiledRule compile(RuleSource source) {
|
||||
if (source == null) throw new IllegalArgumentException("规则源不能为空");
|
||||
if (blank(source.getRuleContent())) throw invalid(source, "rule_content 不能为空");
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(source.getRuleContent());
|
||||
if (root == null || !root.isObject()) throw invalid(source, "rule_content 必须是 JSON 对象");
|
||||
|
||||
String dataType = required(source.getDataType(), source, "data_type").toLowerCase(Locale.ROOT);
|
||||
if (!("json".equals(dataType) || "kv".equals(dataType) || "sep".equals(dataType)
|
||||
|| "regex".equals(dataType) || "xml".equals(dataType))) {
|
||||
throw invalid(source, "未知 data_type: " + dataType);
|
||||
}
|
||||
CompiledCropper cropper = compileCropper(root.get("cropper_params"), source);
|
||||
KvConfig kv = compileKv(root.get("kv_params"), dataType, source);
|
||||
String separator = text(root.get("sep"));
|
||||
String regex = text(root.get("regexp"));
|
||||
Pattern messageRegex = null;
|
||||
if ("regex".equals(dataType)) {
|
||||
if (blank(regex)) throw invalid(source, "regex 规则缺少 regexp");
|
||||
messageRegex = Pattern.compile(regex);
|
||||
}
|
||||
if ("sep".equals(dataType) && separator != null && !separator.isEmpty()) {
|
||||
Pattern.compile(separator);
|
||||
}
|
||||
|
||||
Map<String, List<CompiledMapper>> mappers = compileMappers(root.get("mappers"), source);
|
||||
List<CompiledFilterGroup> filters = compileFilters(root.get("filters_params"), source);
|
||||
List<CompiledCompletion> completions = compileCompletions(root.get("complete_columns"), source);
|
||||
MessageParserSignature signature = new MessageParserSignature(dataType, cropper,
|
||||
kv.internal, kv.external, kv.leftTrim, kv.rightTrim, separator, regex);
|
||||
|
||||
return new CompiledRule(source.getId(), required(source.getName(), source, "name"),
|
||||
source.getDisplayName(), dataType, fingerprint(source), cropper, mappers,
|
||||
filters, completions, signature, kv.internal, kv.external, kv.leftTrim,
|
||||
kv.rightTrim, separator, messageRegex);
|
||||
} catch (RuleCompilationException known) {
|
||||
throw known;
|
||||
} catch (Exception failure) {
|
||||
throw new RuleCompilationException(source.getId(),
|
||||
"规则编译失败: " + failure.getClass().getSimpleName(), failure);
|
||||
}
|
||||
}
|
||||
|
||||
public String fingerprint(RuleSource source) {
|
||||
return source.getId() + ":" + source.getFingerprint();
|
||||
}
|
||||
|
||||
private CompiledCropper compileCropper(JsonNode node, RuleSource source) {
|
||||
if (node == null || node.isNull()) return null;
|
||||
if (!node.isObject()) throw invalid(source, "cropper_params 必须是对象");
|
||||
return new CompiledCropper(textOrEmpty(node.get("head_key")), integer(node, "head_offset", source),
|
||||
textOrEmpty(node.get("tail_key")), integer(node, "tail_offset", source));
|
||||
}
|
||||
|
||||
private KvConfig compileKv(JsonNode node, String dataType, RuleSource source) {
|
||||
if (!"kv".equals(dataType)) {
|
||||
return node != null && node.isObject()
|
||||
? new KvConfig(text(node.get("internal")), text(node.get("external")),
|
||||
text(node.get("l_trim")), text(node.get("r_trim"))) : KvConfig.EMPTY;
|
||||
}
|
||||
if (node == null || !node.isObject()) throw invalid(source, "kv 规则缺少 kv_params");
|
||||
return new KvConfig(requiredSeparator(text(node.get("internal")), source, "kv_params.internal"),
|
||||
requiredSeparator(text(node.get("external")), source, "kv_params.external"),
|
||||
textOrEmpty(node.get("l_trim")), textOrEmpty(node.get("r_trim")));
|
||||
}
|
||||
|
||||
private Map<String, List<CompiledMapper>> compileMappers(JsonNode node, RuleSource source) {
|
||||
node = decodeEmbeddedJson(node, source, "mappers");
|
||||
if (node == null || !node.isArray()) throw invalid(source, "mappers 必须是数组");
|
||||
Map<String, List<CompiledMapper>> index = new LinkedHashMap<>();
|
||||
for (JsonNode mapper : node) {
|
||||
String origin = required(text(mapper.get("origin_field")), source, "mappers.origin_field");
|
||||
String destination = required(text(mapper.get("dest_field")), source, "mappers.dest_field");
|
||||
JsonNode actionNode = mapper.get("action");
|
||||
if (actionNode == null || !actionNode.isObject()) throw invalid(source, "mapper.action 必须是对象");
|
||||
String type = text(actionNode.get("type"));
|
||||
JsonNode param = actionNode.get("param");
|
||||
CompiledMapper compiled;
|
||||
if (blank(type)) {
|
||||
// 旧执行器不会读取 mapper 外层的 type;action.type 为空时仍写入目标字段 null。
|
||||
compiled = new CompiledMapper(origin, destination,
|
||||
CompiledMapper.Action.LEGACY_NULL, null, null);
|
||||
} else if ("equal".equals(type)) {
|
||||
compiled = new CompiledMapper(origin, destination, CompiledMapper.Action.EQUAL, null, null);
|
||||
} else if ("mapping".equals(type)) {
|
||||
JsonNode mappingNode = param == null ? null : param.get("mapping");
|
||||
if (mappingNode == null || !mappingNode.isObject()) {
|
||||
throw invalid(source, "mapping action 缺少 param.mapping");
|
||||
}
|
||||
Map<String, Object> mapping = new LinkedHashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = mappingNode.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
mapping.put(entry.getKey(), freeze(objectMapper.convertValue(entry.getValue(), Object.class)));
|
||||
}
|
||||
compiled = new CompiledMapper(origin, destination, CompiledMapper.Action.MAPPING, mapping, null);
|
||||
} else if ("time".equals(type)) {
|
||||
String timezone = param == null ? null : text(param.get("timezone"));
|
||||
compiled = new CompiledMapper(origin, destination, CompiledMapper.Action.TIME,
|
||||
null, required(timezone, source, "time action param.timezone"));
|
||||
} else {
|
||||
throw invalid(source, "未知 mapper action: " + type);
|
||||
}
|
||||
index.computeIfAbsent(origin, ignored -> new ArrayList<>()).add(compiled);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private List<CompiledFilterGroup> compileFilters(JsonNode node, RuleSource source) {
|
||||
if (node == null || node.isNull()) return Collections.emptyList();
|
||||
// 旧执行器遇到 []、空字符串等非对象结构时捕获异常并按“无过滤条件”继续。
|
||||
// 字符串即使内容是 JSON 对象也不会被旧执行器二次解析,必须同样忽略。
|
||||
// 编译路径必须保持相同语义,不能让历史脏格式阻塞整条消息。
|
||||
if (!node.isObject()) return Collections.emptyList();
|
||||
JsonNode groups = node.get("expressions");
|
||||
if (groups == null || groups.isNull()) return Collections.emptyList();
|
||||
if (!groups.isArray()) throw invalid(source, "filters_params.expressions 必须是数组");
|
||||
List<CompiledFilterGroup> result = new ArrayList<>();
|
||||
for (JsonNode group : groups) {
|
||||
JsonNode expressions = group.get("expressions");
|
||||
List<CompiledPredicate> predicates = compilePredicates(expressions, source);
|
||||
if (!predicates.isEmpty()) {
|
||||
result.add(new CompiledFilterGroup("or".equalsIgnoreCase(text(group.get("filters_relation"))),
|
||||
predicates));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<CompiledCompletion> compileCompletions(JsonNode node, RuleSource source) {
|
||||
if (node == null || node.isNull()) return Collections.emptyList();
|
||||
// 旧补全服务对 {}、空字符串等非数组结构捕获异常后按“无补全配置”继续。
|
||||
// 字符串即使内容是 JSON 数组也不会被旧执行器二次解析,必须同样忽略。
|
||||
if (!node.isArray()) return Collections.emptyList();
|
||||
List<CompiledCompletion> result = new ArrayList<>();
|
||||
for (JsonNode completion : node) {
|
||||
String column = required(text(completion.get("column_name")), source,
|
||||
"complete_columns.column_name");
|
||||
Object value = freeze(objectMapper.convertValue(completion.get("value"), Object.class));
|
||||
List<CompiledPredicate> conditions = compilePredicates(completion.get("conditions"), source);
|
||||
result.add(new CompiledCompletion(column, value,
|
||||
"or".equalsIgnoreCase(text(completion.get("filters_relation"))), conditions));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<CompiledPredicate> compilePredicates(JsonNode node, RuleSource source) {
|
||||
if (node == null || node.isNull()) return Collections.emptyList();
|
||||
if (!node.isArray()) throw invalid(source, "条件 expressions/conditions 必须是数组");
|
||||
List<CompiledPredicate> result = new ArrayList<>();
|
||||
for (JsonNode expression : node) {
|
||||
String column = required(text(expression.get("column_name")), source, "condition.column_name");
|
||||
String op = required(text(expression.get("op")), source, "condition.op");
|
||||
Object value = expression.has("value") && !expression.get("value").isNull()
|
||||
? freeze(objectMapper.convertValue(expression.get("value"), Object.class)) : null;
|
||||
List<Object> values = value instanceof List ? castList(value) : Collections.emptyList();
|
||||
Pattern pattern = null;
|
||||
CompiledPredicate.Operation operation;
|
||||
switch (op) {
|
||||
case "=": operation = CompiledPredicate.Operation.EQUAL; break;
|
||||
case "!=": operation = CompiledPredicate.Operation.NOT_EQUAL; break;
|
||||
case "in": operation = CompiledPredicate.Operation.IN; break;
|
||||
case "zero_len": operation = CompiledPredicate.Operation.ZERO_LEN; break;
|
||||
case "contain": operation = CompiledPredicate.Operation.CONTAIN; break;
|
||||
case "regexp":
|
||||
operation = CompiledPredicate.Operation.REGEXP;
|
||||
if (value != null) pattern = Pattern.compile(value.toString());
|
||||
break;
|
||||
default: throw invalid(source, "未知条件操作符: " + op);
|
||||
}
|
||||
result.add(new CompiledPredicate(column, operation, value, values, pattern));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Object> castList(Object value) {
|
||||
return (List<Object>) value;
|
||||
}
|
||||
|
||||
private static Object freeze(Object value) {
|
||||
if (value instanceof Map) {
|
||||
Map<Object, Object> copy = new LinkedHashMap<>();
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
|
||||
copy.put(entry.getKey(), freeze(entry.getValue()));
|
||||
}
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
if (value instanceof List) {
|
||||
List<Object> copy = new ArrayList<>();
|
||||
for (Object item : (List<?>) value) copy.add(freeze(item));
|
||||
return Collections.unmodifiableList(copy);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static int integer(JsonNode parent, String name, RuleSource source) {
|
||||
JsonNode value = parent.get(name);
|
||||
if (value == null) throw invalid(source, name + " 必须是整数");
|
||||
if (value.isIntegralNumber() && value.canConvertToInt()) return value.intValue();
|
||||
// 达梦历史规则中 offset 可能以 JSON 字符串保存;旧执行器使用 Integer.parseInt 接受该格式。
|
||||
if (value.isTextual()) {
|
||||
try {
|
||||
return Integer.parseInt(value.textValue().trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
// 统一转换为不包含规则正文的结构化编译错误。
|
||||
}
|
||||
}
|
||||
throw invalid(source, name + " 必须是整数");
|
||||
}
|
||||
|
||||
private static String required(String value, RuleSource source, String name) {
|
||||
if (blank(value)) throw invalid(source, "缺少必需字段: " + name);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String requiredSeparator(String value, RuleSource source, String name) {
|
||||
// 空格本身是合法且常用的 KV 外部分隔符,不能按 blank 处理。
|
||||
if (value == null || value.isEmpty()) throw invalid(source, "缺少必需字段: " + name);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node) {
|
||||
return node == null || node.isNull() ? null : node.asText();
|
||||
}
|
||||
|
||||
private static String textOrEmpty(JsonNode node) {
|
||||
String value = text(node);
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static boolean blank(String value) {
|
||||
return value == null || value.trim().isEmpty();
|
||||
}
|
||||
|
||||
private static RuleCompilationException invalid(RuleSource source, String message) {
|
||||
return new RuleCompilationException(source.getId(), message);
|
||||
}
|
||||
|
||||
private JsonNode decodeEmbeddedJson(JsonNode node, RuleSource source, String name) {
|
||||
if (node == null || !node.isTextual()) return node;
|
||||
String text = node.textValue();
|
||||
if (text == null || text.trim().isEmpty()) return node;
|
||||
try {
|
||||
return objectMapper.readTree(text);
|
||||
} catch (Exception invalidEmbeddedJson) {
|
||||
throw invalid(source, name + " 内嵌 JSON 无效");
|
||||
}
|
||||
}
|
||||
|
||||
private static final class KvConfig {
|
||||
private static final KvConfig EMPTY = new KvConfig(null, null, null, null);
|
||||
private final String internal;
|
||||
private final String external;
|
||||
private final String leftTrim;
|
||||
private final String rightTrim;
|
||||
|
||||
private KvConfig(String internal, String external, String leftTrim, String rightTrim) {
|
||||
this.internal = internal;
|
||||
this.external = external;
|
||||
this.leftTrim = leftTrim;
|
||||
this.rightTrim = rightTrim;
|
||||
}
|
||||
}
|
||||
|
||||
public static class RuleCompilationException extends IllegalArgumentException {
|
||||
private final long ruleId;
|
||||
|
||||
public RuleCompilationException(long ruleId, String message) {
|
||||
super(message);
|
||||
this.ruleId = ruleId;
|
||||
}
|
||||
|
||||
public RuleCompilationException(long ruleId, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.ruleId = ruleId;
|
||||
}
|
||||
|
||||
public long getRuleId() { return ruleId; }
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.common.entity.DeviceDevice;
|
||||
|
||||
/** 批次内不可变的设备补全数据。 */
|
||||
public final class DeviceSnapshot {
|
||||
private final String ip;
|
||||
private final String vendor;
|
||||
private final String name;
|
||||
|
||||
private DeviceSnapshot(String ip, String vendor, String name) {
|
||||
this.ip = ip;
|
||||
this.vendor = vendor;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static DeviceSnapshot from(DeviceDevice device) {
|
||||
return device == null ? null : new DeviceSnapshot(device.getIp(), device.getVendor(), device.getName());
|
||||
}
|
||||
|
||||
public String getIp() { return ip; }
|
||||
public String getVendor() { return vendor; }
|
||||
public String getName() { return name; }
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
|
||||
|
||||
/** 单条原始消息内按解析签名复用解析结果。 */
|
||||
public final class MessageParseContext {
|
||||
private final boolean enabled;
|
||||
private final Map<MessageParserSignature, ParsedMessage> parsed = new HashMap<>();
|
||||
private final NormalizationRuleMetrics globalMetrics;
|
||||
|
||||
public MessageParseContext(boolean enabled) {
|
||||
this(enabled, null);
|
||||
}
|
||||
|
||||
public MessageParseContext(boolean enabled, NormalizationRuleMetrics globalMetrics) {
|
||||
this.enabled = enabled;
|
||||
this.globalMetrics = globalMetrics;
|
||||
}
|
||||
|
||||
public ParsedMessage parse(CompiledRule rule, String message, RuleExecutionMetrics metrics) {
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
if (!enabled) {
|
||||
if (metrics != null) metrics.parseMiss();
|
||||
if (globalMetrics != null) globalMetrics.messageParse("miss");
|
||||
return rule.parse(message);
|
||||
}
|
||||
ParsedMessage existing = parsed.get(rule.getParserSignature());
|
||||
if (existing != null) {
|
||||
if (metrics != null) metrics.parseHit();
|
||||
if (globalMetrics != null) globalMetrics.messageParse("hit");
|
||||
return existing;
|
||||
}
|
||||
if (metrics != null) metrics.parseMiss();
|
||||
if (globalMetrics != null) globalMetrics.messageParse("miss");
|
||||
ParsedMessage loaded = rule.parse(message);
|
||||
if (loaded != null) parsed.put(rule.getParserSignature(), loaded);
|
||||
return loaded;
|
||||
} finally {
|
||||
if (metrics != null) metrics.addMessageParseNanos(System.nanoTime() - started);
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/** 只有所有解析参数一致时,同一条消息的解析结果才允许复用。 */
|
||||
public final class MessageParserSignature {
|
||||
private static final int FLATTEN_STRATEGY_VERSION = 1;
|
||||
|
||||
private final String dataType;
|
||||
private final String headKey;
|
||||
private final int headOffset;
|
||||
private final String tailKey;
|
||||
private final int tailOffset;
|
||||
private final String kvInternal;
|
||||
private final String kvExternal;
|
||||
private final String kvLeftTrim;
|
||||
private final String kvRightTrim;
|
||||
private final String separator;
|
||||
private final String regex;
|
||||
|
||||
public MessageParserSignature(String dataType, CompiledCropper cropper,
|
||||
String kvInternal, String kvExternal,
|
||||
String kvLeftTrim, String kvRightTrim,
|
||||
String separator, String regex) {
|
||||
this.dataType = dataType;
|
||||
this.headKey = cropper == null ? null : cropper.getHeadKey();
|
||||
this.headOffset = cropper == null ? 0 : cropper.getHeadOffset();
|
||||
this.tailKey = cropper == null ? null : cropper.getTailKey();
|
||||
this.tailOffset = cropper == null ? 0 : cropper.getTailOffset();
|
||||
this.kvInternal = kvInternal;
|
||||
this.kvExternal = kvExternal;
|
||||
this.kvLeftTrim = kvLeftTrim;
|
||||
this.kvRightTrim = kvRightTrim;
|
||||
this.separator = separator;
|
||||
this.regex = regex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof MessageParserSignature)) return false;
|
||||
MessageParserSignature that = (MessageParserSignature) other;
|
||||
return headOffset == that.headOffset && tailOffset == that.tailOffset
|
||||
&& Objects.equals(dataType, that.dataType)
|
||||
&& Objects.equals(headKey, that.headKey)
|
||||
&& Objects.equals(tailKey, that.tailKey)
|
||||
&& Objects.equals(kvInternal, that.kvInternal)
|
||||
&& Objects.equals(kvExternal, that.kvExternal)
|
||||
&& Objects.equals(kvLeftTrim, that.kvLeftTrim)
|
||||
&& Objects.equals(kvRightTrim, that.kvRightTrim)
|
||||
&& Objects.equals(separator, that.separator)
|
||||
&& Objects.equals(regex, that.regex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(dataType, headKey, headOffset, tailKey, tailOffset,
|
||||
kvInternal, kvExternal, kvLeftTrim, kvRightTrim, separator, regex,
|
||||
FLATTEN_STRATEGY_VERSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MessageParserSignature{" +
|
||||
"dataType='" + dataType + '\'' +
|
||||
", headKey='" + headKey + '\'' +
|
||||
", headOffset=" + headOffset +
|
||||
", tailKey='" + tailKey + '\'' +
|
||||
", tailOffset=" + tailOffset +
|
||||
", kvInternal='" + kvInternal + '\'' +
|
||||
", kvExternal='" + kvExternal + '\'' +
|
||||
", kvLeftTrim='" + kvLeftTrim + '\'' +
|
||||
", kvRightTrim='" + kvRightTrim + '\'' +
|
||||
", separator='" + separator + '\'' +
|
||||
", regex='" + regex + '\'' +
|
||||
", flattenStrategyVersion=" + FLATTEN_STRATEGY_VERSION +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.alicp.jetcache.anno.CacheInvalidate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** JetCache BOTH 的统一失效入口;syncLocal 会通过独立广播通道清理其他 JVM 的 L1。 */
|
||||
@Component
|
||||
public class NormalizationCacheInvalidator {
|
||||
|
||||
@CacheInvalidate(name = NormalizationCacheNames.DEVICE_BY_ID, key = "#id")
|
||||
public void device(Integer id) {
|
||||
// 失效由 JetCache AOP 完成。
|
||||
}
|
||||
|
||||
@CacheInvalidate(name = NormalizationCacheNames.COLLECT_TASK_BY_ID, key = "#id")
|
||||
public void collectTask(Integer id) {
|
||||
// 失效由 JetCache AOP 完成。
|
||||
}
|
||||
|
||||
@CacheInvalidate(name = NormalizationCacheNames.RULES_BY_DEVICE, key = "#deviceId")
|
||||
public void rulesForDevice(Long deviceId) {
|
||||
// 失效由 JetCache AOP 完成。
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
public final class NormalizationCacheNames {
|
||||
public static final String DEVICE_BY_ID = "xdr:norm:v1:device:";
|
||||
public static final String COLLECT_TASK_BY_ID = "xdr:norm:v1:collect-task:";
|
||||
public static final String RULES_BY_DEVICE = "xdr:norm:v1:rule-source:device:";
|
||||
|
||||
private NormalizationCacheNames() {}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import com.Modules.NormalData.LogNormalProcessor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/** 影子结果的确定性深比较器。null、缺失和不同类型不会被折叠。 */
|
||||
@Component
|
||||
public class NormalizationShadowComparator {
|
||||
|
||||
public Diff compare(LogNormalProcessor.NormalizationResult legacy,
|
||||
LogNormalProcessor.NormalizationResult candidate) {
|
||||
if (legacy.getOutcome() != candidate.getOutcome()) {
|
||||
return Diff.mismatch("outcome", Collections.singleton("$outcome"));
|
||||
}
|
||||
if (legacy.getRows().size() != candidate.getRows().size()) {
|
||||
return Diff.mismatch("row_count", Collections.singleton("$rowCount"));
|
||||
}
|
||||
List<Map<String, Object>> leftRows = sortedRows(legacy.getRows());
|
||||
List<Map<String, Object>> rightRows = sortedRows(candidate.getRows());
|
||||
Set<String> differing = new TreeSet<>();
|
||||
String type = "value";
|
||||
for (int i = 0; i < leftRows.size(); i++) {
|
||||
Map<String, Object> left = leftRows.get(i);
|
||||
Map<String, Object> right = rightRows.get(i);
|
||||
if (!left.keySet().equals(right.keySet())) {
|
||||
type = "field_set";
|
||||
Set<String> keys = new TreeSet<>(left.keySet());
|
||||
keys.addAll(right.keySet());
|
||||
for (String key : keys) {
|
||||
if (left.containsKey(key) != right.containsKey(key)) differing.add(key);
|
||||
}
|
||||
}
|
||||
Set<String> common = new TreeSet<>(left.keySet());
|
||||
common.retainAll(right.keySet());
|
||||
for (String key : common) {
|
||||
if (!canonical(left.get(key)).equals(canonical(right.get(key)))) differing.add(key);
|
||||
}
|
||||
}
|
||||
return differing.isEmpty() ? Diff.match() : Diff.mismatch(type, differing);
|
||||
}
|
||||
|
||||
public boolean sampled(String eventId, double rate) {
|
||||
if (rate <= 0.0d || eventId == null) return false;
|
||||
if (rate >= 1.0d) return true;
|
||||
byte[] hash = sha256(eventId);
|
||||
long value = 0L;
|
||||
for (int i = 0; i < 8; i++) value = (value << 8) | (hash[i] & 0xffL);
|
||||
double unit = (double) (value >>> 1) / (double) Long.MAX_VALUE;
|
||||
return unit < rate;
|
||||
}
|
||||
|
||||
public String eventHash(String eventId) {
|
||||
StringBuilder value = new StringBuilder(12);
|
||||
byte[] hash = sha256(eventId == null ? "" : eventId);
|
||||
for (int i = 0; i < 6; i++) value.append(String.format("%02x", hash[i] & 0xff));
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> sortedRows(List<Map<String, Object>> rows) {
|
||||
List<Map<String, Object>> sorted = new ArrayList<>(rows);
|
||||
sorted.sort(Comparator.comparing(NormalizationShadowComparator::rowKey));
|
||||
return sorted;
|
||||
}
|
||||
|
||||
private static String rowKey(Map<String, Object> row) {
|
||||
Object id = row.get("id");
|
||||
if (id == null) id = row.get("event_id");
|
||||
if (id != null) return "0:" + canonical(id);
|
||||
Object ruleId = row.get("normalize_rule_id");
|
||||
return "1:" + canonical(ruleId) + ':' + hex(sha256(canonical(row)));
|
||||
}
|
||||
|
||||
private static String canonical(Object value) {
|
||||
if (value == null) return "N:null";
|
||||
if (value instanceof Number) {
|
||||
return "D:" + new BigDecimal(value.toString()).stripTrailingZeros().toPlainString();
|
||||
}
|
||||
if (value instanceof LocalDateTime) {
|
||||
return "L:" + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format((LocalDateTime) value);
|
||||
}
|
||||
if (value instanceof Instant) return "I:" + ((Instant) value).toEpochMilli();
|
||||
if (value instanceof Date) return "I:" + ((Date) value).getTime();
|
||||
if (value instanceof byte[]) return "B:" + Base64.getEncoder().encodeToString((byte[]) value);
|
||||
if (value instanceof Map) {
|
||||
Map<String, Object> sorted = new java.util.TreeMap<>();
|
||||
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
|
||||
sorted.put(String.valueOf(entry.getKey()), entry.getValue());
|
||||
}
|
||||
StringBuilder text = new StringBuilder("M:");
|
||||
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
|
||||
text.append(entry.getKey()).append('=').append(canonical(entry.getValue())).append(';');
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
if (value instanceof List) {
|
||||
StringBuilder text = new StringBuilder("A:");
|
||||
for (Object item : (List<?>) value) text.append(canonical(item)).append(';');
|
||||
return text.toString();
|
||||
}
|
||||
if (value instanceof Boolean) return "Z:" + value;
|
||||
return "S:" + value;
|
||||
}
|
||||
|
||||
private static byte[] sha256(String value) {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception impossible) {
|
||||
throw new IllegalStateException("JVM 不支持 SHA-256", impossible);
|
||||
}
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||
for (byte value : bytes) result.append(String.format("%02x", value & 0xff));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static final class Diff {
|
||||
private final boolean matches;
|
||||
private final String type;
|
||||
private final Set<String> fields;
|
||||
|
||||
private Diff(boolean matches, String type, Set<String> fields) {
|
||||
this.matches = matches;
|
||||
this.type = type;
|
||||
this.fields = Collections.unmodifiableSet(new TreeSet<>(fields));
|
||||
}
|
||||
|
||||
public static Diff match() { return new Diff(true, "match", Collections.emptySet()); }
|
||||
public static Diff mismatch(String type, Set<String> fields) {
|
||||
return new Diff(false, type, fields);
|
||||
}
|
||||
public boolean isMatches() { return matches; }
|
||||
public String getType() { return type; }
|
||||
public Set<String> getFields() { return fields; }
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/** 影子计算使用独立有界线程池,队列满时只跳过影子,不反压 Kafka 主路径。 */
|
||||
@Component
|
||||
public class NormalizationShadowExecutor {
|
||||
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 30L, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(100), new ShadowThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
|
||||
|
||||
public <T> Future<T> submit(java.util.concurrent.Callable<T> task) {
|
||||
return executor.submit(task);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void close() {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
|
||||
private static final class ShadowThreadFactory implements ThreadFactory {
|
||||
private final AtomicInteger sequence = new AtomicInteger();
|
||||
@Override public Thread newThread(Runnable task) {
|
||||
Thread thread = new Thread(task, "normalization-shadow-" + sequence.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** 规则间共享但绝不允许被规则修改的消息解析结果。 */
|
||||
public final class ParsedMessage {
|
||||
private final Map<String, Object> fields;
|
||||
|
||||
public ParsedMessage(Map<String, Object> fields) {
|
||||
this.fields = Collections.unmodifiableMap(new LinkedHashMap<>(fields));
|
||||
}
|
||||
|
||||
public Map<String, Object> getFields() {
|
||||
return fields;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Kafka listener 在线程切换前完成 envelope 解析后生成的不可变输入。 */
|
||||
public final class PreparedNormalizationInput {
|
||||
private final String eventId;
|
||||
private final String topic;
|
||||
private final LocalDateTime receivedAt;
|
||||
private final Long deviceId;
|
||||
private final Long deviceCollectId;
|
||||
private final String dataType;
|
||||
private final String syslogBody;
|
||||
private final String fullMessage;
|
||||
private final String deviceHeader;
|
||||
private final Map<String, String> deviceInfo;
|
||||
|
||||
public PreparedNormalizationInput(String eventId, String topic, LocalDateTime receivedAt,
|
||||
Long deviceId, Long deviceCollectId, String dataType,
|
||||
String syslogBody, String fullMessage, String deviceHeader,
|
||||
Map<String, String> deviceInfo) {
|
||||
this.eventId = eventId;
|
||||
this.topic = topic;
|
||||
this.receivedAt = receivedAt;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCollectId = deviceCollectId;
|
||||
this.dataType = dataType;
|
||||
this.syslogBody = syslogBody;
|
||||
this.fullMessage = fullMessage;
|
||||
this.deviceHeader = deviceHeader;
|
||||
this.deviceInfo = Collections.unmodifiableMap(new LinkedHashMap<>(deviceInfo));
|
||||
}
|
||||
|
||||
public String getEventId() { return eventId; }
|
||||
public String getTopic() { return topic; }
|
||||
public LocalDateTime getReceivedAt() { return receivedAt; }
|
||||
public Long getDeviceId() { return deviceId; }
|
||||
public Long getDeviceCollectId() { return deviceCollectId; }
|
||||
public String getDataType() { return dataType; }
|
||||
public String getSyslogBody() { return syslogBody; }
|
||||
public String getFullMessage() { return fullMessage; }
|
||||
public String getDeviceHeader() { return deviceHeader; }
|
||||
public Map<String, String> getDeviceInfo() { return deviceInfo; }
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
/** 单个 Kafka 批次内共享的低基数聚合指标。 */
|
||||
public final class RuleExecutionMetrics {
|
||||
private final LongAdder messageParseNanos = new LongAdder();
|
||||
private final LongAdder fieldMappingNanos = new LongAdder();
|
||||
private final LongAdder filterCompleteNanos = new LongAdder();
|
||||
private final LongAdder enrichmentNanos = new LongAdder();
|
||||
private final LongAdder assembleNanos = new LongAdder();
|
||||
private final LongAdder compiledHits = new LongAdder();
|
||||
private final LongAdder compiledMisses = new LongAdder();
|
||||
private final LongAdder parseHits = new LongAdder();
|
||||
private final LongAdder parseMisses = new LongAdder();
|
||||
private final LongAdder shadowCompared = new LongAdder();
|
||||
private final LongAdder shadowDifferences = new LongAdder();
|
||||
|
||||
public void addMessageParseNanos(long value) { messageParseNanos.add(nonNegative(value)); }
|
||||
public void addFieldMappingNanos(long value) { fieldMappingNanos.add(nonNegative(value)); }
|
||||
public void addFilterCompleteNanos(long value) { filterCompleteNanos.add(nonNegative(value)); }
|
||||
public void addEnrichmentNanos(long value) { enrichmentNanos.add(nonNegative(value)); }
|
||||
public void addAssembleNanos(long value) { assembleNanos.add(nonNegative(value)); }
|
||||
public void compiledHit() { compiledHits.increment(); }
|
||||
public void compiledMiss() { compiledMisses.increment(); }
|
||||
public void parseHit() { parseHits.increment(); }
|
||||
public void parseMiss() { parseMisses.increment(); }
|
||||
public void shadowCompared(boolean different) {
|
||||
shadowCompared.increment();
|
||||
if (different) shadowDifferences.increment();
|
||||
}
|
||||
|
||||
public long getMessageParseMs() { return millis(messageParseNanos.sum()); }
|
||||
public long getFieldMappingMs() { return millis(fieldMappingNanos.sum()); }
|
||||
public long getFilterCompleteMs() { return millis(filterCompleteNanos.sum()); }
|
||||
public long getEnrichmentMs() { return millis(enrichmentNanos.sum()); }
|
||||
public long getAssembleMs() { return millis(assembleNanos.sum()); }
|
||||
public long getCompiledHits() { return compiledHits.sum(); }
|
||||
public long getCompiledMisses() { return compiledMisses.sum(); }
|
||||
public long getParseHits() { return parseHits.sum(); }
|
||||
public long getParseMisses() { return parseMisses.sum(); }
|
||||
public long getShadowCompared() { return shadowCompared.sum(); }
|
||||
public long getShadowDifferences() { return shadowDifferences.sum(); }
|
||||
|
||||
private static long millis(long nanos) { return TimeUnit.NANOSECONDS.toMillis(nanos); }
|
||||
private static long nonNegative(long value) { return Math.max(0L, value); }
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package com.Modules.NormalData.compiled;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Collections;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/** 脱离 JDBC/CLOB 生命周期的原始规则事实。 */
|
||||
public final class RuleSource implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final long id;
|
||||
private final String name;
|
||||
private final String displayName;
|
||||
private final String dataType;
|
||||
private final String ruleContent;
|
||||
private final Boolean running;
|
||||
private final String delFlag;
|
||||
private final String fingerprint;
|
||||
|
||||
/** 仅供 Kryo5 反序列化;业务代码只能通过完整构造器创建不可变快照。 */
|
||||
@SuppressWarnings("unused")
|
||||
private RuleSource() {
|
||||
this(0L, null, null, null, null, null, null);
|
||||
}
|
||||
|
||||
public RuleSource(long id, String name, String displayName, String dataType,
|
||||
String ruleContent, Boolean running, String delFlag) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.displayName = displayName;
|
||||
this.dataType = dataType;
|
||||
this.ruleContent = ruleContent;
|
||||
this.running = running;
|
||||
this.delFlag = delFlag;
|
||||
this.fingerprint = fingerprint(id, name, dataType, ruleContent, running, delFlag);
|
||||
}
|
||||
|
||||
public static RuleSource fromMap(Map<String, Object> source) {
|
||||
if (source == null) {
|
||||
throw new IllegalArgumentException("规则不能为空");
|
||||
}
|
||||
return new RuleSource(requiredLong(source, "id"), string(source.get("name")),
|
||||
string(source.get("display_name")), string(source.get("data_type")),
|
||||
string(source.get("rule_content")), booleanValue(source.get("is_running")),
|
||||
string(source.get("del_flag")));
|
||||
}
|
||||
|
||||
public Map<String, Object> asLegacyMap() {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("id", id);
|
||||
map.put("name", name);
|
||||
map.put("display_name", displayName);
|
||||
map.put("data_type", dataType);
|
||||
map.put("rule_content", ruleContent);
|
||||
map.put("is_running", running);
|
||||
map.put("del_flag", delFlag);
|
||||
return Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
private static long requiredLong(Map<String, Object> source, String key) {
|
||||
Object value = source.get(key);
|
||||
if (value == null) {
|
||||
throw new IllegalArgumentException("规则缺少字段: " + key);
|
||||
}
|
||||
return Long.parseLong(value.toString());
|
||||
}
|
||||
|
||||
private static String string(Object value) {
|
||||
return value == null ? null : value.toString();
|
||||
}
|
||||
|
||||
private static Boolean booleanValue(Object value) {
|
||||
if (value == null) return null;
|
||||
String text = value.toString().trim();
|
||||
if ("1".equals(text) || "y".equalsIgnoreCase(text) || "yes".equalsIgnoreCase(text)) return true;
|
||||
if ("0".equals(text) || "n".equalsIgnoreCase(text) || "no".equalsIgnoreCase(text)) return false;
|
||||
return Boolean.valueOf(text);
|
||||
}
|
||||
|
||||
public long getId() { return id; }
|
||||
public long getRuleId() { return id; }
|
||||
public String getName() { return name; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public String getDataType() { return dataType; }
|
||||
public String getRuleContent() { return ruleContent; }
|
||||
public Boolean getRunning() { return running; }
|
||||
public String getDelFlag() { return delFlag; }
|
||||
public String getFingerprint() { return fingerprint; }
|
||||
|
||||
private static String fingerprint(long id, String name, String dataType, String content,
|
||||
Boolean running, String delFlag) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
update(digest, Long.toString(id));
|
||||
update(digest, name);
|
||||
update(digest, dataType);
|
||||
update(digest, content);
|
||||
update(digest, running == null ? null : running.toString());
|
||||
update(digest, delFlag);
|
||||
StringBuilder hex = new StringBuilder(64);
|
||||
for (byte value : digest.digest()) hex.append(String.format("%02x", value & 0xff));
|
||||
return hex.toString();
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException("JVM 不支持 SHA-256", impossible);
|
||||
}
|
||||
}
|
||||
|
||||
private static void update(MessageDigest digest, String value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8);
|
||||
digest.update(ByteBuffer.allocate(4).putInt(value == null ? -1 : bytes.length).array());
|
||||
if (value != null) digest.update(bytes);
|
||||
}
|
||||
}
|
||||
+1
-11
@@ -44,10 +44,7 @@ public class logNormalData {
|
||||
{
|
||||
//解析SyslogMessage
|
||||
SyslogMessage msg = SyslogParser.parse(MsgContent);
|
||||
System.out.println("解析结果-log content: " + msg.getMessage().toString());
|
||||
Map<String, Object> flatMap = JsonParser.parseJsonToFlatMap(msg.getMessage().toString());
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
|
||||
return flatMap;
|
||||
}
|
||||
|
||||
@@ -55,10 +52,6 @@ public class logNormalData {
|
||||
public List<Map<String, Object>> getRuleList( long device_id)
|
||||
{
|
||||
List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
|
||||
if (rulelst!=null)
|
||||
{
|
||||
System.out.println("rulelst: " + rulelst);
|
||||
}
|
||||
return rulelst;
|
||||
}
|
||||
|
||||
@@ -70,14 +63,13 @@ public class logNormalData {
|
||||
*/
|
||||
public static String ParserMessageJsonType(String MsgContent , Cropper_paramsType cropperParams)
|
||||
{
|
||||
System.out.println("ParserMessageJsonType MsgContent:" +MsgContent );
|
||||
logger.trace("准备截取JSON内容,日志长度={}", MsgContent == null ? 0 : MsgContent.length());
|
||||
if(cropperParams ==null) {
|
||||
return removeBOM(JsonParser.extractJsonFromLogMessage(MsgContent));
|
||||
}
|
||||
String strJson ="";
|
||||
if(cropperParams.gettail_key().equals("") && cropperParams.gettail_offset()==0 ) {
|
||||
strJson = StringExtractorUtil.extractFromStartToEnd(MsgContent, cropperParams.gethead_key(), cropperParams.gethead_offset());
|
||||
System.out.println("ParserMessageJsonType extractFromStartToEnd strJson" +strJson );
|
||||
}
|
||||
else {
|
||||
strJson= StringExtractorUtil.extract(MsgContent,cropperParams.gethead_key(),cropperParams.gethead_offset(),cropperParams.gettail_key(),cropperParams.gettail_offset() );
|
||||
@@ -159,5 +151,3 @@ public class logNormalData {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.Modules.NormalData.metrics;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
/** 固定维度的进程内规则指标;不以 rule/device/event 作为长期标签。 */
|
||||
@Component
|
||||
public class NormalizationRuleMetrics {
|
||||
private final Counters compiledGet = new Counters("hit", "miss", "failure_hit");
|
||||
private final Counters compiledCompile = new Counters("success", "failure");
|
||||
private final Counters shadow = new Counters("match", "mismatch", "error", "timeout", "skipped");
|
||||
private final Counters ruleSource = new Counters("l1_hit", "l2_hit", "load", "suppressed", "failure");
|
||||
private final Counters enrichment = new Counters("device_hit", "device_load", "device_failure",
|
||||
"collect_task_hit", "collect_task_load", "collect_task_failure");
|
||||
private final Counters invalidation = new Counters("local", "remote", "after_commit", "failure");
|
||||
private final Counters messageParse = new Counters("hit", "miss");
|
||||
private final LongAdder ruleJsonParse = new LongAdder();
|
||||
private final LongAdder compileDurationTotalNanos = new LongAdder();
|
||||
private final LongAdder compileDurationCount = new LongAdder();
|
||||
private final AtomicLong compileDurationMaxNanos = new AtomicLong();
|
||||
private final AtomicLong compiledCacheSize = new AtomicLong();
|
||||
private final AtomicLong compiledEvictions = new AtomicLong();
|
||||
|
||||
public void compiledGet(String outcome) { compiledGet.increment(outcome); }
|
||||
public void compiled(String outcome, long nanos) {
|
||||
compiledCompile.increment(outcome);
|
||||
compileDurationTotalNanos.add(Math.max(0L, nanos));
|
||||
compileDurationCount.increment();
|
||||
updateMax(compileDurationMaxNanos, nanos);
|
||||
}
|
||||
public void shadow(String outcome) { shadow.increment(outcome); }
|
||||
public void ruleSource(String outcome) { ruleSource.increment(outcome); }
|
||||
public void enrichment(String entity, String outcome) {
|
||||
enrichment.increment(("collect_task".equals(entity) ? "collect_task" : "device") + "_" + outcome);
|
||||
}
|
||||
public void invalidation(String outcome) { invalidation.increment(outcome); }
|
||||
public void messageParse(String outcome) { messageParse.increment(outcome); }
|
||||
public void ruleJsonParse() { ruleJsonParse.increment(); }
|
||||
public void compiledCacheGauge(long size, long evictions) {
|
||||
compiledCacheSize.set(Math.max(0L, size));
|
||||
compiledEvictions.set(Math.max(0L, evictions));
|
||||
}
|
||||
|
||||
public Map<String, Object> snapshot() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("compiled_rule_cache_get_total", compiledGet.snapshot());
|
||||
result.put("compiled_rule_compile_total", compiledCompile.snapshot());
|
||||
result.put("compiled_rule_compile_duration_ms_total",
|
||||
nanosToMillis(compileDurationTotalNanos.sum()));
|
||||
result.put("compiled_rule_compile_duration_ms_count", compileDurationCount.sum());
|
||||
result.put("compiled_rule_compile_duration_ms_max",
|
||||
nanosToMillis(compileDurationMaxNanos.get()));
|
||||
result.put("compiled_rule_cache_size", compiledCacheSize.get());
|
||||
result.put("compiled_rule_cache_eviction_total", compiledEvictions.get());
|
||||
result.put("shadow_compare_total", shadow.snapshot());
|
||||
result.put("rule_source_cache_get_total", ruleSource.snapshot());
|
||||
result.put("enrichment_cache_get_total", enrichment.snapshot());
|
||||
result.put("rule_invalidation_total", invalidation.snapshot());
|
||||
result.put("message_parse_cache_get_total", messageParse.snapshot());
|
||||
result.put("rule_json_parse_total", ruleJsonParse.sum());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void updateMax(AtomicLong target, long value) {
|
||||
long nonNegative = Math.max(0L, value);
|
||||
long current;
|
||||
do {
|
||||
current = target.get();
|
||||
if (current >= nonNegative) return;
|
||||
} while (!target.compareAndSet(current, nonNegative));
|
||||
}
|
||||
|
||||
private static long nanosToMillis(long nanos) { return nanos / 1_000_000L; }
|
||||
|
||||
private static final class Counters {
|
||||
private final Map<String, LongAdder> values = new LinkedHashMap<>();
|
||||
|
||||
private Counters(String... names) {
|
||||
for (String name : names) values.put(name, new LongAdder());
|
||||
}
|
||||
|
||||
private void increment(String name) {
|
||||
LongAdder counter = values.get(name);
|
||||
if (counter == null) throw new IllegalArgumentException("未知指标维度: " + name);
|
||||
counter.increment();
|
||||
}
|
||||
|
||||
private Map<String, Long> snapshot() {
|
||||
Map<String, Long> copy = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, LongAdder> entry : values.entrySet()) {
|
||||
copy.put(entry.getKey(), entry.getValue().sum());
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,5 +74,10 @@ public class Alarm {
|
||||
private String[] httpReqBody;
|
||||
private String[] httpRespHeader;
|
||||
private String[] httpRespBody;
|
||||
/** 规则告警幂等与追踪元数据。 */
|
||||
private String ruleId;
|
||||
private String ruleVersion;
|
||||
private LocalDateTime windowStart;
|
||||
private String groupKeyHash;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -79,4 +79,9 @@ public class AlarmVisit {
|
||||
private String dtype;
|
||||
private String originField;
|
||||
private String originLog;
|
||||
}
|
||||
/** 算法告警幂等与追踪元数据。 */
|
||||
private String algorithmId;
|
||||
private String algorithmVersion;
|
||||
private String eventId;
|
||||
private String resultType;
|
||||
}
|
||||
|
||||
+12
-1
@@ -2,6 +2,7 @@ package com.common.entity;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
public class DeviceDevice {
|
||||
public Integer id;
|
||||
@@ -38,6 +39,7 @@ public class DeviceDevice {
|
||||
public String managerName;
|
||||
public Integer todayParseCount;
|
||||
public Integer todayNonLogCount;
|
||||
public LocalDate todayStatsDate;
|
||||
public Long createDept;
|
||||
public Integer deviceCollectId;
|
||||
|
||||
@@ -315,6 +317,14 @@ public class DeviceDevice {
|
||||
this.todayNonLogCount = todayNonLogCount;
|
||||
}
|
||||
|
||||
public LocalDate getTodayStatsDate() {
|
||||
return todayStatsDate;
|
||||
}
|
||||
|
||||
public void setTodayStatsDate(LocalDate todayStatsDate) {
|
||||
this.todayStatsDate = todayStatsDate;
|
||||
}
|
||||
|
||||
public Long getCreateDept() {
|
||||
return createDept;
|
||||
}
|
||||
@@ -368,9 +378,10 @@ public class DeviceDevice {
|
||||
", managerName='" + managerName + '\'' +
|
||||
", todayParseCount=" + todayParseCount +
|
||||
", todayNonLogCount=" + todayNonLogCount +
|
||||
", todayStatsDate=" + todayStatsDate +
|
||||
", createDept=" + createDept +
|
||||
", deviceCollectId=" + deviceCollectId +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.common.entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** Kafka 入口元数据形成的轻量接收状态事件,不包含原始 Syslog 正文。 */
|
||||
public final class IngressStatsEvent {
|
||||
private final String eventId;
|
||||
private final Long deviceId;
|
||||
private final Long deviceCollectId;
|
||||
private final LocalDateTime receiveTime;
|
||||
|
||||
public IngressStatsEvent(String eventId, Long deviceId, Long deviceCollectId,
|
||||
LocalDateTime receiveTime) {
|
||||
this.eventId = eventId;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceCollectId = deviceCollectId;
|
||||
this.receiveTime = receiveTime;
|
||||
}
|
||||
|
||||
public String getEventId() { return eventId; }
|
||||
public Long getDeviceId() { return deviceId; }
|
||||
public Long getDeviceCollectId() { return deviceCollectId; }
|
||||
public LocalDateTime getReceiveTime() { return receiveTime; }
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.common.entity;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 统计投影所需的最小事实变化,不包含原始日志正文。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class StatsChangeRecord {
|
||||
private Long changeSeq;
|
||||
private String changeId;
|
||||
private String sourceType;
|
||||
private String sourceRowId;
|
||||
private String operationType;
|
||||
private LocalDate oldStatDate;
|
||||
private LocalDate newStatDate;
|
||||
private Long oldDeviceId;
|
||||
private Long newDeviceId;
|
||||
private Long oldCollectId;
|
||||
private Long newCollectId;
|
||||
private Long oldRuleId;
|
||||
private Long newRuleId;
|
||||
private LocalDateTime oldEventTime;
|
||||
private LocalDateTime newEventTime;
|
||||
private LocalDateTime oldCollectTime;
|
||||
private LocalDateTime newCollectTime;
|
||||
private Integer oldPushSuccess;
|
||||
private Integer newPushSuccess;
|
||||
private LocalDateTime committedAt;
|
||||
}
|
||||
+2
-1
@@ -376,8 +376,9 @@ public class SyslogNormalAlarm {
|
||||
private String destinationSystem;
|
||||
private String etlHost;
|
||||
private Integer normalizeRuleId;
|
||||
private String ruleVersion;
|
||||
private String normalizeRuleName;
|
||||
private String syslogUuid;
|
||||
private String syslogTopic;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -375,7 +375,8 @@ public class SyslogNormalData {
|
||||
private String destinationSystem;
|
||||
private String etlHost;
|
||||
private Integer normalizeRuleId;
|
||||
private String ruleVersion;
|
||||
private String normalizeRuleName;
|
||||
private String syslogUuid;
|
||||
private String syslogTopic;
|
||||
}
|
||||
}
|
||||
|
||||
+15
-5
@@ -8,6 +8,12 @@ import java.util.List;
|
||||
@Mapper
|
||||
public interface AlarmMapper {
|
||||
|
||||
@Select({"<script>",
|
||||
"SELECT id FROM alarm WHERE id IN",
|
||||
"<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach>",
|
||||
"</script>"})
|
||||
List<String> selectExistingIds(@Param("ids") List<String> ids);
|
||||
|
||||
/**
|
||||
* 批量插入告警数据
|
||||
*/
|
||||
@@ -19,7 +25,8 @@ public interface AlarmMapper {
|
||||
"attack_port, victim_port, attack_method, etl_time, log_count, ",
|
||||
"attack_chain_phase, disposition_advice, attack_direction, ",
|
||||
"judged_state, disposed_state, attack_result, fall, payload, dns_info, engine_type, " ,
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body ",
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body, ",
|
||||
"rule_id, rule_version, window_start, group_key_hash ",
|
||||
") VALUES ",
|
||||
"<foreach collection='list' item='item' separator=','>",
|
||||
"( #{item.id}, #{item.createdAt}, #{item.alarmName}, #{item.alarmLevel}, ",
|
||||
@@ -41,7 +48,8 @@ public interface AlarmMapper {
|
||||
"#{item.httpReqHeader, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpReqBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespHeader, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler})",
|
||||
"#{item.httpRespBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.ruleId}, #{item.ruleVersion}, #{item.windowStart}, #{item.groupKeyHash})",
|
||||
"</foreach>",
|
||||
"</script>"})
|
||||
void batchInsert(@Param("list") List<Alarm> alarmList);
|
||||
@@ -56,7 +64,8 @@ public interface AlarmMapper {
|
||||
"attack_port, victim_port, attack_method, etl_time, log_count, " +
|
||||
"attack_chain_phase, disposition_advice, attack_direction, " +
|
||||
"judged_state, disposed_state, attack_result, fall, payload, dns_info, engine_type, " +
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body " +
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body, " +
|
||||
"rule_id, rule_version, window_start, group_key_hash " +
|
||||
") VALUES (" +
|
||||
"#{id}, #{createdAt}, #{alarmName}, #{alarmLevel}, " +
|
||||
"#{alarmType}, #{alarmMajorType}, #{alarmMinorType}, #{alarmAreaId}, " +
|
||||
@@ -76,7 +85,8 @@ public interface AlarmMapper {
|
||||
"#{httpReqHeader, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpReqBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespHeader, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler} " +
|
||||
"#{httpRespBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{ruleId}, #{ruleVersion}, #{windowStart}, #{groupKeyHash} " +
|
||||
")")
|
||||
void insert(Alarm alarm);
|
||||
}
|
||||
}
|
||||
|
||||
+9
-5
@@ -24,7 +24,8 @@ public interface AlarmVisitMapper {
|
||||
"attack_chain_phase, disposition_advice, attack_direction, ",
|
||||
"judged_state, disposed_state, attack_result, fall, payload, dns_info, engine_type, " ,
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body, ",
|
||||
"reason, dtype, origin_field, origin_log ",
|
||||
"reason, dtype, origin_field, origin_log, ",
|
||||
"algorithm_id, algorithm_version, event_id, result_type ",
|
||||
") VALUES ",
|
||||
"<foreach collection='list' item='item' separator=','>",
|
||||
"(#{item.id}, #{item.createdAt}, #{item.alarmName}, #{item.alarmLevel}, ",
|
||||
@@ -47,7 +48,8 @@ public interface AlarmVisitMapper {
|
||||
"#{item.httpReqBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespHeader, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.reason}, #{item.dtype}, #{item.originField}, #{item.originLog}) ",
|
||||
"#{item.reason}, #{item.dtype}, #{item.originField}, #{item.originLog}, ",
|
||||
"#{item.algorithmId}, #{item.algorithmVersion}, #{item.eventId}, #{item.resultType}) ",
|
||||
"</foreach>",
|
||||
"</script>"})
|
||||
void batchInsert(@Param("list") List<AlarmVisit> alarmList);
|
||||
@@ -63,7 +65,8 @@ public interface AlarmVisitMapper {
|
||||
"attack_chain_phase, disposition_advice, attack_direction, " +
|
||||
"judged_state, disposed_state, attack_result, fall, payload, dns_info,engine_type, " +
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body, " +
|
||||
"reason, dtype, origin_field, origin_log " +
|
||||
"reason, dtype, origin_field, origin_log, " +
|
||||
"algorithm_id, algorithm_version, event_id, result_type " +
|
||||
") VALUES (" +
|
||||
"#{id}, #{createdAt}, #{alarmName}, #{alarmLevel}, " +
|
||||
"#{alarmType}, #{alarmMajorType}, #{alarmMinorType}, #{alarmAreaId}, " +
|
||||
@@ -84,7 +87,8 @@ public interface AlarmVisitMapper {
|
||||
"#{httpReqBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespHeader, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespBody, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{reason}, #{dtype}, #{originField}, #{originLog} " +
|
||||
"#{reason}, #{dtype}, #{originField}, #{originLog}, " +
|
||||
"#{algorithmId}, #{algorithmVersion}, #{eventId}, #{resultType} " +
|
||||
")")
|
||||
void insert(AlarmVisit alarm);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -22,6 +22,8 @@ public interface DmNormalizeRuleMapper {
|
||||
*/
|
||||
List<Map<String, Object>> selectByDeviceId(@Param("id") Long id);
|
||||
|
||||
List<Long> selectDeviceIdsByRuleId(@Param("ruleId") Long ruleId);
|
||||
|
||||
/**
|
||||
* 根据ID更新数据标准化规则
|
||||
* @param rule 数据标准化规则对象
|
||||
@@ -43,4 +45,4 @@ public interface DmNormalizeRuleMapper {
|
||||
* @return 更新影响的行数
|
||||
*/
|
||||
int updateByIdAndTenant(DmNormalizeRule rule);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -13,6 +13,7 @@ public interface SecExceptionAlgorithmMapper {
|
||||
@Select("SELECT * FROM sec_exception_algorithm WHERE status = 1 AND del_flag = '0'")
|
||||
List<SecExceptionAlgorithm> findEnabledAlgorithms();
|
||||
|
||||
@Select("SELECT * FROM sec_exception_algorithm WHERE id = #{id}")
|
||||
// findById 的 SQL 统一由 SecExceptionAlgorithmMapper.xml 提供。两个消费模块保持一致,
|
||||
// 防止任一容器启动时再次打印 duplicate mapped statement 错误。
|
||||
SecExceptionAlgorithm findById(@Param("id") Long id);
|
||||
}
|
||||
}
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.StatsChangeRecord;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Mapper
|
||||
public interface StatsChangeLogMapper {
|
||||
|
||||
@Insert("INSERT INTO syslog_stats_change_log (" +
|
||||
"change_seq,change_id,source_type,source_row_id,operation_type," +
|
||||
"old_stat_date,new_stat_date,old_device_id,new_device_id," +
|
||||
"old_collect_id,new_collect_id,old_rule_id,new_rule_id," +
|
||||
"old_event_time,new_event_time,old_collect_time,new_collect_time," +
|
||||
"old_push_success,new_push_success,committed_at" +
|
||||
") VALUES (seq_syslog_stats_change.NEXTVAL,#{changeId},#{sourceType},#{sourceRowId},#{operationType}," +
|
||||
"#{oldStatDate},#{newStatDate},#{oldDeviceId},#{newDeviceId}," +
|
||||
"#{oldCollectId},#{newCollectId},#{oldRuleId},#{newRuleId}," +
|
||||
"#{oldEventTime},#{newEventTime},#{oldCollectTime},#{newCollectTime}," +
|
||||
"#{oldPushSuccess},#{newPushSuccess},SYSDATE)")
|
||||
int insert(StatsChangeRecord record);
|
||||
|
||||
@Insert("INSERT INTO stats_projection_pending_change(projection_name,change_seq,change_id,created_at) " +
|
||||
"SELECT 'SYSLOG_STATS',change_seq,change_id,SYSDATE FROM syslog_stats_change_log " +
|
||||
"WHERE change_id=#{changeId}")
|
||||
int insertPending(StatsChangeRecord record);
|
||||
|
||||
@Insert("INSERT INTO syslog_stats_change_log (change_seq,change_id,source_type,source_row_id," +
|
||||
"operation_type,old_stat_date,old_device_id,old_collect_id,old_event_time,old_collect_time," +
|
||||
"old_push_success,committed_at) SELECT seq_syslog_stats_change.NEXTVAL," +
|
||||
"'DEVICE_RECEIVE:'||TO_CHAR(id)||':DELETE','DEVICE_RECEIVE',TO_CHAR(id),'DELETE'," +
|
||||
"TRUNC(receive_time),device_id,device_collect_id,receive_time,created_at,push_success,SYSDATE " +
|
||||
"FROM device_receive_log WHERE created_at BETWEEN #{startTime} AND #{endTime}")
|
||||
int captureDeviceReceiveDeletes(@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
|
||||
@Insert("INSERT INTO stats_projection_pending_change(projection_name,change_seq,change_id,created_at) " +
|
||||
"SELECT 'SYSLOG_STATS',l.change_seq,l.change_id,SYSDATE FROM syslog_stats_change_log l " +
|
||||
"WHERE l.source_type='DEVICE_RECEIVE' AND l.operation_type='DELETE' " +
|
||||
"AND EXISTS (SELECT 1 FROM device_receive_log d WHERE d.created_at BETWEEN #{startTime} AND #{endTime} " +
|
||||
"AND TO_CHAR(d.id)=l.source_row_id) AND NOT EXISTS (SELECT 1 FROM stats_projection_pending_change p " +
|
||||
"WHERE p.projection_name='SYSLOG_STATS' AND p.change_seq=l.change_seq)")
|
||||
int enqueueDeviceReceiveDeletes(@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
}
|
||||
+7
-1
@@ -83,4 +83,10 @@ public interface SyslogNormalAlarmMapper {
|
||||
@Param("endTime") LocalDateTime endTime,
|
||||
@Param("offset") int offset,
|
||||
@Param("pageSize") int pageSize);
|
||||
}
|
||||
|
||||
@Select("SELECT COUNT(1) FROM syslog_normal_alarm " +
|
||||
"WHERE log_time = #{logTime, jdbcType=TIMESTAMP} " +
|
||||
"AND id = #{id}")
|
||||
int countByLogTimeAndId(@Param("logTime") LocalDateTime logTime,
|
||||
@Param("id") String id);
|
||||
}
|
||||
|
||||
+7
-1
@@ -100,4 +100,10 @@ public interface SyslogNormalDataMapper {
|
||||
|
||||
@Select("SELECT * FROM syslog_normal_data WHERE id = #{id}")
|
||||
SyslogNormalData findById(@Param("id") String id);
|
||||
}
|
||||
|
||||
@Select("SELECT COUNT(1) FROM syslog_normal_data " +
|
||||
"WHERE log_time = #{logTime, jdbcType=TIMESTAMP} " +
|
||||
"AND id = #{id}")
|
||||
int countByLogTimeAndId(@Param("logTime") LocalDateTime logTime,
|
||||
@Param("id") String id);
|
||||
}
|
||||
|
||||
+48
-18
@@ -1,28 +1,36 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.Modules.NormalData.cache.NormalizationCacheInvalidationService;
|
||||
import com.Modules.NormalData.cache.NormalizationLookupFacade;
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.mapper.DeviceCollectTaskMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "collectTask")
|
||||
public class DeviceCollectTaskService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(DeviceCollectTaskService.class);
|
||||
|
||||
@Autowired
|
||||
private DeviceCollectTaskMapper deviceCollectTaskMapper;
|
||||
|
||||
@Autowired
|
||||
private NormalizationCacheInvalidationService cacheInvalidationService;
|
||||
|
||||
@Autowired
|
||||
private NormalizationLookupFacade normalizationLookupFacade;
|
||||
|
||||
/**
|
||||
* 根据ID查询采集任务 - 缓存
|
||||
*/
|
||||
@Cacheable(key = "'id:' + #id")
|
||||
public DeviceCollectTask getById(Integer id) {
|
||||
return deviceCollectTaskMapper.selectById(id);
|
||||
return normalizationLookupFacade.collectTask(id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,51 +66,73 @@ public class DeviceCollectTaskService {
|
||||
/**
|
||||
* 新增采集任务 - 清除相关缓存
|
||||
*/
|
||||
@CacheEvict(allEntries = true)
|
||||
public int create(DeviceCollectTask task) {
|
||||
return deviceCollectTaskMapper.insert(task);
|
||||
int rows = deviceCollectTaskMapper.insert(task);
|
||||
if (rows > 0) invalidateCollectTaskSafely(task.getId(), task.getDeviceId());
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新采集任务 - 更新缓存
|
||||
*/
|
||||
@CachePut(key = "'id:' + #task.id")
|
||||
@CacheEvict(key = "'device:' + #task.deviceId")
|
||||
public DeviceCollectTask update(DeviceCollectTask task) {
|
||||
DeviceCollectTask before = deviceCollectTaskMapper.selectById(task.getId());
|
||||
deviceCollectTaskMapper.update(task);
|
||||
return deviceCollectTaskMapper.selectById(task.getId());
|
||||
DeviceCollectTask updated = deviceCollectTaskMapper.selectById(task.getId());
|
||||
invalidateCollectTaskSafely(task.getId(),
|
||||
before == null ? null : before.getDeviceId(),
|
||||
updated == null ? task.getDeviceId() : updated.getDeviceId());
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除采集任务 - 清除缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int delete(Integer id) {
|
||||
return deviceCollectTaskMapper.deleteById(id);
|
||||
DeviceCollectTask before = deviceCollectTaskMapper.selectById(id);
|
||||
int rows = deviceCollectTaskMapper.deleteById(id);
|
||||
if (rows > 0) invalidateCollectTaskSafely(id, before == null ? null : before.getDeviceId());
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记任务成功 - 更新缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int markSuccess(Integer id) {
|
||||
return deviceCollectTaskMapper.updateSuccessStatus(id);
|
||||
DeviceCollectTask before = deviceCollectTaskMapper.selectById(id);
|
||||
int rows = deviceCollectTaskMapper.updateSuccessStatus(id);
|
||||
if (rows > 0) invalidateCollectTaskSafely(id, before == null ? null : before.getDeviceId());
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记任务失败 - 更新缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int markFailed(Integer id) {
|
||||
return deviceCollectTaskMapper.updateFailedStatus(id);
|
||||
DeviceCollectTask before = deviceCollectTaskMapper.selectById(id);
|
||||
int rows = deviceCollectTaskMapper.updateFailedStatus(id);
|
||||
if (rows > 0) invalidateCollectTaskSafely(id, before == null ? null : before.getDeviceId());
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新EPM指标 - 更新缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int updateEpm(Integer id, Integer epm) {
|
||||
return deviceCollectTaskMapper.updateEpm(id, epm);
|
||||
DeviceCollectTask before = deviceCollectTaskMapper.selectById(id);
|
||||
int rows = deviceCollectTaskMapper.updateEpm(id, epm);
|
||||
if (rows > 0) invalidateCollectTaskSafely(id, before == null ? null : before.getDeviceId());
|
||||
return rows;
|
||||
}
|
||||
|
||||
private void invalidateCollectTaskSafely(Integer id, Integer... deviceIds) {
|
||||
try {
|
||||
if (id != null) cacheInvalidationService.invalidateCollectTask(id);
|
||||
cacheInvalidationService.invalidateCollectTaskViews(deviceIds);
|
||||
} catch (RuntimeException cacheFailure) {
|
||||
// 数据库事实已经成功,缓存失效失败只影响 TTL 窗口内的新鲜度。
|
||||
logger.error("采集任务缓存失效失败: id={}", id, cacheFailure);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -133,4 +163,4 @@ public class DeviceCollectTaskService {
|
||||
public int countByDeviceId(Integer deviceId) {
|
||||
return deviceCollectTaskMapper.countByDeviceId(deviceId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -31,4 +31,4 @@ public interface DeviceDeviceService {
|
||||
List<DeviceDevice> getMonitoringDevices();
|
||||
|
||||
List<DeviceDevice> getActiveDevices();
|
||||
}
|
||||
}
|
||||
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 单个达梦事实事务内的临时统计聚合器。实例不跨事务共享,也不承担持久化职责。
|
||||
*/
|
||||
public final class DirectStatsAccumulator {
|
||||
|
||||
private final SortedMap<DailyKey, DeviceDelta> devices = new TreeMap<>();
|
||||
private final SortedMap<DailyKey, RuleDelta> rules = new TreeMap<>();
|
||||
private final ZoneId businessZone;
|
||||
private int inputRows;
|
||||
|
||||
public DirectStatsAccumulator() {
|
||||
this(ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
public DirectStatsAccumulator(ZoneId businessZone) {
|
||||
this.businessZone = Objects.requireNonNull(businessZone, "businessZone");
|
||||
}
|
||||
|
||||
public DirectStatsAccumulator addStandardizedRows(List<Map<String, Object>> rows) {
|
||||
if (rows != null) {
|
||||
for (Map<String, Object> row : rows) {
|
||||
addStandardizedRow(row);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public DirectStatsAccumulator addStandardizedRow(Map<String, Object> row) {
|
||||
if (row == null) {
|
||||
return this;
|
||||
}
|
||||
LocalDate statDate = dateValue(row.get("created_at"), businessZone);
|
||||
Long deviceId = longValue(row.get("device_id"));
|
||||
Long ruleId = longValue(row.get("normalize_rule_id"));
|
||||
LocalDateTime logTime = timeValue(row.get("log_time"), businessZone);
|
||||
if (statDate == null) {
|
||||
throw new IllegalArgumentException("标准化统计缺少 created_at");
|
||||
}
|
||||
if (deviceId != null) {
|
||||
device(statDate, deviceId).parseDelta++;
|
||||
}
|
||||
if (ruleId != null) {
|
||||
rules.computeIfAbsent(new DailyKey(statDate, ruleId), ignored -> new RuleDelta())
|
||||
.include(logTime);
|
||||
}
|
||||
inputRows++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DirectStatsAccumulator addNonNormalRows(List<SyslogNonNormalMessage> messages) {
|
||||
if (messages != null) {
|
||||
for (SyslogNonNormalMessage message : messages) {
|
||||
addNonNormalInsert(message);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public DirectStatsAccumulator addNonNormalInsert(SyslogNonNormalMessage message) {
|
||||
if (message == null) {
|
||||
return this;
|
||||
}
|
||||
LocalDate statDate = dateValue(message.getCreatedAt(), businessZone);
|
||||
Long deviceId = longValue(message.getDeviceId());
|
||||
if (statDate == null) {
|
||||
throw new IllegalArgumentException("非标统计缺少 created_at");
|
||||
}
|
||||
if (deviceId != null) {
|
||||
device(statDate, deviceId).nonLogDelta++;
|
||||
}
|
||||
inputRows++;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** UPDATE 等价于撤销旧维度贡献,再应用合并后的新维度贡献。 */
|
||||
public DirectStatsAccumulator addNonNormalUpdate(SyslogNonNormalMessage oldValue,
|
||||
SyslogNonNormalMessage patch) {
|
||||
if (oldValue == null || patch == null) {
|
||||
return this;
|
||||
}
|
||||
LocalDate oldDate = dateValue(oldValue.getCreatedAt(), businessZone);
|
||||
Long oldDeviceId = longValue(oldValue.getDeviceId());
|
||||
LocalDate newDate = dateValue(patch.getCreatedAt() != null
|
||||
? patch.getCreatedAt() : oldValue.getCreatedAt(), businessZone);
|
||||
Long newDeviceId = longValue(patch.getDeviceId() != null
|
||||
? patch.getDeviceId() : oldValue.getDeviceId());
|
||||
if (oldDate != null && oldDeviceId != null) {
|
||||
device(oldDate, oldDeviceId).nonLogDelta--;
|
||||
}
|
||||
if (newDate != null && newDeviceId != null) {
|
||||
device(newDate, newDeviceId).nonLogDelta++;
|
||||
}
|
||||
inputRows++;
|
||||
return this;
|
||||
}
|
||||
|
||||
private DeviceDelta device(LocalDate date, long deviceId) {
|
||||
return devices.computeIfAbsent(new DailyKey(date, deviceId), ignored -> new DeviceDelta());
|
||||
}
|
||||
|
||||
public SortedMap<DailyKey, DeviceDelta> getDevices() {
|
||||
return devices;
|
||||
}
|
||||
|
||||
public SortedMap<DailyKey, RuleDelta> getRules() {
|
||||
return rules;
|
||||
}
|
||||
|
||||
public int getInputRows() {
|
||||
return inputRows;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return devices.isEmpty() && rules.isEmpty();
|
||||
}
|
||||
|
||||
static Long longValue(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value instanceof Number
|
||||
? ((Number) value).longValue()
|
||||
: Long.valueOf(value.toString());
|
||||
}
|
||||
|
||||
static LocalDate dateValue(Object value) {
|
||||
return dateValue(value, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
static LocalDate dateValue(Object value, ZoneId zone) {
|
||||
LocalDateTime time = timeValue(value, zone);
|
||||
return time == null ? null : time.toLocalDate();
|
||||
}
|
||||
|
||||
static LocalDateTime timeValue(Object value) {
|
||||
return timeValue(value, ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
static LocalDateTime timeValue(Object value, ZoneId zone) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof LocalDateTime) {
|
||||
return (LocalDateTime) value;
|
||||
}
|
||||
if (value instanceof LocalDate) {
|
||||
return ((LocalDate) value).atStartOfDay();
|
||||
}
|
||||
if (value instanceof OffsetDateTime) {
|
||||
return ((OffsetDateTime) value).atZoneSameInstant(zone).toLocalDateTime();
|
||||
}
|
||||
if (value instanceof Timestamp) {
|
||||
return ((Timestamp) value).toLocalDateTime();
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
Instant instant = Instant.ofEpochMilli(((Date) value).getTime());
|
||||
return LocalDateTime.ofInstant(instant, zone);
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的统计时间类型: " + value.getClass().getName());
|
||||
}
|
||||
|
||||
public static final class DailyKey implements Comparable<DailyKey> {
|
||||
private final LocalDate date;
|
||||
private final long dimensionId;
|
||||
|
||||
public DailyKey(LocalDate date, long dimensionId) {
|
||||
this.date = Objects.requireNonNull(date, "date");
|
||||
this.dimensionId = dimensionId;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public long getDimensionId() {
|
||||
return dimensionId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(DailyKey other) {
|
||||
int dateOrder = date.compareTo(other.date);
|
||||
return dateOrder != 0 ? dateOrder : Long.compare(dimensionId, other.dimensionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof DailyKey)) return false;
|
||||
DailyKey key = (DailyKey) other;
|
||||
return dimensionId == key.dimensionId && date.equals(key.date);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(date, dimensionId);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class DeviceDelta {
|
||||
private long parseDelta;
|
||||
private long nonLogDelta;
|
||||
|
||||
public long getParseDelta() {
|
||||
return parseDelta;
|
||||
}
|
||||
|
||||
public long getNonLogDelta() {
|
||||
return nonLogDelta;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class RuleDelta {
|
||||
private LocalDateTime maxLogTime;
|
||||
|
||||
private void include(LocalDateTime value) {
|
||||
if (value != null && (maxLogTime == null || value.isAfter(maxLogTime))) {
|
||||
maxLogTime = value;
|
||||
}
|
||||
}
|
||||
|
||||
public LocalDateTime getMaxLogTime() {
|
||||
return maxLogTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.common.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DIRECT 事实写入节点负责的设备今日计数日切。
|
||||
*
|
||||
* <p>这里只更新小型设备维度表,不扫描任何 Syslog 事实表。显式传入业务日期,避免数据库会话时区
|
||||
* 与 {@code stats.business-zone} 不一致时提前或延后清零。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class DirectStatsDayRolloverService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
|
||||
@Value("${stats.business-zone:Asia/Shanghai}")
|
||||
private String businessZone;
|
||||
|
||||
@Value("${stats.incremental.transaction-timeout-seconds:45}")
|
||||
private int transactionTimeoutSeconds;
|
||||
|
||||
private volatile LocalDate completedDate;
|
||||
private volatile LocalDateTime lastSuccessTime;
|
||||
private volatile LocalDateTime lastFailureTime;
|
||||
private volatile int lastUpdatedDevices;
|
||||
|
||||
public DirectStatsDayRolloverService(JdbcTemplate jdbc,
|
||||
PlatformTransactionManager transactionManager,
|
||||
StatsWriteModeProvider modeProvider) {
|
||||
this.jdbc = jdbc;
|
||||
this.transactionManager = transactionManager;
|
||||
this.modeProvider = modeProvider;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "${stats.direct.day-rollover-check-cron:5 * * * * ?}")
|
||||
public void scheduledRollover() {
|
||||
if (modeProvider.getMode() != StatsWriteModeProvider.Mode.DIRECT) return;
|
||||
LocalDate today = LocalDate.now(ZoneId.of(businessZone));
|
||||
if (today.equals(completedDate)) return;
|
||||
try {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
Date businessDate = Date.valueOf(today);
|
||||
Integer updated = transaction.execute(status -> jdbc.update(
|
||||
"UPDATE device_device SET today_parse_count=0,today_non_log_count=0," +
|
||||
"today_stats_date=?,updated_at=SYSDATE " +
|
||||
"WHERE today_stats_date IS NULL OR today_stats_date<?",
|
||||
businessDate, businessDate));
|
||||
lastUpdatedDevices = updated == null ? 0 : updated;
|
||||
completedDate = today;
|
||||
lastSuccessTime = LocalDateTime.now();
|
||||
log.info("DIRECT 设备今日计数日切完成: businessDate={}, resetDevices={}",
|
||||
today, lastUpdatedDevices);
|
||||
} catch (RuntimeException failure) {
|
||||
lastFailureTime = LocalDateTime.now();
|
||||
// completedDate 不推进;下一分钟自动重试。
|
||||
log.error("DIRECT 设备今日计数日切失败,将在下一检查周期重试: businessDate={}", today, failure);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> status = new LinkedHashMap<>();
|
||||
status.put("write_mode", modeProvider.getMode().name());
|
||||
status.put("business_zone", businessZone);
|
||||
status.put("completed_date", completedDate);
|
||||
status.put("last_updated_devices", lastUpdatedDevices);
|
||||
status.put("last_success_time", lastSuccessTime);
|
||||
status.put("last_failure_time", lastFailureTime);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
+495
@@ -0,0 +1,495 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.CannotAcquireLockException;
|
||||
import org.springframework.dao.DeadlockLoserDataAccessException;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 把当前事实事务的内存聚合结果直接写入小型统计表。
|
||||
*
|
||||
* <p>调用方必须已经开启事实事务;本类不会新开事务,也不会吞掉任何数据库异常。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class DirectStatsProjectionWriter {
|
||||
|
||||
private static final String DEVICE_MERGE_TEMPLATE =
|
||||
"MERGE INTO %s t USING (SELECT ? stat_date,? device_id,? parse_delta,? non_log_delta FROM DUAL) s " +
|
||||
"ON (t.stat_date=s.stat_date AND t.device_id=s.device_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.parse_count=t.parse_count+s.parse_delta," +
|
||||
"t.non_log_count=t.non_log_count+s.non_log_delta,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (stat_date,device_id,parse_count,non_log_count," +
|
||||
"last_receive_time,projection_seq,updated_at) " +
|
||||
"VALUES (s.stat_date,s.device_id,s.parse_delta,s.non_log_delta,NULL,0,SYSDATE)";
|
||||
|
||||
private static final String RULE_MERGE_TEMPLATE =
|
||||
"MERGE INTO %s t USING (SELECT ? stat_date,? normalize_rule_id,? max_log_time FROM DUAL) s " +
|
||||
"ON (t.stat_date=s.stat_date AND t.normalize_rule_id=s.normalize_rule_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.max_log_time=CASE " +
|
||||
"WHEN s.max_log_time IS NULL THEN t.max_log_time " +
|
||||
"WHEN t.max_log_time IS NULL OR t.max_log_time<s.max_log_time THEN s.max_log_time " +
|
||||
"ELSE t.max_log_time END,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (stat_date,normalize_rule_id,max_log_time,projection_seq,updated_at) " +
|
||||
"VALUES (s.stat_date,s.normalize_rule_id,s.max_log_time,0,SYSDATE)";
|
||||
|
||||
private static final String DEVICE_EXACT_MERGE_TEMPLATE =
|
||||
"MERGE INTO %s t USING (SELECT ? stat_date,? device_id,? parse_count,? non_log_count FROM DUAL) s " +
|
||||
"ON (t.stat_date=s.stat_date AND t.device_id=s.device_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.parse_count=s.parse_count," +
|
||||
"t.non_log_count=s.non_log_count,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (stat_date,device_id,parse_count,non_log_count," +
|
||||
"last_receive_time,projection_seq,updated_at) " +
|
||||
"VALUES (s.stat_date,s.device_id,s.parse_count,s.non_log_count,NULL,0,SYSDATE)";
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
private final DirectStatsWriteMetrics metrics;
|
||||
|
||||
@Value("${stats.incremental.read-enabled:false}")
|
||||
private boolean readEnabled;
|
||||
|
||||
@Value("${stats.direct.device-table:device_daily_stats}")
|
||||
private String directDeviceTable;
|
||||
|
||||
@Value("${stats.direct.rule-table:normalize_rule_daily_stats}")
|
||||
private String directRuleTable;
|
||||
|
||||
@Value("${stats.direct.shadow-device-table:device_daily_stats_direct_shadow}")
|
||||
private String shadowDeviceTable;
|
||||
|
||||
@Value("${stats.direct.shadow-rule-table:normalize_rule_daily_stats_direct_shadow}")
|
||||
private String shadowRuleTable;
|
||||
|
||||
@Value("${stats.direct.control-table:stats_direct_control}")
|
||||
private String controlTable;
|
||||
|
||||
@Value("${stats.direct.today-stats-date-enabled:true}")
|
||||
private boolean todayStatsDateEnabled;
|
||||
|
||||
@Value("${stats.business-zone:Asia/Shanghai}")
|
||||
private String businessZone;
|
||||
|
||||
public DirectStatsProjectionWriter(JdbcTemplate jdbc,
|
||||
StatsWriteModeProvider modeProvider,
|
||||
DirectStatsWriteMetrics metrics) {
|
||||
this.jdbc = jdbc;
|
||||
this.modeProvider = modeProvider;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
public WriteResult writeStandardizedRows(List<Map<String, Object>> rows) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(rows == null ? 0 : rows.size());
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addStandardizedRows(rows);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public WriteResult writeStandardizedRow(Map<String, Object> row) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(row == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addStandardizedRow(row);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalRows(List<SyslogNonNormalMessage> messages) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(messages == null ? 0 : messages.size());
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalRows(messages);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalInsert(SyslogNonNormalMessage message) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(message == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalInsert(message);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalUpdate(SyslogNonNormalMessage oldValue, SyslogNonNormalMessage patch) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(oldValue == null || patch == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalUpdate(oldValue, patch);
|
||||
return writeExactDeviceGroups(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public void recordTransactionRetry() {
|
||||
metrics.recordRetry();
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> status = new LinkedHashMap<>(metrics.snapshot(modeProvider.getMode()));
|
||||
status.put("read_enabled", readEnabled);
|
||||
status.put("device_table", selectedDeviceTable());
|
||||
status.put("rule_table", selectedRuleTable());
|
||||
status.put("today_stats_date_enabled", todayStatsDateEnabled);
|
||||
return status;
|
||||
}
|
||||
|
||||
private boolean shouldBuildAggregation() {
|
||||
return modeProvider.writesDirectProjection();
|
||||
}
|
||||
|
||||
private DirectStatsAccumulator accumulator() {
|
||||
return new DirectStatsAccumulator(ZoneId.of(businessZone));
|
||||
}
|
||||
|
||||
private void handleFactOnlyMode() {
|
||||
if (!modeProvider.requiresRebuild()) {
|
||||
return;
|
||||
}
|
||||
requireTransaction();
|
||||
metrics.markRebuildRequired();
|
||||
String table = safeTable(controlTable);
|
||||
jdbc.update("MERGE INTO " + table + " t USING " +
|
||||
"(SELECT 'SYSLOG_STATS' control_name FROM DUAL) s " +
|
||||
"ON (t.control_name=s.control_name) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.rebuild_required=1,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (control_name,rebuild_required,updated_at) " +
|
||||
"VALUES (s.control_name,1,SYSDATE)");
|
||||
}
|
||||
|
||||
private WriteResult write(DirectStatsAccumulator accumulator, long aggregateMs) {
|
||||
if (accumulator.isEmpty()) {
|
||||
metrics.recordSuccess(accumulator.getInputRows(), 0, 0, aggregateMs, 0L, 0L);
|
||||
return WriteResult.direct(accumulator.getInputRows(), 0, 0,
|
||||
aggregateMs, 0L, 0L);
|
||||
}
|
||||
requireTransaction();
|
||||
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> devices =
|
||||
effectiveDeviceEntries(accumulator);
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> rules =
|
||||
effectiveRuleEntries(accumulator);
|
||||
long mergeMs;
|
||||
long materializeMs = 0L;
|
||||
try {
|
||||
long mergeStarted = System.nanoTime();
|
||||
mergeDevices(devices);
|
||||
mergeRules(rules);
|
||||
mergeMs = elapsedMs(mergeStarted);
|
||||
|
||||
if (modeProvider.materializesBusinessFields() && readEnabled) {
|
||||
long materializeStarted = System.nanoTime();
|
||||
materializeDevices(devices);
|
||||
materializeRules(rules);
|
||||
materializeMs = elapsedMs(materializeStarted);
|
||||
}
|
||||
metrics.recordSuccess(accumulator.getInputRows(), devices.size(), rules.size(),
|
||||
aggregateMs, mergeMs, materializeMs);
|
||||
log.debug("直接统计事务块完成: factRows={}, deviceGroups={}, ruleGroups={}, " +
|
||||
"aggregateMs={}, statsMergeMs={}, materializeMs={}",
|
||||
accumulator.getInputRows(), devices.size(), rules.size(),
|
||||
aggregateMs, mergeMs, materializeMs);
|
||||
return WriteResult.direct(accumulator.getInputRows(), devices.size(), rules.size(),
|
||||
aggregateMs, mergeMs, materializeMs);
|
||||
} catch (RuntimeException failure) {
|
||||
metrics.recordFailure();
|
||||
if (isConcurrentWrite(failure)) {
|
||||
throw new ConcurrentStatsWriteException("直接统计聚合键并发写入失败,可安全回滚后有限重试", failure);
|
||||
}
|
||||
throw new DirectStatsWriteException("直接统计写入失败,事实事务必须整体回滚", failure);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UPDATE/物理 DELETE 属于低频管理路径。负 delta 可能移除当前最大值或命中未建立历史基线的日期,
|
||||
* 因此直接从事实表精确重算受影响的小分组,不能把负数插入一个不存在的聚合键。
|
||||
*/
|
||||
private WriteResult writeExactDeviceGroups(DirectStatsAccumulator accumulator, long aggregateMs) {
|
||||
if (accumulator.getDevices().isEmpty()) {
|
||||
metrics.recordSuccess(accumulator.getInputRows(), 0, 0, aggregateMs, 0L, 0L);
|
||||
return WriteResult.direct(accumulator.getInputRows(), 0, 0,
|
||||
aggregateMs, 0L, 0L);
|
||||
}
|
||||
requireTransaction();
|
||||
List<DirectStatsAccumulator.DailyKey> keys = new ArrayList<>(accumulator.getDevices().keySet());
|
||||
try {
|
||||
long mergeStarted = System.nanoTime();
|
||||
List<Object[]> exactValues = new ArrayList<>(keys.size());
|
||||
for (DirectStatsAccumulator.DailyKey key : keys) {
|
||||
LocalDateTime start = key.getDate().atStartOfDay();
|
||||
LocalDateTime end = key.getDate().plusDays(1).atStartOfDay();
|
||||
Map<String, Object> counts = jdbc.queryForMap(
|
||||
"SELECT " +
|
||||
"((SELECT COUNT(*) FROM syslog_normal_data " +
|
||||
"WHERE created_at>=? AND created_at<? AND device_id=?) + " +
|
||||
" (SELECT COUNT(*) FROM syslog_normal_alarm " +
|
||||
"WHERE created_at>=? AND created_at<? AND device_id=?)) parse_count," +
|
||||
"(SELECT COUNT(*) FROM syslog_non_normal_message " +
|
||||
"WHERE created_at>=? AND created_at<? AND device_id=?) non_log_count FROM DUAL",
|
||||
start, end, key.getDimensionId(),
|
||||
start, end, key.getDimensionId(),
|
||||
start, end, key.getDimensionId());
|
||||
exactValues.add(new Object[]{Date.valueOf(key.getDate()), key.getDimensionId(),
|
||||
number(counts, "parse_count"), number(counts, "non_log_count")});
|
||||
}
|
||||
jdbc.batchUpdate(String.format(DEVICE_EXACT_MERGE_TEMPLATE,
|
||||
safeTable(selectedDeviceTable())), exactValues);
|
||||
long mergeMs = elapsedMs(mergeStarted);
|
||||
long materializeMs = 0L;
|
||||
if (modeProvider.materializesBusinessFields() && readEnabled) {
|
||||
long materializeStarted = System.nanoTime();
|
||||
materializeDeviceKeys(keys);
|
||||
materializeMs = elapsedMs(materializeStarted);
|
||||
}
|
||||
metrics.recordSuccess(accumulator.getInputRows(), keys.size(), 0,
|
||||
aggregateMs, mergeMs, materializeMs);
|
||||
return WriteResult.direct(accumulator.getInputRows(), keys.size(), 0,
|
||||
aggregateMs, mergeMs, materializeMs);
|
||||
} catch (RuntimeException failure) {
|
||||
metrics.recordFailure();
|
||||
if (isConcurrentWrite(failure)) {
|
||||
throw new ConcurrentStatsWriteException("直接统计局部分组并发写入失败,可安全回滚后有限重试", failure);
|
||||
}
|
||||
throw new DirectStatsWriteException("直接统计局部分组重算失败,事实事务必须整体回滚", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>>
|
||||
effectiveDeviceEntries(DirectStatsAccumulator accumulator) {
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> result =
|
||||
new ArrayList<>();
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta> entry
|
||||
: accumulator.getDevices().entrySet()) {
|
||||
DirectStatsAccumulator.DeviceDelta delta = entry.getValue();
|
||||
if (delta.getParseDelta() != 0L || delta.getNonLogDelta() != 0L) {
|
||||
result.add(entry);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>>
|
||||
effectiveRuleEntries(DirectStatsAccumulator accumulator) {
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> result =
|
||||
new ArrayList<>();
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta> entry
|
||||
: accumulator.getRules().entrySet()) {
|
||||
if (entry.getValue().getMaxLogTime() != null) {
|
||||
result.add(entry);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void mergeDevices(
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> entries) {
|
||||
if (entries.isEmpty()) return;
|
||||
List<Object[]> parameters = new ArrayList<>(entries.size());
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta> entry : entries) {
|
||||
parameters.add(new Object[]{Date.valueOf(entry.getKey().getDate()),
|
||||
entry.getKey().getDimensionId(), entry.getValue().getParseDelta(),
|
||||
entry.getValue().getNonLogDelta()});
|
||||
}
|
||||
jdbc.batchUpdate(String.format(DEVICE_MERGE_TEMPLATE, safeTable(selectedDeviceTable())), parameters);
|
||||
}
|
||||
|
||||
private void mergeRules(
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> entries) {
|
||||
if (entries.isEmpty()) return;
|
||||
List<Object[]> parameters = new ArrayList<>(entries.size());
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta> entry : entries) {
|
||||
parameters.add(new Object[]{Date.valueOf(entry.getKey().getDate()),
|
||||
entry.getKey().getDimensionId(), entry.getValue().getMaxLogTime()});
|
||||
}
|
||||
jdbc.batchUpdate(String.format(RULE_MERGE_TEMPLATE, safeTable(selectedRuleTable())), parameters);
|
||||
}
|
||||
|
||||
private void materializeDevices(
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> entries) {
|
||||
List<DirectStatsAccumulator.DailyKey> keys = new ArrayList<>(entries.size());
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta> entry : entries) {
|
||||
keys.add(entry.getKey());
|
||||
}
|
||||
materializeDeviceKeys(keys);
|
||||
}
|
||||
|
||||
private void materializeDeviceKeys(List<DirectStatsAccumulator.DailyKey> keys) {
|
||||
LocalDate today = LocalDate.now(ZoneId.of(businessZone));
|
||||
List<Object[]> parameters = new ArrayList<>();
|
||||
for (DirectStatsAccumulator.DailyKey key : keys) {
|
||||
if (today.equals(key.getDate())) {
|
||||
long deviceId = key.getDimensionId();
|
||||
parameters.add(new Object[]{Date.valueOf(today), deviceId,
|
||||
Date.valueOf(today), deviceId, Date.valueOf(today), deviceId});
|
||||
}
|
||||
}
|
||||
if (parameters.isEmpty()) return;
|
||||
String deviceTable = safeTable(selectedDeviceTable());
|
||||
String dateAssignment = todayStatsDateEnabled ? ",today_stats_date=?" : "";
|
||||
String sql = "UPDATE device_device SET " +
|
||||
"today_parse_count=(SELECT parse_count FROM " + deviceTable +
|
||||
" WHERE stat_date=? AND device_id=?)," +
|
||||
"today_non_log_count=(SELECT non_log_count FROM " + deviceTable +
|
||||
" WHERE stat_date=? AND device_id=?)" + dateAssignment +
|
||||
",updated_at=SYSDATE WHERE id=?";
|
||||
if (!todayStatsDateEnabled) {
|
||||
List<Object[]> withoutDateColumn = new ArrayList<>(parameters.size());
|
||||
for (Object[] row : parameters) {
|
||||
withoutDateColumn.add(new Object[]{row[0], row[1], row[2], row[3], row[5]});
|
||||
}
|
||||
jdbc.batchUpdate(sql, withoutDateColumn);
|
||||
} else {
|
||||
jdbc.batchUpdate(sql, parameters);
|
||||
}
|
||||
}
|
||||
|
||||
private void materializeRules(
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> entries) {
|
||||
SortedMap<Long, LocalDateTime> maxima = new TreeMap<>();
|
||||
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta> entry : entries) {
|
||||
long ruleId = entry.getKey().getDimensionId();
|
||||
LocalDateTime candidate = entry.getValue().getMaxLogTime();
|
||||
LocalDateTime current = maxima.get(ruleId);
|
||||
if (current == null || candidate.isAfter(current)) {
|
||||
maxima.put(ruleId, candidate);
|
||||
}
|
||||
}
|
||||
if (maxima.isEmpty()) return;
|
||||
List<Object[]> parameters = new ArrayList<>(maxima.size());
|
||||
for (Map.Entry<Long, LocalDateTime> entry : maxima.entrySet()) {
|
||||
parameters.add(new Object[]{entry.getValue(), entry.getValue(), entry.getValue(), entry.getKey()});
|
||||
}
|
||||
jdbc.batchUpdate("UPDATE dm_normalize_rule SET first_data_saved_at=CASE " +
|
||||
"WHEN ? IS NULL THEN first_data_saved_at " +
|
||||
"WHEN first_data_saved_at IS NULL OR first_data_saved_at<? THEN ? " +
|
||||
"ELSE first_data_saved_at END,updated_at=SYSDATE " +
|
||||
"WHERE id=? AND del_flag='0'", parameters);
|
||||
}
|
||||
|
||||
private String selectedDeviceTable() {
|
||||
return modeProvider.writesShadowProjection() ? shadowDeviceTable : directDeviceTable;
|
||||
}
|
||||
|
||||
private String selectedRuleTable() {
|
||||
return modeProvider.writesShadowProjection() ? shadowRuleTable : directRuleTable;
|
||||
}
|
||||
|
||||
private static String safeTable(String table) {
|
||||
if (table == null || !table.matches("[A-Za-z][A-Za-z0-9_]*")) {
|
||||
throw new IllegalStateException("非法统计表名: " + table);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
private static void requireTransaction() {
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
|
||||
throw new IllegalStateException("直接统计必须与事实写入位于同一个 Spring 达梦事务");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isConcurrentWrite(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
if (current instanceof DuplicateKeyException
|
||||
|| current instanceof CannotAcquireLockException
|
||||
|| current instanceof DeadlockLoserDataAccessException) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static long elapsedMs(long startedNanos) {
|
||||
return (System.nanoTime() - startedNanos) / 1_000_000L;
|
||||
}
|
||||
|
||||
private static long number(Map<String, Object> row, String name) {
|
||||
Object value = row.get(name);
|
||||
if (value == null) value = row.get(name.toUpperCase(java.util.Locale.ROOT));
|
||||
if (value == null) {
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(name)) {
|
||||
value = entry.getValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return value == null ? 0L : ((Number) value).longValue();
|
||||
}
|
||||
|
||||
public static class DirectStatsWriteException extends RuntimeException {
|
||||
DirectStatsWriteException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ConcurrentStatsWriteException extends DirectStatsWriteException {
|
||||
ConcurrentStatsWriteException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
/** 单个事实事务块的统计写入结果,用于批次 INFO 日志和事务耗时观测。 */
|
||||
public static final class WriteResult {
|
||||
private final boolean direct;
|
||||
private final int inputRows;
|
||||
private final int deviceGroups;
|
||||
private final int ruleGroups;
|
||||
private final long aggregateMs;
|
||||
private final long mergeMs;
|
||||
private final long materializeMs;
|
||||
|
||||
private WriteResult(boolean direct, int inputRows, int deviceGroups, int ruleGroups,
|
||||
long aggregateMs, long mergeMs, long materializeMs) {
|
||||
this.direct = direct;
|
||||
this.inputRows = inputRows;
|
||||
this.deviceGroups = deviceGroups;
|
||||
this.ruleGroups = ruleGroups;
|
||||
this.aggregateMs = aggregateMs;
|
||||
this.mergeMs = mergeMs;
|
||||
this.materializeMs = materializeMs;
|
||||
}
|
||||
|
||||
static WriteResult inactive(int inputRows) {
|
||||
return new WriteResult(false, inputRows, 0, 0, 0L, 0L, 0L);
|
||||
}
|
||||
|
||||
static WriteResult direct(int inputRows, int deviceGroups, int ruleGroups,
|
||||
long aggregateMs, long mergeMs, long materializeMs) {
|
||||
return new WriteResult(true, inputRows, deviceGroups, ruleGroups,
|
||||
aggregateMs, mergeMs, materializeMs);
|
||||
}
|
||||
|
||||
public boolean isDirect() { return direct; }
|
||||
public int getInputRows() { return inputRows; }
|
||||
public int getDeviceGroups() { return deviceGroups; }
|
||||
public int getRuleGroups() { return ruleGroups; }
|
||||
public long getAggregateMs() { return aggregateMs; }
|
||||
public long getMergeMs() { return mergeMs; }
|
||||
public long getMaterializeMs() { return materializeMs; }
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 直接统计写入的进程级低成本指标。 */
|
||||
@Component
|
||||
public class DirectStatsWriteMetrics {
|
||||
private final AtomicLong batches = new AtomicLong();
|
||||
private final AtomicLong inputRows = new AtomicLong();
|
||||
private final AtomicLong deviceGroups = new AtomicLong();
|
||||
private final AtomicLong ruleGroups = new AtomicLong();
|
||||
private final AtomicLong aggregateDurationMs = new AtomicLong();
|
||||
private final AtomicLong mergeDurationMs = new AtomicLong();
|
||||
private final AtomicLong materializeDurationMs = new AtomicLong();
|
||||
private final AtomicLong retries = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private volatile boolean rebuildRequired;
|
||||
private volatile LocalDateTime lastSuccessTime;
|
||||
private volatile LocalDateTime lastFailureTime;
|
||||
|
||||
void recordSuccess(int rows, int devices, int rules, long aggregateMs,
|
||||
long mergeMs, long materializeMs) {
|
||||
batches.incrementAndGet();
|
||||
inputRows.addAndGet(rows);
|
||||
deviceGroups.addAndGet(devices);
|
||||
ruleGroups.addAndGet(rules);
|
||||
aggregateDurationMs.addAndGet(aggregateMs);
|
||||
mergeDurationMs.addAndGet(mergeMs);
|
||||
materializeDurationMs.addAndGet(materializeMs);
|
||||
lastSuccessTime = LocalDateTime.now();
|
||||
}
|
||||
|
||||
void recordRetry() {
|
||||
retries.incrementAndGet();
|
||||
}
|
||||
|
||||
void recordFailure() {
|
||||
failures.incrementAndGet();
|
||||
lastFailureTime = LocalDateTime.now();
|
||||
}
|
||||
|
||||
void markRebuildRequired() {
|
||||
rebuildRequired = true;
|
||||
}
|
||||
|
||||
public Map<String, Object> snapshot(StatsWriteModeProvider.Mode mode) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("write_mode", mode.name());
|
||||
result.put("batches", batches.get());
|
||||
result.put("input_rows", inputRows.get());
|
||||
result.put("device_groups", deviceGroups.get());
|
||||
result.put("rule_groups", ruleGroups.get());
|
||||
result.put("aggregate_duration_ms", aggregateDurationMs.get());
|
||||
result.put("merge_duration_ms", mergeDurationMs.get());
|
||||
result.put("materialize_duration_ms", materializeDurationMs.get());
|
||||
result.put("transaction_retries", retries.get());
|
||||
result.put("failures", failures.get());
|
||||
result.put("rebuild_required", rebuildRequired);
|
||||
result.put("last_success_time", lastSuccessTime);
|
||||
result.put("last_failure_time", lastFailureTime);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 达梦事实与直接统计同事务写入的累计耗时指标。 */
|
||||
@Component
|
||||
public class DmDirectTransactionMetrics {
|
||||
private final AtomicLong transactions = new AtomicLong();
|
||||
private final AtomicLong factRows = new AtomicLong();
|
||||
private final AtomicLong factFlushMs = new AtomicLong();
|
||||
private final AtomicLong factFlushMaxMs = new AtomicLong();
|
||||
private final AtomicLong commitMs = new AtomicLong();
|
||||
private final AtomicLong commitMaxMs = new AtomicLong();
|
||||
private final AtomicLong transactionMs = new AtomicLong();
|
||||
private final AtomicLong transactionMaxMs = new AtomicLong();
|
||||
private final AtomicLong retries = new AtomicLong();
|
||||
private volatile LocalDateTime lastSuccessTime;
|
||||
|
||||
void recordSuccess(int rows, long flushDurationMs, long commitDurationMs,
|
||||
long transactionDurationMs) {
|
||||
transactions.incrementAndGet();
|
||||
factRows.addAndGet(rows);
|
||||
factFlushMs.addAndGet(flushDurationMs);
|
||||
updateMax(factFlushMaxMs, flushDurationMs);
|
||||
commitMs.addAndGet(commitDurationMs);
|
||||
updateMax(commitMaxMs, commitDurationMs);
|
||||
transactionMs.addAndGet(transactionDurationMs);
|
||||
updateMax(transactionMaxMs, transactionDurationMs);
|
||||
lastSuccessTime = LocalDateTime.now();
|
||||
}
|
||||
|
||||
void recordRetry() {
|
||||
retries.incrementAndGet();
|
||||
}
|
||||
|
||||
public Map<String, Object> snapshot() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("transactions", transactions.get());
|
||||
result.put("fact_rows", factRows.get());
|
||||
result.put("fact_flush_duration_ms_total", factFlushMs.get());
|
||||
result.put("fact_flush_duration_ms_max", factFlushMaxMs.get());
|
||||
result.put("commit_duration_ms_total", commitMs.get());
|
||||
result.put("commit_duration_ms_max", commitMaxMs.get());
|
||||
result.put("transaction_duration_ms_total", transactionMs.get());
|
||||
result.put("transaction_duration_ms_max", transactionMaxMs.get());
|
||||
result.put("transaction_retries", retries.get());
|
||||
result.put("last_success_time", lastSuccessTime);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void updateMax(AtomicLong target, long candidate) {
|
||||
long current;
|
||||
do {
|
||||
current = target.get();
|
||||
if (candidate <= current) return;
|
||||
} while (!target.compareAndSet(current, candidate));
|
||||
}
|
||||
}
|
||||
+51
-6
@@ -1,5 +1,9 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.Modules.NormalData.compiled.CompiledRuleCompiler;
|
||||
import com.Modules.NormalData.compiled.RuleSource;
|
||||
import com.Modules.NormalData.cache.NormalizationLookupFacade;
|
||||
import com.Modules.NormalData.cache.NormalizeRuleChangedEvent;
|
||||
import com.common.entity.XdrHoneypot;
|
||||
import com.common.mapper.XdrHoneypotMapper;
|
||||
import com.common.util.MyBatisUtil;
|
||||
@@ -11,13 +15,17 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import com.common.entity.DmNormalizeRule;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +36,15 @@ public class DmNormalizeRuleService {
|
||||
@Autowired
|
||||
private DmNormalizeRuleMapper dmNormalizeRuleMapper;
|
||||
|
||||
@Autowired
|
||||
private CompiledRuleCompiler compiledRuleCompiler;
|
||||
|
||||
@Autowired
|
||||
private NormalizationLookupFacade normalizationLookupFacade;
|
||||
|
||||
@Autowired
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DmNormalizeRuleService.class);
|
||||
|
||||
|
||||
@@ -48,22 +65,32 @@ public class DmNormalizeRuleService {
|
||||
/**
|
||||
* 根据ID更新规则
|
||||
*/
|
||||
@Transactional
|
||||
public boolean updateById(DmNormalizeRule rule) {
|
||||
validateUpdate(rule, null);
|
||||
// 设置更新时间
|
||||
rule.setUpdatedAt(java.time.LocalDateTime.now());
|
||||
rule.setUpdateTime(java.time.LocalDateTime.now());
|
||||
List<Long> affectedDevices = dmNormalizeRuleMapper.selectDeviceIdsByRuleId(rule.getId());
|
||||
int result = dmNormalizeRuleMapper.updateById(rule);
|
||||
if (result > 0) eventPublisher.publishEvent(
|
||||
new NormalizeRuleChangedEvent(rule.getId(), affectedDevices, "UPDATE"));
|
||||
return result > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID和租户更新规则
|
||||
*/
|
||||
@Transactional
|
||||
public boolean updateByIdAndTenant(DmNormalizeRule rule) {
|
||||
validateUpdate(rule, rule.getTenantId());
|
||||
// 设置更新时间
|
||||
rule.setUpdatedAt(java.time.LocalDateTime.now());
|
||||
rule.setUpdateTime(java.time.LocalDateTime.now());
|
||||
List<Long> affectedDevices = dmNormalizeRuleMapper.selectDeviceIdsByRuleId(rule.getId());
|
||||
int result = dmNormalizeRuleMapper.updateByIdAndTenant(rule);
|
||||
if (result > 0) eventPublisher.publishEvent(
|
||||
new NormalizeRuleChangedEvent(rule.getId(), affectedDevices, "UPDATE_TENANT"));
|
||||
return result > 0;
|
||||
}
|
||||
/**
|
||||
@@ -90,12 +117,30 @@ public class DmNormalizeRuleService {
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@Cacheable(key = "'deviceId:' + #id")
|
||||
public List<Map<String, Object>> selectByDeviceIdAuto( Long id)
|
||||
public List<RuleSource> selectByDeviceIdAuto(Long id)
|
||||
{
|
||||
System.out.println("调用selectByDeviceIdAuto 方法,id:"+id);
|
||||
List<Map<String, Object>> ruleMap=dmNormalizeRuleMapper.selectByDeviceId(id);
|
||||
return convertClobToString(ruleMap);
|
||||
return normalizationLookupFacade.rules(id).getRules();
|
||||
}
|
||||
|
||||
private void validateUpdate(DmNormalizeRule patch, String tenantId) {
|
||||
if (patch == null || patch.getId() == null) {
|
||||
throw new IllegalArgumentException("规则更新必须提供 id");
|
||||
}
|
||||
DmNormalizeRule current = tenantId == null
|
||||
? dmNormalizeRuleMapper.selectById(patch.getId())
|
||||
: dmNormalizeRuleMapper.selectByIdAndTenant(patch.getId(), tenantId);
|
||||
if (current == null) throw new IllegalArgumentException("待更新规则不存在: " + patch.getId());
|
||||
RuleSource merged = new RuleSource(patch.getId(), first(patch.getName(), current.getName()),
|
||||
first(patch.getDisplayName(), current.getDisplayName()),
|
||||
first(patch.getDataType(), current.getDataType()),
|
||||
first(patch.getRuleContent(), current.getRuleContent()),
|
||||
patch.getIsRunning() == null ? current.getIsRunning() : patch.getIsRunning(),
|
||||
first(patch.getDelFlag(), current.getDelFlag()));
|
||||
compiledRuleCompiler.compile(merged);
|
||||
}
|
||||
|
||||
private static String first(String preferred, String fallback) {
|
||||
return preferred == null ? fallback : preferred;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,4 +177,4 @@ public class DmNormalizeRuleService {
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.mapper.SyslogNormalAlarmMapper;
|
||||
import com.common.mapper.SyslogNormalDataMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.session.ExecutorType;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 在一个达梦小事务中执行真正的 MyBatis JDBC batch。
|
||||
*
|
||||
* <p>这个类只负责数据库执行,不负责错误分类、拆分或 Kafka 状态。上层写入器保证传入的所有行
|
||||
* 属于同一张表和同一个动态列签名,因此 MyBatis BatchExecutor 可以复用同一个 PreparedStatement。
|
||||
* 每个 {@link #execute(boolean, List, int)} 调用都会创建独立事务;失败时整个小批次回滚,上层随后
|
||||
* 决定二分定位还是按系统故障停止。</p>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class DmStandardizedBatchExecutor {
|
||||
|
||||
private final SqlSessionTemplate batchSqlSession;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final StatsChangeCaptureService statsChangeCaptureService;
|
||||
private final DirectStatsProjectionWriter directStatsProjectionWriter;
|
||||
private final DmDirectTransactionMetrics transactionMetrics;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.transaction-log-enabled:false}")
|
||||
private boolean transactionLogEnabled;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.max-concurrency-retries:1}")
|
||||
private int maxConcurrencyRetries;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.concurrency-retry-backoff-ms:20}")
|
||||
private long concurrencyRetryBackoffMs;
|
||||
|
||||
public DmStandardizedBatchExecutor(SqlSessionFactory sqlSessionFactory,
|
||||
PlatformTransactionManager transactionManager,
|
||||
StatsChangeCaptureService statsChangeCaptureService,
|
||||
DirectStatsProjectionWriter directStatsProjectionWriter,
|
||||
DmDirectTransactionMetrics transactionMetrics) {
|
||||
// SqlSessionTemplate 本身线程安全。ExecutorType.BATCH 会把相同 SQL 的参数暂存在当前事务会话中,
|
||||
// 直到 flushStatements()/commit 时才真正交给 JDBC 驱动批量执行。
|
||||
this.batchSqlSession = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
|
||||
this.transactionManager = transactionManager;
|
||||
this.statsChangeCaptureService = statsChangeCaptureService;
|
||||
this.directStatsProjectionWriter = directStatsProjectionWriter;
|
||||
this.transactionMetrics = transactionMetrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一个同构小批次。
|
||||
*
|
||||
* @param alarmTable true 写 syslog_normal_alarm,false 写 syslog_normal_data
|
||||
* @param rows 已按相同动态列集合分组的行
|
||||
* @param transactionTimeoutSeconds 当前小事务硬超时
|
||||
*/
|
||||
public void execute(boolean alarmTable, List<Map<String, Object>> rows,
|
||||
int transactionTimeoutSeconds) {
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
executeTransaction(alarmTable, rows, transactionTimeoutSeconds, attempt);
|
||||
return;
|
||||
} catch (DirectStatsProjectionWriter.ConcurrentStatsWriteException concurrentFailure) {
|
||||
if (attempt >= Math.max(0, maxConcurrencyRetries)) {
|
||||
throw concurrentFailure;
|
||||
}
|
||||
attempt++;
|
||||
directStatsProjectionWriter.recordTransactionRetry();
|
||||
transactionMetrics.recordRetry();
|
||||
backoff(attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void executeTransaction(boolean alarmTable, List<Map<String, Object>> rows,
|
||||
int transactionTimeoutSeconds, int retries) {
|
||||
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
long transactionStarted = System.nanoTime();
|
||||
final TransactionTiming timing = new TransactionTiming();
|
||||
transaction.execute(status -> {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
|
||||
@Override
|
||||
public void beforeCommit(boolean readOnly) {
|
||||
timing.commitStarted = System.nanoTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
timing.commitMs = elapsedMs(timing.commitStarted);
|
||||
}
|
||||
});
|
||||
if (alarmTable) {
|
||||
SyslogNormalAlarmMapper mapper = batchSqlSession.getMapper(SyslogNormalAlarmMapper.class);
|
||||
for (Map<String, Object> row : rows) {
|
||||
// BatchExecutor 下这里不会逐条提交;返回值也不是最终影响行数,不能据此判断成功。
|
||||
mapper.insertDynamic(row);
|
||||
}
|
||||
} else {
|
||||
SyslogNormalDataMapper mapper = batchSqlSession.getMapper(SyslogNormalDataMapper.class);
|
||||
for (Map<String, Object> row : rows) {
|
||||
mapper.insertDynamic(row);
|
||||
}
|
||||
}
|
||||
|
||||
// 与事实行共用当前达梦事务;任一变更日志写入失败都会使整批事实回滚。
|
||||
statsChangeCaptureService.captureStandardizedBatch(batchSqlSession, rows, alarmTable);
|
||||
|
||||
// 先 flush 事实和兼容期变更日志,让唯一键、类型和分区错误在统计增量前暴露。
|
||||
long flushStarted = System.nanoTime();
|
||||
batchSqlSession.flushStatements();
|
||||
timing.factFlushMs = elapsedMs(flushStarted);
|
||||
|
||||
// DIRECT/SHADOW 模式在当前事务内按设备、规则聚合写统计;LEGACY 模式会直接返回。
|
||||
// 任一统计 SQL 失败都会回滚本事务的事实行,禁止产生无法定位的统计缺口。
|
||||
timing.statsResult = directStatsProjectionWriter.writeStandardizedRows(rows);
|
||||
return null;
|
||||
});
|
||||
long transactionMs = elapsedMs(transactionStarted);
|
||||
transactionMetrics.recordSuccess(rows.size(), timing.factFlushMs, timing.commitMs, transactionMs);
|
||||
if (transactionLogEnabled && timing.statsResult != null && timing.statsResult.isDirect()) {
|
||||
log.info("DIRECT 达梦事务完成: factRows={}, deviceGroups={}, ruleGroups={}, aggregateMs={}, " +
|
||||
"factFlushMs={}, statsMergeMs={}, materializeMs={}, commitMs={}, transactionMs={}, retry={}",
|
||||
rows.size(), timing.statsResult.getDeviceGroups(), timing.statsResult.getRuleGroups(),
|
||||
timing.statsResult.getAggregateMs(), timing.factFlushMs,
|
||||
timing.statsResult.getMergeMs(), timing.statsResult.getMaterializeMs(),
|
||||
timing.commitMs, transactionMs, retries);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
return transactionMetrics.snapshot();
|
||||
}
|
||||
|
||||
private static long elapsedMs(long startedNanos) {
|
||||
return startedNanos == 0L ? 0L : (System.nanoTime() - startedNanos) / 1_000_000L;
|
||||
}
|
||||
|
||||
private static final class TransactionTiming {
|
||||
private long factFlushMs;
|
||||
private long commitStarted;
|
||||
private long commitMs;
|
||||
private DirectStatsProjectionWriter.WriteResult statsResult;
|
||||
}
|
||||
|
||||
private void backoff(int attempt) {
|
||||
long delay = Math.max(0L, concurrencyRetryBackoffMs) * attempt;
|
||||
if (delay == 0L) return;
|
||||
try {
|
||||
Thread.sleep(delay);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("直接统计并发重试等待被中断", interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
+555
@@ -0,0 +1,555 @@
|
||||
package com.common.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.CannotAcquireLockException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.QueryTimeoutException;
|
||||
import org.springframework.dao.TransientDataAccessResourceException;
|
||||
import org.springframework.dao.TypeMismatchDataAccessException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.jdbc.CannotGetJdbcConnectionException;
|
||||
|
||||
import java.net.ConnectException;
|
||||
import java.net.SocketException;
|
||||
import java.sql.SQLDataException;
|
||||
import java.sql.SQLIntegrityConstraintViolationException;
|
||||
import java.sql.SQLNonTransientConnectionException;
|
||||
import java.sql.SQLRecoverableException;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLTimeoutException;
|
||||
import java.sql.SQLTransientConnectionException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* 把一个 Kafka poll 产生的动态标准化结果转换为有限、可隔离的达梦批量事务。
|
||||
*
|
||||
* <p>写入器遵守三条不能破坏的可靠性规则:</p>
|
||||
*
|
||||
* <ol>
|
||||
* <li>正常行按目标表、分区日期和动态列签名分组后批量提交;</li>
|
||||
* <li>数据类错误回滚当前小批次并有限二分,最终只把坏行交给 Retry/DLT;</li>
|
||||
* <li>连接、超时、提交未知等系统故障绝不降级为大量单条请求,而是立即失败并保留 Kafka offset。</li>
|
||||
* </ol>
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DmStandardizedBatchWriter {
|
||||
|
||||
private static final String MODE_BATCH = "BATCH";
|
||||
|
||||
private final SyslogNormalDataService normalDataService;
|
||||
private final DmStandardizedBatchExecutor batchExecutor;
|
||||
private final Executor writerExecutor;
|
||||
|
||||
// 未配置时直接启用本次改造的批写路径;SINGLE 只作为现场故障回退开关保留。
|
||||
@Value("${dm.standardized-write.mode:BATCH}")
|
||||
private String mode;
|
||||
|
||||
@Value("${dm.standardized-write.batch-size:100}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${dm.standardized-write.transaction-timeout-seconds:45}")
|
||||
private int transactionTimeoutSeconds;
|
||||
|
||||
@Value("${dm.standardized-write.kafka-batch-deadline-ms:90000}")
|
||||
private long kafkaBatchDeadlineMs;
|
||||
|
||||
@Value("${dm.standardized-write.max-split-depth:10}")
|
||||
private int maxSplitDepth;
|
||||
|
||||
@Value("${dm.standardized-write.max-fallback-operations:100}")
|
||||
private int maxFallbackOperations;
|
||||
|
||||
@Value("${dm.standardized-write.circuit-breaker-failure-threshold:3}")
|
||||
private int circuitBreakerFailureThreshold;
|
||||
|
||||
@Value("${dm.standardized-write.circuit-breaker-backoff-ms:30000}")
|
||||
private long circuitBreakerBackoffMs;
|
||||
|
||||
private final AtomicInteger consecutiveSystemFailures = new AtomicInteger();
|
||||
private volatile long circuitOpenUntilMs;
|
||||
|
||||
public DmStandardizedBatchWriter(SyslogNormalDataService normalDataService,
|
||||
DmStandardizedBatchExecutor batchExecutor,
|
||||
@Qualifier("dmStandardizedWriterExecutor") Executor writerExecutor) {
|
||||
this.normalDataService = normalDataService;
|
||||
this.batchExecutor = batchExecutor;
|
||||
this.writerExecutor = writerExecutor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入当前 Kafka 批次的全部标准化行。
|
||||
*
|
||||
* <p>返回值只包含可归因到具体原始消息的数据错误。系统故障会直接抛出
|
||||
* {@link SystemicWriteException},调用方必须让整个 Kafka 批次不 ACK。</p>
|
||||
*/
|
||||
public <T> WriteReport<T> write(List<WriteRequest<T>> requests) {
|
||||
WriteReport<T> report = new WriteReport<>();
|
||||
if (requests == null || requests.isEmpty()) {
|
||||
return report;
|
||||
}
|
||||
|
||||
ensureCircuitAllowsAttempt();
|
||||
long deadlineMs = System.currentTimeMillis() + Math.max(1L, kafkaBatchDeadlineMs);
|
||||
IsolationBudget budget = new IsolationBudget(deadlineMs,
|
||||
Math.max(0, maxSplitDepth), Math.max(0, maxFallbackOperations));
|
||||
|
||||
try {
|
||||
List<WriteRequest<T>> prepared = prepareRows(requests, report);
|
||||
if (prepared.isEmpty()) {
|
||||
consecutiveSystemFailures.set(0);
|
||||
return report;
|
||||
}
|
||||
|
||||
if (!MODE_BATCH.equalsIgnoreCase(String.valueOf(mode).trim())) {
|
||||
// 安全开关:SINGLE 模式仍走统一的数据校验和错误分类,便于灰度比较和快速回滚。
|
||||
for (WriteRequest<T> request : prepared) {
|
||||
writeSingle(request, report);
|
||||
}
|
||||
} else {
|
||||
writeGroupedBatches(prepared, report, budget);
|
||||
}
|
||||
|
||||
consecutiveSystemFailures.set(0);
|
||||
return report;
|
||||
} catch (SystemicWriteException systemicFailure) {
|
||||
recordSystemicFailure(systemicFailure);
|
||||
throw systemicFailure;
|
||||
} catch (RuntimeException unexpectedFailure) {
|
||||
SystemicWriteException systemicFailure = new SystemicWriteException(
|
||||
"达梦标准化批写出现未确认异常,禁止提交 Kafka offset", unexpectedFailure);
|
||||
recordSystemicFailure(systemicFailure);
|
||||
throw systemicFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/** 在任何 SQL 分组前执行与单条路径相同的校验,坏行不应拖累同批正常数据。 */
|
||||
private <T> List<WriteRequest<T>> prepareRows(List<WriteRequest<T>> requests, WriteReport<T> report) {
|
||||
List<WriteRequest<T>> prepared = new ArrayList<>(requests.size());
|
||||
for (WriteRequest<T> request : requests) {
|
||||
try {
|
||||
normalDataService.prepareForInsert(request.getData());
|
||||
prepared.add(request);
|
||||
} catch (RuntimeException invalidRow) {
|
||||
report.recordFailure(request.getSource(), new PermanentRowWriteException(
|
||||
"标准化结果未通过写入前校验", invalidRow));
|
||||
}
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
/**
|
||||
* 相同目标表、log_time 日期和非空列集合才会进入同一批次。
|
||||
* LinkedHashMap 保持稳定遍历顺序,便于测试和现场日志复现。
|
||||
*/
|
||||
private <T> void writeGroupedBatches(List<WriteRequest<T>> requests, WriteReport<T> report,
|
||||
IsolationBudget budget) {
|
||||
Map<BatchKey, List<WriteRequest<T>>> groups = new LinkedHashMap<>();
|
||||
for (WriteRequest<T> request : requests) {
|
||||
try {
|
||||
BatchKey key = batchKey(request.getData());
|
||||
groups.computeIfAbsent(key, ignored -> new ArrayList<>()).add(request);
|
||||
} catch (RuntimeException invalidGroupingKey) {
|
||||
report.recordFailure(request.getSource(), new PermanentRowWriteException(
|
||||
"标准化结果缺少稳定分区时间或列签名无效", invalidGroupingKey));
|
||||
}
|
||||
}
|
||||
|
||||
List<CompletableFuture<WriteReport<T>>> futures = new ArrayList<>(groups.size());
|
||||
try {
|
||||
for (Map.Entry<BatchKey, List<WriteRequest<T>>> entry : groups.entrySet()) {
|
||||
futures.add(CompletableFuture.supplyAsync(() -> {
|
||||
WriteReport<T> groupReport = new WriteReport<>();
|
||||
writeGroup(entry.getKey(), entry.getValue(), groupReport, budget);
|
||||
return groupReport;
|
||||
}, writerExecutor));
|
||||
}
|
||||
|
||||
CompletableFuture<Void> allGroups = CompletableFuture.allOf(
|
||||
futures.toArray(new CompletableFuture[0]));
|
||||
long remainingMs = budget.remainingMs();
|
||||
if (remainingMs <= 0L) {
|
||||
throw new TimeoutException("达梦批写在任务提交后已超过 Kafka 批次 deadline");
|
||||
}
|
||||
allGroups.get(remainingMs, TimeUnit.MILLISECONDS);
|
||||
for (CompletableFuture<WriteReport<T>> future : futures) {
|
||||
report.merge(future.join());
|
||||
}
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
cancelOutstanding(futures);
|
||||
throw new SystemicWriteException("达梦批写线程池已满,保留 Kafka offset 进行背压", rejected);
|
||||
} catch (TimeoutException timeout) {
|
||||
cancelOutstanding(futures);
|
||||
throw new SystemicWriteException("达梦批写超过 Kafka 批次 deadline,禁止降级为逐条请求", timeout);
|
||||
} catch (InterruptedException interrupted) {
|
||||
cancelOutstanding(futures);
|
||||
Thread.currentThread().interrupt();
|
||||
throw new SystemicWriteException("达梦批写等待被中断,写入结果未确认", interrupted);
|
||||
} catch (ExecutionException executionFailure) {
|
||||
cancelOutstanding(futures);
|
||||
Throwable cause = executionFailure.getCause();
|
||||
if (cause instanceof SystemicWriteException) {
|
||||
throw (SystemicWriteException) cause;
|
||||
}
|
||||
throw new SystemicWriteException("达梦批写任务异常结束,写入结果未确认", cause);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> void writeGroup(BatchKey key, List<WriteRequest<T>> requests,
|
||||
WriteReport<T> report, IsolationBudget budget) {
|
||||
int effectiveBatchSize = Math.max(1, batchSize);
|
||||
for (int start = 0; start < requests.size(); start += effectiveBatchSize) {
|
||||
budget.ensureTimeRemaining();
|
||||
int end = Math.min(start + effectiveBatchSize, requests.size());
|
||||
writeChunkWithIsolation(key, new ArrayList<>(requests.subList(start, end)),
|
||||
report, budget, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个失败小事务只拆失败路径。系统故障绝不进入递归,避免一次达梦故障被放大成 N 次请求。
|
||||
*/
|
||||
private <T> void writeChunkWithIsolation(BatchKey key, List<WriteRequest<T>> chunk,
|
||||
WriteReport<T> report, IsolationBudget budget, int depth) {
|
||||
budget.ensureTimeRemaining();
|
||||
try {
|
||||
List<Map<String, Object>> rows = new ArrayList<>(chunk.size());
|
||||
for (WriteRequest<T> request : chunk) {
|
||||
rows.add(request.getData());
|
||||
}
|
||||
batchExecutor.execute(key.alarmTable, rows, transactionTimeoutSeconds);
|
||||
report.recordSuccessfulRows(chunk.size());
|
||||
} catch (RuntimeException batchFailure) {
|
||||
if (isSystemic(batchFailure)) {
|
||||
throw new SystemicWriteException(
|
||||
"达梦连接、超时或事务状态异常;禁止把失败批次放大为逐条写入", batchFailure);
|
||||
}
|
||||
|
||||
if (chunk.size() == 1) {
|
||||
// 批执行缩小到一行后改走原单条服务。该服务保留唯一冲突存在性确认逻辑,
|
||||
// 能把 Retry/Replay 已写入的确定性 ID 当作幂等成功。
|
||||
writeSingle(chunk.get(0), report);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!budget.tryConsumeFallback(depth)) {
|
||||
RuntimeException limitedFailure = new RetryableRowWriteException(
|
||||
"批写失败隔离达到次数、深度或时间上限,转入受限 Retry,禁止无限拆分", batchFailure);
|
||||
for (WriteRequest<T> request : chunk) {
|
||||
report.recordFailure(request.getSource(), limitedFailure);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
int middle = chunk.size() / 2;
|
||||
writeChunkWithIsolation(key, new ArrayList<>(chunk.subList(0, middle)),
|
||||
report, budget, depth + 1);
|
||||
writeChunkWithIsolation(key, new ArrayList<>(chunk.subList(middle, chunk.size())),
|
||||
report, budget, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条写入只用于 SINGLE 模式或失败隔离的叶子节点。第一条系统性错误会立即抛出,
|
||||
* 调用方不会继续尝试同批剩余行,因此不会形成“100 条批写超时后再超时 100 次”的风暴。
|
||||
*/
|
||||
private <T> void writeSingle(WriteRequest<T> request, WriteReport<T> report) {
|
||||
try {
|
||||
normalDataService.insertDynamic(request.getData());
|
||||
report.recordSuccessfulRows(1);
|
||||
} catch (RuntimeException singleFailure) {
|
||||
if (isSystemic(singleFailure)) {
|
||||
throw new SystemicWriteException("达梦单条写入发生系统性故障,立即停止后续降级", singleFailure);
|
||||
}
|
||||
RuntimeException routedFailure = isPermanentData(singleFailure)
|
||||
? new PermanentRowWriteException("标准化结果包含达梦无法接受的永久数据错误", singleFailure)
|
||||
: new RetryableRowWriteException("标准化结果单条写入失败,进入有限 Retry", singleFailure);
|
||||
report.recordFailure(request.getSource(), routedFailure);
|
||||
}
|
||||
}
|
||||
|
||||
private BatchKey batchKey(Map<String, Object> data) {
|
||||
boolean alarmTable = normalDataService.isAlarmData(data);
|
||||
LocalDate partitionDate = partitionDate(data.get("log_time"));
|
||||
|
||||
// MyBatis XML 的动态列判断只包含非 null 值,所以签名也只记录非 null 列。
|
||||
// TreeSet 提供固定顺序,避免 HashMap 插入顺序不同却被错误拆成多个批次。
|
||||
Set<String> columns = new TreeSet<>();
|
||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||
if (entry.getValue() != null) {
|
||||
columns.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
if (columns.isEmpty()) {
|
||||
throw new IllegalArgumentException("标准化结果没有可写入列");
|
||||
}
|
||||
return new BatchKey(alarmTable, partitionDate, String.join(",", columns));
|
||||
}
|
||||
|
||||
private LocalDate partitionDate(Object value) {
|
||||
if (value instanceof LocalDateTime) {
|
||||
return ((LocalDateTime) value).toLocalDate();
|
||||
}
|
||||
if (value instanceof Timestamp) {
|
||||
return ((Timestamp) value).toLocalDateTime().toLocalDate();
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return new Timestamp(((Date) value).getTime()).toLocalDateTime().toLocalDate();
|
||||
}
|
||||
throw new IllegalArgumentException("log_time 不是受支持的稳定时间类型: "
|
||||
+ (value == null ? "null" : value.getClass().getName()));
|
||||
}
|
||||
|
||||
/** 连接、超时、锁/资源故障属于整库级问题,不能用逐条降级处理。 */
|
||||
private boolean isSystemic(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
if (current instanceof CannotGetJdbcConnectionException
|
||||
|| current instanceof DirectStatsProjectionWriter.DirectStatsWriteException
|
||||
|| current instanceof DataAccessResourceFailureException
|
||||
|| current instanceof QueryTimeoutException
|
||||
|| current instanceof TransientDataAccessResourceException
|
||||
|| current instanceof CannotAcquireLockException
|
||||
|| current instanceof SQLTimeoutException
|
||||
|| current instanceof SQLTransientConnectionException
|
||||
|| current instanceof SQLNonTransientConnectionException
|
||||
|| current instanceof SQLRecoverableException
|
||||
|| current instanceof ConnectException
|
||||
|| current instanceof SocketException
|
||||
|| current instanceof TimeoutException) {
|
||||
return true;
|
||||
}
|
||||
if (current instanceof SQLException) {
|
||||
String sqlState = ((SQLException) current).getSQLState();
|
||||
// SQLState 08 表示连接异常,40 表示事务回滚/并发冲突,HYT 表示 ODBC/JDBC 超时。
|
||||
// 这些错误无法限定到某一行,必须停止整批而不是逐条放大。
|
||||
if (sqlState != null && (sqlState.startsWith("08")
|
||||
|| sqlState.startsWith("40") || sqlState.startsWith("HYT"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
String message = String.valueOf(current.getMessage()).toLowerCase(Locale.ROOT);
|
||||
if (containsAny(message, "connection refused", "connection closed", "broken pipe",
|
||||
"socket", "network", "timeout", "timed out", "database unavailable",
|
||||
"连接失败", "连接关闭", "网络", "超时", "数据库不可用")) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 明确的数据和约束问题可直接进入永久失败终态;未知单行错误先走有限 Retry。 */
|
||||
private boolean isPermanentData(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
if (current instanceof DataIntegrityViolationException
|
||||
|| current instanceof TypeMismatchDataAccessException
|
||||
|| current instanceof SQLDataException
|
||||
|| current instanceof SQLIntegrityConstraintViolationException
|
||||
|| current instanceof IllegalArgumentException) {
|
||||
return true;
|
||||
}
|
||||
if (current instanceof SQLException) {
|
||||
String sqlState = ((SQLException) current).getSQLState();
|
||||
// SQLState 22 是数据转换/范围错误,23 是完整性约束错误;两者都可以在
|
||||
// 回滚后通过二分稳定定位到具体行。
|
||||
if (sqlState != null && (sqlState.startsWith("22") || sqlState.startsWith("23"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
String message = String.valueOf(current.getMessage()).toLowerCase(Locale.ROOT);
|
||||
if (containsAny(message, "value too long", "data too long", "truncat", "invalid number",
|
||||
"data conversion", "not null", "check constraint", "unique constraint",
|
||||
"duplicate key", "violate constraint", "字段长度", "数据超长", "类型转换",
|
||||
"非空约束", "检查约束", "唯一约束")) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean containsAny(String text, String... tokens) {
|
||||
for (String token : tokens) {
|
||||
if (text.contains(token)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void ensureCircuitAllowsAttempt() {
|
||||
long remaining = circuitOpenUntilMs - System.currentTimeMillis();
|
||||
if (remaining > 0L) {
|
||||
throw new SystemicWriteException("达梦批写熔断器处于退避期,剩余 " + remaining + "ms", null);
|
||||
}
|
||||
}
|
||||
|
||||
private void recordSystemicFailure(SystemicWriteException failure) {
|
||||
int failures = consecutiveSystemFailures.incrementAndGet();
|
||||
if (failures >= Math.max(1, circuitBreakerFailureThreshold)) {
|
||||
circuitOpenUntilMs = System.currentTimeMillis() + Math.max(1L, circuitBreakerBackoffMs);
|
||||
log.error("达梦标准化写入连续系统故障,熔断并停止试写: failures={}, backoffMs={}",
|
||||
failures, circuitBreakerBackoffMs, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelOutstanding(List<? extends CompletableFuture<?>> futures) {
|
||||
for (CompletableFuture<?> future : futures) {
|
||||
if (!future.isDone()) {
|
||||
future.cancel(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 一条待写记录及其原 Kafka 消息关联对象。 */
|
||||
public static final class WriteRequest<T> {
|
||||
private final T source;
|
||||
private final Map<String, Object> data;
|
||||
|
||||
public WriteRequest(T source, Map<String, Object> data) {
|
||||
this.source = Objects.requireNonNull(source, "source");
|
||||
this.data = Objects.requireNonNull(data, "data");
|
||||
}
|
||||
|
||||
public T getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
public Map<String, Object> getData() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 可归因到具体消息的失败集合。相同源消息产生多行时只保留第一项失败,调用方据此只发布一次 Retry/DLT。
|
||||
*/
|
||||
public static final class WriteReport<T> {
|
||||
private final Map<T, RuntimeException> failures = new LinkedHashMap<>();
|
||||
private int successfulRows;
|
||||
|
||||
private synchronized void recordFailure(T source, RuntimeException failure) {
|
||||
failures.putIfAbsent(source, failure);
|
||||
}
|
||||
|
||||
private synchronized void recordSuccessfulRows(int rows) {
|
||||
successfulRows += rows;
|
||||
}
|
||||
|
||||
private synchronized void merge(WriteReport<T> other) {
|
||||
successfulRows += other.successfulRows;
|
||||
for (Map.Entry<T, RuntimeException> failure : other.failures.entrySet()) {
|
||||
failures.putIfAbsent(failure.getKey(), failure.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public Map<T, RuntimeException> getFailures() {
|
||||
return Collections.unmodifiableMap(failures);
|
||||
}
|
||||
|
||||
public int getSuccessfulRows() {
|
||||
return successfulRows;
|
||||
}
|
||||
}
|
||||
|
||||
/** 已确认只影响某一行,现有失败路由会把它直接送入 DLT。 */
|
||||
public static class PermanentRowWriteException extends RuntimeException {
|
||||
public PermanentRowWriteException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
/** 无法确认永久性的单行错误,现有失败路由会先进入有限 Retry,耗尽后再进 DLT。 */
|
||||
public static class RetryableRowWriteException extends RuntimeException {
|
||||
public RetryableRowWriteException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
/** 影响范围无法限定到单行,调用方必须保留原 Kafka offset。 */
|
||||
public static class SystemicWriteException extends RuntimeException {
|
||||
public SystemicWriteException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class BatchKey {
|
||||
private final boolean alarmTable;
|
||||
private final LocalDate partitionDate;
|
||||
private final String columnSignature;
|
||||
|
||||
private BatchKey(boolean alarmTable, LocalDate partitionDate, String columnSignature) {
|
||||
this.alarmTable = alarmTable;
|
||||
this.partitionDate = partitionDate;
|
||||
this.columnSignature = columnSignature;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof BatchKey)) return false;
|
||||
BatchKey that = (BatchKey) other;
|
||||
return alarmTable == that.alarmTable
|
||||
&& Objects.equals(partitionDate, that.partitionDate)
|
||||
&& Objects.equals(columnSignature, that.columnSignature);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(alarmTable, partitionDate, columnSignature);
|
||||
}
|
||||
}
|
||||
|
||||
/** 所有递归分支共享同一预算,防止多条坏数据把一个 Kafka 批次拖成无限同步重试。 */
|
||||
private static final class IsolationBudget {
|
||||
private final long deadlineMs;
|
||||
private final int maxDepth;
|
||||
private final int maxOperations;
|
||||
private final AtomicInteger operations = new AtomicInteger();
|
||||
|
||||
private IsolationBudget(long deadlineMs, int maxDepth, int maxOperations) {
|
||||
this.deadlineMs = deadlineMs;
|
||||
this.maxDepth = maxDepth;
|
||||
this.maxOperations = maxOperations;
|
||||
}
|
||||
|
||||
private boolean tryConsumeFallback(int currentDepth) {
|
||||
return currentDepth < maxDepth
|
||||
&& System.currentTimeMillis() < deadlineMs
|
||||
&& operations.incrementAndGet() <= maxOperations;
|
||||
}
|
||||
|
||||
private long remainingMs() {
|
||||
return deadlineMs - System.currentTimeMillis();
|
||||
}
|
||||
|
||||
private void ensureTimeRemaining() {
|
||||
if (remainingMs() <= 0L) {
|
||||
throw new SystemicWriteException("达梦批写超过 Kafka 批次 deadline", new TimeoutException());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
-166
@@ -1,209 +1,150 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.influx.InfluxDBClient;
|
||||
import com.influx.InfluxDBClient;
|
||||
import com.influx.raw.RawInfluxMetrics;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
|
||||
/** V1/V2 原始 Syslog 双读、去重和响应兼容层。 */
|
||||
@Slf4j
|
||||
@Service
|
||||
public class InfluxSyslogService {
|
||||
private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai");
|
||||
private static final DateTimeFormatter TABLE_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
@Autowired
|
||||
private com.influx.InfluxDBClient influxDBClient;
|
||||
private final InfluxDBClient influxDBClient;
|
||||
private final RawInfluxMetrics metrics;
|
||||
|
||||
private static final DateTimeFormatter TABLE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
private static final DateTimeFormatter INPUT_DATE_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
|
||||
public InfluxSyslogService(InfluxDBClient influxDBClient, RawInfluxMetrics metrics) {
|
||||
this.influxDBClient = influxDBClient;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口1:按时间范围查询(最长一天)
|
||||
*/
|
||||
public List<Map<String, Object>> queryByTimeRange(String startTime, String endTime) {
|
||||
try {
|
||||
Instant start = parseInstant(startTime);
|
||||
Instant end = parseInstant(endTime);
|
||||
|
||||
validateTimeRange(start, end);
|
||||
|
||||
// 生成需要查询的表名(处理跨天情况)
|
||||
List<String> measurementNames = generateMeasurementNames(start, end);
|
||||
List<Map<String, Object>> allResults = new ArrayList<>();
|
||||
|
||||
for (String measurement : measurementNames) {
|
||||
List<Map<String, Object>> results = influxDBClient.queryByTimeRange(measurement, start, end);
|
||||
allResults.addAll(results);
|
||||
}
|
||||
|
||||
log.info("按时间范围查询成功,查询表: {}, 返回记录数: {}", measurementNames, allResults.size());
|
||||
return allResults;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("按时间范围查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
Instant start = parseInstant(startTime), end = parseInstant(endTime);
|
||||
validateTimeRange(start, end);
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (String measurement : generateMeasurementNames(start, end)) {
|
||||
rows.addAll(influxDBClient.queryByTimeRange(measurement, start, end));
|
||||
}
|
||||
return merge(rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口2:按UUID查询详细日志
|
||||
*/
|
||||
public List<Map<String, Object>> queryByUuid(String uuid) {
|
||||
try {
|
||||
// 从UUID中提取日期部分
|
||||
String datePart = extractDateFromUuid(uuid);
|
||||
String measurement = "syslog_security_" + datePart;
|
||||
|
||||
List<Map<String, Object>> results = influxDBClient.queryByUuid(measurement, uuid);
|
||||
|
||||
log.info("按UUID查询成功,表: {}, UUID: {}, 返回记录数: {}", measurement, uuid, results.size());
|
||||
return results;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("按UUID查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
}
|
||||
String datePart = extractDateFromUuid(uuid);
|
||||
return merge(influxDBClient.queryByUuid("syslog_security_" + datePart, uuid));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 接口3:按设备ID和时间范围查询
|
||||
*/
|
||||
public List<Map<String, Object>> queryByDeviceIdAndTime(String deviceId, String startTime, String endTime) {
|
||||
try {
|
||||
Instant start = parseInstant(startTime);
|
||||
Instant end = parseInstant(endTime);
|
||||
|
||||
validateTimeRange(start, end);
|
||||
|
||||
List<String> measurementNames = generateMeasurementNames(start, end);
|
||||
List<Map<String, Object>> allResults = new ArrayList<>();
|
||||
|
||||
for (String measurement : measurementNames) {
|
||||
List<Map<String, Object>> results = influxDBClient.queryByDeviceIdAndTime(measurement, deviceId, start, end);
|
||||
allResults.addAll(results);
|
||||
}
|
||||
|
||||
log.info("按设备ID查询成功,设备: {}, 返回记录数: {}", deviceId, allResults.size());
|
||||
return allResults;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("按设备ID查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
if (deviceId == null || deviceId.trim().isEmpty()) throw new IllegalArgumentException("设备ID不能为空");
|
||||
Instant start = parseInstant(startTime), end = parseInstant(endTime);
|
||||
validateTimeRange(start, end);
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (String measurement : generateMeasurementNames(start, end)) {
|
||||
rows.addAll(influxDBClient.queryByDeviceIdAndTime(measurement, deviceId, start, end));
|
||||
}
|
||||
return merge(rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口4:模糊查询message内容
|
||||
*/
|
||||
public List<Map<String, Object>> queryByMessageContent(String startTime, String endTime, String keyword) {
|
||||
try {
|
||||
Instant start = parseInstant(startTime);
|
||||
Instant end = parseInstant(endTime);
|
||||
|
||||
validateTimeRange(start, end);
|
||||
validateKeyword(keyword);
|
||||
|
||||
List<String> measurementNames = generateMeasurementNames(start, end);
|
||||
List<Map<String, Object>> allResults = new ArrayList<>();
|
||||
|
||||
for (String measurement : measurementNames) {
|
||||
List<Map<String, Object>> results = influxDBClient.queryByMessageContent(measurement, start, end, keyword);
|
||||
allResults.addAll(results);
|
||||
}
|
||||
|
||||
log.info("模糊查询成功,关键字: {}, 返回记录数: {}", keyword, allResults.size());
|
||||
return allResults;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("模糊查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
Instant start = parseInstant(startTime), end = parseInstant(endTime);
|
||||
validateTimeRange(start, end); validateKeyword(keyword);
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (String measurement : generateMeasurementNames(start, end)) {
|
||||
rows.addAll(influxDBClient.queryByMessageContent(measurement, start, end, keyword));
|
||||
}
|
||||
return merge(rows);
|
||||
}
|
||||
|
||||
public Map<String, List<Map<String, Object>>> queryByUuids(List<String> uuids) {
|
||||
if (CollectionUtils.isEmpty(uuids)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
Map<String, List<Map<String, Object>>> resultMap = new HashMap<>();
|
||||
for (String uuid : uuids) {
|
||||
// 查询单个UUID的日志
|
||||
List<Map<String, Object>> logList = queryByUuid(uuid);
|
||||
resultMap.put(uuid, logList);
|
||||
}
|
||||
return resultMap;
|
||||
if (CollectionUtils.isEmpty(uuids)) return Collections.emptyMap();
|
||||
Map<String, List<Map<String, Object>>> result = new LinkedHashMap<>();
|
||||
for (String uuid : uuids) result.put(uuid, queryByUuid(uuid));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 按 uuid 去重;跨 schema 冲突优先 V2,同 schema 重复选择更早的 _time。 */
|
||||
List<Map<String, Object>> merge(List<Map<String, Object>> rows) {
|
||||
Map<String, List<Map<String, Object>>> grouped = new LinkedHashMap<>();
|
||||
List<Map<String, Object>> withoutUuid = new ArrayList<>();
|
||||
for (Map<String, Object> row : rows) {
|
||||
Object uuid = row.get("uuid");
|
||||
if (uuid == null || String.valueOf(uuid).isEmpty()) { withoutUuid.add(copyForResponse(row)); continue; }
|
||||
grouped.computeIfAbsent(String.valueOf(uuid), ignored -> new ArrayList<>()).add(row);
|
||||
}
|
||||
List<Map<String, Object>> result = new ArrayList<>(withoutUuid);
|
||||
for (List<Map<String, Object>> candidates : grouped.values()) {
|
||||
candidates.sort(Comparator
|
||||
.comparing((Map<String, Object> row) -> !"V2".equals(row.get("__raw_schema")))
|
||||
.thenComparing(this::rowTime));
|
||||
Map<String, Object> selected = candidates.get(0);
|
||||
if (candidates.size() > 1) {
|
||||
metrics.dualReadDuplicate();
|
||||
for (int i = 1; i < candidates.size(); i++) {
|
||||
if (contentConflicts(selected, candidates.get(i))) { metrics.dualReadConflict(); break; }
|
||||
}
|
||||
}
|
||||
result.add(copyForResponse(selected));
|
||||
}
|
||||
result.sort(Comparator.comparing(this::receiveSortValue).reversed()
|
||||
.thenComparing(row -> String.valueOf(row.get("uuid"))));
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean contentConflicts(Map<String, Object> left, Map<String, Object> right) {
|
||||
return !java.util.Objects.equals(left.get("message"), right.get("message"))
|
||||
|| !java.util.Objects.equals(left.get("receive_time"), right.get("receive_time"));
|
||||
}
|
||||
|
||||
private Map<String, Object> copyForResponse(Map<String, Object> row) {
|
||||
Map<String, Object> copy = new LinkedHashMap<>(row); copy.remove("__raw_schema"); return copy;
|
||||
}
|
||||
private Instant rowTime(Map<String, Object> row) {
|
||||
Object value = row.get("time"); if (value instanceof Instant) return (Instant) value; return Instant.MAX;
|
||||
}
|
||||
private String receiveSortValue(Map<String, Object> row) {
|
||||
Object value = row.get("receive_time"); return value == null ? "" : String.valueOf(value);
|
||||
}
|
||||
/**
|
||||
* 从UUID中提取日期部分
|
||||
*/
|
||||
private String extractDateFromUuid(String uuid) {
|
||||
if (uuid == null || uuid.length() < 8) {
|
||||
throw new IllegalArgumentException("UUID格式不正确,无法提取日期");
|
||||
}
|
||||
return uuid.substring(0, 8);
|
||||
if (uuid == null || !uuid.matches("\\d{8}-.+")) throw new IllegalArgumentException("UUID格式不正确,无法提取日期");
|
||||
LocalDate.parse(uuid.substring(0, 8), DateTimeFormatter.BASIC_ISO_DATE); return uuid.substring(0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析时间字符串为Instant
|
||||
*/
|
||||
private Instant parseInstant(String timeString) {
|
||||
try {
|
||||
return Instant.parse(timeString);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("时间格式不正确,请使用ISO格式,例如: 2023-11-20T00:00:00Z");
|
||||
}
|
||||
private Instant parseInstant(String value) {
|
||||
try { return Instant.parse(value); }
|
||||
catch (Exception failure) { throw new IllegalArgumentException("时间格式不正确,请使用ISO Instant格式", failure); }
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证时间范围(最长一天)
|
||||
*/
|
||||
private void validateTimeRange(Instant start, Instant end) {
|
||||
long hours = ChronoUnit.HOURS.between(start, end);
|
||||
if (hours > 24) {
|
||||
if (!start.isBefore(end)) throw new IllegalArgumentException("开始时间必须早于结束时间");
|
||||
if (Duration.between(start, end).compareTo(Duration.ofHours(24)) > 0)
|
||||
throw new IllegalArgumentException("查询时间范围不能超过24小时");
|
||||
}
|
||||
if (start.isAfter(end)) {
|
||||
throw new IllegalArgumentException("开始时间不能晚于结束时间");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证搜索关键字
|
||||
*/
|
||||
private void validateKeyword(String keyword) {
|
||||
if (keyword == null || keyword.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("搜索关键字不能为空");
|
||||
}
|
||||
if (keyword.length() > 32) {
|
||||
throw new IllegalArgumentException("搜索关键字长度不能超过32个字符");
|
||||
}
|
||||
if (keyword == null || keyword.trim().isEmpty()) throw new IllegalArgumentException("搜索关键字不能为空");
|
||||
if (keyword.length() > 32) throw new IllegalArgumentException("搜索关键字长度不能超过32个字符");
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成需要查询的表名列表(处理跨天情况)
|
||||
*/
|
||||
private List<String> generateMeasurementNames(Instant start, Instant end) {
|
||||
List<String> measurements = new ArrayList<>();
|
||||
|
||||
LocalDateTime startDate = LocalDateTime.ofInstant(start, ZoneId.of("UTC"));
|
||||
LocalDateTime endDate = LocalDateTime.ofInstant(end, ZoneId.of("UTC"));
|
||||
|
||||
LocalDateTime currentDate = startDate;
|
||||
while (!currentDate.toLocalDate().isAfter(endDate.toLocalDate())) {
|
||||
String dateStr = currentDate.format(TABLE_DATE_FORMATTER);
|
||||
measurements.add("syslog_security_" + dateStr);
|
||||
currentDate = currentDate.plusDays(1);
|
||||
/** Flux stop 为排他边界,因此精确上海零点不额外枚举下一日 measurement。 */
|
||||
static List<String> generateMeasurementNames(Instant start, Instant endExclusive) {
|
||||
LocalDate first = start.atZone(SHANGHAI).toLocalDate();
|
||||
LocalDate last = endExclusive.minusNanos(1L).atZone(SHANGHAI).toLocalDate();
|
||||
List<String> names = new ArrayList<>();
|
||||
for (LocalDate date = first; !date.isAfter(last); date = date.plusDays(1)) {
|
||||
names.add("syslog_security_" + TABLE_DATE.format(date));
|
||||
}
|
||||
|
||||
return measurements;
|
||||
return names;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.IngressStatsEvent;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.dao.CannotAcquireLockException;
|
||||
import org.springframework.dao.DeadlockLoserDataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.sql.Date;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* 把 Kafka 入口元数据按设备/探针批内聚合后幂等写入小型统计投影。
|
||||
* 不写逐事件接收日志;失败时抛出,让调用方禁止提交 Kafka offset。
|
||||
*/
|
||||
@Service
|
||||
public class IngressStatsProjectionWriter {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
|
||||
@Value("${stats.ingress-metadata.enabled:false}")
|
||||
private boolean enabled;
|
||||
@Value("${stats.incremental.read-enabled:false}")
|
||||
private boolean readEnabled;
|
||||
@Value("${stats.incremental.transaction-timeout-seconds:45}")
|
||||
private int transactionTimeoutSeconds;
|
||||
@Value("${stats.direct.shadow-device-table:device_daily_stats_direct_shadow}")
|
||||
private String shadowDeviceTable;
|
||||
@Value("${stats.business-zone:Asia/Shanghai}")
|
||||
private String businessZone;
|
||||
private final AtomicLong successfulBatches = new AtomicLong();
|
||||
private final AtomicLong receivedEvents = new AtomicLong();
|
||||
private final AtomicLong updatedGroups = new AtomicLong();
|
||||
private final AtomicLong failedBatches = new AtomicLong();
|
||||
private volatile LocalDateTime lastSuccessTime;
|
||||
private volatile LocalDateTime lastFailureTime;
|
||||
|
||||
public IngressStatsProjectionWriter(JdbcTemplate jdbc,
|
||||
PlatformTransactionManager transactionManager,
|
||||
StatsWriteModeProvider modeProvider) {
|
||||
this.jdbc = jdbc;
|
||||
this.transactionManager = transactionManager;
|
||||
this.modeProvider = modeProvider;
|
||||
}
|
||||
|
||||
public int writeBatch(List<IngressStatsEvent> events) {
|
||||
if (!enabled || events == null || events.isEmpty()) return 0;
|
||||
final Aggregation aggregation = aggregate(events);
|
||||
if (aggregation.devices.isEmpty() && aggregation.collects.isEmpty()) return 0;
|
||||
|
||||
try {
|
||||
int groups;
|
||||
try {
|
||||
groups = writeAggregation(aggregation);
|
||||
} catch (RuntimeException concurrentWrite) {
|
||||
if (!retryableConcurrentWrite(concurrentWrite)) throw concurrentWrite;
|
||||
// 新设备/探针在多节点首次出现时,两个 MERGE 可能同时走 NOT MATCHED。
|
||||
// 锁冲突或失败事务已整体回滚;重试后的 MIN/MAX 更新仍保持幂等。
|
||||
groups = writeAggregation(aggregation);
|
||||
}
|
||||
successfulBatches.incrementAndGet();
|
||||
receivedEvents.addAndGet(events.size());
|
||||
updatedGroups.addAndGet(groups);
|
||||
lastSuccessTime = LocalDateTime.now();
|
||||
return groups;
|
||||
} catch (RuntimeException failure) {
|
||||
failedBatches.incrementAndGet();
|
||||
lastFailureTime = LocalDateTime.now();
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> status = new LinkedHashMap<>();
|
||||
status.put("enabled", enabled);
|
||||
status.put("read_enabled", readEnabled);
|
||||
status.put("target_device_table", modeProvider.writesShadowProjection()
|
||||
? "device_daily_stats+" + shadowDeviceTable : "device_daily_stats");
|
||||
status.put("successful_batches", successfulBatches.get());
|
||||
status.put("received_events", receivedEvents.get());
|
||||
status.put("updated_groups", updatedGroups.get());
|
||||
status.put("failed_batches", failedBatches.get());
|
||||
status.put("last_success_time", lastSuccessTime);
|
||||
status.put("last_failure_time", lastFailureTime);
|
||||
return status;
|
||||
}
|
||||
|
||||
private static boolean retryableConcurrentWrite(RuntimeException failure) {
|
||||
return failure instanceof DuplicateKeyException
|
||||
|| failure instanceof CannotAcquireLockException
|
||||
|| failure instanceof DeadlockLoserDataAccessException;
|
||||
}
|
||||
|
||||
private int writeAggregation(Aggregation aggregation) {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
Integer updated = transaction.execute(status -> {
|
||||
int groups = 0;
|
||||
for (Map.Entry<DeviceKey, LocalDateTime> entry : aggregation.devices.entrySet()) {
|
||||
DeviceKey key = entry.getKey();
|
||||
LocalDateTime receiveTime = entry.getValue();
|
||||
// 接收时间是 MIN/MAX 幂等字段。SHADOW 期间正式表仍需对外服务,因此同时写正式和影子;
|
||||
// 与可累加的 parse/non-log 不同,重复 MAX 不会造成双计数。
|
||||
mergeDeviceReceive("device_daily_stats", key, receiveTime);
|
||||
if (modeProvider.writesShadowProjection()) {
|
||||
mergeDeviceReceive(safeTable(shadowDeviceTable), key, receiveTime);
|
||||
}
|
||||
if (readEnabled && LocalDate.now(ZoneId.of(businessZone)).equals(key.date)) {
|
||||
jdbc.update("UPDATE device_device SET last_receive_time=CASE " +
|
||||
"WHEN last_receive_time IS NULL OR last_receive_time<? THEN ? ELSE last_receive_time END," +
|
||||
"updated_at=SYSDATE WHERE id=?",
|
||||
receiveTime, receiveTime, key.deviceId);
|
||||
}
|
||||
groups++;
|
||||
}
|
||||
for (Map.Entry<Long, CollectTimes> entry : aggregation.collects.entrySet()) {
|
||||
CollectTimes times = entry.getValue();
|
||||
jdbc.update("MERGE INTO device_collect_stats t USING " +
|
||||
"(SELECT ? device_collect_id,? first_success_time,? last_success_time FROM DUAL) s " +
|
||||
"ON (t.device_collect_id=s.device_collect_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.first_success_time=CASE " +
|
||||
"WHEN t.first_success_time IS NULL OR t.first_success_time>s.first_success_time " +
|
||||
"THEN s.first_success_time ELSE t.first_success_time END," +
|
||||
"t.last_success_time=CASE WHEN t.last_success_time IS NULL " +
|
||||
"OR t.last_success_time<s.last_success_time THEN s.last_success_time " +
|
||||
"ELSE t.last_success_time END,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (device_collect_id,first_success_time,last_success_time," +
|
||||
"last_fail_time,projection_seq,updated_at) VALUES " +
|
||||
"(s.device_collect_id,s.first_success_time,s.last_success_time,NULL,0,SYSDATE)",
|
||||
entry.getKey(), times.min, times.max);
|
||||
if (readEnabled) {
|
||||
jdbc.update("UPDATE device_collect_task SET " +
|
||||
"first_time=CASE WHEN first_time IS NULL OR first_time>? THEN ? ELSE first_time END," +
|
||||
"last_success_time=CASE WHEN last_success_time IS NULL OR last_success_time<? " +
|
||||
"THEN ? ELSE last_success_time END,updated_at=SYSDATE WHERE id=?",
|
||||
times.min, times.min, times.max, times.max, entry.getKey());
|
||||
}
|
||||
groups++;
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
return updated == null ? 0 : updated;
|
||||
}
|
||||
|
||||
static Aggregation aggregate(List<IngressStatsEvent> events) {
|
||||
Aggregation result = new Aggregation();
|
||||
for (IngressStatsEvent event : events) {
|
||||
if (event == null || event.getReceiveTime() == null) continue;
|
||||
if (event.getDeviceId() != null) {
|
||||
DeviceKey key = new DeviceKey(event.getReceiveTime().toLocalDate(), event.getDeviceId());
|
||||
LocalDateTime current = result.devices.get(key);
|
||||
if (current == null || event.getReceiveTime().isAfter(current)) {
|
||||
result.devices.put(key, event.getReceiveTime());
|
||||
}
|
||||
}
|
||||
if (event.getDeviceCollectId() != null) {
|
||||
CollectTimes times = result.collects.get(event.getDeviceCollectId());
|
||||
if (times == null) result.collects.put(event.getDeviceCollectId(),
|
||||
new CollectTimes(event.getReceiveTime(), event.getReceiveTime()));
|
||||
else {
|
||||
if (event.getReceiveTime().isBefore(times.min)) times.min = event.getReceiveTime();
|
||||
if (event.getReceiveTime().isAfter(times.max)) times.max = event.getReceiveTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static final class Aggregation {
|
||||
// 所有节点使用相同顺序取得投影行锁,避免不同 Kafka 批次顺序造成交叉等待。
|
||||
final Map<DeviceKey, LocalDateTime> devices = new TreeMap<>(
|
||||
Comparator.comparing((DeviceKey key) -> key.date)
|
||||
.thenComparingLong(key -> key.deviceId));
|
||||
final Map<Long, CollectTimes> collects = new TreeMap<>();
|
||||
}
|
||||
static final class DeviceKey {
|
||||
final LocalDate date; final long deviceId;
|
||||
DeviceKey(LocalDate date, long deviceId) { this.date = date; this.deviceId = deviceId; }
|
||||
@Override public boolean equals(Object other) {
|
||||
if (this == other) return true;
|
||||
if (!(other instanceof DeviceKey)) return false;
|
||||
DeviceKey key = (DeviceKey) other;
|
||||
return deviceId == key.deviceId && date.equals(key.date);
|
||||
}
|
||||
@Override public int hashCode() { return 31 * date.hashCode() + Long.hashCode(deviceId); }
|
||||
}
|
||||
static final class CollectTimes {
|
||||
LocalDateTime min; LocalDateTime max;
|
||||
CollectTimes(LocalDateTime min, LocalDateTime max) { this.min = min; this.max = max; }
|
||||
}
|
||||
|
||||
private void mergeDeviceReceive(String table, DeviceKey key, LocalDateTime receiveTime) {
|
||||
jdbc.update("MERGE INTO " + safeTable(table) + " t USING " +
|
||||
"(SELECT ? stat_date,? device_id,? receive_time FROM DUAL) s " +
|
||||
"ON (t.stat_date=s.stat_date AND t.device_id=s.device_id) " +
|
||||
"WHEN MATCHED THEN UPDATE SET t.last_receive_time=CASE " +
|
||||
"WHEN t.last_receive_time IS NULL OR t.last_receive_time<s.receive_time " +
|
||||
"THEN s.receive_time ELSE t.last_receive_time END,t.updated_at=SYSDATE " +
|
||||
"WHEN NOT MATCHED THEN INSERT (stat_date,device_id,parse_count,non_log_count," +
|
||||
"last_receive_time,projection_seq,updated_at) VALUES " +
|
||||
"(s.stat_date,s.device_id,0,0,s.receive_time,0,SYSDATE)",
|
||||
Date.valueOf(key.date), key.deviceId, receiveTime);
|
||||
}
|
||||
|
||||
private static String safeTable(String table) {
|
||||
if (table == null || !table.matches("[A-Za-z][A-Za-z0-9_]*")) {
|
||||
throw new IllegalStateException("非法入口设备统计表名: " + table);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -51,7 +51,10 @@ public class LogDataCompleteService {
|
||||
JSONArray completeColumns = ruleJson.getJSONArray("complete_columns");
|
||||
|
||||
if (completeColumns == null || completeColumns.isEmpty()) {
|
||||
log.warn("补全规则为空");
|
||||
// 空补全规则表示当前规则不需要补全,是正常业务分支。
|
||||
// 本方法位于逐消息、逐规则的消费热路径,避免输出 WARN/INFO
|
||||
// 造成日志刷屏和同步日志 I/O 开销。
|
||||
log.debug("泛化规则未配置数据补全条件,跳过补全");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -255,4 +258,4 @@ public class LogDataCompleteService {
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+5
-4
@@ -4,13 +4,11 @@ package com.common.service;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.common.mapper.SyslogNormalDataMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -30,7 +28,10 @@ public class LogDataFilterService {
|
||||
JSONArray filtersParams = filtersParamsObj.getJSONArray("expressions");
|
||||
|
||||
if (filtersParams == null || filtersParams.isEmpty()) {
|
||||
log.warn("泛化规则-数据过滤规则为空,默认不处理!");
|
||||
// 空过滤规则表示当前规则不需要过滤,是正常业务分支。
|
||||
// 本方法位于逐消息、逐规则的消费热路径,禁止在此打印 WARN/INFO,
|
||||
// 否则高吞吐场景会产生海量同步日志 I/O,显著降低 Kafka 消费速度。
|
||||
log.debug("泛化规则未配置数据过滤条件,跳过过滤");
|
||||
return false;
|
||||
}
|
||||
// 遍历所有过滤组,只要满足任一过滤组即可
|
||||
@@ -201,4 +202,4 @@ public class LogDataFilterService {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.DeviceReceiveLog;
|
||||
import com.common.entity.StatsChangeRecord;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import com.common.mapper.StatsChangeLogMapper;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 在事实写入事务中同步追加最小变更记录。开关关闭时不访问增量统计表,便于先部署代码再执行 DDL。
|
||||
*/
|
||||
@Service
|
||||
public class StatsChangeCaptureService {
|
||||
|
||||
private final StatsChangeLogMapper mapper;
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
|
||||
@Value("${stats.incremental.capture-enabled:false}")
|
||||
private boolean enabled;
|
||||
|
||||
/** 旧接收明细的逐行捕获可能放大历史清理,客户确认前默认关闭但保留实现。 */
|
||||
@Value("${stats.device-receive.change-capture-enabled:false}")
|
||||
private boolean deviceReceiveCaptureEnabled;
|
||||
|
||||
public StatsChangeCaptureService(StatsChangeLogMapper mapper,
|
||||
StatsWriteModeProvider modeProvider) {
|
||||
this.mapper = mapper;
|
||||
this.modeProvider = modeProvider;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled && modeProvider.writesLegacyChangeLog();
|
||||
}
|
||||
|
||||
public void captureStandardizedInsert(Map<String, Object> row, boolean alarm) {
|
||||
if (isEnabled()) {
|
||||
insertChange(mapper, standardizedInsert(row, alarm));
|
||||
}
|
||||
}
|
||||
|
||||
/** BatchExecutor 必须使用同一个 BATCH SqlSession,避免同一事务切换 ExecutorType。 */
|
||||
public void captureStandardizedBatch(SqlSessionTemplate batchSession,
|
||||
List<Map<String, Object>> rows,
|
||||
boolean alarm) {
|
||||
if (!isEnabled() || rows == null || rows.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
StatsChangeLogMapper batchMapper = batchSession.getMapper(StatsChangeLogMapper.class);
|
||||
List<StatsChangeRecord> changes = new java.util.ArrayList<>(rows.size());
|
||||
for (Map<String, Object> row : rows) {
|
||||
StatsChangeRecord change = standardizedInsert(row, alarm);
|
||||
changes.add(change);
|
||||
batchMapper.insert(change);
|
||||
}
|
||||
for (StatsChangeRecord change : changes) {
|
||||
batchMapper.insertPending(change);
|
||||
}
|
||||
}
|
||||
|
||||
public void captureNonNormalInsert(SyslogNonNormalMessage message) {
|
||||
if (!isEnabled()) {
|
||||
return;
|
||||
}
|
||||
String rowId = requiredText(message.getId(), "非标日志缺少主键");
|
||||
insertChange(mapper, StatsChangeRecord.builder()
|
||||
.changeId("NON_NORMAL:" + rowId + ":INSERT")
|
||||
.sourceType("NON_NORMAL")
|
||||
.sourceRowId(rowId)
|
||||
.operationType("INSERT")
|
||||
.newStatDate(dateValue(message.getCreatedAt()))
|
||||
.newDeviceId(longValue(message.getDeviceId()))
|
||||
.newEventTime(message.getLogTime())
|
||||
.build());
|
||||
}
|
||||
|
||||
public void captureNonNormalUpdate(SyslogNonNormalMessage oldValue,
|
||||
SyslogNonNormalMessage newValue) {
|
||||
if (!isEnabled() || oldValue == null || newValue == null) {
|
||||
return;
|
||||
}
|
||||
String rowId = requiredText(oldValue.getId(), "非标日志缺少主键");
|
||||
insertChange(mapper, StatsChangeRecord.builder()
|
||||
.changeId("NON_NORMAL:" + rowId + ":UPDATE:" + UUID.randomUUID())
|
||||
.sourceType("NON_NORMAL")
|
||||
.sourceRowId(rowId)
|
||||
.operationType("UPDATE")
|
||||
.oldStatDate(dateValue(oldValue.getCreatedAt()))
|
||||
.newStatDate(dateValue(newValue.getCreatedAt() != null
|
||||
? newValue.getCreatedAt() : oldValue.getCreatedAt()))
|
||||
.oldDeviceId(longValue(oldValue.getDeviceId()))
|
||||
.newDeviceId(longValue(newValue.getDeviceId() != null
|
||||
? newValue.getDeviceId() : oldValue.getDeviceId()))
|
||||
.oldEventTime(oldValue.getLogTime())
|
||||
.newEventTime(newValue.getLogTime() != null
|
||||
? newValue.getLogTime() : oldValue.getLogTime())
|
||||
.build());
|
||||
}
|
||||
|
||||
public void captureDeviceReceiveInsert(DeviceReceiveLog log) {
|
||||
if (!isEnabled() || !deviceReceiveCaptureEnabled) {
|
||||
return;
|
||||
}
|
||||
String rowId = log.getId() == null ? UUID.randomUUID().toString() : log.getId().toString();
|
||||
insertChange(mapper, StatsChangeRecord.builder()
|
||||
.changeId("DEVICE_RECEIVE:" + rowId + ":INSERT")
|
||||
.sourceType("DEVICE_RECEIVE")
|
||||
.sourceRowId(rowId)
|
||||
.operationType("INSERT")
|
||||
.newStatDate(dateValue(log.getReceiveTime() != null
|
||||
? log.getReceiveTime() : log.getCreatedAt()))
|
||||
.newDeviceId(longValue(log.getDeviceId()))
|
||||
.newCollectId(longValue(log.getDeviceCollectId()))
|
||||
.newEventTime(log.getReceiveTime())
|
||||
.newCollectTime(log.getCreatedAt())
|
||||
.newPushSuccess(booleanValue(log.getPushSuccess()))
|
||||
.build());
|
||||
}
|
||||
|
||||
public void captureDeviceReceiveBatch(List<DeviceReceiveLog> logs) {
|
||||
if (!isEnabled() || !deviceReceiveCaptureEnabled || logs == null) {
|
||||
return;
|
||||
}
|
||||
for (DeviceReceiveLog log : logs) {
|
||||
captureDeviceReceiveInsert(log);
|
||||
}
|
||||
}
|
||||
|
||||
public void captureDeviceReceiveDeletes(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
if (isEnabled() && deviceReceiveCaptureEnabled) {
|
||||
mapper.captureDeviceReceiveDeletes(startTime, endTime);
|
||||
mapper.enqueueDeviceReceiveDeletes(startTime, endTime);
|
||||
}
|
||||
}
|
||||
|
||||
private void insertChange(StatsChangeLogMapper targetMapper, StatsChangeRecord change) {
|
||||
targetMapper.insert(change);
|
||||
targetMapper.insertPending(change);
|
||||
}
|
||||
|
||||
private StatsChangeRecord standardizedInsert(Map<String, Object> row, boolean alarm) {
|
||||
String source = alarm ? "NORMAL_ALARM" : "NORMAL_DATA";
|
||||
String rowId = requiredText(row.get("id"), "标准化结果缺少确定性 id");
|
||||
return StatsChangeRecord.builder()
|
||||
.changeId(source + ":" + rowId + ":INSERT")
|
||||
.sourceType(source)
|
||||
.sourceRowId(rowId)
|
||||
.operationType("INSERT")
|
||||
.newStatDate(dateValue(row.get("created_at")))
|
||||
.newDeviceId(longValue(row.get("device_id")))
|
||||
.newRuleId(longValue(row.get("normalize_rule_id")))
|
||||
.newEventTime(timeValue(row.get("log_time")))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String requiredText(Object value, String message) {
|
||||
if (value == null || value.toString().trim().isEmpty()) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static Long longValue(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value instanceof Number
|
||||
? ((Number) value).longValue()
|
||||
: Long.valueOf(value.toString());
|
||||
}
|
||||
|
||||
private static Integer booleanValue(Boolean value) {
|
||||
return value == null ? null : (value ? 1 : 0);
|
||||
}
|
||||
|
||||
private static LocalDate dateValue(Object value) {
|
||||
LocalDateTime time = timeValue(value);
|
||||
return time == null ? null : time.toLocalDate();
|
||||
}
|
||||
|
||||
private static LocalDateTime timeValue(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof LocalDateTime) {
|
||||
return (LocalDateTime) value;
|
||||
}
|
||||
if (value instanceof LocalDate) {
|
||||
return ((LocalDate) value).atStartOfDay();
|
||||
}
|
||||
if (value instanceof OffsetDateTime) {
|
||||
return ((OffsetDateTime) value).atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
|
||||
}
|
||||
if (value instanceof Timestamp) {
|
||||
return ((Timestamp) value).toLocalDateTime();
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
Instant instant = Instant.ofEpochMilli(((Date) value).getTime());
|
||||
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的统计时间类型: " + value.getClass().getName());
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 统计写入模式的唯一解释入口,避免多个布尔开关组合出双计数或无人维护统计的状态。
|
||||
*/
|
||||
@Component
|
||||
public class StatsWriteModeProvider {
|
||||
|
||||
public enum Mode {
|
||||
LEGACY_CHANGE_LOG,
|
||||
DIRECT_SHADOW,
|
||||
DIRECT,
|
||||
FACT_ONLY_REBUILD_REQUIRED
|
||||
}
|
||||
|
||||
private final Mode mode;
|
||||
|
||||
public StatsWriteModeProvider(@Value("${stats.write-mode:LEGACY_CHANGE_LOG}") String configuredMode) {
|
||||
this.mode = parse(configuredMode);
|
||||
}
|
||||
|
||||
public Mode getMode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
public boolean writesLegacyChangeLog() {
|
||||
return mode == Mode.LEGACY_CHANGE_LOG || mode == Mode.DIRECT_SHADOW;
|
||||
}
|
||||
|
||||
public boolean writesDirectProjection() {
|
||||
return mode == Mode.DIRECT || mode == Mode.DIRECT_SHADOW;
|
||||
}
|
||||
|
||||
public boolean writesShadowProjection() {
|
||||
return mode == Mode.DIRECT_SHADOW;
|
||||
}
|
||||
|
||||
public boolean materializesBusinessFields() {
|
||||
return mode == Mode.DIRECT;
|
||||
}
|
||||
|
||||
public boolean requiresRebuild() {
|
||||
return mode == Mode.FACT_ONLY_REBUILD_REQUIRED;
|
||||
}
|
||||
|
||||
static Mode parse(String configuredMode) {
|
||||
String normalized = configuredMode == null
|
||||
? ""
|
||||
: configuredMode.trim().toUpperCase(Locale.ROOT);
|
||||
try {
|
||||
return Mode.valueOf(normalized);
|
||||
} catch (IllegalArgumentException invalidMode) {
|
||||
throw new IllegalStateException("不支持的 stats.write-mode: " + configuredMode
|
||||
+ ",允许值为 LEGACY_CHANGE_LOG、DIRECT_SHADOW、DIRECT、FACT_ONLY_REBUILD_REQUIRED",
|
||||
invalidMode);
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
-12
@@ -10,11 +10,14 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Service
|
||||
public class SyslogNormalDataService {
|
||||
@@ -23,6 +26,10 @@ public class SyslogNormalDataService {
|
||||
private SyslogNormalDataMapper syslogNormalDataMapper;
|
||||
@Autowired
|
||||
private SyslogNormalAlarmMapper syslogNormalAlarmMapper;
|
||||
@Autowired
|
||||
private StatsChangeCaptureService statsChangeCaptureService;
|
||||
@Autowired
|
||||
private DirectStatsProjectionWriter directStatsProjectionWriter;
|
||||
|
||||
|
||||
/**
|
||||
@@ -30,11 +37,64 @@ public class SyslogNormalDataService {
|
||||
*/
|
||||
@Transactional
|
||||
public int insertDynamic(Map<String, Object> dataMap) {
|
||||
// 设置必要字段的默认值
|
||||
if (!dataMap.containsKey("created_at")) {
|
||||
// [流程节点7] 根据标准化结果分类落库:安全事件写入 syslog_normal_alarm,访问事件写入 syslog_normal_data。
|
||||
// [SYSLOG-ALARM][DBBATCH] 每条标准化结果单独开启事务并执行动态 INSERT,会产生大量数据库往返、SQL 解析和提交开销;
|
||||
// 高峰期 DB 变慢又会放大 Kafka 批次超时。建议按目标表和固定列集合聚合批次写入,并用 event_id + 规则版本唯一键保证重试幂等。
|
||||
prepareForInsert(dataMap);
|
||||
|
||||
// [流程节点7.2] event_level 非空走安全事件表;为空走访问事件表,这是两条后续分析链路的分叉点。
|
||||
boolean alarmData = isAlarmData(dataMap);
|
||||
try {
|
||||
int inserted = alarmData
|
||||
? syslogNormalAlarmMapper.insertDynamic(dataMap)
|
||||
: syslogNormalDataMapper.insertDynamic(dataMap);
|
||||
if (inserted > 0) {
|
||||
statsChangeCaptureService.captureStandardizedInsert(dataMap, alarmData);
|
||||
directStatsProjectionWriter.writeStandardizedRow(dataMap);
|
||||
}
|
||||
return inserted;
|
||||
} catch (DataAccessException dataAccessFailure) {
|
||||
if (isUniqueConstraintViolation(dataAccessFailure)
|
||||
&& idempotentResultExists(dataMap, alarmData)) {
|
||||
// 达梦可能不会把唯一约束冲突翻译为 DuplicateKeyException。确认原结果存在后按幂等成功处理,
|
||||
// 只保留一条简洁告警,不打印异常栈,也不进入非标、Retry 或 DLT。
|
||||
logger.warn("标准化结果重复,已按幂等成功处理: table={}, eventId={}, ruleId={}, ruleVersion={}",
|
||||
alarmData ? "syslog_normal_alarm" : "syslog_normal_data",
|
||||
dataMap.get("syslog_uuid"), dataMap.get("normalize_rule_id"), dataMap.get("rule_version"));
|
||||
return 0;
|
||||
}
|
||||
throw dataAccessFailure;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在单条和批量写入之前执行完全相同的数据准备与关键字段校验。
|
||||
*
|
||||
* <p>批写器必须在分组前调用本方法。这样无效 IP、稳定时间和幂等字段的处理不会因为
|
||||
* SINGLE/BATCH 模式不同而产生两套数据口径。本方法只修改当前行 Map,不访问数据库,
|
||||
* 也不开启事务。</p>
|
||||
*/
|
||||
public void prepareForInsert(Map<String, Object> dataMap) {
|
||||
if (dataMap == null) {
|
||||
throw new IllegalArgumentException("标准化写入数据不能为空");
|
||||
}
|
||||
|
||||
// [流程节点7.1] 补齐入库时间并校验关键字段,保证动态 SQL 使用的数据满足基础约束。
|
||||
boolean idempotentWrite = dataMap.get("id") != null && dataMap.get("rule_version") != null;
|
||||
if (!dataMap.containsKey("created_at") || dataMap.get("created_at") == null) {
|
||||
if (idempotentWrite) {
|
||||
throw new IllegalArgumentException("幂等标准化写入缺少稳定 created_at");
|
||||
}
|
||||
// 仅供历史非 Syslog 调用入口兼容。活动 Syslog 主链路会在上游把 created_at
|
||||
// 固定为首次 receive_time。
|
||||
dataMap.put("created_at", new java.util.Date());
|
||||
}
|
||||
if (!dataMap.containsKey("log_time")) {
|
||||
if (!dataMap.containsKey("log_time") || dataMap.get("log_time") == null) {
|
||||
if (idempotentWrite) {
|
||||
throw new IllegalArgumentException("幂等标准化写入缺少稳定分区键 log_time");
|
||||
}
|
||||
// 仅供历史非 Syslog 调用入口兼容。log_time 是现场标准化表的真实分区键;活动 Syslog
|
||||
// 主链路会在上游把它固定为首次 receive_time,保证 Retry/Replay 进入同一分区并命中本地唯一键。
|
||||
dataMap.put("log_time", new java.util.Date());
|
||||
}
|
||||
if (dataMap.containsKey("tc_hostip")) {
|
||||
@@ -43,15 +103,78 @@ public class SyslogNormalDataService {
|
||||
String hostip=dataMap.get("tc_hostip").toString();
|
||||
logger.error("tc_hostip 字段非IP类型,值为:{},将赋值为null",hostip);
|
||||
dataMap.remove("tc_hostip");
|
||||
|
||||
}
|
||||
}
|
||||
//判断是否包含event_level (事件级别),区分告警日志和访问日志,分别进入不同的标准化数据表
|
||||
if (dataMap != null && dataMap.get("event_level") != null) {
|
||||
return syslogNormalAlarmMapper.insertDynamic(dataMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批写器和单条写入共用同一个目标表判断,避免两种模式产生不同分流结果。
|
||||
*
|
||||
* <p>这里仍保持现有业务口径:event_level 非空写告警表,否则写普通表。这个口径本身
|
||||
* 可能把“缺失 event_level 的安全事件”分到普通表,但它是另一个业务改造事项,不能在
|
||||
* 本次批写优化中顺带改变。</p>
|
||||
*/
|
||||
public boolean isAlarmData(Map<String, Object> dataMap) {
|
||||
return dataMap != null && dataMap.get("event_level") != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量失败缩小到单条后,用于确认唯一冲突是否属于已成功写入的幂等重投。
|
||||
*/
|
||||
public boolean isIdempotentResultPresent(Map<String, Object> dataMap) {
|
||||
return idempotentResultExists(dataMap, isAlarmData(dataMap));
|
||||
}
|
||||
|
||||
/** 暴露统一的唯一冲突识别,供批写失败隔离逻辑复用。 */
|
||||
public boolean isUniqueViolation(Throwable failure) {
|
||||
return isUniqueConstraintViolation(failure);
|
||||
}
|
||||
|
||||
private boolean idempotentResultExists(Map<String, Object> dataMap, boolean alarmData) {
|
||||
LocalDateTime logTime = localDateTimeValue(dataMap.get("log_time"));
|
||||
String id = stringValue(dataMap.get("id"));
|
||||
if (logTime == null || id == null) {
|
||||
return false;
|
||||
}
|
||||
else
|
||||
return syslogNormalDataMapper.insertDynamic(dataMap);
|
||||
if (alarmData) {
|
||||
return syslogNormalAlarmMapper.countByLogTimeAndId(logTime, id) > 0;
|
||||
}
|
||||
return syslogNormalDataMapper.countByLogTimeAndId(logTime, id) > 0;
|
||||
}
|
||||
|
||||
private boolean isUniqueConstraintViolation(Throwable failure) {
|
||||
Throwable current = failure;
|
||||
while (current != null) {
|
||||
String message = String.valueOf(current.getMessage()).toLowerCase(Locale.ROOT);
|
||||
if (message.contains("violate unique constraint")
|
||||
|| message.contains("unique constraint")
|
||||
|| message.contains("duplicate key")) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private LocalDateTime localDateTimeValue(Object value) {
|
||||
if (value instanceof LocalDateTime) {
|
||||
return (LocalDateTime) value;
|
||||
}
|
||||
if (value instanceof java.sql.Timestamp) {
|
||||
return ((java.sql.Timestamp) value).toLocalDateTime();
|
||||
}
|
||||
if (value instanceof java.util.Date) {
|
||||
return new java.sql.Timestamp(((java.util.Date) value).getTime()).toLocalDateTime();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String stringValue(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String result = value.toString();
|
||||
return result.trim().isEmpty() ? null : result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,7 +189,12 @@ public class SyslogNormalDataService {
|
||||
if (entity.getLogTime() == null) {
|
||||
entity.setLogTime(java.time.LocalDateTime.now());
|
||||
}
|
||||
return syslogNormalDataMapper.insertByEntity(entity);
|
||||
int inserted = syslogNormalDataMapper.insertByEntity(entity);
|
||||
if (inserted > 0) {
|
||||
Map<String, Object> row = convertEntityToMap(entity);
|
||||
directStatsProjectionWriter.writeStandardizedRow(row);
|
||||
}
|
||||
return inserted;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,7 +215,14 @@ public class SyslogNormalDataService {
|
||||
data.put("log_time", new java.util.Date());
|
||||
}
|
||||
}
|
||||
return syslogNormalDataMapper.batchInsert(dataList);
|
||||
// 旧 mapper 的 batchInsert 只写固定的少数字段,DIRECT 下会造成“统计有 device/rule,
|
||||
// 事实行却丢了 device/rule”的永久差异。主 Kafka 链路使用 DmStandardizedBatchExecutor;
|
||||
// 这个低频兼容 API 逐条复用完整动态 INSERT,但仍处于本方法的同一个 Spring 事务中。
|
||||
int inserted = 0;
|
||||
for (Map<String, Object> data : dataList) {
|
||||
inserted += insertDynamic(data);
|
||||
}
|
||||
return inserted;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,4 +264,4 @@ public class SyslogNormalDataService {
|
||||
private String camelToSnake(String str) {
|
||||
return str.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-1
@@ -69,6 +69,7 @@ public class AnalysisRuleServiceImpl implements AnalysisRuleService {
|
||||
|
||||
@Override
|
||||
public Map<String, Object> executeRealtimeRule(String ruleId) {
|
||||
// [流程节点8] 加载指定实时规则并转交实时分析引擎执行;该入口也供手工触发和调度器调用。
|
||||
log.info("执行实时分析规则: ruleId={}", ruleId);
|
||||
|
||||
// 查询规则
|
||||
@@ -93,14 +94,21 @@ public class AnalysisRuleServiceImpl implements AnalysisRuleService {
|
||||
// 执行单个规则
|
||||
List<AnalysisAnalysisRule> ruleList = new ArrayList<>();
|
||||
ruleList.add(rule);
|
||||
// [流程节点8.3] 把已校验的规则交给实时分析引擎;返回结果供调用方判断本次窗口是否成功。
|
||||
List<Map<String, Object>> results = realtimeAnalysisEngine.executeRules(ruleList);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("success", true);
|
||||
boolean allCompleted = !results.isEmpty() && results.stream()
|
||||
.allMatch(item -> "success".equalsIgnoreCase(String.valueOf(item.get("status"))));
|
||||
// [SYSLOG-ALARM][RULECP][已修复] 内部任一窗口失败都会向调度器返回 success=false,禁止推进计划时间。
|
||||
result.put("success", allCompleted);
|
||||
result.put("ruleId", ruleId);
|
||||
result.put("ruleName", rule.getRuleName());
|
||||
result.put("resultCount", results.size());
|
||||
result.put("results", results);
|
||||
if (!allCompleted) {
|
||||
result.put("message", "规则窗口未完整成功,成功水位保持不变");
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error("执行实时分析规则失败: ruleId={}", ruleId, e);
|
||||
|
||||
+8
-7
@@ -1,9 +1,11 @@
|
||||
package com.common.service.impl;
|
||||
|
||||
|
||||
import com.Modules.NormalData.cache.NormalizationLookupFacade;
|
||||
import com.common.entity.DeviceDevice;
|
||||
import com.common.mapper.DeviceDeviceMapper;
|
||||
import com.common.service.DeviceDeviceService;
|
||||
import com.common.util.SafeCacheUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -11,7 +13,6 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import com.common.util.SafeCacheUtil;
|
||||
|
||||
@CacheConfig(cacheNames = "device")
|
||||
@Service
|
||||
@@ -21,18 +22,19 @@ public class DeviceDeviceServiceImpl implements DeviceDeviceService {
|
||||
private DeviceDeviceMapper deviceDeviceMapper;
|
||||
|
||||
|
||||
// 仅保留给尚未迁移的 IP 列表查询。
|
||||
@Autowired
|
||||
private SafeCacheUtil safeCacheUtil;
|
||||
|
||||
@Autowired
|
||||
private NormalizationLookupFacade normalizationLookupFacade;
|
||||
|
||||
/**
|
||||
* 使用安全的缓存方法
|
||||
*/
|
||||
@Cacheable( key = "'device:id:' +#id")
|
||||
@Override
|
||||
public DeviceDevice getByIdSafely(Integer id) {
|
||||
String cacheKey = "device:id:" + id;
|
||||
return safeCacheUtil.getSafe(cacheKey, DeviceDevice.class,
|
||||
() -> deviceDeviceMapper.selectById(id));
|
||||
return normalizationLookupFacade.device(id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,7 +51,6 @@ public class DeviceDeviceServiceImpl implements DeviceDeviceService {
|
||||
@Cacheable( key = "'device:id:' +#id")
|
||||
@Override
|
||||
public DeviceDevice getById(Integer id) {
|
||||
System.out.println("exec deviceDeviceMapper.selectById :" + id.toString());
|
||||
return deviceDeviceMapper.selectById(id);
|
||||
}
|
||||
|
||||
@@ -100,4 +101,4 @@ public class DeviceDeviceServiceImpl implements DeviceDeviceService {
|
||||
public List<DeviceDevice> getActiveDevices() {
|
||||
return deviceDeviceMapper.selectActiveDevices();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-5
@@ -4,6 +4,7 @@ package com.common.service.impl;
|
||||
import com.common.entity.DeviceReceiveLog;
|
||||
import com.common.mapper.DeviceReceiveLogMapper;
|
||||
import com.common.service.DeviceReceiveLogService;
|
||||
import com.common.service.StatsChangeCaptureService;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -21,6 +22,7 @@ import java.util.Map;
|
||||
public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {
|
||||
|
||||
private final DeviceReceiveLogMapper deviceReceiveLogMapper;
|
||||
private final StatsChangeCaptureService statsChangeCaptureService;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -35,6 +37,7 @@ public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {
|
||||
}
|
||||
|
||||
deviceReceiveLogMapper.insert(log);
|
||||
statsChangeCaptureService.captureDeviceReceiveInsert(log);
|
||||
// log.info("插入设备接收日志成功,ID: {}", log.getId());
|
||||
return log.getId();
|
||||
}
|
||||
@@ -65,6 +68,7 @@ public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {
|
||||
});
|
||||
|
||||
int inserted = deviceReceiveLogMapper.batchInsert(batchList);
|
||||
statsChangeCaptureService.captureDeviceReceiveBatch(batchList);
|
||||
totalInserted += inserted;
|
||||
log.info("批量插入进度: {}/{}", end, logs.size());
|
||||
}
|
||||
@@ -142,10 +146,9 @@ public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {
|
||||
}
|
||||
|
||||
|
||||
int deleted = deviceReceiveLogMapper.deleteByTimeRange(
|
||||
LocalDateTime.of(2025, 11, 1, 0, 0,0) , // 默认2025年11月
|
||||
beforeTime
|
||||
);
|
||||
LocalDateTime startTime = LocalDateTime.of(2025, 11, 1, 0, 0, 0);
|
||||
statsChangeCaptureService.captureDeviceReceiveDeletes(startTime, beforeTime);
|
||||
int deleted = deviceReceiveLogMapper.deleteByTimeRange(startTime, beforeTime);
|
||||
|
||||
log.info("删除{}天前的日志,共删除{}条", beforeTime, deleted);
|
||||
return deleted;
|
||||
@@ -158,4 +161,4 @@ public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {
|
||||
}
|
||||
return deviceReceiveLogMapper.selectRecent(limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+40
-4
@@ -1,5 +1,6 @@
|
||||
package com.common.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.common.entity.*;
|
||||
import com.common.mapper.*;
|
||||
import com.common.service.AnalysisEngine;
|
||||
@@ -12,6 +13,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
@@ -62,11 +64,16 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
|
||||
@Override
|
||||
public Map<String, Object> executeRule(AnalysisAnalysisRule rule) {
|
||||
// [流程节点9] 生成规则 SQL,执行过滤、分组和时间窗口计算,并把规则告警写入最终结果表 alarm。
|
||||
String batchNo = generateBatchNo();
|
||||
//LocalDateTime startTime = LocalDateTime.now();
|
||||
//LocalDateTime dataEndTime = startTime;
|
||||
//LocalDateTime dataStartTime = startTime.minusMinutes(30); // 默认查询最近30分钟
|
||||
// 时间点取整分钟,避免秒级时间导致窗口计算不一致
|
||||
// [SYSLOG-ALARM][RULECP] 以当前机器时间回看固定窗口不是可靠 checkpoint:停机、调度延迟、数据库故障或标准化积压后,
|
||||
// 当前时间仍向前走,未成功窗口不会自然补跑;不同节点时钟偏差也会产生重叠/空洞。
|
||||
// 建议从持久化的“最后连续成功 window_end”计算下一窗口,并为迟到数据配置 allowed lateness。
|
||||
// [流程节点9.1] 根据规则窗口配置计算本次查询的 window_start 和 window_end。
|
||||
LocalDateTime startTime = LocalDateTime.now().withSecond(0).withNano(0);
|
||||
LocalDateTime dataEndTime = startTime;
|
||||
|
||||
@@ -117,6 +124,7 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
// 更新规则状态为运行中
|
||||
ruleMapper.updateTaskStatus(rule.getRuleId(), "running", 1L);
|
||||
|
||||
// [流程节点9.2] 加载字段、WHERE、过滤、GROUP BY 和 HAVING 配置,组成完整规则快照。
|
||||
// 加载规则配置
|
||||
List<AnalysisField> fields = fieldMapper.selectByRuleId(rule.getRuleId());
|
||||
List<AnalysisWhereCondition> whereConditions = whereConditionMapper.selectByRuleId(rule.getRuleId());
|
||||
@@ -136,6 +144,7 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
}
|
||||
***/
|
||||
|
||||
// [流程节点9.3] 将规则配置和时间范围转换为实际执行 SQL;SQL 中的过滤和分组决定候选告警数量。
|
||||
// 生成SQL
|
||||
String sql = sqlGeneratorService.generateSql(
|
||||
rule,
|
||||
@@ -151,6 +160,7 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
|
||||
log.info("生成的SQL: {}", sql);
|
||||
|
||||
// [流程节点9.4] 在标准化安全事件数据上执行 SQL,得到窗口内聚合后的告警候选结果。
|
||||
// 执行SQL
|
||||
List<Map<String, Object>> queryResult = jdbcTemplate.queryForList(sql);
|
||||
result.put("queryResult", queryResult);
|
||||
@@ -158,15 +168,19 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
// 处理结果,生成告警
|
||||
long alarmCount = 0;
|
||||
if (!queryResult.isEmpty()) {
|
||||
List<Alarm> alarms = convertToAlarms(rule, queryResult);
|
||||
// [流程节点9.5] 将每个查询结果组转换为 Alarm 实体,补充规则、时间窗口和告警属性。
|
||||
List<Alarm> alarms = convertToAlarms(rule, queryResult, dataStartTime);
|
||||
if (!alarms.isEmpty()) {
|
||||
//String tableName = "alarm_" + dataStartTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
|
||||
String tableName = "alarm";
|
||||
alarmMapper.batchInsert( alarms);
|
||||
// [SYSLOG-ALARM][AIDEMP][部分修复] 稳定 ID + 已存在集合过滤保证同一规则结果重跑不重复;该兼容模块仍需部署方确认唯一调度实例。
|
||||
// [流程节点9.6] 写入最终规则告警表 alarm;该数量应与本窗口可落库告警组数一致。
|
||||
insertMissingAlarms(alarms);
|
||||
alarmCount = alarms.size();
|
||||
}
|
||||
}
|
||||
|
||||
// [流程节点9.7] 记录输入数、告警数和 COMPLETED 状态,作为窗口执行结果和后续对账依据。
|
||||
// 更新任务历史
|
||||
LocalDateTime endTime = LocalDateTime.now();
|
||||
long durationSeconds = java.time.Duration.between(startTime, endTime).getSeconds();
|
||||
@@ -190,6 +204,8 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
rule.getRuleId(), queryResult.size(), alarmCount);
|
||||
|
||||
} catch (Exception e) {
|
||||
// [SYSLOG-ALARM][RULECP] 捕获后只返回 status=failed 而不抛异常,上层若只看“调用未抛错”会误判成功并推进窗口。
|
||||
// 建议使用强类型结果并强制上层校验,或抛出异常;失败窗口保持 FAILED/RETRYING。
|
||||
log.error("规则执行失败: ruleId={}", rule.getRuleId(), e);
|
||||
|
||||
// 更新任务历史
|
||||
@@ -445,12 +461,13 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
/**
|
||||
* 转换查询结果为告警对象
|
||||
*/
|
||||
private List<Alarm> convertToAlarms(AnalysisAnalysisRule rule, List<Map<String, Object>> queryResult) {
|
||||
private List<Alarm> convertToAlarms(AnalysisAnalysisRule rule, List<Map<String, Object>> queryResult,
|
||||
LocalDateTime windowStart) {
|
||||
List<Alarm> alarms = new ArrayList<>();
|
||||
|
||||
for (Map<String, Object> row : queryResult) {
|
||||
Alarm alarm = Alarm.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.id(stableAlarmId(rule, row, windowStart))
|
||||
.createdAt(LocalDateTime.now())
|
||||
.updatedAt(LocalDateTime.now())
|
||||
.alarmName(rule.getRuleName())
|
||||
@@ -470,6 +487,10 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
.comment(buildComment(row))
|
||||
.attackChainPhase(getIntegerArray(-1))
|
||||
.judgedState(0)
|
||||
.ruleId(rule.getRuleId())
|
||||
.ruleVersion(String.valueOf(rule.getVersion()))
|
||||
.windowStart(windowStart)
|
||||
.groupKeyHash(stableAlarmId(rule, row, windowStart))
|
||||
.build();
|
||||
|
||||
// 映射查询结果字段到告警对象
|
||||
@@ -635,6 +656,21 @@ public class RealtimeAnalysisEngine implements AnalysisEngine {
|
||||
return alarms;
|
||||
}
|
||||
|
||||
private String stableAlarmId(AnalysisAnalysisRule rule, Map<String, Object> row, LocalDateTime windowStart) {
|
||||
String material = rule.getRuleId() + ":" + String.valueOf(rule.getVersion()) + ":" + windowStart + ":"
|
||||
+ JSON.toJSONString(new TreeMap<>(row));
|
||||
return UUID.nameUUIDFromBytes(material.getBytes(StandardCharsets.UTF_8)).toString();
|
||||
}
|
||||
|
||||
private void insertMissingAlarms(List<Alarm> candidates) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (Alarm alarm : candidates) ids.add(alarm.getId());
|
||||
Set<String> existing = new HashSet<>(alarmMapper.selectExistingIds(ids));
|
||||
List<Alarm> missing = new ArrayList<>();
|
||||
for (Alarm alarm : candidates) if (!existing.contains(alarm.getId())) missing.add(alarm);
|
||||
if (!missing.isEmpty()) alarmMapper.batchInsert(missing);
|
||||
}
|
||||
|
||||
private byte[] getBytesValue(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
|
||||
+8
@@ -23,6 +23,9 @@ import java.time.temporal.ChronoUnit;
|
||||
@Service
|
||||
public class RuleExecutionTimeServiceImpl implements RuleExecutionTimeService {
|
||||
|
||||
// [SYSLOG-ALARM][REDISCP] 这里只保存“下次计划执行时间”,没有保存最后连续成功的 window_start/window_end、状态和重试次数。
|
||||
// 调度时间不是业务成功水位:即使 SQL/写库失败,next_execute 仍可能前移。建议以数据库 checkpoint 状态机为事实源,
|
||||
// Redis 仅做缓存/租约;checkpoint 至少包含 rule_id、rule_version、窗口、COMPLETED/FAILED 和计数。
|
||||
private static final String REDIS_KEY_PREFIX = "rule:next_execute:";
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@@ -55,6 +58,9 @@ public class RuleExecutionTimeServiceImpl implements RuleExecutionTimeService {
|
||||
String key = REDIS_KEY_PREFIX + ruleId;
|
||||
String value = nextTime.format(DATE_FORMATTER);
|
||||
|
||||
// [SYSLOG-ALARM][REDISCP] Redis 可以配置 RDB/AOF 持久化,但当前 key 主动设置 5 天 TTL,过期、淘汰、故障恢复或误删后会返回 null。
|
||||
// 调度器随后按“当前时间”重新计算,不能知道历史漏跑窗口;而且 Redis set 与数据库告警写入不在同一事务中。
|
||||
// 建议成功 checkpoint 不设置短 TTL,或持久化到数据库,并在告警提交成功后以 CAS/事务方式原子推进。
|
||||
// 设置过期时间:5天
|
||||
redisTemplate.opsForValue().set(key, value, Duration.ofDays(5));
|
||||
|
||||
@@ -69,6 +75,8 @@ public class RuleExecutionTimeServiceImpl implements RuleExecutionTimeService {
|
||||
String ruleId = rule.getRuleId();
|
||||
String key = REDIS_KEY_PREFIX + ruleId;
|
||||
|
||||
// [SYSLOG-ALARM][DISTLOCK] hasKey + 后续 set 是两个 Redis 命令,不具备原子互斥语义;多实例可同时判断不存在并执行同一窗口。
|
||||
// 若 Redis 用作分布式锁,应使用 SET key value NX PX,并实现 owner、续租和 fencing token;更推荐数据库唯一约束兜底。
|
||||
// 如果已存在,则不覆盖(防止重启后重新计算)
|
||||
if (redisTemplate.hasKey(key)) {
|
||||
log.info("规则执行时间已存在,跳过初始化,ruleId={}", ruleId);
|
||||
|
||||
+5
@@ -22,6 +22,8 @@ import java.util.List;
|
||||
@Service
|
||||
public class SqlGeneratorServiceImpl implements SqlGeneratorService {
|
||||
|
||||
// [SYSLOG-ALARM][ROUTE] 实时规则默认只查询 syslog_normal_alarm;若标准化因 event_level 为空而误写
|
||||
// syslog_normal_data,该事件不会成为实时规则候选。建议数据路由改为显式 event_category,并对两表数量做阶段对账。
|
||||
private static final String DEFAULT_TABLE_NAME = "syslog_normal_alarm";
|
||||
|
||||
@Override
|
||||
@@ -311,6 +313,9 @@ public class SqlGeneratorServiceImpl implements SqlGeneratorService {
|
||||
return "";
|
||||
}
|
||||
|
||||
// [SYSLOG-ALARM][RULESEM] GROUP BY/时间窗口会把多条原始 Syslog 合并为一个告警组,这是业务降噪语义,不应直接认定为丢失。
|
||||
// 建议规则界面明确“单事件/聚合”模式,并在结果保留 log_count、origin_event_ids、group_key 和 window_start/end,
|
||||
// 使客户能解释“32 条输入为什么只有十几组”;HAVING/WHERE 被过滤数量也应单独计数。
|
||||
return "GROUP BY " + String.join(", ", groupByFields);
|
||||
}
|
||||
|
||||
|
||||
+32
-4
@@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import com.common.mapper.SyslogNonNormalMessageMapper;
|
||||
import com.common.service.SyslogNonNormalMessageService;
|
||||
import com.common.service.StatsChangeCaptureService;
|
||||
import com.common.service.DirectStatsProjectionWriter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -30,6 +32,12 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
@Autowired
|
||||
private SyslogNonNormalMessageMapper messageMapper;
|
||||
|
||||
@Autowired
|
||||
private StatsChangeCaptureService statsChangeCaptureService;
|
||||
|
||||
@Autowired
|
||||
private DirectStatsProjectionWriter directStatsProjectionWriter;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean saveMessage(SyslogNonNormalMessage message) {
|
||||
@@ -66,7 +74,12 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
}
|
||||
|
||||
// 执行插入
|
||||
return this.save(message);
|
||||
boolean inserted = this.save(message);
|
||||
if (inserted) {
|
||||
statsChangeCaptureService.captureNonNormalInsert(message);
|
||||
directStatsProjectionWriter.writeNonNormalInsert(message);
|
||||
}
|
||||
return inserted;
|
||||
} catch (Exception e) {
|
||||
log.error("保存非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("保存非标日志失败", e);
|
||||
@@ -113,7 +126,16 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
}
|
||||
|
||||
// 批量插入
|
||||
return messageMapper.batchInsert(messages);
|
||||
int inserted = messageMapper.batchInsert(messages);
|
||||
if (inserted > 0) {
|
||||
if (statsChangeCaptureService.isEnabled()) {
|
||||
for (SyslogNonNormalMessage message : messages) {
|
||||
statsChangeCaptureService.captureNonNormalInsert(message);
|
||||
}
|
||||
}
|
||||
directStatsProjectionWriter.writeNonNormalRows(messages);
|
||||
}
|
||||
return inserted;
|
||||
} catch (Exception e) {
|
||||
log.error("批量保存非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("批量保存非标日志失败", e);
|
||||
@@ -124,6 +146,7 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateMessage(SyslogNonNormalMessage message) {
|
||||
try {
|
||||
SyslogNonNormalMessage oldValue = getMessageById(message.getId());
|
||||
// 设置更新时间
|
||||
message.setUpdateTime(LocalDateTime.now());
|
||||
|
||||
@@ -132,7 +155,12 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
wrapper.eq(SyslogNonNormalMessage::getId, message.getId())
|
||||
.eq(SyslogNonNormalMessage::getDelFlag, "0");
|
||||
|
||||
return this.update(message, wrapper);
|
||||
boolean updated = this.update(message, wrapper);
|
||||
if (updated) {
|
||||
statsChangeCaptureService.captureNonNormalUpdate(oldValue, message);
|
||||
directStatsProjectionWriter.writeNonNormalUpdate(oldValue, message);
|
||||
}
|
||||
return updated;
|
||||
} catch (Exception e) {
|
||||
log.error("更新非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("更新非标日志失败", e);
|
||||
@@ -216,4 +244,4 @@ public class SyslogNonNormalMessageServiceImpl
|
||||
// 使用UUID生成唯一ID
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.common.util;
|
||||
|
||||
import java.time.DateTimeException;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 解析接入端固定的 yyyyMMddHHmmssSSS 接收时间,兼容生产使用的 Java 8。 */
|
||||
public final class IngressReceiveTimeUtil {
|
||||
|
||||
private static final int RECEIVE_TIME_LENGTH = 17;
|
||||
|
||||
private IngressReceiveTimeUtil() {
|
||||
}
|
||||
|
||||
public static LocalDateTime parse(String value) {
|
||||
if (value == null) {
|
||||
throw new IllegalArgumentException("receive_time 不能为空");
|
||||
}
|
||||
String text = value.trim();
|
||||
if (text.length() != RECEIVE_TIME_LENGTH) {
|
||||
throw new IllegalArgumentException("receive_time 必须为17位数字");
|
||||
}
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
if (!Character.isDigit(text.charAt(i))) {
|
||||
throw new IllegalArgumentException("receive_time 包含非数字字符");
|
||||
}
|
||||
}
|
||||
try {
|
||||
return LocalDateTime.of(
|
||||
integer(text, 0, 4),
|
||||
integer(text, 4, 6),
|
||||
integer(text, 6, 8),
|
||||
integer(text, 8, 10),
|
||||
integer(text, 10, 12),
|
||||
integer(text, 12, 14),
|
||||
integer(text, 14, 17) * 1_000_000);
|
||||
} catch (DateTimeException invalidDate) {
|
||||
throw new IllegalArgumentException("receive_time 日期时间无效", invalidDate);
|
||||
}
|
||||
}
|
||||
|
||||
private static int integer(String value, int start, int end) {
|
||||
return Integer.parseInt(value.substring(start, end));
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -144,8 +144,7 @@ public class JsonParser {
|
||||
LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
|
||||
if(!isValidJson(jsonStr))
|
||||
{
|
||||
System.out.println("parseJsonToFlatMap() json str:"+jsonStr);
|
||||
System.out.println("isValidJson(string) is false");
|
||||
logger.warn("parseJsonToFlatMap 收到无效JSON,长度={}", jsonStr == null ? 0 : jsonStr.length());
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -188,8 +187,7 @@ public class JsonParser {
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception ex.message:"+ e.getMessage());
|
||||
|
||||
logger.error("flattenJson 处理异常: path={}, reason={}", currentPath, e.getMessage());
|
||||
throw new RuntimeException("flattenJson 处理异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
+6
-7
@@ -53,9 +53,8 @@ public class NestedJsonParserUtil {
|
||||
try {
|
||||
// 1. 预处理JSON字符串
|
||||
// String processedJson = preprocessJsonString(jsonStr, allowUnquoted, allowSingleQuotes);
|
||||
String processedJson =jsonStr;
|
||||
|
||||
System.out.println("processedJson:"+processedJson);
|
||||
String processedJson = jsonStr;
|
||||
logger.trace("准备解析JSON,长度={}", processedJson.length());
|
||||
// 2. 深度验证嵌套结构
|
||||
//validateNestedStructure(processedJson, maxDepth);
|
||||
//ObjectMapper mapper = new ObjectMapper(); // 这里使用Jackson
|
||||
@@ -73,7 +72,7 @@ public class NestedJsonParserUtil {
|
||||
return postProcessParsedData(result, maxDepth);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
logger.error("JSON解析失败json:{} 错误消息: {}",jsonStr, e.getMessage());
|
||||
logger.warn("JSON解析失败,长度={}, 原因={}", jsonStr.length(), e.getMessage());
|
||||
|
||||
// 5. 尝试修复并重新解析
|
||||
try {
|
||||
@@ -84,13 +83,13 @@ public class NestedJsonParserUtil {
|
||||
return postProcessParsedData(result, maxDepth);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error("JSON修复后解析仍然失败", ex);
|
||||
logger.debug("JSON修复后解析仍然失败: {}", ex.getMessage());
|
||||
}
|
||||
return null;
|
||||
//return Collections.emptyMap();
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("JSON解析发生未知异常", e);
|
||||
logger.warn("JSON解析发生未知异常,长度={}, 原因={}", jsonStr.length(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -507,4 +506,4 @@ public class NestedJsonParserUtil {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+10
-1
@@ -106,4 +106,13 @@ public class SafeCacheUtil {
|
||||
return loader.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 缓存失效失败只记录为 false,不覆盖已经成功提交的数据库事实。 */
|
||||
public boolean evictSafely(String key) {
|
||||
try {
|
||||
return Boolean.TRUE.equals(redisTemplate.delete(key));
|
||||
} catch (Exception ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* 应用配置属性 - 替代静态 AppConfig
|
||||
* 使用 Spring Boot 标准 @Value 机制,支持 docker-compose 环境变量覆盖
|
||||
@@ -50,6 +52,15 @@ public class AppProperties {
|
||||
@Value("${influxdb.retry.delay:100}")
|
||||
private int influxRetryDelay;
|
||||
|
||||
@Value("${influxdb.connection.timeout:30s}")
|
||||
private Duration influxConnectionTimeout;
|
||||
|
||||
@Value("${influxdb.connection.read-timeout:30s}")
|
||||
private Duration influxReadTimeout;
|
||||
|
||||
@Value("${influxdb.connection.write-timeout:60s}")
|
||||
private Duration influxWriteTimeout;
|
||||
|
||||
// ========== 应用配置 ==========
|
||||
@Value("${app.worker.threads:4}")
|
||||
private int workerThreads;
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.config;
|
||||
|
||||
import com.common.service.StatsWriteModeProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.time.DateTimeException;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/** 启动时拒绝会造成双计数、统计缺失或影子表误写正式表的配置。 */
|
||||
@Component
|
||||
public class DirectStatsConfigurationVerifier {
|
||||
private final StatsWriteModeProvider.Mode mode;
|
||||
private final boolean legacyCaptureEnabled;
|
||||
private final boolean readEnabled;
|
||||
private final boolean factOnlyConfirmed;
|
||||
private final boolean todayStatsDateEnabled;
|
||||
private final String directDeviceTable;
|
||||
private final String directRuleTable;
|
||||
private final String shadowDeviceTable;
|
||||
private final String shadowRuleTable;
|
||||
private final String businessZone;
|
||||
|
||||
public DirectStatsConfigurationVerifier(
|
||||
@Value("${stats.write-mode:LEGACY_CHANGE_LOG}") String configuredMode,
|
||||
@Value("${stats.incremental.capture-enabled:false}") boolean legacyCaptureEnabled,
|
||||
@Value("${stats.incremental.read-enabled:false}") boolean readEnabled,
|
||||
@Value("${stats.fact-only.confirm-rebuild-required:false}") boolean factOnlyConfirmed,
|
||||
@Value("${stats.direct.today-stats-date-enabled:true}") boolean todayStatsDateEnabled,
|
||||
@Value("${stats.direct.device-table:device_daily_stats}") String directDeviceTable,
|
||||
@Value("${stats.direct.rule-table:normalize_rule_daily_stats}") String directRuleTable,
|
||||
@Value("${stats.direct.shadow-device-table:device_daily_stats_direct_shadow}") String shadowDeviceTable,
|
||||
@Value("${stats.direct.shadow-rule-table:normalize_rule_daily_stats_direct_shadow}") String shadowRuleTable,
|
||||
@Value("${stats.business-zone:Asia/Shanghai}") String businessZone) {
|
||||
this.mode = parse(configuredMode);
|
||||
this.legacyCaptureEnabled = legacyCaptureEnabled;
|
||||
this.readEnabled = readEnabled;
|
||||
this.factOnlyConfirmed = factOnlyConfirmed;
|
||||
this.todayStatsDateEnabled = todayStatsDateEnabled;
|
||||
this.directDeviceTable = directDeviceTable;
|
||||
this.directRuleTable = directRuleTable;
|
||||
this.shadowDeviceTable = shadowDeviceTable;
|
||||
this.shadowRuleTable = shadowRuleTable;
|
||||
this.businessZone = businessZone;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void validate() {
|
||||
try {
|
||||
ZoneId.of(businessZone);
|
||||
} catch (DateTimeException invalidZone) {
|
||||
throw new IllegalStateException("非法 stats.business-zone: " + businessZone, invalidZone);
|
||||
}
|
||||
if (mode == StatsWriteModeProvider.Mode.LEGACY_CHANGE_LOG && !legacyCaptureEnabled) {
|
||||
throw new IllegalStateException("LEGACY_CHANGE_LOG 模式必须开启 stats.incremental.capture-enabled");
|
||||
}
|
||||
if (mode == StatsWriteModeProvider.Mode.DIRECT_SHADOW) {
|
||||
if (!legacyCaptureEnabled) {
|
||||
throw new IllegalStateException("DIRECT_SHADOW 模式必须保留旧 change log 捕获用于对账");
|
||||
}
|
||||
if (same(directDeviceTable, shadowDeviceTable) || same(directRuleTable, shadowRuleTable)) {
|
||||
throw new IllegalStateException("DIRECT_SHADOW 的影子表不能与正式聚合表相同,否则会双计数");
|
||||
}
|
||||
}
|
||||
if (mode == StatsWriteModeProvider.Mode.DIRECT) {
|
||||
if (legacyCaptureEnabled) {
|
||||
throw new IllegalStateException("DIRECT 模式禁止继续写 syslog_stats_change_log/pending");
|
||||
}
|
||||
if (!readEnabled) {
|
||||
throw new IllegalStateException("DIRECT 正式模式必须开启 stats.incremental.read-enabled");
|
||||
}
|
||||
if (!todayStatsDateEnabled) {
|
||||
throw new IllegalStateException("DIRECT 正式模式必须启用 today_stats_date 日切保护字段");
|
||||
}
|
||||
}
|
||||
if (mode == StatsWriteModeProvider.Mode.FACT_ONLY_REBUILD_REQUIRED) {
|
||||
if (legacyCaptureEnabled) {
|
||||
throw new IllegalStateException("FACT_ONLY_REBUILD_REQUIRED 模式禁止同时写旧变更日志");
|
||||
}
|
||||
if (!factOnlyConfirmed) {
|
||||
throw new IllegalStateException("事实单写降级必须显式确认 stats.fact-only.confirm-rebuild-required=true");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean same(String first, String second) {
|
||||
return first != null && second != null && first.equalsIgnoreCase(second);
|
||||
}
|
||||
|
||||
private static StatsWriteModeProvider.Mode parse(String value) {
|
||||
try {
|
||||
return StatsWriteModeProvider.Mode.valueOf(value.trim().toUpperCase(java.util.Locale.ROOT));
|
||||
} catch (Exception invalid) {
|
||||
throw new IllegalStateException("不支持的 stats.write-mode: " + value, invalid);
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
/** 防止正式接收状态回写在入口元数据投影关闭时静默失效。 */
|
||||
@Component
|
||||
public class IngressStatsConfigurationVerifier {
|
||||
private final boolean ingressEnabled;
|
||||
private final boolean readEnabled;
|
||||
|
||||
public IngressStatsConfigurationVerifier(
|
||||
@Value("${stats.ingress-metadata.enabled:false}") boolean ingressEnabled,
|
||||
@Value("${stats.incremental.read-enabled:false}") boolean readEnabled) {
|
||||
this.ingressEnabled = ingressEnabled;
|
||||
this.readEnabled = readEnabled;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void validate() {
|
||||
if (readEnabled && !ingressEnabled) {
|
||||
throw new IllegalStateException(
|
||||
"入口状态正式回写前必须开启 stats.ingress-metadata.enabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.config;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.env.EnvironmentPostProcessor;
|
||||
import org.springframework.boot.convert.DurationStyle;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* JetCache Lettuce 需要 URI;这里从已有 spring.redis.* 生成,避免维护第二套地址和凭据。
|
||||
*/
|
||||
public class JetCacheRedisEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
|
||||
private static final String URI_PROPERTY = "jetcache.remote.default.uri.0";
|
||||
private static final String TIMEOUT_PROPERTY = "jetcache.remote.default.asyncResultTimeoutInMillis";
|
||||
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
||||
if (environment.containsProperty(URI_PROPERTY)) return;
|
||||
String host = environment.getProperty("spring.redis.host", "localhost");
|
||||
int port = environment.getProperty("spring.redis.port", Integer.class, 6379);
|
||||
int database = environment.getProperty("spring.redis.database", Integer.class, 0);
|
||||
String username = environment.getProperty("spring.redis.username");
|
||||
String password = environment.getProperty("spring.redis.password");
|
||||
boolean ssl = environment.getProperty("spring.redis.ssl", Boolean.class, false);
|
||||
try {
|
||||
String userInfo = null;
|
||||
if (username != null && !username.isEmpty()) {
|
||||
userInfo = username + (password == null ? "" : ":" + password);
|
||||
} else if (password != null && !password.isEmpty()) {
|
||||
userInfo = ":" + password;
|
||||
}
|
||||
URI uri = new URI(ssl ? "rediss" : "redis", userInfo, host, port,
|
||||
"/" + database, null, null);
|
||||
Map<String, Object> derived = new LinkedHashMap<>();
|
||||
derived.put(URI_PROPERTY, uri.toASCIIString());
|
||||
if (!environment.containsProperty(TIMEOUT_PROPERTY)) {
|
||||
String configuredTimeout = environment.getProperty("spring.redis.timeout");
|
||||
Duration timeout = configuredTimeout == null
|
||||
? Duration.ofSeconds(5) : DurationStyle.detectAndParse(configuredTimeout);
|
||||
derived.put(TIMEOUT_PROPERTY, timeout.toMillis());
|
||||
}
|
||||
environment.getPropertySources().addFirst(new MapPropertySource(
|
||||
"jetCacheRedisFromSpringRedis", derived));
|
||||
} catch (Exception invalidRedisConfiguration) {
|
||||
throw new IllegalStateException("无法从 spring.redis.* 构造 JetCache Redis URI", invalidRedisConfiguration);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
// application*.properties 已加载后再派生 URI。
|
||||
return Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.config;
|
||||
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
|
||||
import org.springframework.kafka.core.ConsumerFactory;
|
||||
import org.springframework.kafka.listener.DefaultErrorHandler;
|
||||
import org.springframework.util.backoff.FixedBackOff;
|
||||
|
||||
/** Kafka 消费失败边界:业务未确认的消息绝不能被框架默认恢复器静默跳过。 */
|
||||
@Configuration
|
||||
public class KafkaReliabilityConfig {
|
||||
|
||||
@Bean
|
||||
public DefaultErrorHandler syslogDefaultErrorHandler() {
|
||||
DefaultErrorHandler handler = new DefaultErrorHandler((ConsumerRecord<?, ?> record, Exception failure) -> {
|
||||
throw new IllegalStateException("未到可靠终态的 Syslog 不允许由容器恢复器跳过", failure);
|
||||
}, new FixedBackOff(1000L, FixedBackOff.UNLIMITED_ATTEMPTS));
|
||||
handler.setAckAfterHandle(false);
|
||||
return handler;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConcurrentKafkaListenerContainerFactory<Object, Object> kafkaListenerContainerFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler) {
|
||||
return configuredFactory(configurer, consumerFactory, syslogDefaultErrorHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw 使用独立容器工厂并显式设置并发,避免通用 listener 配置在现场只创建一个 consumer。
|
||||
* Retry/Replay 继续使用默认工厂及其独立并发配置,二者互不影响。
|
||||
*/
|
||||
@Bean("rawKafkaListenerContainerFactory")
|
||||
public ConcurrentKafkaListenerContainerFactory<Object, Object> rawKafkaListenerContainerFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler,
|
||||
@Value("${syslog.raw-listener.concurrency:3}") int concurrency) {
|
||||
if (concurrency < 1) {
|
||||
throw new IllegalArgumentException("syslog.raw-listener.concurrency 必须大于 0");
|
||||
}
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
|
||||
configuredFactory(configurer, consumerFactory, syslogDefaultErrorHandler);
|
||||
factory.setConcurrency(concurrency);
|
||||
return factory;
|
||||
}
|
||||
|
||||
private ConcurrentKafkaListenerContainerFactory<Object, Object> configuredFactory(
|
||||
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
|
||||
ConsumerFactory<Object, Object> consumerFactory,
|
||||
DefaultErrorHandler syslogDefaultErrorHandler) {
|
||||
ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
|
||||
new ConcurrentKafkaListenerContainerFactory<>();
|
||||
configurer.configure(factory, consumerFactory);
|
||||
// [SYSLOG-ALARM][KACK][已修复] 非终态异常无限重试并保持分区位置;框架不得在固定次数后跳过记录。
|
||||
factory.setCommonErrorHandler(syslogDefaultErrorHandler);
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package com.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 灰度控制和本地缓存边界。默认值必须与 application*.properties 保持一致。
|
||||
*/
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "normalization")
|
||||
public class NormalizationOptimizationProperties implements InitializingBean {
|
||||
|
||||
private final Toggle jetcache = new Toggle();
|
||||
private final CompiledRule compiledRule = new CompiledRule();
|
||||
private final Toggle batchEnrichmentCache = new Toggle();
|
||||
private final Toggle messageParseCache = new Toggle();
|
||||
private final RuleSourceCache ruleSourceCache = new RuleSourceCache();
|
||||
private final EnrichmentCache enrichmentCache = new EnrichmentCache();
|
||||
|
||||
public boolean isJetcacheEnabled() {
|
||||
return jetcache.isEnabled();
|
||||
}
|
||||
|
||||
public void setJetcacheEnabled(boolean jetcacheEnabled) {
|
||||
this.jetcache.setEnabled(jetcacheEnabled);
|
||||
}
|
||||
|
||||
/** 对应配置层级 normalization.jetcache.enabled。 */
|
||||
public Toggle getJetcache() {
|
||||
return jetcache;
|
||||
}
|
||||
|
||||
public CompiledRule getCompiledRule() {
|
||||
return compiledRule;
|
||||
}
|
||||
|
||||
public Toggle getBatchEnrichmentCache() {
|
||||
return batchEnrichmentCache;
|
||||
}
|
||||
|
||||
public Toggle getMessageParseCache() {
|
||||
return messageParseCache;
|
||||
}
|
||||
|
||||
public RuleSourceCache getRuleSourceCache() {
|
||||
return ruleSourceCache;
|
||||
}
|
||||
|
||||
public EnrichmentCache getEnrichmentCache() {
|
||||
return enrichmentCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
if (ruleSourceCache.isEnabled() && !jetcache.isEnabled()) {
|
||||
throw new IllegalStateException(
|
||||
"normalization.rule-source-cache.enabled=true 要求 normalization.jetcache.enabled=true");
|
||||
}
|
||||
if (batchEnrichmentCache.isEnabled() && !jetcache.isEnabled()) {
|
||||
throw new IllegalStateException(
|
||||
"normalization.batch-enrichment-cache.enabled=true 要求 normalization.jetcache.enabled=true");
|
||||
}
|
||||
compiledRule.validate();
|
||||
ruleSourceCache.validate();
|
||||
enrichmentCache.validate();
|
||||
}
|
||||
|
||||
public static class Toggle {
|
||||
private boolean enabled;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
public static class CompiledRule {
|
||||
private boolean enabled;
|
||||
private boolean shadowCompareEnabled = true;
|
||||
private double shadowSampleRate = 0.001d;
|
||||
private int localLimit = 10_000;
|
||||
private int expireAfterAccessMinutes = 30;
|
||||
private int failureCacheSeconds = 10;
|
||||
private int shadowTimeoutMs = 1_000;
|
||||
private boolean ruleDetailLogEnabled = true;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public boolean isShadowCompareEnabled() {
|
||||
return shadowCompareEnabled;
|
||||
}
|
||||
|
||||
public void setShadowCompareEnabled(boolean shadowCompareEnabled) {
|
||||
this.shadowCompareEnabled = shadowCompareEnabled;
|
||||
}
|
||||
|
||||
public double getShadowSampleRate() {
|
||||
return shadowSampleRate;
|
||||
}
|
||||
|
||||
public void setShadowSampleRate(double shadowSampleRate) {
|
||||
if (shadowSampleRate < 0.0d || shadowSampleRate > 1.0d) {
|
||||
throw new IllegalArgumentException("shadowSampleRate 必须在 0 到 1 之间");
|
||||
}
|
||||
this.shadowSampleRate = shadowSampleRate;
|
||||
}
|
||||
|
||||
public int getLocalLimit() {
|
||||
return localLimit;
|
||||
}
|
||||
|
||||
public void setLocalLimit(int localLimit) {
|
||||
this.localLimit = positive(localLimit, "localLimit");
|
||||
}
|
||||
|
||||
public int getExpireAfterAccessMinutes() {
|
||||
return expireAfterAccessMinutes;
|
||||
}
|
||||
|
||||
public void setExpireAfterAccessMinutes(int expireAfterAccessMinutes) {
|
||||
this.expireAfterAccessMinutes = positive(expireAfterAccessMinutes, "expireAfterAccessMinutes");
|
||||
}
|
||||
|
||||
public int getFailureCacheSeconds() {
|
||||
return failureCacheSeconds;
|
||||
}
|
||||
|
||||
public void setFailureCacheSeconds(int failureCacheSeconds) {
|
||||
this.failureCacheSeconds = positive(failureCacheSeconds, "failureCacheSeconds");
|
||||
}
|
||||
|
||||
public int getShadowTimeoutMs() {
|
||||
return shadowTimeoutMs;
|
||||
}
|
||||
|
||||
public void setShadowTimeoutMs(int shadowTimeoutMs) {
|
||||
this.shadowTimeoutMs = positive(shadowTimeoutMs, "shadowTimeoutMs");
|
||||
}
|
||||
|
||||
public boolean isRuleDetailLogEnabled() {
|
||||
return ruleDetailLogEnabled;
|
||||
}
|
||||
|
||||
public void setRuleDetailLogEnabled(boolean ruleDetailLogEnabled) {
|
||||
this.ruleDetailLogEnabled = ruleDetailLogEnabled;
|
||||
}
|
||||
|
||||
private void validate() {
|
||||
positive(localLimit, "localLimit");
|
||||
positive(expireAfterAccessMinutes, "expireAfterAccessMinutes");
|
||||
positive(failureCacheSeconds, "failureCacheSeconds");
|
||||
positive(shadowTimeoutMs, "shadowTimeoutMs");
|
||||
if (shadowSampleRate < 0.0d || shadowSampleRate > 1.0d) {
|
||||
throw new IllegalArgumentException("shadowSampleRate 必须在 0 到 1 之间");
|
||||
}
|
||||
}
|
||||
|
||||
private static int positive(int value, String name) {
|
||||
if (value <= 0) {
|
||||
throw new IllegalArgumentException(name + " 必须大于 0");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public static class RuleSourceCache extends Toggle {
|
||||
private int localTtlSeconds = 30;
|
||||
private int remoteTtlSeconds = 300;
|
||||
private int emptyTtlSeconds = 10;
|
||||
|
||||
public int getLocalTtlSeconds() { return localTtlSeconds; }
|
||||
public void setLocalTtlSeconds(int value) { localTtlSeconds = positive(value, "ruleSource.localTtlSeconds"); }
|
||||
public int getRemoteTtlSeconds() { return remoteTtlSeconds; }
|
||||
public void setRemoteTtlSeconds(int value) { remoteTtlSeconds = positive(value, "ruleSource.remoteTtlSeconds"); }
|
||||
public int getEmptyTtlSeconds() { return emptyTtlSeconds; }
|
||||
public void setEmptyTtlSeconds(int value) { emptyTtlSeconds = positive(value, "ruleSource.emptyTtlSeconds"); }
|
||||
private void validate() {
|
||||
positive(localTtlSeconds, "ruleSource.localTtlSeconds");
|
||||
positive(remoteTtlSeconds, "ruleSource.remoteTtlSeconds");
|
||||
positive(emptyTtlSeconds, "ruleSource.emptyTtlSeconds");
|
||||
}
|
||||
}
|
||||
|
||||
public static class EnrichmentCache {
|
||||
private int localTtlSeconds = 60;
|
||||
private int remoteTtlSeconds = 3600;
|
||||
|
||||
public int getLocalTtlSeconds() { return localTtlSeconds; }
|
||||
public void setLocalTtlSeconds(int value) { localTtlSeconds = positive(value, "enrichment.localTtlSeconds"); }
|
||||
public int getRemoteTtlSeconds() { return remoteTtlSeconds; }
|
||||
public void setRemoteTtlSeconds(int value) { remoteTtlSeconds = positive(value, "enrichment.remoteTtlSeconds"); }
|
||||
private void validate() {
|
||||
positive(localTtlSeconds, "enrichment.localTtlSeconds");
|
||||
positive(remoteTtlSeconds, "enrichment.remoteTtlSeconds");
|
||||
}
|
||||
}
|
||||
|
||||
private static int positive(int value, String name) {
|
||||
if (value <= 0) throw new IllegalArgumentException(name + " 必须大于 0");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
|
||||
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
|
||||
import org.springframework.kafka.listener.MessageListenerContainer;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 启动时核对 Raw listener 的实际子容器数,避免只看配置文件误判消费并发。 */
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RawKafkaListenerRuntimeVerifier {
|
||||
|
||||
static final String RAW_LISTENER_ID = "syslog-consumer-rule-raw";
|
||||
|
||||
private final KafkaListenerEndpointRegistry registry;
|
||||
private final int configuredConcurrency;
|
||||
private final boolean rawConsumerEnabled;
|
||||
|
||||
public RawKafkaListenerRuntimeVerifier(
|
||||
KafkaListenerEndpointRegistry registry,
|
||||
@Value("${syslog.raw-listener.concurrency:3}") int configuredConcurrency,
|
||||
@Value("${syslog.raw-consumer.enabled:true}") boolean rawConsumerEnabled) {
|
||||
this.registry = registry;
|
||||
this.configuredConcurrency = configuredConcurrency;
|
||||
this.rawConsumerEnabled = rawConsumerEnabled;
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onApplicationReady() {
|
||||
verifyNow();
|
||||
}
|
||||
|
||||
/** 返回值供回归测试和健康检查复用;不因观察性校验失败而中止已经启动的可靠消费链路。 */
|
||||
boolean verifyNow() {
|
||||
if (!rawConsumerEnabled) {
|
||||
log.info("Raw Kafka listener 已按配置关闭: listenerId={}", RAW_LISTENER_ID);
|
||||
return true;
|
||||
}
|
||||
|
||||
MessageListenerContainer container = registry.getListenerContainer(RAW_LISTENER_ID);
|
||||
if (!(container instanceof ConcurrentMessageListenerContainer)) {
|
||||
log.error("Raw Kafka listener 运行时校验失败: listenerId={}, containerType={}",
|
||||
RAW_LISTENER_ID, container == null ? "missing" : container.getClass().getName());
|
||||
return false;
|
||||
}
|
||||
|
||||
ConcurrentMessageListenerContainer<?, ?> concurrent =
|
||||
(ConcurrentMessageListenerContainer<?, ?>) container;
|
||||
int declaredConcurrency = concurrent.getConcurrency();
|
||||
int actualChildContainers = concurrent.getContainers().size();
|
||||
int assignedPartitions = concurrent.getAssignedPartitions() == null
|
||||
? 0 : concurrent.getAssignedPartitions().size();
|
||||
boolean matched = configuredConcurrency == declaredConcurrency
|
||||
&& configuredConcurrency == actualChildContainers;
|
||||
|
||||
if (matched) {
|
||||
log.info("Raw Kafka listener ready: configuredConcurrency={}, declaredConcurrency={}, "
|
||||
+ "actualChildContainers={}, assignedPartitions={}, assignments={}",
|
||||
configuredConcurrency, declaredConcurrency, actualChildContainers,
|
||||
assignedPartitions, concurrent.getAssignmentsByClientId());
|
||||
} else {
|
||||
log.error("Raw Kafka listener 并发未按配置生效: configuredConcurrency={}, "
|
||||
+ "declaredConcurrency={}, actualChildContainers={}, assignedPartitions={}, assignments={}",
|
||||
configuredConcurrency, declaredConcurrency, actualChildContainers,
|
||||
assignedPartitions, concurrent.getAssignmentsByClientId());
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user