37 Commits

Author SHA1 Message Date
fufeng 1629ad21d6 - Round-1 :① SHA256 hex 查表(写线程热点,5.9x);②SO_RCVBUF<=0 跳过显式设置;附随 JDK8 兼容补丁(生产级风险必修)
- Round-2 :① getBytes+SHA256 前移接入线程;② 专职 force 线程解耦 fsync/checkpoint(先摘批后 force、force 失败显式完成整批、inFlightWrite 兜底);③ 游标 64KB 持久缓冲 + 单次解析
2026-10-01 17:22:36 +08:00
王绍宏 3acd90ecc9 fix(syslog-serve): 扩大微步5万条日志响应容量
- 按50000条、每条最大10KiB将响应上限调整为512MiB
- 将微步适配器最大响应字节数提高至536870912
- 将JSON解析token上限由200万提高至2500万
- 同步放宽管理接口和达梦数据库响应大小约束
- 更新微步任务模板、v6升级脚本和现场部署文档
- 增加50000条及512MiB配置边界测试
- 更新启动版本标识为WEIBU_5S_50000_512M_V20260917_71

验证:
- JDK 8测试通过:167个,失败0,错误0,跳过2
- Maven BUILD SUCCESS
- git diff --check通过
2026-09-17 23:40:07 +08:00
王绍宏 d7fcbdde92 feat(syslog-serve): 优化微步5秒窗口与5万条日志采集
- 将 API 拉取任务的 lookbackSeconds 通用默认值调整为 0
- 微步任务采用5秒时间窗口、50000条单窗口上限和64MiB响应保护
- 将微步适配器及管理接口的 pageSize 上限放宽至50000
- 将 API 调度扫描默认周期调整为1000毫秒
- 兼容新旧调度扫描环境变量名称
- 更新达梦数据库 PAGE_SIZE 约束及 LOOKBACK_SECONDS 默认值
- 补充 v6 数据库预检、升级和验证脚本
- 更新微步任务模板、现场操作说明和启动版本标识
- 增加配置边界及启动参数自动化测试

验证:
- JDK 8 Maven测试通过:167个,失败0,错误0,跳过2
- git diff --check通过
2026-09-17 23:15:15 +08:00
王绍宏 261f1d38e9 feat(syslog-serve): 完善微步全量拉取、探针归属控制及诊断接口
- 按 DEVICE_DEVICE.DEVICE_COLLECT_ID 过滤 API 拉取任务
- 仅允许与 APP_SERVICE_DEVICE_COLLECT_ID 匹配的节点执行任务
- 在任务扫描和数据库租约获取阶段双重校验设备归属
- 设备迁移后原节点不执行 HTTP 请求且不推进 NEXT_RUN_AT
- 保留数据库租约,避免同一探针的多实例重复拉取

- 微步 searchBySql 改为全量逐条日志查询
- 移除 net_data_type=attack/risk 固定过滤
- 支持采集 attack、action、risk 并原样写入 WAL/Kafka
- 保留空 sql、完整字段和时间窗口查询

- 新增微步原始查询诊断接口
- 支持自定义 size、page、pageSize、cur_page 等查询字段
- 复用任务绑定的地址、凭据、TLS 和超时配置
- 诊断查询不写 WAL/Kafka、不推进 checkpoint
- 响应隐藏 API Key、Secret、签名和认证字段

- 更新启动版本标识为 WEIBU_DIAGNOSTIC_V20260917_66
- 更新 v6 部署、验证和 curl 调用文档
- Docker 基础镜像调整为 eclipse-temurin:8-jre
- 补充探针归属、全量查询、诊断透传和状态隔离测试

测试:
- JDK 8
- Tests run: 165
- Failures: 0
- Errors: 0
- Skipped: 2
- git diff --check 通过
2026-09-17 22:25:40 +08:00
王绍宏 2d297eb996 feat(syslog): 为三个生产模块增加启动版本标识
- syslog-serve 增加 SYSLOG_BUILD_READY 启动日志
- syslog-consumer 增加 SYSLOG_BUILD_READY 启动日志
- 更新 syslog-consumer-rule 代码修订标识至 v63
- 输出模块名、代码修订号、运行环境及关键非敏感配置
- 支持通过容器日志快速确认实际部署的 JAR 版本
- 补充 syslog-serve 和 syslog-consumer 启动日志测试
- 不输出数据库密码、API 凭据等敏感信息
- 不修改 Maven POM 配置
2026-09-17 18:47:25 +08:00
王绍宏 8f1a8b6283 feat(syslog): 增加 WAL 与分 IP 接入诊断
- 每分钟保存 WAL 全局状态和分 IP 接收统计,历史保留 7 天
- 记录接收、WAL 落盘、Kafka ACK、过滤、背压及丢弃数量
- 增加 wal_max_pending_bytes 和 wal_admission_unavailable 指标
- 增加 TCP pending 当前值及进程内峰值统计
- 网络异常后同一 IP 恢复接收时打印恢复日志
- 提供当前状态及按日期查询诊断历史的接口
- 连接关闭时清理 TCP pending 计数并停止无效重试
- 增加相关单元测试和现场排查文档
2026-09-16 17:32:08 +08:00
王绍宏 faa9ffe2d9 feat(syslog): 优化WAL配置并在入站阶段丢弃无效设备日志
- 默认在进入WAL前丢弃未注册、重复或未分配到当前探针的Syslog日志
- 使用后台设备内存快照,避免Netty网络线程访问Redis或达梦
- 增加Terminal审计开关,允许恢复原有逐条审计文件模式
- 历史WAL中的无效设备记录直接推进checkpoint
- 增加无效设备丢弃、快照状态及刷新失败监控指标
- 生产WAL队列调整为20000条
- WAL待写预算和分段大小调整为2GiB
- 同步生产配置、Docker Compose及升级文档
- 增加无效设备前置过滤和Terminal开关测试

chore(syslog): 统一生产环境 WAL 挂载目录

- 将生产环境 WAL 默认目录调整为 /app/logs/syslog-wal
- Docker Compose 显式设置 SYSLOG_WAL_DIRECTORY
- WAL 与应用日志共用 /app/logs 宿主机挂载
- 移除旧的 /data/syslog-archive 独立挂载
- 宿主机 WAL 路径统一为 /home/syslog/logs/syslog-wal
2026-09-15 22:10:46 +08:00
王绍宏 5a86a4f950 fix(syslog-consumer): 修复算法批次序号无法递增
- 兼容 yyyyMMdd_NNNN-algorithmId 批次号格式
- 仅解析日期后的批次序号,忽略算法 ID 后缀
- 同一轮任务的所有算法共享同一批次序号
- 保持算法 ID 后缀用于区分算法处理记录
- 补充普通、长算法 ID 及异常格式测试
2026-09-15 13:14:24 +08:00
王绍宏 668a0aca88 fix(syslog-consumer-rule)解决ObjectMapper多实例冲突 2026-09-14 23:38:47 +08:00
王绍宏 1c07acc01d feat(syslog-consumer-rule): 增加多节点原始日志采集并修复天眼/微步JSON规则匹配
一、增加现场原始日志采集功能

1. 新增按设备采集原始日志的API:
   - 指定设备ID;
   - 采集时长最长10分钟;
   - 单次最多返回50条样本。

2. 样本选择策略:
   - 优先保留时间窗口内最早到达的N条日志;
   - 后续出现JSON解析异常、非标、规则执行异常、InfluxDB/达梦写入异常或Retry/DLT时,
     使用异常日志逐条替换最早的正常样本;
   - 异常样本同样遵循先到先得。

3. 支持三个syslog-consumer-rule实例联合采集:
   - 采集请求只需发送到任意一个实例;
   - 三个实例通过公共Redis同步采集任务并汇总候选样本;
   - 不需要配置其他实例IP;
   - Redis只保存有界候选集,不保存时间窗口内的全部日志。

4. 生命周期和资源控制:
   - 采集到期后自动停止接收新日志;
   - 默认进入30秒DRAINING阶段,等待异步处理异常完成样本替换;
   - 最终结果默认保留30分钟,之后自动删除;
   - 单实例、单会话最多保留“前N条+前N条异常”;
   - Redis故障不阻断Kafka主消费链路。

5. 返回规则解析和非标表截断之前的完整原始报文,不受
   HB_XDR_TRUNCATED字段截断影响。

6. 原始日志采集和多实例汇聚默认启用:
   SYSLOG_RAW_CAPTURE_ENABLED=true
   SYSLOG_RAW_CAPTURE_CLUSTER_ENABLED=true

二、修复天眼/微步JSON规则匹配问题

1. JSON规则配置了cropper时,先判断原始报文是否包含对应head_key;
   不匹配的规则不再将当前报文误判为非法JSON。

2. 同一设备绑定多条规则时,单条不适用或解析失败的JSON规则不再立即终止整个规则链,
   程序会继续匹配后续适用规则。

3. 只有全部适用JSON规则均解析失败、且没有其他规则成功处理时,才写入
   “JSON解析异常”非标记录。

4. 对cropper截取后仍包含Syslog或设备前缀的内容,在JSON专用路径中重新收敛到
   第一个“{”至最后一个“}”,确保交给Jackson的是完整外层JSON。

5. 修复以下现场场景:
   - 天眼规则129截取结果仍带有alarm前缀;
   - 微步设备同时绑定固定偏移规则和Threatbook/TDP JSON规则;
   - 不适用的固定偏移规则抢先产生JSON解析异常;
   - Syslog头加JSON正文不能继续匹配后续适用规则。

三、增加现场采集工具及运维说明

新增upgrade-doc/v5:
   - README.md:升级、配置、生命周期和故障排查说明;
   - capture-device-raw-logs.sh:一键创建采集会话、等待完成并自动落盘。

脚本输出:
   - result.json:完整采集结果;
   - samples.jsonl:每行一条样本及处理状态;
   - raw/*.log:每条未截断原始报文;
   - summary.txt:采集数量、异常数量和替换数量;
   - latest.json:中断或超时时的最后有效快照。

四、兼容性与升级范围

- 兼容JDK 8;
- 无需新增或修改达梦数据库表;
- 无需创建新的Kafka Topic;
- 需要滚动升级全部syslog-consumer-rule实例;
- 三个实例必须连接相同的Redis;
- 本次提交不包含syslog-serve的高内存、WAL或JVM参数调整。
2026-09-14 23:11:45 +08:00
王绍宏 7e6b2fc4dc feat(syslog): 提升RAW消费及达梦批量写入上限
- 将普通RAW基础处理批量调整为3000条
- 将RAW自适应拉取上限调整为5000条
- 将普通、告警及非标达梦批量写入上限调整为2000条
- 启动日志增加达梦实际批量配置输出
- 补充自适应分块和达梦批量写入测试
- 更新v4吞吐优化升级说明
2026-09-13 11:19:35 +08:00
王绍宏 e393350c8b feat(syslog): 增加普通通道字段截断并完善慢写诊断
- 新增普通通道字段上限配置,默认2048个UTF-8字节,截断尾部保留标记
- 规则计算后执行截断,告警不应用新增2KB限制,原有256KB策略不变
- 非标原文、头部及详细原因应用新增限制,大日志通道和InfluxDB策略不变
- Retry/Replay按原始Topic识别通道,启动日志输出生效上限
- 补充达梦实际写入内容大小、最大行及最大字段诊断
- 慢日志默认阈值统一调整为1000毫秒,异常和失败仍记录
- 更新v4配置说明及回归测试

验证:JDK 8构建成功,250项测试通过
升级:替换JAR并重启,无需数据库或Kafka脚本
2026-09-13 08:00:08 +08:00
王绍宏 8173c2ff3f perf(syslog): 统计异步化并按采样保留率自适应调整业务批量
- 入口统计改用独立 Kafka 消费组,移除主消费同步统计写库
- DIRECT 模式入库计数改为事务提交后异步投递,取消事实事务内统计 Outbox 写入
- 采样审计、告警分钟桶通知改为后台处理,异常不阻断主消费或回滚告警
- RAW 基础业务批量默认 500,按保留率动态扩大,上限 3000
- 限制业务块字节数及规则任务数量,保留告警全量处理和整次 poll 完成后提交
- 细化 SLOW_SYSLOG_BATCH,补充批次关联、线程排队、数据库执行及提交耗时
- 更新 v4 升级说明,明确异步统计损失风险及现场验证方法

验证:JDK 8 构建成功,232 项测试通过。
升级:复用现有表和 Kafka Topic,无新增建表或建 Topic 脚本要求。
2026-09-13 06:11:12 +08:00
王绍宏 44d327139b feat(syslog-consumer-rule): 补充慢批次消息长度统计
- 记录Kafka批次消费消息条数
- 记录批次日志正文总字节数
- 记录批次内单条日志最大字节数
- 优先使用Kafka序列化长度,避免重复编码带来的额外开销
2026-09-13 04:04:47 +08:00
王绍宏 c392f7b47f feat(syslog-consumer-rule): 增加慢批次全链路耗时诊断
- 批次端到端耗时达到500ms时输出SLOW_SYSLOG_BATCH日志
- 记录入口统计、规则计算、InfluxDB和达梦写入的分阶段耗时
- 使用MANUAL_IMMEDIATE模式准确统计Kafka offset同步提交耗时
- 记录Kafka提交状态、异常类型和端到端总耗时
- 在常规批次日志中补充ingressMs
- 增加Kafka监听器ACK模式回归测试
2026-09-13 04:01:01 +08:00
王绍宏 d3bc083b88 perf(syslog-consumer-rule): 消除达梦批写动态SQL性能瓶颈
- 使用原生JDBC PreparedStatement执行标准化事实批写
- 按批次字段并集只生成一次INSERT语句
- 移除批写主路径逐行执行MyBatis OGNL动态SQL的开销
- 从达梦表元数据缓存合法列名和NULL字段类型
- 保留告警优先、事务一致性及失败隔离逻辑
- 默认关闭统计变更捕获时跳过无效MyBatis BatchSession
- 增加SQL规划、参数绑定和批量执行耗时指标
- 补充JDBC批写、字段白名单及参数绑定测试
2026-09-13 03:05:42 +08:00
王绍宏 87fee6fe69 feat(syslog): 增加积压采样免采样窗口
- 新增 start-lag-ms 配置,默认15分钟内全量保留
- 在15分钟至1小时之间按10级逐步降低保留率
- 延迟达到1小时后使用普通10%、非标20%的最低保留率
- 校验起始延迟必须小于最低保留率阈值
- 状态接口新增 start_lag_ms 配置展示
- 将采样策略版本升级为 v2
- 更新 Docker Compose 和 v4 升级配置说明
- 补充采样时间边界及非法配置单元测试
2026-09-12 23:43:56 +08:00
王绍宏 c868e3befd feat(syslog): 优化大日志通道并增加异常连续消费兜底
- 128 KiB 及以上日志默认进入大日志 Topic
- InfluxDB 原文及达梦大字段超过 256 KiB 时截断保存
- 截断内容追加 HB_XDR_TRUNCATED 标记
- InfluxDB 写入失败时继续执行规则解析和达梦写入
- 未知或系统性异常优先写入普通/大日志 DLT
- DLT 写入失败时记录特殊告警并提交 offset,避免阻塞后续消息
- DLT 失败等待时间默认限制为 1 秒
- 增加连续性放行、DLT 成功及失败监控指标
- 更新 Docker Compose、v3 升级文档及相关测试
2026-09-12 19:24:58 +08:00
王绍宏 0e9e6656db feat(syslog): 优化大日志通道并增加异常连续消费兜底
- 128 KiB 及以上日志默认进入大日志 Topic
- InfluxDB 原文及达梦大字段超过 256 KiB 时截断保存
- 截断内容追加 HB_XDR_TRUNCATED 标记
- InfluxDB 写入失败时继续执行规则解析和达梦写入
- 未知或系统性异常优先写入普通/大日志 DLT
- DLT 写入失败时记录特殊告警并提交 offset,避免阻塞后续消息
- DLT 失败等待时间默认限制为 1 秒
- 增加连续性放行、DLT 成功及失败监控指标
- 更新 Docker Compose、v3 升级文档及相关测试
2026-09-12 19:22:52 +08:00
王绍宏 3b6c9e4714 fix(syslog-consumer-rule): 修复现场日志解析并补充升级工具
- 支持设备头字段值包含空格,避免 WAF 等名称被误拆为无效键值对
- 将空字符串 cropper offset 按未配置处理,兼容历史标准化规则
- 增加设备头解析和空 offset 回归测试
- 增加统计物化 Topic 创建脚本
- 增加容器内 JAR 热替换脚本及操作说明
2026-09-12 11:40:57 +08:00
王绍宏 c1472b9a95 fix(syslog-consumer-rule): 解耦统计物化并解决多实例达梦死锁
- 将设备、规则和采集任务业务统计改为专用 Kafka Topic 异步物化
- 使用维度 ID 作为 Kafka key,保证同一统计维度串行更新
- 物化过程读取小型统计表精确值,确保重复消费不会重复计数
- 增加提交后发布、失败重试及定时小表对账补偿
- 固定日统计聚合键写入顺序,完善达梦死锁识别和事务重试
- JSON 解析失败直接转为非标日志,避免进入 DLT 重试链路
- 非标日志使用独立异步队列,不再阻塞正常消息 Kafka ACK
- Kafka 升级脚本新增 STATS.MATERIALIZE Topic
- 增加统计物化状态指标、配置示例及单元测试
2026-09-11 20:42:22 +08:00
王绍宏 2def445537 fix(haobang-security-rule)修改json错误处理方式 2026-09-11 18:24:32 +08:00
王绍宏 77580ea0bf fix: 禁用连接本地达梦数据库的单元测试 2026-09-11 16:35:33 +08:00
王绍宏 ce473b2c7d perf(syslog-consumer-rule): 非标日志改为单线程异步批量写入
- 非标写库结果不再参与 Kafka ACK
- 使用独立单线程和有界队列处理非标日志
- 非标数据按固定大小分批写入达梦
- 增加异步成功、失败和队列拒绝指标
- 补充异步解耦及批量写入测试

perf(syslog-consumer-rule): 按批次字段并集优化达梦批量写入

- 普通日志和告警日志按非空字段并集生成批写模板
- 为同批记录补齐缺失字段并绑定 NULL
- 使用 MyBatis ExecutorType.BATCH 复用 PreparedStatement
- 避免固定写入全部 373 个候选字段
- 非标日志保留固定 24 列多行批量写入
- 批量大小和非标队列容量默认调整为 500
- 补充字段并集与动态 SQL 一致性测试
2026-09-11 15:44:48 +08:00
liujl 61863c469b 改成8m 2026-09-11 03:30:34 +08:00
王绍宏 6b4cfac79d [fix] kafka消息最大调整为4M 2026-09-11 03:13:41 +08:00
王绍宏 0837dd116a feat(api-pull): 完善全悉设备接入并修复 NDR 边界重复采集
- 增加全悉设备 API 日志拉取及消费处理
- 完善全悉日志解析、字段映射和标准化逻辑
- NDR 采集窗口统一采用左闭右开规则
- 对设备秒级查询范围向外取整,并在本地精确过滤
- 区分接口原始返回数和实际接收数,保证分页偏移正确推进
- 补充时间窗口、边界过滤和分页推进测试
- 更新设备 API 拉取及对接说明文档
2026-09-07 18:11:17 +08:00
yangyun 957f7193a3 fix: 移除消费者Hikari环境覆盖 2026-09-07 01:55:19 +08:00
yangyun 533e2f3c45 fix: 避免Hikari schema重复绑定 2026-09-07 01:51:54 +08:00
yangyun 8924a71090 fix: 避免Hikari配置在启动后重复绑定 2026-09-07 01:51:03 +08:00
yangyun e293a0a98c fix: 避免默认Hikari配置重复绑定 2026-09-07 01:48:36 +08:00
yangyun ba2991cd7a fix: 避免Hikari连接池启动后重复绑定 2026-09-07 01:44:18 +08:00
yangyun d565ac7beb fix: 绕过DM分区表rule_version列异常 2026-09-07 01:23:33 +08:00
王绍宏 00c0a1fb7f feat: 新增设备 API 拉取采集及配套处理能力
- 接入 NDRServer 告警和流量日志,支持凭据与任务管理
- 支持分页拉取、窗口拆分、调度优先级及 WAL 持久化后推进断点
- 增加迟到告警规则重放,优化多条泛化规则选择和事件时间处理
- 补充回归测试、数据库升级脚本及部署文档
2026-09-06 16:46:21 +08:00
王绍宏 b61ec2e37c - 修复 Kafka Listener 并发配置包含尾部空格时触发 NumberFormatException 的问题
- 移除 SysLogProcessor 注解中对并发配置的直接字符串解析
- 改由 Kafka 容器工厂统一处理并发度配置
- 统一两个 consumer 模块各环境的并发配置格式
- 清理 application.properties 中可能影响类型转换的行尾空格
- 更新 Kafka 监听器拓扑回归测试,防止问题再次引入
2026-09-02 13:54:13 +08:00
王绍宏 f53661931f feat(upgrade): 增加 升级脚本和部署说明
- 新增达梦数据库结构、幂等索引、统计基线及校验脚本
- 新增 Docker Kafka Retry、DLT、Replay Topic 升级脚本
- 更新生产 Compose,启用 DIRECT 并关闭旧增量捕获和投影
- 补充数据库、Kafka、应用启动及验证说明
- 增加日志和本地生成文件忽略规则
2026-08-24 15:09:36 +08:00
王绍宏 29445c6825 feat(syslog): 完成高吞吐可靠链路与统计存储优化
- 新增接入 WAL、检查点、背压恢复及可靠分发机制,完善 Kafka 幂等发布、分区、重试、DLT 和补偿流程
- 引入规则预编译、批内快照及 JetCache/Caffeine 两级缓存,支持缓存失效广播、影子对账和执行指标
- 升级 InfluxDB V2 原始日志模型,统一接收时间与 Point 时间,支持按日 measurement、UUID 分桶及 V1/V2 双读
- 重构达梦标准化批量写入与统计链路,支持事务内直写、增量投影、幂等控制、窗口水位和日期切换
- 完善告警处理、配置校验、运行监控及测试覆盖
2026-08-20 00:18:33 +08:00
538 changed files with 54959 additions and 6200 deletions
+1
View File
@@ -0,0 +1 @@
upgrade-doc/v3/kafka/*.sh text eol=lf
-1
View File
@@ -1 +0,0 @@
security-xdr
-17
View File
@@ -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>
-13
View File
@@ -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>
-14
View File
@@ -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>
-6
View File
@@ -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>
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
java=8.0.392-zulu
+2
View File
@@ -38,6 +38,8 @@
</profiles>
<properties>
<java.version>1.8</java.version>
<!-- Spring Boot 2.7 默认 Lombok 无法在当前 JDK 21 构建;该版本仍生成 Java 8 字节码。 -->
<lombok.version>1.18.36</lombok.version>
</properties>
<packaging>pom</packaging>
<modules>
File diff suppressed because it is too large Load Diff
@@ -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-09-11 16:29:58.327 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.haobang.syslog.SysjavacollectApplicationTests], using SpringBootContextLoader
2026-09-11 16:29:58.338 [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-09-11 16:29:58.340 [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-09-11 16:29:58.524 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.haobang.syslog.syslogClientApplication for test class com.haobang.syslog.SysjavacollectApplicationTests
2026-09-11 16:29:58.774 [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-09-11 16:29:58.789 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3214ee6, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@383dc82c, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@4a07d605, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@74287ea3, org.springframework.test.context.support.DirtiesContextTestExecutionListener@7d7758be, org.springframework.test.context.event.EventPublishingTestExecutionListener@2bdd8394, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@5f9edf14, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@68746f22, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@2f01783a, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@68878f6d, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@41488b16, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@a8ef162]
2026-09-11 16:29:59.280 [main] INFO c.h.s.SysjavacollectApplicationTests - Starting SysjavacollectApplicationTests using Java 1.8.0_351 on wangshaohongdeMacBook-Pro.local with PID 63617 (started by wangshaohong in /Users/wangshaohong/WorkSpace/fufeng/ai-security-xdr/haobang-security-dm/syslog-client)
2026-09-11 16:29:59.286 [main] INFO c.h.s.SysjavacollectApplicationTests - No active profile set, falling back to 1 default profile: "default"
2026-09-11 16:30:00.361 [main] INFO c.h.s.SysjavacollectApplicationTests - Started SysjavacollectApplicationTests in 1.499 seconds (JVM running for 3.309)
@@ -20,6 +20,12 @@ services:
# 环境配置
- SPRING_PROFILES_ACTIVE=prod
- TZ=Asia/Shanghai
# 生产环境只使用 DIRECT:事实与统计同事务写入,不再写旧 change-log/pending。
- STATS_WRITE_MODE=DIRECT
- STATS_INCREMENTAL_CAPTURE_ENABLED=false
- 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 +49,46 @@ 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
- KAFKA_CONSUMER_LARGE_TOPIC=agent-01-syslog-topic.large
# consumer-rule 是活跃原始日志消费节点,多实例通过同一消费组分担分区。
- SYSLOG_RAW_CONSUMER_ENABLED=true
# 特殊异常优先写入 DLT;DLT 失败也记录后放行,避免单条/单批异常永久阻塞分区。
- SYSLOG_FAILURE_CONTINUITY_ENABLED=true
- SYSLOG_FAILURE_CONTINUITY_DLT_PUBLISH_TIMEOUT_MS=1000
# 积压采样默认开启;升级应用前先执行 upgrade-doc/v4/database 脚本。
- SYSLOG_BACKLOG_SAMPLING_ENABLED=true
- SYSLOG_BACKLOG_SAMPLING_START_LAG_MS=900000
- SYSLOG_BACKLOG_SAMPLING_LAG_THRESHOLD_MS=3600000
- SYSLOG_BACKLOG_SAMPLING_NORMAL_RETAIN_BPS=1000
- SYSLOG_BACKLOG_SAMPLING_NON_NORMAL_RETAIN_BPS=2000
- SYSLOG_BACKLOG_SAMPLING_DEGRADE_STEPS=10
- SYSLOG_BACKLOG_SAMPLING_POLICY_VERSION=v2
- SYSLOG_BACKLOG_SAMPLING_AUDIT_TIMEOUT_SECONDS=5
- SYSLOG_BACKLOG_SAMPLING_AUDIT_RETRY_BACKOFF_MS=60000
# 大日志的 poll、fetch、批次和规则计算线程池均独立且有界。
- SYSLOG_LARGE_LISTENER_ENABLED=true
- SYSLOG_LARGE_LISTENER_CONCURRENCY=1
- SYSLOG_LARGE_LISTENER_MAX_POLL_RECORDS=5
- SYSLOG_LARGE_LISTENER_MAX_PARTITION_FETCH_BYTES=33554432
- SYSLOG_LARGE_LISTENER_FETCH_MAX_BYTES=67108864
- SYSLOG_LARGE_PROCESSING_BATCH_MAX_BYTES=8388608
- SYSLOG_LARGE_PROCESSOR_CORE_POOL_SIZE=1
- SYSLOG_LARGE_PROCESSOR_MAX_POOL_SIZE=2
- SYSLOG_LARGE_PROCESSOR_QUEUE_CAPACITY=10
- KAFKA_RELIABILITY_MAX_REQUEST_SIZE=33554432
# 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 +96,21 @@ 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_RAW_MESSAGE_MAX_UTF8_BYTES=262144
- INFLUXDB_RAW_WRITE_BATCH_MAX_BYTES=8388608
# InfluxDB 原文写是非关键旁路:请求超时后熔断退避,主消费继续。
- INFLUXDB_RAW_WRITE_REQUEST_TIMEOUT=5s
- INFLUXDB_RAW_FAILURE_BACKOFF_MS=30000
- DM_NORMAL_LARGE_FIELD_MAX_UTF8_BYTES=262144
- DM_NON_NORMAL_LARGE_FIELD_MAX_UTF8_BYTES=262144
- INFLUXDB_BATCH_SIZE=1000
- INFLUXDB_FLUSH_INTERVAL=1000
- INFLUXDB_CONNECTION_TIMEOUT=30s
@@ -79,4 +133,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>
<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>
@@ -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);
}
}
@@ -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(); }
}
}
@@ -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());
}
}
@@ -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);
}
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -0,0 +1,35 @@
package com.Modules.NormalData;
/** 普通/非标采用较高保留率,倍率由当前策略自动计算;不改变实际采样或告警保留规则。 */
@org.springframework.stereotype.Component
public final class AdaptiveRawBatchSizer {
private final int baseRecords;
private final int maxRecords;
public AdaptiveRawBatchSizer(
@org.springframework.beans.factory.annotation.Value("${syslog.raw-listener.max-poll-records:3000}") int baseRecords,
@org.springframework.beans.factory.annotation.Value("${syslog.raw-listener.adaptive-max-records:5000}") int maxRecords) {
if (baseRecords < 1 || maxRecords < baseRecords) {
throw new IllegalArgumentException("普通自适应批量要求 1 <= 基础条数 <= 上限条数");
}
this.baseRecords = baseRecords;
this.maxRecords = maxRecords;
}
public int targetRecords(int normalRetainBps, int nonNormalRetainBps) {
validateRate(normalRetainBps);
validateRate(nonNormalRetainBps);
int retainBps = Math.max(normalRetainBps, nonNormalRetainBps);
if (retainBps == 0) return maxRecords;
long numerator = (long) baseRecords * 10000L;
long calculated = (numerator + retainBps - 1L) / retainBps;
return (int) Math.min(maxRecords, calculated);
}
public int getBaseRecords() { return baseRecords; }
public int getMaxRecords() { return maxRecords; }
private static void validateRate(int rate) {
if (rate < 0 || rate > 10000) throw new IllegalArgumentException("保留万分比必须在0~10000之间");
}
}
@@ -0,0 +1,99 @@
package com.Modules.NormalData;
import com.config.BacklogSamplingProperties;
import org.springframework.stereotype.Component;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
/** 按延迟阶梯计算当前保留率,再以 event_id 做确定性哈希采样。 */
@Component
public class BacklogSamplingDecider {
private static final ZoneId RECEIVE_TIME_ZONE = ZoneId.of("Asia/Shanghai");
private final BacklogSamplingProperties properties;
public BacklogSamplingDecider(BacklogSamplingProperties properties) {
this.properties = properties;
}
public BacklogSamplingDecision decide(String eventId, LocalDateTime receivedAt,
boolean hasAlarm, boolean hasNormal,
boolean hasNonNormal) {
return decide(eventId, receivedAt, hasAlarm, hasNormal, hasNonNormal, Instant.now());
}
BacklogSamplingDecision decide(String eventId, LocalDateTime receivedAt,
boolean hasAlarm, boolean hasNormal,
boolean hasNonNormal, Instant now) {
LocalDateTime effectiveReceivedAt = receivedAt == null
? LocalDateTime.ofInstant(now, RECEIVE_TIME_ZONE) : receivedAt;
long receivedEpochMs = effectiveReceivedAt.atZone(RECEIVE_TIME_ZONE).toInstant().toEpochMilli();
long lagMs = Math.max(0L, now.toEpochMilli() - receivedEpochMs);
LocalDateTime sourceHour = effectiveReceivedAt.truncatedTo(ChronoUnit.HOURS);
int steps = Math.max(1, properties.getDegradeSteps());
int currentStep = currentStep(
lagMs, properties.getStartLagMs(), properties.getLagThresholdMs(), steps);
int normalRetainBps = effectiveRetainBps(
properties.getNormalRetainBps(), currentStep, steps);
int nonNormalRetainBps = effectiveRetainBps(
properties.getNonNormalRetainBps(), currentStep, steps);
boolean degraded = properties.isEnabled() && currentStep > 0
&& (normalRetainBps < BacklogSamplingProperties.BASIS_POINTS
|| nonNormalRetainBps < BacklogSamplingProperties.BASIS_POINTS);
if (!degraded) {
return new BacklogSamplingDecision(false, true, true, true, lagMs, sourceHour,
properties.getPolicyVersion(), BacklogSamplingProperties.BASIS_POINTS,
BacklogSamplingProperties.BASIS_POINTS);
}
// 没有产出行的 FILTERED 消息仍视为普通消息,使其 InfluxDB 原文遵守普通保留率。
boolean normalCandidate = hasNormal || (!hasAlarm && !hasNonNormal);
boolean keepNormal = !normalCandidate || sampled(eventId, "NORMAL",
normalRetainBps, properties.getPolicyVersion());
boolean keepNonNormal = !hasNonNormal || sampled(eventId, "NON_NORMAL",
nonNormalRetainBps, properties.getPolicyVersion());
boolean keepRaw = hasAlarm
|| (normalCandidate && keepNormal)
|| (hasNonNormal && keepNonNormal);
return new BacklogSamplingDecision(true, keepNormal, keepNonNormal, keepRaw, lagMs,
sourceHour, properties.getPolicyVersion(), normalRetainBps,
nonNormalRetainBps);
}
static int currentStep(long lagMs, long startLagMs, long thresholdMs, int steps) {
if (lagMs <= startLagMs) return 0;
if (lagMs >= thresholdMs) return steps;
long degradableLagMs = lagMs - startLagMs;
long degradableWindowMs = thresholdMs - startLagMs;
return Math.min(steps, (int) Math.floor(
((double) degradableLagMs / (double) degradableWindowMs) * steps));
}
static int effectiveRetainBps(int minimumRetainBps, int currentStep, int steps) {
if (currentStep <= 0) return BacklogSamplingProperties.BASIS_POINTS;
if (currentStep >= steps) return minimumRetainBps;
long totalDrop = BacklogSamplingProperties.BASIS_POINTS - minimumRetainBps;
long appliedDrop = totalDrop * currentStep / steps;
return (int) (BacklogSamplingProperties.BASIS_POINTS - appliedDrop);
}
static boolean sampled(String eventId, String category, int retainBps, String policyVersion) {
if (retainBps <= 0) return false;
if (retainBps >= BacklogSamplingProperties.BASIS_POINTS) return true;
String input = String.valueOf(policyVersion) + '\u0000' + category + '\u0000' + String.valueOf(eventId);
try {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(input.getBytes(StandardCharsets.UTF_8));
int value = ByteBuffer.wrap(digest, 0, 4).getInt() & Integer.MAX_VALUE;
return value % BacklogSamplingProperties.BASIS_POINTS < retainBps;
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("JVM 缺少 SHA-256", impossible);
}
}
}
@@ -0,0 +1,40 @@
package com.Modules.NormalData;
import java.time.LocalDateTime;
/** 一条原始 Kafka 消息完成规则计算后的稳定保留决策。 */
public final class BacklogSamplingDecision {
private final boolean degraded;
private final boolean keepNormal;
private final boolean keepNonNormal;
private final boolean keepRaw;
private final long lagMs;
private final LocalDateTime sourceHour;
private final String policyVersion;
private final int normalRetainBps;
private final int nonNormalRetainBps;
BacklogSamplingDecision(boolean degraded, boolean keepNormal, boolean keepNonNormal,
boolean keepRaw, long lagMs, LocalDateTime sourceHour,
String policyVersion, int normalRetainBps, int nonNormalRetainBps) {
this.degraded = degraded;
this.keepNormal = keepNormal;
this.keepNonNormal = keepNonNormal;
this.keepRaw = keepRaw;
this.lagMs = lagMs;
this.sourceHour = sourceHour;
this.policyVersion = policyVersion;
this.normalRetainBps = normalRetainBps;
this.nonNormalRetainBps = nonNormalRetainBps;
}
public boolean isDegraded() { return degraded; }
public boolean isKeepNormal() { return keepNormal; }
public boolean isKeepNonNormal() { return keepNonNormal; }
public boolean isKeepRaw() { return keepRaw; }
public long getLagMs() { return lagMs; }
public LocalDateTime getSourceHour() { return sourceHour; }
public String getPolicyVersion() { return policyVersion; }
public int getNormalRetainBps() { return normalRetainBps; }
public int getNonNormalRetainBps() { return nonNormalRetainBps; }
}
@@ -0,0 +1,418 @@
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>常规 Retry/DLT 的 send Future 只有取得 Broker ACK 后才返回终态;发布失败或结果未知会抛给
* 调用方。活动 listener 外层另有连续性优先边界,可按现场策略记录后放行。</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("${spring.kafka.consumer.large-topic:${spring.kafka.consumer.topic}.large}")
private String largeOriginalTopic;
@Value("${syslog.large-reliability.retry-1m-topic:${spring.kafka.consumer.large-topic}.RETRY.1M}")
private String largeRetry1mTopic;
@Value("${syslog.large-reliability.retry-10m-topic:${spring.kafka.consumer.large-topic}.RETRY.10M}")
private String largeRetry10mTopic;
@Value("${syslog.large-reliability.retry-1h-topic:${spring.kafka.consumer.large-topic}.RETRY.1H}")
private String largeRetry1hTopic;
@Value("${syslog.large-reliability.dlt-topic:${spring.kafka.consumer.large-topic}.DLT}")
private String largeDltTopic;
@Value("${syslog.reliability.publish-timeout-ms:30000}")
private long publishTimeoutMs;
@Value("${syslog.failure-continuity.dlt-publish-timeout-ms:1000}")
private long continuityDltPublishTimeoutMs;
@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) {
// 常规路由把系统性故障上抛;活动 listener 的连续性边界再决定是否转 DLT 并放行。
return TerminalState.PAUSED;
}
int nextAttempt = Math.max(0, context.getAttemptCount()) + 1;
boolean permanent = category == FailureCategory.PERMANENT_DATA;
boolean exhausted = nextAttempt > 3;
boolean largeLane = largeOriginalTopic != null
&& largeOriginalTopic.equals(context.getOriginalTopic());
String targetTopic = (permanent || exhausted)
? (largeLane ? largeDltTopic : dltTopic)
: retryTopic(nextAttempt, largeLane);
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;
}
/**
* 连续性优先兜底:把无法安全完成当前处理阶段的原消息直接写入 DLT。
* 本方法仍显式报告发布失败;是否继续提交原 offset 由调用方的连续性策略决定。
*/
public TerminalState routeContinuityDlt(ConsumerRecord<String, String> record,
MessageContext context,
Throwable failure,
String failedStage) {
int nextAttempt = Math.max(0, context.getAttemptCount()) + 1;
boolean largeLane = largeOriginalTopic != null
&& largeOriginalTopic.equals(context.getOriginalTopic());
String targetTopic = largeLane ? largeDltTopic : dltTopic;
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());
envelope.setFirstReceivedAt(context.getFirstReceivedAt());
envelope.setFailedStage(failedStage == null ? "UNKNOWN" : failedStage);
envelope.setErrorCode("SYSLOG_CONTINUITY_BYPASS");
Throwable root = rootCause(failure);
envelope.setErrorType(root.getClass().getName());
envelope.setErrorMessage(sanitize(root.getMessage()));
envelope.setAttemptCount(nextAttempt);
envelope.setNextRetryAt(null);
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,
Math.max(1L, continuityDltPublishTimeoutMs));
log.debug("[SYSLOG_CONTINUITY] 特殊异常已可靠写入 DLT: eventId={}, "
+ "stage={}, target={}, errorType={}",
context.getEventId(), envelope.getFailedStage(), targetTopic, envelope.getErrorType());
return TerminalState.DLT_PUBLISHED;
}
private void publishAndAwait(String topic, String key, FailureEnvelope envelope) {
publishAndAwait(topic, key, envelope, publishTimeoutMs);
}
private void publishAndAwait(String topic, String key, FailureEnvelope envelope, long timeoutMs) {
try {
String body = objectMapper.writeValueAsString(envelope);
// [流程节点4.3] 必须等待 Broker ACK;仅调用 send() 不构成 RETRY_PUBLISHED/DLT_PUBLISHED。
kafkaTemplate.send(topic, key, body).get(timeoutMs, 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 属于系统性依赖故障。
// 活动原文批写链路会在外层非阻塞旁路边界覆盖其 offset 行为,不能因此阻塞主消费。
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, boolean largeLane) {
if (attempt == 1) return largeLane ? largeRetry1mTopic : retry1mTopic;
if (attempt == 2) return largeLane ? largeRetry10mTopic : retry10mTopic;
return largeLane ? largeRetry1hTopic : 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); }
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -0,0 +1,92 @@
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);
}
}
/**
* 清空规则专属 Spring Cache,并按设备精确广播 JetCache BOTH 失效。
*
* <p>JetCache 没有安全的全库 clear;调用方传入数据库中的全部设备 ID,既能删除共享 L2,
* 又能通过 syncLocal 让其他实例立即移除对应 L1,且不会误删同 Redis 中的其他业务数据。</p>
*/
public void invalidateAllRules(Collection<Long> deviceIds) {
clearSpring("normalizeRule");
metrics.invalidation("local");
if (deviceIds == null) return;
for (Long deviceId : deviceIds) {
if (deviceId == null) continue;
jetCacheInvalidator.rulesForDevice(deviceId);
metrics.invalidation("remote");
}
}
private void evictSpring(String cacheName, Object key) {
Cache cache = springCacheManager.getCache(cacheName);
if (cache != null) cache.evict(key);
}
private void clearSpring(String cacheName) {
Cache cache = springCacheManager.getCache(cacheName);
if (cache != null) cache.clear();
}
}
@@ -0,0 +1,85 @@
package com.Modules.NormalData.cache;
import com.Modules.NormalData.compiled.CompiledRuleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.StringJoiner;
/** 通过 Redis Pub/Sub 让所有消费节点同步清理 JVM 本地编译规则缓存。 */
@Component
public class NormalizationCompiledCacheInvalidationBus implements MessageListener {
public static final String TOPIC = "xdr:norm:v1:compiled-rule:invalidate";
private static final String ALL = "ALL";
private static final String RULES_PREFIX = "RULES:";
private static final Logger log = LoggerFactory.getLogger(
NormalizationCompiledCacheInvalidationBus.class);
private final CompiledRuleCache compiledRuleCache;
private final StringRedisTemplate redisTemplate;
public NormalizationCompiledCacheInvalidationBus(CompiledRuleCache compiledRuleCache,
StringRedisTemplate redisTemplate) {
this.compiledRuleCache = compiledRuleCache;
this.redisTemplate = redisTemplate;
}
public void invalidateRulesEverywhere(Collection<Long> ruleIds) {
Set<Long> distinct = positiveIds(ruleIds);
if (distinct.isEmpty()) return;
for (Long ruleId : distinct) compiledRuleCache.invalidateRule(ruleId);
redisTemplate.convertAndSend(TOPIC, ruleMessage(distinct));
}
public void invalidateAllEverywhere() {
compiledRuleCache.invalidateAll();
redisTemplate.convertAndSend(TOPIC, ALL);
}
@Override
public void onMessage(Message message, byte[] pattern) {
if (message == null || message.getBody() == null) return;
String command = new String(message.getBody(), StandardCharsets.UTF_8).trim();
if (ALL.equals(command)) {
compiledRuleCache.invalidateAll();
return;
}
if (!command.startsWith(RULES_PREFIX)) {
log.warn("忽略未知的规则缓存失效广播: {}", command);
return;
}
String ids = command.substring(RULES_PREFIX.length());
if (ids.isEmpty()) return;
for (String value : ids.split(",")) {
try {
long ruleId = Long.parseLong(value);
if (ruleId > 0L) compiledRuleCache.invalidateRule(ruleId);
} catch (NumberFormatException invalidId) {
log.warn("忽略非法的规则缓存失效广播参数: {}", value);
}
}
}
private static Set<Long> positiveIds(Collection<Long> ruleIds) {
Set<Long> distinct = new LinkedHashSet<>();
if (ruleIds == null) return distinct;
for (Long ruleId : ruleIds) {
if (ruleId != null && ruleId > 0L) distinct.add(ruleId);
}
return distinct;
}
private static String ruleMessage(Collection<Long> ruleIds) {
StringJoiner values = new StringJoiner(",", RULES_PREFIX, "");
for (Long ruleId : ruleIds) values.add(ruleId.toString());
return values.toString();
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -0,0 +1,83 @@
package com.Modules.NormalData.cache;
import com.common.mapper.DeviceDeviceMapper;
import com.common.mapper.DmNormalizeRuleMapper;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/** 管理接口使用的规则缓存清理编排;不会清除设备、任务或其他业务 Redis 数据。 */
@Service
public class NormalizationRuleCacheManagementService {
private final NormalizationCacheInvalidationService invalidationService;
private final NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus;
private final DeviceDeviceMapper deviceMapper;
private final DmNormalizeRuleMapper ruleMapper;
public NormalizationRuleCacheManagementService(
NormalizationCacheInvalidationService invalidationService,
NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus,
DeviceDeviceMapper deviceMapper,
DmNormalizeRuleMapper ruleMapper) {
this.invalidationService = invalidationService;
this.compiledCacheInvalidationBus = compiledCacheInvalidationBus;
this.deviceMapper = deviceMapper;
this.ruleMapper = ruleMapper;
}
/** 清理一个设备的规则快照,并移除该设备当前关联规则的实体和编译缓存。 */
public ClearResult clearDevice(long deviceId) {
if (deviceId <= 0L) throw new IllegalArgumentException("deviceId 必须大于 0");
Set<Long> ruleIds = new LinkedHashSet<>();
addAllNonNull(ruleIds, nullSafe(ruleMapper.selectRuleIdsByDeviceId(deviceId)));
invalidationService.invalidateRulesForDevice(deviceId);
for (Long ruleId : ruleIds) {
invalidationService.invalidateRuleEntity(ruleId);
}
compiledCacheInvalidationBus.invalidateRulesEverywhere(ruleIds);
return new ClearResult("DEVICE", deviceId, 1, ruleIds.size());
}
/** 清理所有设备规则快照、规则实体和当前 JVM 的全部编译缓存。 */
public ClearResult clearAll() {
Set<Long> deviceIds = new LinkedHashSet<>();
addAllNonNull(deviceIds, deviceMapper.selectAllIds());
// 即使存在历史孤立关联,也应删除其规则快照键。
addAllNonNull(deviceIds, ruleMapper.selectAllAssociatedDeviceIds());
invalidationService.invalidateAllRules(deviceIds);
compiledCacheInvalidationBus.invalidateAllEverywhere();
return new ClearResult("ALL", null, deviceIds.size(), 0);
}
private static List<Long> nullSafe(List<Long> values) {
return values == null ? Collections.emptyList() : values;
}
private static void addAllNonNull(Set<Long> target, Collection<Long> values) {
if (values == null) return;
for (Long value : values) if (value != null) target.add(value);
}
public static final class ClearResult {
private final String scope;
private final Long deviceId;
private final int deviceCount;
private final int associatedRuleCount;
public ClearResult(String scope, Long deviceId, int deviceCount, int associatedRuleCount) {
this.scope = scope;
this.deviceId = deviceId;
this.deviceCount = deviceCount;
this.associatedRuleCount = associatedRuleCount;
}
public String getScope() { return scope; }
public Long getDeviceId() { return deviceId; }
public int getDeviceCount() { return deviceCount; }
public int getAssociatedRuleCount() { return associatedRuleCount; }
}
}
@@ -0,0 +1,56 @@
package com.Modules.NormalData.cache;
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 NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus;
private final NormalizationRuleMetrics metrics;
public NormalizeRuleCacheInvalidationListener(NormalizationCacheInvalidationService invalidationService,
NormalizationCompiledCacheInvalidationBus compiledCacheInvalidationBus,
NormalizationRuleMetrics metrics) {
this.invalidationService = invalidationService;
this.compiledCacheInvalidationBus = compiledCacheInvalidationBus;
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 {
compiledCacheInvalidationBus.invalidateRulesEverywhere(
java.util.Collections.singleton(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);
}
}
}
@@ -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; }
}
@@ -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(); }
}
@@ -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(); }
}
@@ -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(); }
}
@@ -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; }
}
@@ -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 +
'}';
}
}
@@ -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 +
'}';
}
}
@@ -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 +
'}';
}
}
@@ -0,0 +1,77 @@
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, BOUNDED_TEXT, 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 BOUNDED_TEXT:
return sanitize(com.common.util.BoundedText.map(sourceValue,
com.common.util.BoundedText.limit(mapping.get("max_utf8_bytes"))));
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 + '\'' +
'}';
}
}
@@ -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() + "'") +
'}';
}
}
@@ -0,0 +1,270 @@
package com.Modules.NormalData.compiled;
import com.Modules.NormalData.logNormalData;
import com.common.util.JsonParser;
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;
try {
cropped = logNormalData.ParserMessageJsonType(message,
cropper == null ? null : cropper.toLegacyParams());
} catch (IllegalArgumentException invalidJsonContent) {
// JSON 截取器在消息中没有完整 {...} 时会直接抛异常。对 JSON 规则而言,
// 这与 Jackson 解析失败属于同一个确定性业务结果,由上层直接转非标,
// 不能冒泡成系统异常后进入 Retry/DLT。
if ("json".equals(dataType)) {
return null;
}
throw invalidJsonContent;
}
LinkedHashMap<String, Object> parsed;
switch (dataType) {
case "json":
// 历史 JSON 规则的空 tail cropper 使用“head 起点 + offset”语义,部分规则
// 因而会保留诸如 "7|!alarm|!" 的前缀。只在 JSON 专用路径重新收敛到
// 完整对象边界,避免改变 KV/SEP/REGEX 及既有 offset 的全局兼容语义。
if (cropper != null && !hasCompleteObjectBoundary(cropped)) {
try {
cropped = JsonParser.extractJsonFromLogMessage(cropped);
} catch (IllegalArgumentException incompleteJson) {
return null;
}
}
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);
}
/**
* cropper 的 head_key 是规则格式指纹。消息中不存在该指纹时表示规则不适用,
* 不能把空截取结果误判为原始消息 JSON 非法。
*/
public boolean isApplicableTo(String message) {
if (!"json".equals(dataType) || cropper == null || empty(cropper.getHeadKey())) {
return true;
}
return message != null && message.contains(cropper.getHeadKey());
}
private static boolean hasCompleteObjectBoundary(String value) {
return value != null && value.length() >= 2
&& value.charAt(0) == '{' && value.charAt(value.length() - 1) == '}';
}
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() + "'";
}
}
@@ -0,0 +1,281 @@
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",
"match_params", "filters_params", "complete_columns");
private final CompiledRuleCompiler compiler;
private final Cache<String, CompiledRule> compiled;
private final Cache<String, RuleMatchProfile> matchProfiles;
private final Cache<String, FailureRecord> failures;
private final Cache<String, FailureRecord> matchFailures;
private final Cache<String, Boolean> loggedFailures;
private final Cache<Long, Set<String>> keysByRule;
private final Cache<Long, Set<String>> matchKeysByRule;
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.matchKeysByRule = 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.matchProfiles = Caffeine.newBuilder()
.maximumSize(config.getLocalLimit())
.expireAfterAccess(config.getExpireAfterAccessMinutes(), TimeUnit.MINUTES)
.removalListener((key, value, cause) -> {
if (key != null && value != null) {
unlink(matchKeysByRule, sourceRuleId(key.toString()), key.toString());
}
})
.build();
this.failures = Caffeine.newBuilder()
.maximumSize(Math.min(config.getLocalLimit(), 1_000))
.expireAfterWrite(config.getFailureCacheSeconds(), TimeUnit.SECONDS)
.build();
this.matchFailures = 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 RuleMatchProfile getMatchProfile(RuleSource source) {
String key = compiler.fingerprint(source);
RuleMatchProfile cached = matchProfiles.getIfPresent(key);
if (cached != null) return cached;
FailureRecord failed = matchFailures.getIfPresent(key);
if (failed != null) throw failed.toException(source.getId());
return matchProfiles.get(key, ignored -> {
FailureRecord recentFailure = matchFailures.getIfPresent(key);
if (recentFailure != null) throw recentFailure.toException(source.getId());
try {
RuleMatchProfile profile = compiler.compileMatchProfile(source);
matchKeysByRule.asMap().computeIfAbsent(source.getId(), ruleId ->
Collections.newSetFromMap(new ConcurrentHashMap<>())).add(key);
return profile;
} catch (RuntimeException failure) {
matchFailures.put(key, new FailureRecord(failure));
throw failure;
}
});
}
public void invalidateRule(long ruleId) {
Set<String> keys = keysByRule.asMap().remove(ruleId);
if (keys != null) compiled.invalidateAll(keys);
Set<String> matchKeys = matchKeysByRule.asMap().remove(ruleId);
if (matchKeys != null) matchProfiles.invalidateAll(matchKeys);
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);
}
for (String key : matchFailures.asMap().keySet()) {
if (key.startsWith(ruleId + ":")) matchFailures.invalidate(key);
}
metrics.compiledCacheGauge(compiled.estimatedSize(), evictions.sum());
}
/** 清空当前 JVM 中所有规则编译结果、匹配画像及短失败缓存。 */
public void invalidateAll() {
compiled.invalidateAll();
matchProfiles.invalidateAll();
failures.invalidateAll();
matchFailures.invalidateAll();
loggedFailures.invalidateAll();
keysByRule.invalidateAll();
matchKeysByRule.invalidateAll();
metrics.compiledCacheGauge(0L, 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) {
unlink(keysByRule, ruleId, key);
}
private static void unlink(Cache<Long, Set<String>> index, long ruleId, String key) {
Set<String> keys = index.getIfPresent(ruleId);
if (keys == null) return;
keys.remove(key);
if (keys.isEmpty()) index.invalidate(ruleId);
}
private static long sourceRuleId(String key) {
int colon = key.indexOf(':');
if (colon <= 0) return -1L;
try {
return Long.parseLong(key.substring(0, colon));
} catch (NumberFormatException ignored) {
return -1L;
}
}
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);
}
}
}
@@ -0,0 +1,345 @@
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);
}
// match_params 和自动 origin_field 指纹都是规则执行内容的一部分。
// 即使当前开关未启用唯一选择,也必须在规则保存/编译时完成结构校验。
compileMatchProfile(root, source);
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();
}
/**
* 只编译归属判定画像,不要求 mapper action、过滤和补全能够进入编译执行器。
* 历史规则回退旧执行器时仍可因此参与同一套唯一选择算法。
*/
public RuleMatchProfile compileMatchProfile(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 对象");
return compileMatchProfile(root, source);
} catch (RuleCompilationException known) {
throw known;
} catch (Exception failure) {
throw new RuleCompilationException(source.getId(),
"规则归属画像编译失败: " + failure.getClass().getSimpleName(), failure);
}
}
private RuleMatchProfile compileMatchProfile(JsonNode root, RuleSource source) {
return RuleMatchProfile.compile(root, root.get("mappers"), source, objectMapper);
}
private CompiledCropper compileCropper(JsonNode node, RuleSource source) {
if (node == null || node.isNull()) return null;
if (!node.isObject()) throw invalid(source, "cropper_params 必须是对象");
// 达梦历史规则可能把 offset 保存为空字符串;与旧执行器保持一致,忽略整段截取配置。
if (emptyText(node.get("head_offset")) || emptyText(node.get("tail_offset"))) return null;
return new CompiledCropper(textOrEmpty(node.get("head_key")), integer(node, "head_offset", source),
textOrEmpty(node.get("tail_key")), integer(node, "tail_offset", source));
}
private static boolean emptyText(JsonNode node) {
return node != null && node.isTextual() && node.textValue().trim().isEmpty();
}
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 ("bounded_text".equals(type)) {
JsonNode limit = param == null ? null : param.get("max_utf8_bytes");
if (limit == null || !limit.isIntegralNumber() || !limit.canConvertToInt())
throw invalid(source, "bounded_text requires integer max_utf8_bytes");
int bytes = com.common.util.BoundedText.limit(limit.intValue());
compiled = new CompiledMapper(origin, destination, CompiledMapper.Action.BOUNDED_TEXT,
Collections.singletonMap("max_utf8_bytes", bytes), 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) {
node = decodeEmbeddedJson(node, source, "filters_params");
if (node == null || node.isNull()) return Collections.emptyList();
// Fastjson 的 JSONObject.getJSONObject 会二次解析合法的内嵌 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) {
node = decodeEmbeddedJson(node, source, "complete_columns");
if (node == null || node.isNull()) return Collections.emptyList();
// Fastjson 的 JSONObject.getJSONArray 会二次解析合法的内嵌 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; }
}
}
@@ -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; }
}
@@ -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);
}
}
}
@@ -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 +
'}';
}
}
@@ -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 完成。
}
}
@@ -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() {}
}
@@ -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; }
}
}
@@ -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;
}
}
}
@@ -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;
}
}
@@ -0,0 +1,51 @@
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 LocalDateTime eventAt;
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,
LocalDateTime eventAt,
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.eventAt = eventAt;
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 LocalDateTime getEventAt() { return eventAt; }
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; }
}
@@ -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); }
}
@@ -0,0 +1,292 @@
package com.Modules.NormalData.compiled;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* 一条规则用于“归属判定”的不可变画像。
*
* <p>画像只包含显式匹配计划和由 {@code mappers.origin_field} 生成的自动字段指纹,
* 不包含消息状态,也不会执行映射、过滤、补全或任何外部调用。</p>
*/
public final class RuleMatchProfile {
private final boolean explicitEnabled;
private final int priority;
private final List<MatchCondition> all;
private final List<MatchCondition> any;
private final List<MatchCondition> none;
private final Set<String> originFields;
private RuleMatchProfile(boolean explicitEnabled, int priority,
List<MatchCondition> all, List<MatchCondition> any,
List<MatchCondition> none, Set<String> originFields) {
this.explicitEnabled = explicitEnabled;
this.priority = priority;
this.all = immutable(all);
this.any = immutable(any);
this.none = immutable(none);
this.originFields = Collections.unmodifiableSet(new LinkedHashSet<>(originFields));
}
static RuleMatchProfile compile(JsonNode root, JsonNode mappers, RuleSource source,
ObjectMapper objectMapper) {
Set<String> origins = compileOrigins(mappers, source, objectMapper);
JsonNode params = root.get("match_params");
if (params == null || params.isNull()) {
return new RuleMatchProfile(false, 0, Collections.emptyList(),
Collections.emptyList(), Collections.emptyList(), origins);
}
if (!params.isObject()) throw invalid(source, "match_params 必须是对象");
JsonNode enabledNode = params.get("enabled");
if (enabledNode != null && !enabledNode.isBoolean()) {
throw invalid(source, "match_params.enabled 必须是布尔值");
}
boolean enabled = enabledNode != null && enabledNode.booleanValue();
JsonNode priorityNode = params.get("priority");
if (priorityNode != null && (!priorityNode.isIntegralNumber()
|| !priorityNode.canConvertToInt())) {
throw invalid(source, "match_params.priority 必须是整数");
}
int priority = priorityNode == null ? 0 : priorityNode.intValue();
List<MatchCondition> all = compileConditions(params.get("all"), "all", source, objectMapper);
List<MatchCondition> any = compileConditions(params.get("any"), "any", source, objectMapper);
List<MatchCondition> none = compileConditions(params.get("none"), "none", source, objectMapper);
if (enabled && all.isEmpty() && any.isEmpty() && none.isEmpty()) {
throw invalid(source, "match_params.enabled=true 时必须至少配置一个条件");
}
return new RuleMatchProfile(enabled, priority, all, any, none, origins);
}
public ExplicitEvaluation evaluate(Map<String, Object> parsedFields, String rawMessage) {
if (!explicitEnabled) return ExplicitEvaluation.notMatched();
int specificity = 0;
for (MatchCondition condition : all) {
if (!condition.matches(parsedFields, rawMessage)) return ExplicitEvaluation.notMatched();
specificity += condition.specificity();
}
if (!any.isEmpty()) {
boolean matched = false;
int anySpecificity = 0;
for (MatchCondition condition : any) {
if (condition.matches(parsedFields, rawMessage)) {
matched = true;
anySpecificity = Math.max(anySpecificity, condition.specificity());
}
}
if (!matched) return ExplicitEvaluation.notMatched();
specificity += anySpecificity;
}
for (MatchCondition condition : none) {
if (condition.matches(parsedFields, rawMessage)) return ExplicitEvaluation.notMatched();
// 成功排除一种格式同样提高规则的具体度。
specificity += condition.specificity();
}
return new ExplicitEvaluation(true, specificity);
}
public boolean isExplicitEnabled() { return explicitEnabled; }
public int getPriority() { return priority; }
public Set<String> getOriginFields() { return originFields; }
private static Set<String> compileOrigins(JsonNode node, RuleSource source,
ObjectMapper objectMapper) {
if (node != null && node.isTextual()) {
try {
node = objectMapper.readTree(node.textValue());
} catch (Exception invalidJson) {
throw invalid(source, "mappers 内嵌 JSON 无效");
}
}
if (node == null || !node.isArray()) throw invalid(source, "mappers 必须是数组");
Set<String> result = new LinkedHashSet<>();
for (JsonNode mapper : node) {
JsonNode origin = mapper.get("origin_field");
if (origin == null || !origin.isTextual() || blank(origin.textValue())) {
throw invalid(source, "mappers.origin_field 不能为空");
}
result.add(origin.textValue());
}
return result;
}
private static List<MatchCondition> compileConditions(JsonNode node, String group,
RuleSource source,
ObjectMapper objectMapper) {
if (node == null || node.isNull()) return Collections.emptyList();
if (!node.isArray()) throw invalid(source, "match_params." + group + " 必须是数组");
List<MatchCondition> conditions = new ArrayList<>();
int index = 0;
for (JsonNode condition : node) {
String path = "match_params." + group + "[" + index + "]";
conditions.add(MatchCondition.compile(condition, path, source, objectMapper));
index++;
}
return conditions;
}
private static <T> List<T> immutable(List<T> source) {
return Collections.unmodifiableList(new ArrayList<>(source));
}
private static boolean blank(String value) {
return value == null || value.trim().isEmpty();
}
private static CompiledRuleCompiler.RuleCompilationException invalid(RuleSource source,
String message) {
return new CompiledRuleCompiler.RuleCompilationException(source.getId(), message);
}
public static final class ExplicitEvaluation {
private static final ExplicitEvaluation NOT_MATCHED = new ExplicitEvaluation(false, 0);
private final boolean matched;
private final int specificity;
private ExplicitEvaluation(boolean matched, int specificity) {
this.matched = matched;
this.specificity = specificity;
}
static ExplicitEvaluation notMatched() { return NOT_MATCHED; }
public boolean isMatched() { return matched; }
public int getSpecificity() { return specificity; }
}
private enum Source { PARSED, RAW }
private enum Operation {
EXISTS, NOT_EXISTS, NOT_BLANK, EQ, NE, IN, CONTAINS, REGEXP
}
private static final class MatchCondition {
private final Source source;
private final String field;
private final Operation operation;
private final String value;
private final Set<String> values;
private final Pattern pattern;
private MatchCondition(Source source, String field, Operation operation, String value,
Set<String> values, Pattern pattern) {
this.source = source;
this.field = field;
this.operation = operation;
this.value = value;
this.values = values;
this.pattern = pattern;
}
static MatchCondition compile(JsonNode node, String path, RuleSource rule,
ObjectMapper objectMapper) {
if (node == null || !node.isObject()) throw invalid(rule, path + " 必须是对象");
String sourceText = text(node.get("source"));
Source source;
try {
source = sourceText == null ? Source.PARSED
: Source.valueOf(sourceText.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unsupported) {
throw invalid(rule, path + ".source 不支持: " + sourceText);
}
String opText = text(node.get("op"));
if (blank(opText)) throw invalid(rule, path + ".op 不能为空");
Operation operation;
try {
operation = Operation.valueOf(opText.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException unsupported) {
throw invalid(rule, path + ".op 不支持: " + opText);
}
String field = text(node.get("field"));
if (source == Source.PARSED && blank(field)) {
throw invalid(rule, path + ".field 不能为空");
}
if (source == Source.RAW && !(operation == Operation.EQ || operation == Operation.NE
|| operation == Operation.NOT_BLANK || operation == Operation.CONTAINS
|| operation == Operation.REGEXP)) {
throw invalid(rule, path + ".op 不适用于 raw: " + opText);
}
JsonNode valueNode = node.get("value");
boolean needsSingleValue = operation == Operation.EQ || operation == Operation.NE
|| operation == Operation.CONTAINS || operation == Operation.REGEXP;
if (needsSingleValue && (valueNode == null || valueNode.isNull()
|| !valueNode.isValueNode())) {
throw invalid(rule, path + ".value 必须是单值");
}
String value = needsSingleValue ? valueNode.asText() : null;
Set<String> values = Collections.emptySet();
if (operation == Operation.IN) {
if (valueNode == null || !valueNode.isArray()) {
throw invalid(rule, path + ".value 必须是数组");
}
Set<String> compiledValues = new LinkedHashSet<>();
for (JsonNode item : valueNode) {
if (item == null || item.isContainerNode()) {
throw invalid(rule, path + ".value 只能包含标量");
}
compiledValues.add(item.isNull() ? null : item.asText());
}
values = Collections.unmodifiableSet(compiledValues);
}
Pattern pattern = null;
if (operation == Operation.REGEXP) {
try {
pattern = Pattern.compile(value);
} catch (RuntimeException invalidRegex) {
throw invalid(rule, path + ".value 正则无效");
}
}
return new MatchCondition(source, field, operation, value, values, pattern);
}
boolean matches(Map<String, Object> parsedFields, String rawMessage) {
boolean present;
Object actual;
if (source == Source.RAW) {
present = rawMessage != null;
actual = rawMessage;
} else {
present = parsedFields != null && parsedFields.containsKey(field);
actual = present ? parsedFields.get(field) : null;
}
switch (operation) {
case EXISTS: return present;
case NOT_EXISTS: return !present;
case NOT_BLANK: return present && actual != null && !actual.toString().trim().isEmpty();
case EQ: return present && string(actual).equals(value);
case NE: return present && !string(actual).equals(value);
case IN: return present && values.contains(actual == null ? null : actual.toString());
case CONTAINS: return present && actual != null && actual.toString().contains(value);
case REGEXP: return present && actual != null && pattern.matcher(actual.toString()).find();
default: throw new IllegalStateException("未知显式匹配操作符: " + operation);
}
}
int specificity() {
switch (operation) {
case EQ:
case IN:
case REGEXP: return 3;
case CONTAINS: return 2;
default: return 1;
}
}
private static String string(Object value) {
return value == null ? "" : value.toString();
}
private static String text(JsonNode node) {
return node == null || node.isNull() ? null : node.asText();
}
}
}
@@ -0,0 +1,263 @@
package com.Modules.NormalData.compiled;
import com.Modules.NormalData.metrics.NormalizationRuleMetrics;
import com.config.NormalizationOptimizationProperties;
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.Set;
/** 同设备多规则的纯内存归属选择器。 */
public final class RuleSelectionEngine {
private static final double EPSILON = 1.0e-12d;
private final CompiledRuleCache ruleCache;
private final NormalizationOptimizationProperties properties;
private final NormalizationRuleMetrics metrics;
public RuleSelectionEngine(CompiledRuleCache ruleCache,
NormalizationOptimizationProperties properties,
NormalizationRuleMetrics metrics) {
this.ruleCache = ruleCache;
this.properties = properties;
this.metrics = metrics;
}
public <T> Decision<T> select(List<Candidate<T>> parsedCandidates, String rawMessage,
boolean shadowOnly) {
NormalizationOptimizationProperties.RuleSelection config = properties.getRuleSelection();
List<Ranked<T>> usable = new ArrayList<>();
for (Candidate<T> candidate : parsedCandidates) {
try {
usable.add(new Ranked<>(candidate, ruleCache.getMatchProfile(candidate.getSource())));
} catch (RuntimeException invalidProfile) {
metrics.ruleSelection("invalid_match_config");
}
}
Decision<T> result = null;
if (config.isExplicitEnabled()) {
List<Ranked<T>> explicit = new ArrayList<>();
for (Ranked<T> ranked : usable) {
if (!ranked.profile.isExplicitEnabled()) continue;
RuleMatchProfile.ExplicitEvaluation evaluation = ranked.profile.evaluate(
ranked.candidate.getParsedFields(), rawMessage);
if (evaluation.isMatched()) {
ranked.explicitSpecificity = evaluation.getSpecificity();
explicit.add(ranked);
}
}
if (!explicit.isEmpty()) result = choose(explicit, SelectionMode.EXPLICIT);
}
if (result == null && config.isAutomaticFallbackEnabled()) {
List<Ranked<T>> automatic = new ArrayList<>();
for (Ranked<T> ranked : usable) {
// 启用了显式条件但未命中的规则,严禁绕回字段评分。
if (!ranked.profile.isExplicitEnabled()) automatic.add(ranked);
}
if (!automatic.isEmpty()) result = choose(automatic, SelectionMode.AUTOMATIC);
}
if (result == null || !result.isSelected()) {
metrics.ruleSelection(shadowOnly ? "shadow_no_match" : "no_match");
metrics.ruleSelectionObservation(parsedCandidates.size(), 0.0d, 0.0d);
return Decision.none();
}
if (shadowOnly) {
metrics.ruleSelection("shadow_selected");
} else {
metrics.ruleSelection("selected");
metrics.ruleSelection(result.getMode() == SelectionMode.EXPLICIT
? "explicit_selected" : "automatic_selected");
if (result.isAmbiguous()) metrics.ruleSelection("ambiguous");
}
metrics.ruleSelectionObservation(parsedCandidates.size(),
parsedCandidates.isEmpty() ? 0.0d
: (double) result.getRankedCandidateCount() / parsedCandidates.size(),
result.getScoreMargin());
return result;
}
private <T> Decision<T> choose(List<Ranked<T>> candidates, SelectionMode mode) {
applyAutomaticScores(candidates);
List<Ranked<T>> eligible = new ArrayList<>();
for (Ranked<T> ranked : candidates) {
// 显式条件已经证明格式归属,允许没有 mapper 指纹的完成型规则参与。
if (mode == SelectionMode.EXPLICIT || ranked.score.matchedCount > 0
|| (candidates.size() == 1 && ranked.profile.getOriginFields().isEmpty())) {
eligible.add(ranked);
}
}
if (eligible.isEmpty()) return Decision.none();
Comparator<Ranked<T>> comparator = mode == SelectionMode.EXPLICIT
? RuleSelectionEngine::compareExplicit : RuleSelectionEngine::compareAutomatic;
eligible.sort(comparator);
Ranked<T> first = eligible.get(0);
List<Candidate<T>> tied = new ArrayList<>();
for (Ranked<T> ranked : eligible) {
if (!sameRank(first, ranked, mode)) break;
tied.add(ranked.candidate);
}
tied.sort(Comparator.comparingLong(candidate -> candidate.getSource().getId()));
Candidate<T> winner = tied.get(0);
double margin = eligible.size() < 2 ? first.score.ownershipScore
: Math.max(0.0d, first.score.ownershipScore
- eligible.get(1).score.ownershipScore);
return new Decision<>(winner, mode, tied.size() > 1, tied,
eligible.size(), margin);
}
private static <T> void applyAutomaticScores(List<Ranked<T>> candidates) {
Map<String, Integer> frequency = new HashMap<>();
for (Ranked<T> candidate : candidates) {
for (String field : candidate.profile.getOriginFields()) {
frequency.put(field, frequency.getOrDefault(field, 0) + 1);
}
}
for (Ranked<T> candidate : candidates) {
double totalWeight = 0.0d;
double matchedWeight = 0.0d;
int matchedCount = 0;
Set<String> parsed = candidate.candidate.getParsedFields().keySet();
for (String field : candidate.profile.getOriginFields()) {
double weight = 1.0d / frequency.get(field);
totalWeight += weight;
if (parsed.contains(field)) {
matchedWeight += weight;
matchedCount++;
}
}
double coverage = totalWeight == 0.0d ? 0.0d : matchedWeight / totalWeight;
candidate.score = new AutomaticScore(matchedWeight * coverage,
matchedWeight, coverage, matchedCount);
}
}
private static int compareExplicit(Ranked<?> left, Ranked<?> right) {
int compared = Integer.compare(right.profile.getPriority(), left.profile.getPriority());
if (compared != 0) return compared;
compared = Integer.compare(right.explicitSpecificity, left.explicitSpecificity);
if (compared != 0) return compared;
compared = compareScore(left.score, right.score);
if (compared != 0) return compared;
return Long.compare(left.candidate.getSource().getId(), right.candidate.getSource().getId());
}
private static int compareAutomatic(Ranked<?> left, Ranked<?> right) {
int compared = compareScore(left.score, right.score);
if (compared != 0) return compared;
return Long.compare(left.candidate.getSource().getId(), right.candidate.getSource().getId());
}
private static int compareScore(AutomaticScore left, AutomaticScore right) {
int compared = Double.compare(right.ownershipScore, left.ownershipScore);
if (compared != 0) return compared;
compared = Double.compare(right.matchedWeight, left.matchedWeight);
if (compared != 0) return compared;
compared = Double.compare(right.coverage, left.coverage);
if (compared != 0) return compared;
return Integer.compare(right.matchedCount, left.matchedCount);
}
private static boolean sameRank(Ranked<?> left, Ranked<?> right, SelectionMode mode) {
if (mode == SelectionMode.EXPLICIT
&& (left.profile.getPriority() != right.profile.getPriority()
|| left.explicitSpecificity != right.explicitSpecificity)) {
return false;
}
return close(left.score.ownershipScore, right.score.ownershipScore)
&& close(left.score.matchedWeight, right.score.matchedWeight)
&& close(left.score.coverage, right.score.coverage)
&& left.score.matchedCount == right.score.matchedCount;
}
private static boolean close(double left, double right) {
return Math.abs(left - right) <= EPSILON;
}
public enum SelectionMode { EXPLICIT, AUTOMATIC }
public static final class Candidate<T> {
private final RuleSource source;
private final Map<String, Object> parsedFields;
private final T payload;
public Candidate(RuleSource source, Map<String, Object> parsedFields, T payload) {
this.source = source;
this.parsedFields = Collections.unmodifiableMap(new LinkedHashMap<>(parsedFields));
this.payload = payload;
}
public RuleSource getSource() { return source; }
public Map<String, Object> getParsedFields() { return parsedFields; }
public T getPayload() { return payload; }
}
public static final class Decision<T> {
private static final Decision<?> NONE = new Decision<>(null, null, false,
Collections.emptyList(), 0, 0.0d);
private final Candidate<T> winner;
private final SelectionMode mode;
private final boolean ambiguous;
private final List<Candidate<T>> tiedCandidates;
private final int rankedCandidateCount;
private final double scoreMargin;
private Decision(Candidate<T> winner, SelectionMode mode, boolean ambiguous,
List<Candidate<T>> tiedCandidates, int rankedCandidateCount,
double scoreMargin) {
this.winner = winner;
this.mode = mode;
this.ambiguous = ambiguous;
this.tiedCandidates = Collections.unmodifiableList(new ArrayList<>(tiedCandidates));
this.rankedCandidateCount = rankedCandidateCount;
this.scoreMargin = scoreMargin;
}
@SuppressWarnings("unchecked")
static <T> Decision<T> none() { return (Decision<T>) NONE; }
public boolean isSelected() { return winner != null; }
public Candidate<T> getWinner() { return winner; }
public SelectionMode getMode() { return mode; }
public boolean isAmbiguous() { return ambiguous; }
public List<Candidate<T>> getTiedCandidates() { return tiedCandidates; }
public int getRankedCandidateCount() { return rankedCandidateCount; }
public double getScoreMargin() { return scoreMargin; }
}
private static final class Ranked<T> {
private final Candidate<T> candidate;
private final RuleMatchProfile profile;
private int explicitSpecificity;
private AutomaticScore score = AutomaticScore.ZERO;
private Ranked(Candidate<T> candidate, RuleMatchProfile profile) {
this.candidate = candidate;
this.profile = profile;
}
}
private static final class AutomaticScore {
private static final AutomaticScore ZERO = new AutomaticScore(0.0d, 0.0d, 0.0d, 0);
private final double ownershipScore;
private final double matchedWeight;
private final double coverage;
private final int matchedCount;
private AutomaticScore(double ownershipScore, double matchedWeight,
double coverage, int matchedCount) {
this.ownershipScore = ownershipScore;
this.matchedWeight = matchedWeight;
this.coverage = coverage;
this.matchedCount = matchedCount;
}
}
}
@@ -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);
}
}
@@ -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 {
}
}
@@ -0,0 +1,127 @@
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.DoubleAdder;
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 Counters ruleSelection = new Counters("selected", "explicit_selected",
"automatic_selected", "ambiguous", "equivalent_tie", "conflicting_tie",
"no_match", "invalid_match_config", "shadow_selected", "shadow_no_match");
private final LongAdder ruleJsonParse = new LongAdder();
private final LongAdder selectionObservationCount = new LongAdder();
private final LongAdder selectionCandidateTotal = new LongAdder();
private final AtomicLong selectionCandidateMax = new AtomicLong();
private final DoubleAdder selectionMatchRateTotal = new DoubleAdder();
private final DoubleAdder selectionScoreMarginTotal = new DoubleAdder();
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 ruleSelection(String outcome) { ruleSelection.increment(outcome); }
public void ruleSelectionObservation(int candidateCount, double matchRate, double scoreMargin) {
int candidates = Math.max(0, candidateCount);
selectionObservationCount.increment();
selectionCandidateTotal.add(candidates);
updateMax(selectionCandidateMax, candidates);
selectionMatchRateTotal.add(Math.max(0.0d, Math.min(1.0d, matchRate)));
selectionScoreMarginTotal.add(Math.max(0.0d, scoreMargin));
}
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_selection_total", ruleSelection.snapshot());
result.put("rule_selection_observation_count", selectionObservationCount.sum());
result.put("rule_selection_candidate_count_total", selectionCandidateTotal.sum());
result.put("rule_selection_candidate_count_max", selectionCandidateMax.get());
long observations = selectionObservationCount.sum();
result.put("rule_selection_match_rate_avg", observations == 0L ? 0.0d
: selectionMatchRateTotal.sum() / observations);
result.put("rule_selection_score_margin_avg", observations == 0L ? 0.0d
: selectionScoreMarginTotal.sum() / observations);
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;
}
@@ -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;
}
@@ -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,6 +378,7 @@ public class DeviceDevice {
", managerName='" + managerName + '\'' +
", todayParseCount=" + todayParseCount +
", todayNonLogCount=" + todayNonLogCount +
", todayStatsDate=" + todayStatsDate +
", createDept=" + createDept +
", deviceCollectId=" + deviceCollectId +
'}';
@@ -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; }
}
@@ -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;
}
@@ -376,6 +376,7 @@ public class SyslogNormalAlarm {
private String destinationSystem;
private String etlHost;
private Integer normalizeRuleId;
private String ruleVersion;
private String normalizeRuleName;
private String syslogUuid;
private String syslogTopic;
@@ -375,6 +375,7 @@ public class SyslogNormalData {
private String destinationSystem;
private String etlHost;
private Integer normalizeRuleId;
private String ruleVersion;
private String normalizeRuleName;
private String syslogUuid;
private String syslogTopic;
@@ -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);
}
@@ -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);
}
@@ -0,0 +1,9 @@
package com.common.mapper;
import com.common.service.BacklogRetentionDelta;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BacklogRetentionAuditMapper {
int upsert(BacklogRetentionDelta delta);
}
@@ -21,6 +21,9 @@ public interface DeviceDeviceMapper {
*/
List<DeviceDevice> selectAll();
/** 规则缓存全量失效只需要主键,避免加载整行设备信息。 */
List<Long> selectAllIds();
/**
* 根据IP地址查询设备
*/
@@ -22,6 +22,12 @@ public interface DmNormalizeRuleMapper {
*/
List<Map<String, Object>> selectByDeviceId(@Param("id") Long id);
List<Long> selectDeviceIdsByRuleId(@Param("ruleId") Long ruleId);
List<Long> selectRuleIdsByDeviceId(@Param("deviceId") Long deviceId);
List<Long> selectAllAssociatedDeviceIds();
/**
* 根据ID更新数据标准化规则
* @param rule 数据标准化规则对象
@@ -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);
}
@@ -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);
}
@@ -15,21 +15,16 @@ import java.util.Map;
public interface SyslogNormalAlarmMapper {
/**
* 动态插入数据 - 使用 Map
* 使用当前小批次的字段并集模板插入告警日志。调用方保证同批 Map 具有相同键集合,
* 缺失值绑定为 NULL,使 MyBatis ExecutorType.BATCH 能复用 PreparedStatement。
*/
int insertDynamic(@Param("dataMap") Map<String, Object> dataMap);
int insertBatchPlanned(@Param("dataMap") Map<String, Object> dataMap);
/**
* 动态插入数据 - 使用实体类
*/
int insertByEntity(SyslogNormalAlarm entity);
/**
* 批量插入数据
*/
int batchInsert(@Param("dataList") List<Map<String, Object>> dataList);
/**
* 统计24小时内分组数据量
*/
@@ -83,4 +78,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);
}
@@ -12,21 +12,16 @@ import java.util.List;
public interface SyslogNormalDataMapper {
/**
* 动态插入数据 - 使用 Map
* 使用当前小批次的字段并集模板插入普通日志。调用方保证同批 Map 具有相同键集合,
* 缺失值绑定为 NULL,使 MyBatis ExecutorType.BATCH 能复用 PreparedStatement。
*/
int insertDynamic(@Param("dataMap") Map<String, Object> dataMap);
int insertBatchPlanned(@Param("dataMap") Map<String, Object> dataMap);
/**
* 动态插入数据 - 使用实体类
*/
int insertByEntity(SyslogNormalData entity);
/**
* 批量插入数据
*/
int batchInsert(@Param("dataList") java.util.List<Map<String, Object>> dataList);
/**
* 统计24小时内分组数据量
*/
@@ -100,4 +95,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);
}
@@ -0,0 +1,118 @@
package com.common.service;
import java.time.LocalDateTime;
import java.util.Objects;
/** 一批积压消息按来源小时、Topic、Partition 聚合后的采样审计增量。 */
public final class BacklogRetentionDelta {
private final LocalDateTime sourceHour;
private final String sourceTopic;
private final int kafkaPartition;
private final String policyVersion;
private final int normalRetainBps;
private final int nonNormalRetainBps;
private long messageTotal;
private long alarmRowsTotal;
private long alarmRowsSaved;
private long normalRowsTotal;
private long normalRowsSaved;
private long normalRowsDropped;
private long nonNormalRowsTotal;
private long nonNormalRowsSaved;
private long nonNormalRowsDropped;
private long rawTotal;
private long rawSaved;
private long rawDropped;
private long minLagMs;
private long maxLagMs;
public BacklogRetentionDelta(LocalDateTime sourceHour, String sourceTopic, int kafkaPartition,
String policyVersion, int normalRetainBps, int nonNormalRetainBps,
long messageTotal, long alarmRowsTotal, long alarmRowsSaved,
long normalRowsTotal, long normalRowsSaved, long normalRowsDropped,
long nonNormalRowsTotal, long nonNormalRowsSaved,
long nonNormalRowsDropped, long rawTotal, long rawSaved,
long rawDropped, long minLagMs, long maxLagMs) {
this.sourceHour = Objects.requireNonNull(sourceHour, "sourceHour");
this.sourceTopic = Objects.requireNonNull(sourceTopic, "sourceTopic");
this.kafkaPartition = kafkaPartition;
this.policyVersion = Objects.requireNonNull(policyVersion, "policyVersion");
this.normalRetainBps = normalRetainBps;
this.nonNormalRetainBps = nonNormalRetainBps;
this.messageTotal = messageTotal;
this.alarmRowsTotal = alarmRowsTotal;
this.alarmRowsSaved = alarmRowsSaved;
this.normalRowsTotal = normalRowsTotal;
this.normalRowsSaved = normalRowsSaved;
this.normalRowsDropped = normalRowsDropped;
this.nonNormalRowsTotal = nonNormalRowsTotal;
this.nonNormalRowsSaved = nonNormalRowsSaved;
this.nonNormalRowsDropped = nonNormalRowsDropped;
this.rawTotal = rawTotal;
this.rawSaved = rawSaved;
this.rawDropped = rawDropped;
this.minLagMs = minLagMs;
this.maxLagMs = maxLagMs;
}
public void merge(BacklogRetentionDelta other) {
if (!sameKey(other)) throw new IllegalArgumentException("不能合并不同维度的采样审计增量");
messageTotal += other.messageTotal;
alarmRowsTotal += other.alarmRowsTotal;
alarmRowsSaved += other.alarmRowsSaved;
normalRowsTotal += other.normalRowsTotal;
normalRowsSaved += other.normalRowsSaved;
normalRowsDropped += other.normalRowsDropped;
nonNormalRowsTotal += other.nonNormalRowsTotal;
nonNormalRowsSaved += other.nonNormalRowsSaved;
nonNormalRowsDropped += other.nonNormalRowsDropped;
rawTotal += other.rawTotal;
rawSaved += other.rawSaved;
rawDropped += other.rawDropped;
minLagMs = Math.min(minLagMs, other.minLagMs);
maxLagMs = Math.max(maxLagMs, other.maxLagMs);
}
public BacklogRetentionDelta copy() {
return new BacklogRetentionDelta(sourceHour, sourceTopic, kafkaPartition, policyVersion,
normalRetainBps, nonNormalRetainBps, messageTotal, alarmRowsTotal,
alarmRowsSaved, normalRowsTotal, normalRowsSaved, normalRowsDropped,
nonNormalRowsTotal, nonNormalRowsSaved, nonNormalRowsDropped,
rawTotal, rawSaved, rawDropped, minLagMs, maxLagMs);
}
private boolean sameKey(BacklogRetentionDelta other) {
return other != null && kafkaPartition == other.kafkaPartition
&& normalRetainBps == other.normalRetainBps
&& nonNormalRetainBps == other.nonNormalRetainBps
&& sourceHour.equals(other.sourceHour)
&& sourceTopic.equals(other.sourceTopic)
&& policyVersion.equals(other.policyVersion);
}
public String aggregationKey() {
return sourceHour + "\u0000" + sourceTopic + "\u0000" + kafkaPartition + "\u0000"
+ policyVersion + "\u0000" + normalRetainBps + "\u0000" + nonNormalRetainBps;
}
public LocalDateTime getSourceHour() { return sourceHour; }
public String getSourceTopic() { return sourceTopic; }
public int getKafkaPartition() { return kafkaPartition; }
public String getPolicyVersion() { return policyVersion; }
public int getNormalRetainBps() { return normalRetainBps; }
public int getNonNormalRetainBps() { return nonNormalRetainBps; }
public long getMessageTotal() { return messageTotal; }
public long getAlarmRowsTotal() { return alarmRowsTotal; }
public long getAlarmRowsSaved() { return alarmRowsSaved; }
public long getNormalRowsTotal() { return normalRowsTotal; }
public long getNormalRowsSaved() { return normalRowsSaved; }
public long getNormalRowsDropped() { return normalRowsDropped; }
public long getNonNormalRowsTotal() { return nonNormalRowsTotal; }
public long getNonNormalRowsSaved() { return nonNormalRowsSaved; }
public long getNonNormalRowsDropped() { return nonNormalRowsDropped; }
public long getRawTotal() { return rawTotal; }
public long getRawSaved() { return rawSaved; }
public long getRawDropped() { return rawDropped; }
public long getMinLagMs() { return minLagMs; }
public long getMaxLagMs() { return maxLagMs; }
}
@@ -0,0 +1,98 @@
package com.common.service;
import com.common.mapper.BacklogRetentionAuditMapper;
import com.config.BacklogSamplingProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** 消费优先:小时采样审计后台尽力保存,失败不改变采样决策,不等待主消费。 */
@Slf4j
@Service
public class BacklogSamplingAuditService {
private final BacklogRetentionAuditMapper mapper;
private final BacklogSamplingProperties properties;
private final BacklogSamplingMetrics metrics;
private final PlatformTransactionManager transactionManager;
private volatile long retryAfterMs;
private final BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("SAMPLING_AUDIT", 256, 50000, false);
@javax.annotation.PostConstruct public void start() { queue.start(); }
@javax.annotation.PreDestroy public void stop() { queue.stop(); }
public Map<String, Object> status() { return queue.status(); }
public BacklogSamplingAuditService(BacklogRetentionAuditMapper mapper,
BacklogSamplingProperties properties,
BacklogSamplingMetrics metrics,
PlatformTransactionManager transactionManager) {
this.mapper = mapper;
this.properties = properties;
this.metrics = metrics;
this.transactionManager = transactionManager;
}
/** 返回值仅代表入队是否成功,不影响调用方原采样决策。 */
public boolean recordAsync(List<BacklogRetentionDelta> deltas) {
if (deltas == null || deltas.isEmpty()) return true;
long affectedMessages = 0L;
try {
affectedMessages = messageCount(deltas);
final long taskMessages = affectedMessages;
List<BacklogRetentionDelta> aggregated = aggregate(deltas);
metrics.record(aggregated); // 决策指标,不再假称这些数字已写入审计数据库。
if (System.currentTimeMillis() < retryAfterMs) {
queue.loss("DATABASE_BACKOFF", null);
metrics.auditLoss(affectedMessages);
return false;
}
boolean offered = queue.offer(aggregated.size(), () -> writeAudit(aggregated, taskMessages));
if (!offered) metrics.auditLoss(affectedMessages);
return offered;
} catch (RuntimeException failure) {
queue.loss("PREPARE_FAILED", failure);
metrics.auditLoss(affectedMessages);
return false;
}
}
private void writeAudit(List<BacklogRetentionDelta> aggregated, long affectedMessages) {
try {
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
transaction.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transaction.setTimeout(Math.max(1, properties.getAuditTimeoutSeconds()));
transaction.execute(status -> {
for (BacklogRetentionDelta delta : aggregated) mapper.upsert(delta);
return null;
});
retryAfterMs = 0L;
} catch (RuntimeException failure) {
retryAfterMs = System.currentTimeMillis() + Math.max(1L, properties.getAuditRetryBackoffMs());
queue.pause(properties.getAuditRetryBackoffMs());
metrics.auditWriteFailed(affectedMessages);
// 审计为累加UPSERT;提交结果不确定时自动重放可能双计数,当前选择记录损失而不重放。
throw failure;
}
}
static List<BacklogRetentionDelta> aggregate(List<BacklogRetentionDelta> deltas) {
Map<String, BacklogRetentionDelta> grouped = new LinkedHashMap<>();
for (BacklogRetentionDelta delta : deltas) {
BacklogRetentionDelta existing = grouped.get(delta.aggregationKey());
if (existing == null) grouped.put(delta.aggregationKey(), delta.copy());
else existing.merge(delta);
}
return new ArrayList<>(grouped.values());
}
private long messageCount(List<BacklogRetentionDelta> deltas) {
long total = 0L;
for (BacklogRetentionDelta delta : deltas) total += delta.getMessageTotal();
return total;
}
}
@@ -0,0 +1,62 @@
package com.common.service;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
/** 积压采样热路径指标;表审计失败时仍可从接口和日志发现。 */
@Component
public class BacklogSamplingMetrics {
private final LongAdder degradedMessages = new LongAdder();
private final LongAdder alarmRowsSaved = new LongAdder();
private final LongAdder normalRowsSaved = new LongAdder();
private final LongAdder normalRowsDropped = new LongAdder();
private final LongAdder nonNormalRowsSaved = new LongAdder();
private final LongAdder nonNormalRowsDropped = new LongAdder();
private final LongAdder rawSaved = new LongAdder();
private final LongAdder rawDropped = new LongAdder();
private final LongAdder auditWriteFailures = new LongAdder();
private final LongAdder auditFallbackMessages = new LongAdder();
private final LongAdder auditLostMessages = new LongAdder();
public void auditLoss(long messages) { auditLostMessages.add(Math.max(0L, messages)); }
public void auditWriteFailed(long messages) { auditWriteFailures.increment(); auditLoss(messages); }
public void record(List<BacklogRetentionDelta> deltas) {
for (BacklogRetentionDelta delta : deltas) {
degradedMessages.add(delta.getMessageTotal());
alarmRowsSaved.add(delta.getAlarmRowsSaved());
normalRowsSaved.add(delta.getNormalRowsSaved());
normalRowsDropped.add(delta.getNormalRowsDropped());
nonNormalRowsSaved.add(delta.getNonNormalRowsSaved());
nonNormalRowsDropped.add(delta.getNonNormalRowsDropped());
rawSaved.add(delta.getRawSaved());
rawDropped.add(delta.getRawDropped());
}
}
public void auditFailure(long affectedMessages) {
auditWriteFailures.increment();
auditFallbackMessages.add(Math.max(0L, affectedMessages));
}
public Map<String, Object> snapshot() {
Map<String, Object> values = new LinkedHashMap<>();
values.put("degraded_messages_total", degradedMessages.sum());
values.put("alarm_rows_saved_total", alarmRowsSaved.sum());
values.put("normal_rows_saved_total", normalRowsSaved.sum());
values.put("normal_rows_dropped_total", normalRowsDropped.sum());
values.put("non_normal_rows_saved_total", nonNormalRowsSaved.sum());
values.put("non_normal_rows_dropped_total", nonNormalRowsDropped.sum());
values.put("raw_saved_total", rawSaved.sum());
values.put("raw_dropped_total", rawDropped.sum());
values.put("audit_write_failures_total", auditWriteFailures.sum());
values.put("audit_fallback_messages_total", auditFallbackMessages.sum());
values.put("audit_lost_or_unconfirmed_messages_total", auditLostMessages.sum());
values.put("counter_semantics", "SAMPLING_DECISIONS_NOT_DB_CONFIRMATIONS");
return values;
}
}
@@ -0,0 +1,147 @@
package com.common.service;
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** 辅助写库专用有界队列。入队不执行任务、不等待数据库、不使用CallerRuns。 */
@Slf4j
final class BestEffortAuxiliaryQueue {
private final String kind;
private final ArrayBlockingQueue<Task> queue;
private final long maxGroups;
private final boolean retry;
private final AtomicLong groups = new AtomicLong();
private final AtomicLong accepted = new AtomicLong();
private final AtomicLong completed = new AtomicLong();
private final AtomicLong failures = new AtomicLong();
private final AtomicLong lost = new AtomicLong();
private final AtomicLong logAfter = new AtomicLong();
private volatile Task current;
private volatile boolean closed;
private volatile long resumeAt;
private ScheduledExecutorService executor;
BestEffortAuxiliaryQueue(String kind, int capacity, long maxGroups, boolean retry) {
this.kind = kind;
this.queue = new ArrayBlockingQueue<>(capacity);
this.maxGroups = maxGroups;
this.retry = retry;
}
void start() {
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "syslog-aux-" + kind.toLowerCase(java.util.Locale.ROOT));
t.setDaemon(true);
return t;
});
executor.scheduleWithFixedDelay(this::drain, 0, 200, TimeUnit.MILLISECONDS);
}
boolean offer(int weight, Runnable work) {
boolean reserved = false;
try {
if (closed || weight < 1) { loss("CLOSED_OR_INVALID", null); return false; }
long value;
do {
value = groups.get();
if (weight > maxGroups - value) { loss("GROUP_LIMIT", null); return false; }
} while (!groups.compareAndSet(value, value + weight));
reserved = true;
if (!queue.offer(new Task(weight, work))) { loss("QUEUE_FULL", null); return false; }
reserved = false;
accepted.incrementAndGet();
return true;
} catch (RuntimeException failure) {
loss("ENQUEUE_FAILED", failure);
return false;
} finally {
if (reserved) groups.addAndGet(-weight);
}
}
// 只有后台线程/测试调用;入队和状态查询不获取该锁。
synchronized void drain() {
if (resumeAt != 0L && System.nanoTime() < resumeAt) return;
for (int n = 0; n < 32 && !closed; n++) {
if (current == null) current = queue.poll();
Task task = current;
if (task == null || (task.retryAt != 0L && System.nanoTime() < task.retryAt)) return;
long begin = System.nanoTime();
long queueMs = TimeUnit.NANOSECONDS.toMillis(begin - task.createdAt);
try {
task.work.run();
completed.incrementAndGet();
groups.addAndGet(-task.weight);
current = null;
long workMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin);
if (workMs >= 500 || queueMs >= 500) log.warn(
"[SLOW_SYSLOG_AUX] kind={}, groups={}, queueAgeMs={}, executeMs={}, status=SUCCESS",
kind, task.weight, queueMs, workMs);
} catch (RuntimeException failure) {
failures.incrementAndGet();
if (retry) {
task.retryAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
} else {
groups.addAndGet(-task.weight);
current = null;
lost.incrementAndGet();
}
if (mayLog()) log.error("[SYSLOG_AUX_FAILURE] kind={}, groups={}, queueAgeMs={}, executeMs={}, "
+ "action={}, failuresTotal={}", kind, task.weight, queueMs,
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin),
retry ? "BACKGROUND_RETRY" : "DROP_AUX_ONLY", failures.get(), failure);
return;
}
}
}
void loss(String reason, RuntimeException failure) {
lost.incrementAndGet();
if (mayLog()) log.error("[SYSLOG_AUX_LOSS] kind={}, reason={}, lostTasksTotal={}, action=CONTINUE_FACT_CONSUMPTION",
kind, reason, lost.get(), failure);
}
void pause(long millis) {
resumeAt = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(Math.max(1L, millis));
}
private boolean mayLog() {
long now = System.nanoTime();
long after = logAfter.get();
return (after == 0 || now >= after) && logAfter.compareAndSet(after, now + TimeUnit.SECONDS.toNanos(10));
}
Map<String, Object> status() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("mode", "BEST_EFFORT_BACKGROUND");
result.put("pending_tasks", queue.size() + (current == null ? 0 : 1));
result.put("pending_groups", groups.get());
result.put("max_groups", maxGroups);
result.put("enqueued_total", accepted.get());
result.put("completed_total", completed.get());
result.put("failures_total", failures.get());
result.put("lost_tasks_total", lost.get());
return result;
}
void stop() {
closed = true;
if (executor != null) executor.shutdownNow();
if (groups.get() > 0) log.warn("[SYSLOG_AUX_SHUTDOWN_PENDING] kind={}, pendingGroups={}, action=AUX_DATA_MAY_BE_LOST",
kind, groups.get());
}
private static final class Task {
final int weight;
final Runnable work;
final long createdAt = System.nanoTime();
long retryAt;
Task(int weight, Runnable work) { this.weight = weight; this.work = work; }
}
}
@@ -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);
}
}
/**
@@ -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;
}
}
}
@@ -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;
}
}
@@ -0,0 +1,581 @@
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.sql.SQLException;
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;
import java.util.function.Supplier;
/**
* 把当前事实事务的内存聚合结果交给提交后的有界异步统计队列。
*
* <p>DIRECT 连续消费优先,不写 Outbox 或统计表,统计异常记录后放行。
* 历史 SHADOW 模式仍同步写影子投影,保留原有校验语义。</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;
private final StatsMaterializationPublisher materializationPublisher;
private final StatsProjectionAsyncPublisher asyncPublisher;
@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,
StatsMaterializationPublisher materializationPublisher,
StatsProjectionAsyncPublisher asyncPublisher) {
this.jdbc = jdbc;
this.modeProvider = modeProvider;
this.metrics = metrics;
this.materializationPublisher = materializationPublisher;
this.asyncPublisher = asyncPublisher;
}
public WriteResult writeStandardizedRows(List<Map<String, Object>> rows) {
return project(rows == null ? 0 : rows.size(), () -> accumulator().addStandardizedRows(rows), false);
}
public WriteResult writeStandardizedRow(Map<String, Object> row) {
return project(row == null ? 0 : 1, () -> accumulator().addStandardizedRow(row), false);
}
public WriteResult writeNonNormalRows(List<SyslogNonNormalMessage> messages) {
return project(messages == null ? 0 : messages.size(), () -> accumulator().addNonNormalRows(messages), false);
}
public WriteResult writeNonNormalInsert(SyslogNonNormalMessage message) {
return project(message == null ? 0 : 1, () -> accumulator().addNonNormalInsert(message), false);
}
public WriteResult writeNonNormalUpdate(SyslogNonNormalMessage oldValue, SyslogNonNormalMessage patch) {
return project(oldValue == null || patch == null ? 0 : 1,
() -> accumulator().addNonNormalUpdate(oldValue, patch), true);
}
private WriteResult project(int rows, Supplier<DirectStatsAccumulator> build, boolean exact) {
try {
if (!shouldBuildAggregation()) {
handleFactOnlyMode();
return WriteResult.inactive(rows);
}
long started = System.nanoTime();
DirectStatsAccumulator aggregate = build.get();
return exact ? writeExactDeviceGroups(aggregate, elapsedMs(started))
: write(aggregate, elapsedMs(started));
} catch (RuntimeException failure) {
if (!asynchronousProjection()) throw failure;
metrics.recordFailure();
asyncPublisher.recordLoss(rows, "AGGREGATION_OR_REGISTRATION_FAILED", failure);
return WriteResult.inactive(rows);
}
}
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);
status.put("business_materialization_mode", asynchronousMaterialization()
? "KAFKA_DIRTY_KEY" : "SYNCHRONOUS");
status.put("daily_projection_write_mode", asynchronousProjection()
? "BEST_EFFORT_AFTER_COMMIT_KAFKA" : "SYNCHRONOUS_MERGE");
status.put("async_publisher", asyncPublisher.status());
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();
if (asynchronousProjection()) {
long enqueueStarted = System.nanoTime();
asyncPublisher.enqueueAfterCommit(StatsProjectionOutboxEvent.fromAccumulator(accumulator),
accumulator.getInputRows());
long enqueueMs = elapsedMs(enqueueStarted);
int deviceGroups = effectiveDeviceEntries(accumulator).size();
int ruleGroups = effectiveRuleEntries(accumulator).size();
metrics.recordSuccess(accumulator.getInputRows(), deviceGroups, ruleGroups,
aggregateMs, enqueueMs, 0L);
return WriteResult.direct(accumulator.getInputRows(), deviceGroups, ruleGroups,
aggregateMs, enqueueMs, 0L);
}
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();
if (asynchronousMaterialization()) {
materializationPublisher.enqueueAfterCommit(materializationCommands(devices, rules));
} else {
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 (isConcurrentFailure(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();
// Additive positive/negative changes commute in the serialized projection consumer. This
// keeps non-normal UPDATE statistics outside the fact transaction as well.
if (asynchronousProjection()) {
return write(accumulator, aggregateMs);
}
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();
if (asynchronousMaterialization()) {
materializationPublisher.enqueueAfterCommit(deviceMaterializationCommands(keys));
} else {
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 (isConcurrentFailure(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 boolean asynchronousMaterialization() {
return modeProvider.materializesBusinessFields() && readEnabled
&& materializationPublisher.isEnabled();
}
private boolean asynchronousProjection() {
// 关闭统计发布也绝不回退同步统计SQL,以免再次阻塞事实消费。
return modeProvider.getMode() == StatsWriteModeProvider.Mode.DIRECT;
}
private List<StatsMaterializationCommand> materializationCommands(
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> devices,
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta>> rules) {
List<StatsMaterializationCommand> commands = new ArrayList<>(devices.size() + rules.size());
LocalDate today = LocalDate.now(ZoneId.of(businessZone));
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta> entry : devices) {
DirectStatsAccumulator.DailyKey key = entry.getKey();
if (today.equals(key.getDate())) {
commands.add(StatsMaterializationCommand.device(key.getDate(), key.getDimensionId()));
}
}
for (Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.RuleDelta> entry : rules) {
DirectStatsAccumulator.DailyKey key = entry.getKey();
commands.add(StatsMaterializationCommand.rule(key.getDate(), key.getDimensionId()));
}
return commands;
}
private List<StatsMaterializationCommand> deviceMaterializationCommands(
List<DirectStatsAccumulator.DailyKey> keys) {
List<StatsMaterializationCommand> commands = new ArrayList<>(keys.size());
LocalDate today = LocalDate.now(ZoneId.of(businessZone));
for (DirectStatsAccumulator.DailyKey key : keys) {
if (today.equals(key.getDate())) {
commands.add(StatsMaterializationCommand.device(key.getDate(), key.getDimensionId()));
}
}
return commands;
}
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 达梦事务");
}
}
/**
* 识别 Spring 与不同 JDBC 驱动对并发冲突的各种包装形式。
* 达梦可能把死锁翻译成 DataIntegrityViolationException,并仅在内层
* BatchUpdateException 的 SQLState/消息中保留 Deadlock 信息。
*/
public static boolean isConcurrentFailure(Throwable failure) {
Throwable current = failure;
while (current != null) {
if (current instanceof DuplicateKeyException
|| current instanceof CannotAcquireLockException
|| current instanceof DeadlockLoserDataAccessException) {
return true;
}
if (current instanceof SQLException) {
String sqlState = ((SQLException) current).getSQLState();
if (sqlState != null && sqlState.startsWith("40")) {
return true;
}
}
String message = String.valueOf(current.getMessage())
.toLowerCase(java.util.Locale.ROOT);
if (message.contains("deadlock") || message.contains("死锁")
|| message.contains("unique constraint") || message.contains("duplicate key")) {
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; }
}
}
@@ -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;
}
}
@@ -0,0 +1,82 @@
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 jdbcPlanMs = new AtomicLong();
private final AtomicLong jdbcPlanMaxMs = new AtomicLong();
private final AtomicLong jdbcBindMs = new AtomicLong();
private final AtomicLong jdbcBindMaxMs = new AtomicLong();
private final AtomicLong jdbcExecuteMs = new AtomicLong();
private final AtomicLong jdbcExecuteMaxMs = 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 planDurationMs, long bindDurationMs,
long executeDurationMs, long flushDurationMs, long commitDurationMs,
long transactionDurationMs) {
transactions.incrementAndGet();
factRows.addAndGet(rows);
jdbcPlanMs.addAndGet(planDurationMs);
updateMax(jdbcPlanMaxMs, planDurationMs);
jdbcBindMs.addAndGet(bindDurationMs);
updateMax(jdbcBindMaxMs, bindDurationMs);
jdbcExecuteMs.addAndGet(executeDurationMs);
updateMax(jdbcExecuteMaxMs, executeDurationMs);
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("jdbc_plan_duration_ms_total", jdbcPlanMs.get());
result.put("jdbc_plan_duration_ms_max", jdbcPlanMaxMs.get());
result.put("jdbc_bind_duration_ms_total", jdbcBindMs.get());
result.put("jdbc_bind_duration_ms_max", jdbcBindMaxMs.get());
result.put("jdbc_execute_duration_ms_total", jdbcExecuteMs.get());
result.put("jdbc_execute_duration_ms_max", jdbcExecuteMaxMs.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));
}
}
@@ -0,0 +1,89 @@
package com.common.service;
import com.common.entity.SyslogNonNormalMessage;
import com.common.util.Utf8TextTruncator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.LongAdder;
/** 达梦持久化边界的大字段保护;0 表示兼容模式下不限制。 */
@Component
public class DmLargeTextLimiter {
private static final long MIN_ENABLED_LIMIT = 64L;
@Value("${dm.normal.large-field-max-utf8-bytes:262144}")
private long normalMaxBytes;
@Value("${dm.normal.large-fields:http_req_body,http_resp_body,http_req_header,http_resp_header,detail,description,cmdline,shell_cmdline,parent_cmdline,mail_message}")
private String normalFieldsValue;
@Value("${dm.non-normal.large-field-max-utf8-bytes:262144}")
private long nonNormalMaxBytes;
private volatile Set<String> normalFields = Collections.emptySet();
private final LongAdder normalFieldsTruncated = new LongAdder();
private final LongAdder nonNormalFieldsTruncated = new LongAdder();
@PostConstruct
public void validate() {
validateLimit(normalMaxBytes, "dm.normal.large-field-max-utf8-bytes");
validateLimit(nonNormalMaxBytes, "dm.non-normal.large-field-max-utf8-bytes");
Set<String> parsed = new LinkedHashSet<>();
if (normalFieldsValue != null) {
Arrays.stream(normalFieldsValue.split(","))
.map(String::trim).filter(value -> !value.isEmpty()).forEach(parsed::add);
}
normalFields = Collections.unmodifiableSet(parsed);
}
private static void validateLimit(long value, String name) {
if (value < 0L || (value > 0L && value < MIN_ENABLED_LIMIT)) {
throw new IllegalArgumentException(name + " 必须为 0 或至少 " + MIN_ENABLED_LIMIT);
}
}
public void truncateNormalRow(Map<String, Object> row) {
if (row == null || normalMaxBytes == 0L) return;
for (String field : normalFields) {
Object value = row.get(field);
if (!(value instanceof String)) continue;
Utf8TextTruncator.Result result = Utf8TextTruncator.truncate((String) value, normalMaxBytes);
if (result.isTruncated()) {
row.put(field, result.getValue());
normalFieldsTruncated.increment();
}
}
}
public void truncateNonNormal(SyslogNonNormalMessage message) {
if (message == null || nonNormalMaxBytes == 0L) return;
message.setSyslogMessage(truncateNonNormalValue(message.getSyslogMessage()));
message.setHeaderMessage(truncateNonNormalValue(message.getHeaderMessage()));
message.setReasonDetail(truncateNonNormalValue(message.getReasonDetail()));
}
private String truncateNonNormalValue(String value) {
Utf8TextTruncator.Result result = Utf8TextTruncator.truncate(value, nonNormalMaxBytes);
if (result.isTruncated()) nonNormalFieldsTruncated.increment();
return result.getValue();
}
public long getNormalFieldsTruncated() { return normalFieldsTruncated.sum(); }
public long getNonNormalFieldsTruncated() { return nonNormalFieldsTruncated.sum(); }
/** 测试和非 Spring 兼容入口。 */
static DmLargeTextLimiter unlimited() {
DmLargeTextLimiter limiter = new DmLargeTextLimiter();
limiter.normalMaxBytes = 0L;
limiter.nonNormalMaxBytes = 0L;
limiter.validate();
return limiter;
}
}
@@ -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;
}
/**
@@ -0,0 +1,272 @@
package com.common.service;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 使用一个固定 {@link PreparedStatement} 写入一批标准化事实。
*
* <p>字段白名单和 NULL 的 JDBC 类型从目标表元数据读取并缓存。每个批次只根据字段并集生成
* 一次 INSERT,后续每行只绑定参数和 {@code addBatch()},避免 MyBatis 动态 XML 为每行执行
* 数百次 OGNL 表达式和反射方法查找。</p>
*/
@Component
public class DmPreparedBatchInserter {
static final String NORMAL_TABLE = "syslog_normal_data";
static final String ALARM_TABLE = "syslog_normal_alarm";
private final JdbcTemplate jdbcTemplate;
private final ConcurrentMap<String, TableMetadata> metadataCache = new ConcurrentHashMap<>();
public DmPreparedBatchInserter(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public BatchExecution insert(boolean alarmTable, List<Map<String, Object>> rows,
int statementTimeoutSeconds) {
return insert(alarmTable, rows, statementTimeoutSeconds, new DmWriteSizeEstimate());
}
BatchExecution insert(boolean alarmTable, List<Map<String, Object>> rows,
int statementTimeoutSeconds, DmWriteSizeEstimate writeSize) {
if (rows == null || rows.isEmpty()) {
return BatchExecution.EMPTY;
}
final String table = alarmTable ? ALARM_TABLE : NORMAL_TABLE;
return jdbcTemplate.execute((ConnectionCallback<BatchExecution>) connection ->
execute(connection, table, rows, statementTimeoutSeconds, writeSize));
}
BatchExecution execute(Connection connection, String table, List<Map<String, Object>> rows,
int statementTimeoutSeconds) throws SQLException {
return execute(connection, table, rows, statementTimeoutSeconds, new DmWriteSizeEstimate());
}
BatchExecution execute(Connection connection, String table, List<Map<String, Object>> rows,
int statementTimeoutSeconds, DmWriteSizeEstimate writeSize) throws SQLException {
long planStarted = System.nanoTime();
TableMetadata metadata = metadata(connection, table);
BatchPlan plan = buildPlan(table, rows, metadata);
long planMs = elapsedMillis(planStarted);
// 使用元数据白名单选中的列,排除规则携带但不会实际绑定的字段。
// 执行前完成测量,使JDBC绑定/执行失败时仍可输出这次尝试的数据量。
writeSize.measure(rows, plan.columns);
long bindMs;
long executeMs;
try (PreparedStatement statement = connection.prepareStatement(plan.sql)) {
statement.setQueryTimeout(Math.max(1, statementTimeoutSeconds));
long bindStarted = System.nanoTime();
for (Map<String, Object> row : rows) {
bindRow(statement, row, plan.columns);
statement.addBatch();
}
bindMs = elapsedMillis(bindStarted);
long executeStarted = System.nanoTime();
int[] results = statement.executeBatch();
executeMs = elapsedMillis(executeStarted);
rejectFailedResult(results);
}
return new BatchExecution(rows.size(), plan.columns.size(), planMs, bindMs, executeMs);
}
private TableMetadata metadata(Connection connection, String table) throws SQLException {
TableMetadata cached = metadataCache.get(table);
if (cached != null) {
return cached;
}
TableMetadata loaded = loadMetadata(connection, table);
TableMetadata raced = metadataCache.putIfAbsent(table, loaded);
return raced == null ? loaded : raced;
}
private static TableMetadata loadMetadata(Connection connection, String table) throws SQLException {
validateIdentifier(table);
List<ColumnMetadata> columns = new ArrayList<>();
try (PreparedStatement statement = connection.prepareStatement(
"SELECT * FROM " + table + " WHERE 1=0");
ResultSet resultSet = statement.executeQuery()) {
ResultSetMetaData metadata = resultSet.getMetaData();
for (int index = 1; index <= metadata.getColumnCount(); index++) {
String name = metadata.getColumnName(index);
validateIdentifier(name);
columns.add(new ColumnMetadata(name.toLowerCase(Locale.ROOT), metadata.getColumnType(index)));
}
}
if (columns.isEmpty()) {
throw new SQLException("目标表没有可写字段: " + table);
}
return new TableMetadata(columns);
}
static BatchPlan buildPlan(String table, List<Map<String, Object>> rows, TableMetadata metadata) {
validateIdentifier(table);
Set<String> requestedColumns = new HashSet<>();
for (Map<String, Object> row : rows) {
if (row == null) {
throw new IllegalArgumentException("达梦批写行不能为空");
}
for (Map.Entry<String, Object> entry : row.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
// 标准化字段契约使用小写 snake_case;与旧 Mapper 一致,未知或大小写错误的键忽略。
requestedColumns.add(entry.getKey());
}
}
}
List<ColumnMetadata> selected = new ArrayList<>();
for (ColumnMetadata column : metadata.columns) {
if (requestedColumns.contains(column.name)) {
selected.add(column);
}
}
if (selected.isEmpty()) {
throw new IllegalArgumentException("达梦批写没有目标表允许的非空字段: " + table);
}
StringBuilder sql = new StringBuilder(64 + selected.size() * 12);
sql.append("INSERT INTO ").append(table).append(" (");
for (int index = 0; index < selected.size(); index++) {
if (index > 0) sql.append(',');
sql.append(selected.get(index).name);
}
sql.append(") VALUES (");
for (int index = 0; index < selected.size(); index++) {
if (index > 0) sql.append(',');
sql.append('?');
}
sql.append(')');
return new BatchPlan(sql.toString(), selected);
}
static void bindRow(PreparedStatement statement, Map<String, Object> row,
List<ColumnMetadata> columns) throws SQLException {
for (int index = 0; index < columns.size(); index++) {
ColumnMetadata column = columns.get(index);
Object value = row.get(column.name);
int parameterIndex = index + 1;
if (value == null) {
statement.setNull(parameterIndex, column.jdbcType);
} else if (value instanceof Timestamp) {
statement.setTimestamp(parameterIndex, (Timestamp) value);
} else if (value instanceof java.sql.Date) {
statement.setDate(parameterIndex, (java.sql.Date) value);
} else if (value instanceof java.sql.Time) {
statement.setTime(parameterIndex, (java.sql.Time) value);
} else if (value instanceof java.util.Date) {
statement.setTimestamp(parameterIndex,
new Timestamp(((java.util.Date) value).getTime()));
} else if (value instanceof LocalDateTime) {
statement.setTimestamp(parameterIndex, Timestamp.valueOf((LocalDateTime) value));
} else if (value instanceof LocalDate) {
statement.setDate(parameterIndex, java.sql.Date.valueOf((LocalDate) value));
} else if (value instanceof byte[]) {
statement.setBytes(parameterIndex, (byte[]) value);
} else {
statement.setObject(parameterIndex, value);
}
}
}
private static void rejectFailedResult(int[] results) throws SQLException {
if (results == null) return;
for (int result : results) {
if (result == Statement.EXECUTE_FAILED) {
throw new SQLException("达梦 JDBC batch 返回 EXECUTE_FAILED");
}
}
}
private static void validateIdentifier(String identifier) {
if (identifier == null || !identifier.matches("[A-Za-z_][A-Za-z0-9_$#]*")) {
throw new IllegalArgumentException("非法达梦标识符: " + identifier);
}
}
private static long elapsedMillis(long startedAt) {
return (System.nanoTime() - startedAt) / 1_000_000L;
}
static final class TableMetadata {
final List<ColumnMetadata> columns;
TableMetadata(List<ColumnMetadata> columns) {
this.columns = Collections.unmodifiableList(new ArrayList<>(columns));
}
static TableMetadata of(Map<String, Integer> columns) {
List<ColumnMetadata> result = new ArrayList<>();
for (Map.Entry<String, Integer> entry : new LinkedHashMap<>(columns).entrySet()) {
result.add(new ColumnMetadata(entry.getKey().toLowerCase(Locale.ROOT), entry.getValue()));
}
return new TableMetadata(result);
}
}
static final class ColumnMetadata {
final String name;
final int jdbcType;
ColumnMetadata(String name, int jdbcType) {
validateIdentifier(name);
this.name = name.toLowerCase(Locale.ROOT);
this.jdbcType = jdbcType;
}
}
static final class BatchPlan {
final String sql;
final List<ColumnMetadata> columns;
BatchPlan(String sql, List<ColumnMetadata> columns) {
this.sql = sql;
this.columns = Collections.unmodifiableList(new ArrayList<>(columns));
}
}
public static final class BatchExecution {
static final BatchExecution EMPTY = new BatchExecution(0, 0, 0L, 0L, 0L);
private final int rows;
private final int columns;
private final long planMs;
private final long bindMs;
private final long executeMs;
BatchExecution(int rows, int columns, long planMs, long bindMs, long executeMs) {
this.rows = rows;
this.columns = columns;
this.planMs = planMs;
this.bindMs = bindMs;
this.executeMs = executeMs;
}
public int getRows() { return rows; }
public int getColumns() { return columns; }
public long getPlanMs() { return planMs; }
public long getBindMs() { return bindMs; }
public long getExecuteMs() { return executeMs; }
}
}
@@ -0,0 +1,216 @@
package com.common.service;
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;
/**
* 在一个达梦小事务中执行标准化事实的直接 JDBC batch。
*
* <p>事实表每批只生成一个固定 PreparedStatement,避免逐行解析大型 MyBatis 动态 XML;仅在旧增量
* 捕获兼容开关开启时使用 BATCH SqlSession 追加变更日志。每个
* {@link #execute(boolean, List, int)} 调用都会创建独立事务;失败时整个小批次回滚,上层随后决定
* 二分定位还是按系统故障停止。</p>
*/
@Component
@Slf4j
public class DmStandardizedBatchExecutor {
private final SqlSessionTemplate batchSqlSession;
private final PlatformTransactionManager transactionManager;
private final DmPreparedBatchInserter preparedBatchInserter;
private final StatsChangeCaptureService statsChangeCaptureService;
private final DirectStatsProjectionWriter directStatsProjectionWriter;
private final DmDirectTransactionMetrics transactionMetrics;
private final LateAlarmBucketWriter lateAlarmBucketWriter;
@org.springframework.beans.factory.annotation.Value("${stats.direct.transaction-log-enabled:false}")
private boolean transactionLogEnabled;
@org.springframework.beans.factory.annotation.Value("${syslog.slow-batch.threshold-ms:1000}")
private long slowTransactionThresholdMs;
@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,
DmPreparedBatchInserter preparedBatchInserter,
StatsChangeCaptureService statsChangeCaptureService,
DirectStatsProjectionWriter directStatsProjectionWriter,
DmDirectTransactionMetrics transactionMetrics,
LateAlarmBucketWriter lateAlarmBucketWriter) {
// 该 BATCH Session 仅供旧统计变更日志兼容链路使用;事实行由 preparedBatchInserter 直接批写。
this.batchSqlSession = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
this.transactionManager = transactionManager;
this.preparedBatchInserter = preparedBatchInserter;
this.statsChangeCaptureService = statsChangeCaptureService;
this.directStatsProjectionWriter = directStatsProjectionWriter;
this.transactionMetrics = transactionMetrics;
this.lateAlarmBucketWriter = lateAlarmBucketWriter;
}
/**
* 执行一个同构小批次。
*
* @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();
try {
transaction.execute(status -> {
timing.beginMs = elapsedMs(transactionStarted);
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void beforeCommit(boolean readOnly) {
timing.commitStarted = System.nanoTime();
timing.phase("FACT_COMMIT");
}
@Override
public void afterCommit() {
timing.commitMs = elapsedMs(timing.commitStarted);
}
});
long flushStarted = System.nanoTime();
// 事实表使用一个固定 PreparedStatement 直接 addBatch,彻底绕开逐行 OGNL 动态 SQL。
timing.phase("JDBC_FACT_WRITE");
timing.batchExecution = preparedBatchInserter.insert(
alarmTable, rows, transactionTimeoutSeconds, timing.writeSize);
// 兼容期变更日志仍与事实行共用当前事务;默认关闭时完全不创建 MyBatis BatchSession。
if (statsChangeCaptureService.isEnabled()) {
timing.phase("LEGACY_STATS_CAPTURE");
statsChangeCaptureService.captureStandardizedBatch(batchSqlSession, rows, alarmTable);
batchSqlSession.flushStatements();
}
timing.factFlushMs = elapsedMs(flushStarted);
// 只注册提交后入队;分钟桶在独立后台事务写入,失败不回滚当前告警。
if (alarmTable) {
timing.phase("LATE_BUCKET_REGISTER");
long bucketStarted = System.nanoTime();
lateAlarmBucketWriter.record(rows);
timing.lateBucketMs = elapsedMs(bucketStarted);
}
// DIRECT 只聚合并注册afterCommit入队;此处不写Outbox/统计表、不发送Kafka。
// 独立后台线程发送统计事件,失败不影响事实提交;历史SHADOW模式保留同步MERGE。
timing.phase("STATS_REGISTER");
timing.statsResult = directStatsProjectionWriter.writeStandardizedRows(rows);
return null;
});
} catch (RuntimeException failure) {
log.error("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=FAILED, "
+ "failureStage={}, phaseElapsedMs={}, transactionMs={}, connectionBeginMs={}, "
+ "jdbcExecuteMs={}, lateAlarmBucketMs={}, retry={}, errorType={}, {}",
org.slf4j.MDC.get("syslogBatchId"), alarmTable ? "syslog_normal_alarm" : "syslog_normal_data",
rows.size(), timing.phase, elapsedMs(timing.phaseStarted), elapsedMs(transactionStarted),
timing.beginMs, timing.batchExecution.getExecuteMs(), timing.lateBucketMs, retries,
failure.getClass().getName(), timing.writeSize);
throw failure;
}
long transactionMs = elapsedMs(transactionStarted);
transactionMetrics.recordSuccess(rows.size(), timing.batchExecution.getPlanMs(),
timing.batchExecution.getBindMs(), timing.batchExecution.getExecuteMs(),
timing.factFlushMs, timing.commitMs, transactionMs);
if (slowTransactionThresholdMs > 0 && transactionMs >= slowTransactionThresholdMs) {
log.warn("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=SUCCESS, connectionBeginMs={}, jdbcPlanMs={}, "
+ "jdbcBindMs={}, jdbcExecuteMs={}, lateAlarmBucketMs={}, statsProjectionStageMs={}, "
+ "commitMs={}, transactionMs={}, retry={}, {}",
org.slf4j.MDC.get("syslogBatchId"), alarmTable ? "syslog_normal_alarm" : "syslog_normal_data", rows.size(), timing.beginMs,
timing.batchExecution.getPlanMs(), timing.batchExecution.getBindMs(),
timing.batchExecution.getExecuteMs(), timing.lateBucketMs,
timing.statsResult == null ? 0L : timing.statsResult.getMergeMs(),
timing.commitMs, transactionMs, retries, timing.writeSize);
}
if (transactionLogEnabled && timing.statsResult != null && timing.statsResult.isDirect()) {
log.info("DIRECT 达梦事务完成: factRows={}, deviceGroups={}, ruleGroups={}, aggregateMs={}, " +
"jdbcPlanMs={}, jdbcBindMs={}, jdbcExecuteMs={}, factFlushMs={}, "
+ "statsProjectionStageMs={}, materializeMs={}, commitMs={}, transactionMs={}, retry={}, {}",
rows.size(), timing.statsResult.getDeviceGroups(), timing.statsResult.getRuleGroups(),
timing.statsResult.getAggregateMs(), timing.batchExecution.getPlanMs(),
timing.batchExecution.getBindMs(), timing.batchExecution.getExecuteMs(), timing.factFlushMs,
timing.statsResult.getMergeMs(), timing.statsResult.getMaterializeMs(),
timing.commitMs, transactionMs, retries, timing.writeSize);
}
}
public Map<String, Object> status() {
Map<String, Object> result = transactionMetrics.snapshot();
result.put("late_alarm_bucket_async", lateAlarmBucketWriter.status());
return result;
}
private static long elapsedMs(long startedNanos) {
return startedNanos == 0L ? 0L : (System.nanoTime() - startedNanos) / 1_000_000L;
}
private static final class TransactionTiming {
private final DmWriteSizeEstimate writeSize = new DmWriteSizeEstimate();
private String phase = "CONNECTION_BEGIN";
private long phaseStarted = System.nanoTime();
private void phase(String value) { phase = value; phaseStarted = System.nanoTime(); }
private long beginMs;
private long lateBucketMs;
private long factFlushMs;
private long commitStarted;
private long commitMs;
private DmPreparedBatchInserter.BatchExecution batchExecution =
DmPreparedBatchInserter.BatchExecution.EMPTY;
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);
}
}
}
@@ -0,0 +1,569 @@
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.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;
private final DmLargeTextLimiter largeTextLimiter;
// 未配置时直接启用本次改造的批写路径;SINGLE 只作为现场故障回退开关保留。
@Value("${dm.standardized-write.mode:BATCH}")
private String mode;
@Value("${dm.standardized-write.batch-size:2000}")
private int batchSize;
@Value("${syslog.slow-batch.threshold-ms:1000}")
private long slowQueueThresholdMs;
@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;
@org.springframework.beans.factory.annotation.Autowired
public DmStandardizedBatchWriter(SyslogNormalDataService normalDataService,
DmStandardizedBatchExecutor batchExecutor,
@Qualifier("dmStandardizedWriterExecutor") Executor writerExecutor,
DmLargeTextLimiter largeTextLimiter) {
this.normalDataService = normalDataService;
this.batchExecutor = batchExecutor;
this.writerExecutor = writerExecutor;
this.largeTextLimiter = largeTextLimiter;
}
/** 保留已有单元测试和离线工具入口,默认不改变历史存储内容。 */
public DmStandardizedBatchWriter(SyslogNormalDataService normalDataService,
DmStandardizedBatchExecutor batchExecutor,
Executor writerExecutor) {
this(normalDataService, batchExecutor, writerExecutor, DmLargeTextLimiter.unlimited());
}
/**
* 写入当前 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 {
largeTextLimiter.truncateNormalRow(request.getData());
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()) {
long queuedAt = System.nanoTime();
String batchId = org.slf4j.MDC.get("syslogBatchId");
futures.add(CompletableFuture.supplyAsync(() -> {
String previous = org.slf4j.MDC.get("syslogBatchId");
if (batchId != null) org.slf4j.MDC.put("syslogBatchId", batchId);
else org.slf4j.MDC.remove("syslogBatchId");
try {
long queueMs = (System.nanoTime() - queuedAt) / 1_000_000L;
if (slowQueueThresholdMs > 0 && queueMs >= slowQueueThresholdMs) {
log.warn("[SLOW_DM_QUEUE] batchId={}, alarmTable={}, rows={}, queueMs={}",
batchId, entry.getKey().alarmTable, entry.getValue().size(), queueMs);
}
WriteReport<T> groupReport = new WriteReport<>();
writeGroup(entry.getKey(), entry.getValue(), groupReport, budget);
return groupReport;
} finally {
if (previous == null) org.slf4j.MDC.remove("syslogBatchId");
else org.slf4j.MDC.put("syslogBatchId", previous);
}
}, 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"));
return new BatchKey(alarmTable, partitionDate);
}
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 BatchKey(boolean alarmTable, LocalDate partitionDate) {
this.alarmTable = alarmTable;
this.partitionDate = partitionDate;
}
@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);
}
@Override
public int hashCode() {
return Objects.hash(alarmTable, partitionDate);
}
}
/** 所有递归分支共享同一预算,防止多条坏数据把一个 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());
}
}
}
}
@@ -0,0 +1,107 @@
package com.common.service;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
/**
* JDBC参数内容大小估算,不是网络包、数据库页或REDO大小。
* 只统计实际INSERT字段,调用位置在截断/字段准备之后、绑定/执行之前。
* 不读取LOB或流,不序列化任意对象,不保留字段值,不创建大字符串的UTF-8副本。
*/
final class DmWriteSizeEstimate {
private String status = "NOT_MEASURED";
private long payloadBytes;
private long maxRowBytes;
private long maxFieldBytes;
private String maxFieldName = "none";
private long unmeasuredValues;
private long elapsedMs;
void measure(List<Map<String, Object>> rows, List<DmPreparedBatchInserter.ColumnMetadata> columns) {
long started = System.nanoTime();
try {
for (Map<String, Object> row : rows) {
long rowBytes = 0L;
for (DmPreparedBatchInserter.ColumnMetadata column : columns) {
long bytes = valueBytes(row.get(column.name));
if (bytes < 0L) {
unmeasuredValues++;
continue;
}
rowBytes += bytes;
if (bytes > maxFieldBytes) {
maxFieldBytes = bytes;
maxFieldName = column.name;
}
}
payloadBytes += rowBytes;
maxRowBytes = Math.max(maxRowBytes, rowBytes);
}
status = unmeasuredValues == 0L ? "COMPLETE" : "PARTIAL";
} catch (RuntimeException diagnosticFailure) {
// 观测失败不能改变事实写入行为;不记录异常消息,避免携带字段内容。
status = "FAILED";
} finally {
elapsedMs = (System.nanoTime() - started) / 1_000_000L;
}
}
static long valueBytes(Object value) {
if (value == null) return 0L;
if (value instanceof String) return utf8Length((String) value);
if (value instanceof byte[]) return ((byte[]) value).length;
// 只对已知标量计其文本表示,避免任意对象toString触发IO或泄漏内容。
Class<?> type = value.getClass();
if (type == Boolean.class || type == Character.class || type == Byte.class
|| type == Short.class || type == Integer.class || type == Long.class
|| type == Float.class || type == Double.class || type == BigDecimal.class
|| type == BigInteger.class || type == LocalDate.class || type == LocalDateTime.class
|| type == Timestamp.class || type == java.sql.Date.class || type == java.sql.Time.class) {
return utf8Length(value.toString());
}
if (type == java.util.Date.class) {
return utf8Length(new Timestamp(((java.util.Date) value).getTime()).toString());
}
return -1L;
}
/** 与JDK8 String.getBytes(UTF_8)一致:有效代理对4字节,孤立代理字符替换为一个问号字节。 */
static long utf8Length(String text) {
long bytes = 0L;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (ch < 0x80) bytes++;
else if (ch < 0x800) bytes += 2L;
else if (Character.isHighSurrogate(ch) && i + 1 < text.length()
&& Character.isLowSurrogate(text.charAt(i + 1))) {
bytes += 4L;
i++;
} else if (Character.isSurrogate(ch)) bytes++;
else bytes += 3L;
}
return bytes;
}
long getPayloadBytes() { return payloadBytes; }
long getMaxRowBytes() { return maxRowBytes; }
long getMaxFieldBytes() { return maxFieldBytes; }
String getMaxFieldName() { return maxFieldName; }
long getUnmeasuredValues() { return unmeasuredValues; }
String getStatus() { return status; }
@Override
public String toString() {
return "sizeEstimateStatus=" + status
+ ", estimatedPayloadBytes=" + payloadBytes
+ ", maxRowEstimatedBytes=" + maxRowBytes
+ ", maxFieldEstimatedBytes=" + maxFieldBytes
+ ", maxFieldName=" + maxFieldName
+ ", unmeasuredValues=" + unmeasuredValues
+ ", sizeEstimateMs=" + elapsedMs;
}
}
@@ -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;
}
}
@@ -0,0 +1,140 @@
package com.common.service;
import com.Modules.NormalData.SyslogFailureRouter;
import com.common.entity.IngressStatsEvent;
import com.common.util.Sm4Util;
import com.common.util.SyslogParser;
import com.config.AppProperties;
import com.influx.raw.ReceiveTimeParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/** 独立消费原始Topic,只维护接收时间;不执行规则、采样或事实表写入。 */
@Component
@Slf4j
public class IngressStatsConsumer {
private final IngressStatsProjectionWriter writer;
private final SyslogFailureRouter failureRouter;
private final AppProperties appProperties;
private final AtomicLong batches = new AtomicLong();
private final AtomicLong invalidAttempts = new AtomicLong();
private final AtomicLong writeFailures = new AtomicLong();
@Value("${spring.kafka.consumer.group-id}") private String rawGroup;
@Value("${syslog.large-listener.group-id:${spring.kafka.consumer.group-id}-large}")
private String largeRawGroup;
@Value("${stats.ingress-metadata.group-id:${spring.kafka.consumer.group-id}-ingress-v1}")
private String group;
@Value("${stats.ingress-metadata.large-group-id:${stats.ingress-metadata.group-id}-large}")
private String largeGroup;
public IngressStatsConsumer(IngressStatsProjectionWriter writer,
SyslogFailureRouter failureRouter, AppProperties appProperties) {
this.writer = writer;
this.failureRouter = failureRouter;
this.appProperties = appProperties;
}
@PostConstruct
public void validateGroups() {
if (group == null || group.trim().isEmpty() || largeGroup == null || largeGroup.trim().isEmpty()
|| group.equals(largeGroup) || group.equals(rawGroup) || group.equals(largeRawGroup)
|| largeGroup.equals(rawGroup) || largeGroup.equals(largeRawGroup)) {
throw new IllegalStateException("入口统计必须使用与主消费隔离的非空 Kafka group-id");
}
log.info("Ingress stats consumer ready: group={}, largeGroup={}, mode=INDEPENDENT_KAFKA_DIRECT_MERGE",
group, largeGroup);
}
@KafkaListener(id = "syslog-ingress-stats", groupId = "${stats.ingress-metadata.group-id}",
topics = "${spring.kafka.consumer.topic}",
autoStartup = "${stats.ingress-metadata.enabled:true}",
containerFactory = "ingressStatsKafkaListenerContainerFactory")
public void consume(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
consumeBatch(records, ack, "RAW");
}
@KafkaListener(id = "syslog-ingress-stats-large", groupId = "${stats.ingress-metadata.large-group-id}",
topics = "${spring.kafka.consumer.large-topic}",
autoStartup = "#{${stats.ingress-metadata.enabled:true} && ${syslog.large-listener.enabled:true}}",
containerFactory = "largeIngressStatsKafkaListenerContainerFactory")
public void consumeLarge(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
consumeBatch(records, ack, "RAW_LARGE");
}
private void consumeBatch(List<ConsumerRecord<String, String>> records, Acknowledgment ack, String lane) {
long started = System.nanoTime();
List<IngressStatsEvent> events = new ArrayList<>(records.size());
int invalid = 0;
String firstInvalid = null;
for (ConsumerRecord<String, String> record : records) {
try {
events.add(decode(record));
} catch (RuntimeException malformed) {
invalid++;
if (firstInvalid == null) firstInvalid = record.topic() + "-" + record.partition()
+ "@" + record.offset() + ":" + malformed.getClass().getSimpleName();
}
}
if (invalid > 0) {
invalidAttempts.addAndGet(invalid);
// 原始消息仍留在Kafka;坏头不会永久挡住其它设备接收状态,也不向业务Retry重复投递。
log.error("[INGRESS_STATS_INVALID] lane={}, invalidRecords={}, firstInvalid={}, "
+ "action=SKIP_INVALID_METADATA", lane, invalid, firstInvalid);
}
int groups;
try {
groups = writer.writeBatch(events);
} catch (RuntimeException failure) {
writeFailures.incrementAndGet();
log.error("[INGRESS_STATS_WRITE_FAILED] lane={}, records={}, action=RETRY_STATS_GROUP",
lane, records.size(), failure);
throw failure;
}
// MIN/MAX更新和达梦提交均已完成,才推进独立统计组;重复消费不重复增加事实数量。
ack.acknowledge();
batches.incrementAndGet();
log.info("[INGRESS_STATS_BATCH] lane={}, records={}, valid={}, invalid={}, groups={}, totalMs={}",
lane, records.size(), events.size(), invalid, groups, (System.nanoTime() - started) / 1_000_000L);
}
IngressStatsEvent decode(ConsumerRecord<String, String> record) {
SyslogFailureRouter.MessageContext context = failureRouter.resolve(record);
String decrypted = Sm4Util.decryptCbc(context.getPayload(), appProperties.getSm4Key());
if (decrypted.indexOf(']') < 0) throw new IllegalArgumentException("缺少设备元数据头");
Map<String, String> header = SyslogParser.parseKeyValuePairs(
SyslogParser.substringBeforeFirstChar(decrypted, ']'));
Long device = positiveId(header.get("device_id"));
Long collector = positiveId(header.get("device_collect_id"));
if (device == null && collector == null) throw new IllegalArgumentException("缺少有效设备/采集任务ID");
return new IngressStatsEvent(context.getEventId(), device, collector,
ReceiveTimeParser.parse(header.get("receive_time")).getLocalDateTime());
}
private static Long positiveId(String value) {
if (value == null || value.trim().isEmpty()) return null;
long parsed = Long.parseLong(value);
return parsed > 0L ? parsed : null;
}
public Map<String, Object> status() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("group_id", group);
result.put("large_group_id", largeGroup);
result.put("successful_batches", batches.get());
result.put("invalid_record_attempts", invalidAttempts.get());
result.put("write_failures", writeFailures.get());
return result;
}
}
@@ -0,0 +1,247 @@
package com.common.service;
import com.common.entity.IngressStatsEvent;
import org.springframework.beans.factory.annotation.Value;
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.ArrayList;
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;
private final StatsMaterializationPublisher materializationPublisher;
@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,
StatsMaterializationPublisher materializationPublisher) {
this.jdbc = jdbc;
this.transactionManager = transactionManager;
this.modeProvider = modeProvider;
this.materializationPublisher = materializationPublisher;
}
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("business_materialization_mode", asynchronousMaterialization()
? "KAFKA_DIRTY_KEY" : "SYNCHRONOUS");
status.put("daily_projection_write_mode", "INDEPENDENT_KAFKA_DIRECT_MERGE");
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 DirectStatsProjectionWriter.isConcurrentFailure(failure);
}
private int writeAggregation(Aggregation aggregation) {
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
Integer updated = transaction.execute(status -> {
int groups = 0;
boolean asyncMaterialization = asynchronousMaterialization();
List<StatsMaterializationCommand> commands = asyncMaterialization
? new ArrayList<>(aggregation.devices.size() + aggregation.collects.size())
: null;
LocalDate today = LocalDate.now(ZoneId.of(businessZone));
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 && today.equals(key.date)) {
if (asyncMaterialization) {
commands.add(StatsMaterializationCommand.device(key.date, key.deviceId));
} else {
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) {
if (asyncMaterialization) {
commands.add(StatsMaterializationCommand.collect(entry.getKey()));
} else {
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++;
}
if (asyncMaterialization) {
materializationPublisher.enqueueAfterCommit(commands);
}
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 boolean asynchronousMaterialization() {
return modeProvider.materializesBusinessFields() && readEnabled
&& materializationPublisher.isEnabled();
}
private static String safeTable(String table) {
if (table == null || !table.matches("[A-Za-z][A-Za-z0-9_]*")) {
throw new IllegalStateException("非法入口设备统计表名: " + table);
}
return table;
}
}
@@ -0,0 +1,190 @@
package com.common.service;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
/**
* 告警提交后登记事件时间桶,后台独立事务失败只重试通知,不回滚告警。
*
* <p>该通知不是“告警一定迟到”的结论。事实提交后才入队;下游能领取通知时,事实必然
* 已经可见,再根据领取时已经完成的规则窗口决定是否重放。这里刻意不使用事实的
* {@code created_at} 判断提交先后,因为 Kafka 积压时接收时间可能早于实际入库时间。
*/
@Component
public class LateAlarmBucketWriter {
private static final String UPSERT_SQL =
"MERGE INTO analysis_late_alarm_bucket t "
+ "USING (SELECT ? device_id, ? bucket_start FROM dual) s "
+ "ON (t.device_id=s.device_id AND t.bucket_start=s.bucket_start) "
+ "WHEN MATCHED THEN UPDATE SET "
+ "t.requested_generation=t.requested_generation+1, "
+ "t.last_observed_at=SYSDATE, "
+ "t.status=CASE WHEN t.status='RUNNING' THEN 'RUNNING' ELSE 'PENDING' END, "
+ "t.updated_at=SYSDATE "
+ "WHEN NOT MATCHED THEN INSERT "
+ "(id,device_id,bucket_start,bucket_end,last_observed_at,requested_generation,"
+ "claimed_generation,processed_generation,status,attempt_count,fencing_token,created_at,updated_at) "
+ "VALUES (?,?,?,?,SYSDATE,1,0,0,'PENDING',0,0,SYSDATE,SYSDATE)";
private final JdbcTemplate jdbcTemplate;
private final PlatformTransactionManager transactionManager;
private final BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("LATE_ALARM_BUCKET", 256, 50000, true);
@Value("${analysis.late-replay.notify-timeout-seconds:5}")
private int transactionTimeoutSeconds = 5;
@javax.annotation.PostConstruct public void start() { queue.start(); }
@javax.annotation.PreDestroy public void stop() { queue.stop(); }
public Map<String, Object> status() { return queue.status(); }
@Value("${analysis.late-replay.outbox-enabled:true}")
private boolean enabled;
public LateAlarmBucketWriter(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
this.jdbcTemplate = jdbcTemplate;
this.transactionManager = transactionManager;
}
/**
* 每个设备每分钟只写一条通知。调用方必须已经开启标准化事实事务。
*
* @param rows 已确认写入 {@code syslog_normal_alarm} 的同构小批次
*/
public void record(List<Map<String, Object>> rows) {
if (!enabled || rows == null || rows.isEmpty()) {
return;
}
try {
// 只保留设备/分钟的小键,不把原始日志和事实行滞留在后台队列。
Set<BucketKey> buckets = buckets(rows);
if (!TransactionSynchronizationManager.isActualTransactionActive()
|| !TransactionSynchronizationManager.isSynchronizationActive()) {
throw new IllegalStateException("迟到告警通知必须在事实提交后入队");
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() {
queue.offer(buckets.size(), () -> writeBuckets(buckets));
}
});
} catch (RuntimeException failure) {
queue.loss("PREPARE_OR_REGISTER_FAILED", failure);
}
}
private Set<BucketKey> buckets(List<Map<String, Object>> rows) {
// 不同Kafka批次可能含有相反顺序的设备/分钟,统一加锁顺序避免交叉等待。
Set<BucketKey> buckets = new TreeSet<>(Comparator
.comparing((BucketKey key) -> key.deviceId).thenComparing(key -> key.bucketStart));
for (Map<String, Object> row : rows) {
Integer deviceId = integerValue(row.get("device_id"));
LocalDateTime eventTime = timeValue(row.get("log_time"));
if (deviceId == null || eventTime == null) {
throw new IllegalArgumentException("迟到告警通知缺少 device_id 或 log_time");
}
buckets.add(new BucketKey(deviceId, eventTime.truncatedTo(ChronoUnit.MINUTES)));
}
return buckets;
}
private void writeBuckets(Set<BucketKey> buckets) {
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
transaction.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
transaction.execute(status -> {
for (BucketKey key : buckets) {
LocalDateTime bucketEnd = key.bucketStart.plusMinutes(1);
try {
jdbcTemplate.update(
UPSERT_SQL,
key.deviceId,
Timestamp.valueOf(key.bucketStart),
UUID.randomUUID().toString(),
key.deviceId,
Timestamp.valueOf(key.bucketStart),
Timestamp.valueOf(bucketEnd));
} catch (RuntimeException failure) {
// 多个 Kafka 分区可能同时首次写同一设备分钟,MERGE 的并发插入会竞争唯一键。
// 仅后台通知事务回滚重试,绝不返回事实事务。
if (isConcurrentWrite(failure)) {
throw new DirectStatsProjectionWriter.ConcurrentStatsWriteException(
"迟到告警分钟桶并发写入失败,仅后台通知事务回滚重试", failure);
}
throw failure;
}
}
return null;
});
}
private Integer integerValue(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return null;
}
return Integer.valueOf(value.toString());
}
private LocalDateTime timeValue(Object value) {
if (value instanceof LocalDateTime) {
return (LocalDateTime) value;
}
if (value instanceof Timestamp) {
return ((Timestamp) value).toLocalDateTime();
}
if (value instanceof java.util.Date) {
return new Timestamp(((java.util.Date) value).getTime()).toLocalDateTime();
}
return null;
}
private boolean isConcurrentWrite(Throwable failure) {
return DirectStatsProjectionWriter.isConcurrentFailure(failure);
}
private static final class BucketKey {
private final Integer deviceId;
private final LocalDateTime bucketStart;
private BucketKey(Integer deviceId, LocalDateTime bucketStart) {
this.deviceId = deviceId;
this.bucketStart = bucketStart;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof BucketKey)) {
return false;
}
BucketKey that = (BucketKey) other;
return Objects.equals(deviceId, that.deviceId)
&& Objects.equals(bucketStart, that.bucketStart);
}
@Override
public int hashCode() {
return Objects.hash(deviceId, bucketStart);
}
}
}
@@ -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;
}
@@ -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;
}
// 遍历所有过滤组,只要满足任一过滤组即可
@@ -0,0 +1,62 @@
package com.common.service;
import com.common.entity.SyslogNonNormalMessage;
import com.common.util.Utf8TextTruncator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/** 普通来源消息完成规则和采样后,限制非告警达梦输出文本;调用方排除告警,不修改规则输入和InfluxDB原文。 */
@Component
public class RawLaneFieldLimiter {
// 这些字段参与幂等、路由、分区或关联,不允许截断改变其语义。
private static final Set<String> IDENTITY_FIELDS = new HashSet<>(Arrays.asList(
"id", "syslog_uuid", "syslog_topic", "normalize_rule_id", "rule_version",
"device_id", "tenant_id", "agent_id", "origin_agent_id", "collect_task_id",
"log_time", "created_at", "receive_time", "event_level"));
private final long maxBytes;
private final String rawTopic;
public RawLaneFieldLimiter(
@Value("${syslog.raw-listener.field-max-utf8-bytes:2048}") long maxBytes,
@Value("${spring.kafka.consumer.topic}") String rawTopic) {
if (maxBytes < 0 || (maxBytes > 0 && maxBytes < 64)) {
throw new IllegalArgumentException("syslog.raw-listener.field-max-utf8-bytes 必须为0或至少64");
}
this.maxBytes = maxBytes;
this.rawTopic = rawTopic;
}
public boolean appliesTo(String currentTopic, String originalTopic) {
String sourceTopic = originalTopic == null || originalTopic.isEmpty() ? currentTopic : originalTopic;
return maxBytes > 0 && rawTopic != null && rawTopic.equals(sourceTopic);
}
/** 包括自定义映射文本,不限于旧的大字段白名单;数值、日期、二进制值保持原类型。 */
public void truncateRow(Map<String, Object> row) {
if (row == null || maxBytes == 0) return;
for (Map.Entry<String, Object> entry : row.entrySet()) {
if (entry.getValue() instanceof String && !IDENTITY_FIELDS.contains(entry.getKey())) {
entry.setValue(truncate((String) entry.getValue()));
}
}
}
public void truncateNonNormal(SyslogNonNormalMessage message) {
if (message == null || maxBytes == 0) return;
message.setSyslogMessage(truncate(message.getSyslogMessage()));
message.setHeaderMessage(truncate(message.getHeaderMessage()));
message.setReasonDetail(truncate(message.getReasonDetail()));
}
private String truncate(String value) {
// 每个UTF-16代码单元最多占3个UTF-8字节,短字段无需分配UTF-8数组。
if (value == null || (long) value.length() * 3L <= maxBytes) return value;
return Utf8TextTruncator.truncate(value, maxBytes).getValue();
}
}

Some files were not shown because too many files have changed in this diff Show More