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参数调整。
This commit is contained in:
王绍宏
2026-09-14 23:11:45 +08:00
parent 7e6b2fc4dc
commit 1c07acc01d
17 changed files with 3131 additions and 43 deletions
@@ -0,0 +1,304 @@
package com.common.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/** Redis只保存每个消费实例的有界候选集,用于多实例汇聚,不承载逐条日志流。 */
@Slf4j
@Component
public class RawLogCaptureClusterStore {
private static final String PREFIX = "hb:xdr:raw-capture:";
private static final String ACTIVE_KEY = PREFIX + "active";
private static final TypeReference<Map<String, Object>> MAP_TYPE =
new TypeReference<Map<String, Object>>() { };
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
private final String nodeId;
private final AtomicLong lastFailureLogAt = new AtomicLong();
@Value("${syslog.raw-capture.cluster-activation-delay-ms:1000}")
private long activationDelayMs = 1000L;
public RawLogCaptureClusterStore(StringRedisTemplate redis, ObjectMapper mapper,
@Value("${syslog.raw-capture.node-id:${HOSTNAME:unknown}}")
String configuredNodeId) {
this.redis = redis;
this.mapper = mapper;
this.nodeId = "unknown".equals(configuredNodeId)
? UUID.randomUUID().toString() : configuredNodeId;
}
Definition create(long deviceId, int durationSeconds, int settleSeconds, int messageCount,
int maxActiveSessions, int retentionMinutes) {
try {
long now = System.currentTimeMillis();
redis.opsForZSet().removeRangeByScore(ACTIVE_KEY, 0D, now - 1D);
Long active = redis.opsForZSet().zCard(ACTIVE_KEY);
if (active != null && active >= maxActiveSessions) {
throw new RawLogCaptureService.CaptureCapacityException(maxActiveSessions);
}
long startedAt = now + Math.max(200L, activationDelayMs);
Definition definition = new Definition(UUID.randomUUID().toString(), deviceId,
startedAt, startedAt + durationSeconds * 1000L,
startedAt + (durationSeconds + settleSeconds) * 1000L, messageCount,
retentionMinutes);
String metaKey = metaKey(definition.id);
redis.opsForHash().putAll(metaKey, definition.toHash());
redis.expire(metaKey, definition.ttlSeconds(now), TimeUnit.SECONDS);
redis.opsForZSet().add(ACTIVE_KEY, definition.id, definition.settleEndsAt);
return definition;
} catch (RawLogCaptureService.CaptureCapacityException failure) {
throw failure;
} catch (RuntimeException failure) {
throw new RawLogCaptureService.CaptureCoordinationException(failure);
}
}
List<Definition> active(long now) {
redis.opsForZSet().removeRangeByScore(ACTIVE_KEY, 0D, now - 1D);
Set<String> ids = redis.opsForZSet().rangeByScore(ACTIVE_KEY, now, Double.MAX_VALUE);
if (ids == null || ids.isEmpty()) return Collections.emptyList();
List<Definition> result = new ArrayList<>(ids.size());
for (String id : ids) {
Definition definition = definition(id);
if (definition != null && definition.stoppedAt == 0L) result.add(definition);
}
return result;
}
void publish(RawLogCaptureService.CaptureCandidates candidates) {
try {
Definition definition = definition(candidates.getSessionId());
if (definition == null || definition.stoppedAt > 0L) return;
String snapshotKey = snapshotKey(candidates.getSessionId(), nodeId);
redis.opsForValue().set(snapshotKey, mapper.writeValueAsString(toMap(candidates)),
definition.ttlSeconds(System.currentTimeMillis()), TimeUnit.SECONDS);
String nodesKey = nodesKey(candidates.getSessionId());
redis.opsForSet().add(nodesKey, nodeId);
redis.expire(nodesKey, definition.ttlSeconds(System.currentTimeMillis()), TimeUnit.SECONDS);
} catch (Exception failure) {
throw new RawLogCaptureService.CaptureCoordinationException(failure);
}
}
RawLogCaptureService.CaptureSnapshot get(String sessionId) {
try {
Definition definition = definition(sessionId);
if (definition == null) return null;
Set<String> nodes = redis.opsForSet().members(nodesKey(sessionId));
List<RawLogCaptureService.CapturedLogSnapshot> first = new ArrayList<>();
List<RawLogCaptureService.CapturedLogSnapshot> anomalies = new ArrayList<>();
long received = 0L, processed = 0L, observedAnomalies = 0L;
if (nodes != null) {
for (String node : nodes) {
String json = redis.opsForValue().get(snapshotKey(sessionId, node));
if (json == null) continue;
Map<String, Object> candidate = mapper.readValue(json, MAP_TYPE);
received += longValue(candidate.get("receivedCount"));
processed += longValue(candidate.get("processedCount"));
observedAnomalies += longValue(candidate.get("observedAnomalyCount"));
first.addAll(messages(candidate.get("firstMessages")));
anomalies.addAll(messages(candidate.get("firstAnomalies")));
}
}
List<RawLogCaptureService.CapturedLogSnapshot> selected =
RawLogCaptureService.mergeCandidates(first, anomalies, definition.messageCount);
int retainedAnomalies = 0;
for (RawLogCaptureService.CapturedLogSnapshot message : selected) {
if (message.isAnomaly()) retainedAnomalies++;
}
long replacements = replacementCount(first, anomalies, definition.messageCount);
long now = System.currentTimeMillis();
return new RawLogCaptureService.CaptureSnapshot(definition.id, definition.deviceId,
definition.status(now), RawLogCaptureService.instant(definition.startedAt),
RawLogCaptureService.instant(definition.captureEndsAt),
RawLogCaptureService.instant(definition.settleEndsAt), definition.messageCount,
received, processed, observedAnomalies, retainedAnomalies, replacements, selected);
} catch (RawLogCaptureService.CaptureCoordinationException failure) {
throw failure;
} catch (Exception failure) {
throw new RawLogCaptureService.CaptureCoordinationException(failure);
}
}
RawLogCaptureService.CaptureSnapshot stop(String sessionId) {
try {
Definition definition = definition(sessionId);
if (definition == null) return null;
redis.opsForHash().put(metaKey(sessionId), "stoppedAt",
String.valueOf(System.currentTimeMillis()));
redis.opsForZSet().remove(ACTIVE_KEY, sessionId);
return get(sessionId);
} catch (RawLogCaptureService.CaptureCoordinationException failure) {
throw failure;
} catch (RuntimeException failure) {
throw new RawLogCaptureService.CaptureCoordinationException(failure);
}
}
void recordSyncFailure(RuntimeException failure) {
long now = System.currentTimeMillis(), previous = lastFailureLogAt.get();
if (now - previous >= 30_000L && lastFailureLogAt.compareAndSet(previous, now)) {
log.warn("原始日志采样跨实例同步失败;不影响主消费链路: {}", failure.getMessage());
}
}
private Definition definition(String id) {
Map<Object, Object> values = redis.opsForHash().entries(metaKey(id));
return values == null || values.isEmpty() ? null : Definition.from(id, values);
}
private Map<String, Object> toMap(RawLogCaptureService.CaptureCandidates candidates) {
Map<String, Object> value = new LinkedHashMap<>();
value.put("receivedCount", candidates.getReceivedCount());
value.put("processedCount", candidates.getProcessedCount());
value.put("observedAnomalyCount", candidates.getObservedAnomalyCount());
value.put("firstMessages", candidates.getFirstMessages());
value.put("firstAnomalies", candidates.getFirstAnomalies());
return value;
}
@SuppressWarnings("unchecked")
private List<RawLogCaptureService.CapturedLogSnapshot> messages(Object value) {
if (!(value instanceof List)) return Collections.emptyList();
List<RawLogCaptureService.CapturedLogSnapshot> result = new ArrayList<>();
for (Object item : (List<?>) value) {
if (!(item instanceof Map)) continue;
Map<String, Object> map = (Map<String, Object>) item;
Object receivedAt = map.get("receivedAt");
result.add(new RawLogCaptureService.CapturedLogSnapshot(
longValue(map.get("sequence")), string(map.get("eventId")),
nullableLong(map.get("deviceId")), nullableLong(map.get("deviceCollectId")),
string(map.get("topic")), localDateTime(receivedAt), string(map.get("observedAt")),
string(map.get("processingStatus")), booleanValue(map.get("anomaly")),
string(map.get("reason")), string(map.get("reasonDetail")),
string(map.get("processedAt")), string(map.get("rawMessage"))));
}
return result;
}
private long replacementCount(List<RawLogCaptureService.CapturedLogSnapshot> first,
List<RawLogCaptureService.CapturedLogSnapshot> anomalies, int limit) {
int finalAnomalies = 0, initialAnomalies = 0;
for (RawLogCaptureService.CapturedLogSnapshot value
: RawLogCaptureService.mergeCandidates(first, anomalies, limit)) {
if (value.isAnomaly()) finalAnomalies++;
}
List<RawLogCaptureService.CapturedLogSnapshot> initial =
RawLogCaptureService.mergeCandidates(first, Collections.emptyList(), limit);
for (RawLogCaptureService.CapturedLogSnapshot value : initial) {
if (value.isAnomaly()) initialAnomalies++;
}
return Math.max(0, finalAnomalies - initialAnomalies);
}
private static String metaKey(String id) { return PREFIX + "{" + id + "}:meta"; }
private static String nodesKey(String id) { return PREFIX + "{" + id + "}:nodes"; }
private static String snapshotKey(String id, String node) {
return PREFIX + "{" + id + "}:node:" + node;
}
private static String string(Object value) { return value == null ? null : String.valueOf(value); }
private static long longValue(Object value) {
return value == null ? 0L : Long.parseLong(String.valueOf(value));
}
private static Long nullableLong(Object value) {
return value == null ? null : Long.valueOf(String.valueOf(value));
}
private static boolean booleanValue(Object value) {
return value != null && Boolean.parseBoolean(String.valueOf(value));
}
private static LocalDateTime localDateTime(Object value) {
if (value == null) return null;
if (value instanceof List) {
List<?> parts = (List<?>) value;
if (parts.size() >= 6) {
int nano = parts.size() >= 7 ? ((Number) parts.get(6)).intValue() : 0;
return LocalDateTime.of(((Number) parts.get(0)).intValue(),
((Number) parts.get(1)).intValue(), ((Number) parts.get(2)).intValue(),
((Number) parts.get(3)).intValue(), ((Number) parts.get(4)).intValue(),
((Number) parts.get(5)).intValue(), nano);
}
}
return LocalDateTime.parse(String.valueOf(value));
}
static final class Definition {
private final String id;
private final long deviceId;
private final long startedAt;
private final long captureEndsAt;
private final long settleEndsAt;
private final int messageCount;
private final int retentionMinutes;
private final long stoppedAt;
Definition(String id, long deviceId, long startedAt, long captureEndsAt,
long settleEndsAt, int messageCount, int retentionMinutes) {
this(id, deviceId, startedAt, captureEndsAt, settleEndsAt, messageCount,
retentionMinutes, 0L);
}
private Definition(String id, long deviceId, long startedAt, long captureEndsAt,
long settleEndsAt, int messageCount, int retentionMinutes,
long stoppedAt) {
this.id = id; this.deviceId = deviceId; this.startedAt = startedAt;
this.captureEndsAt = captureEndsAt; this.settleEndsAt = settleEndsAt;
this.messageCount = messageCount; this.retentionMinutes = retentionMinutes;
this.stoppedAt = stoppedAt;
}
private Map<String, String> toHash() {
Map<String, String> value = new LinkedHashMap<>();
value.put("deviceId", String.valueOf(deviceId));
value.put("startedAt", String.valueOf(startedAt));
value.put("captureEndsAt", String.valueOf(captureEndsAt));
value.put("settleEndsAt", String.valueOf(settleEndsAt));
value.put("messageCount", String.valueOf(messageCount));
value.put("retentionMinutes", String.valueOf(retentionMinutes));
value.put("stoppedAt", String.valueOf(stoppedAt));
return value;
}
private static Definition from(String id, Map<Object, Object> map) {
return new Definition(id, longValue(map.get("deviceId")), longValue(map.get("startedAt")),
longValue(map.get("captureEndsAt")), longValue(map.get("settleEndsAt")),
(int) longValue(map.get("messageCount")),
(int) longValue(map.get("retentionMinutes")), longValue(map.get("stoppedAt")));
}
private long ttlSeconds(long now) {
long remainingMillis = Math.max(0L, settleEndsAt - now);
return Math.max(60L, (remainingMillis + 999L) / 1000L
+ retentionMinutes * 60L);
}
private String status(long now) {
if (stoppedAt > 0L) return "CANCELLED";
if (now < startedAt) return "SCHEDULED";
if (now <= captureEndsAt) return "RUNNING";
if (now <= settleEndsAt) return "DRAINING";
return "COMPLETED";
}
String getId() { return id; }
long getDeviceId() { return deviceId; }
long getStartedAt() { return startedAt; }
long getCaptureEndsAt() { return captureEndsAt; }
long getSettleEndsAt() { return settleEndsAt; }
int getMessageCount() { return messageCount; }
}
}
@@ -0,0 +1,798 @@
package com.common.service;
import com.Modules.NormalData.LogNormalProcessor;
import com.common.entity.SyslogNonNormalMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.annotation.PostConstruct;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
/**
* 面向现场诊断的有界原始日志采样器。
*
* <p>普通消息按到达顺序填充固定容量;容量满后,新的异常消息会淘汰最早的非异常消息。
* 异常消息之间仍保持先到先得,避免高流量设备导致内存随消息数增长。</p>
*/
@Service
public class RawLogCaptureService {
public static final int MAX_DURATION_SECONDS = 600;
public static final int MAX_MESSAGE_COUNT = 50;
@Value("${syslog.raw-capture.enabled:true}")
private boolean enabled = true;
@Value("${syslog.raw-capture.max-active-sessions:20}")
private int maxActiveSessions = 20;
@Value("${syslog.raw-capture.max-retained-sessions:100}")
private int maxRetainedSessions = 100;
@Value("${syslog.raw-capture.settle-seconds:30}")
private int settleSeconds = 30;
@Value("${syslog.raw-capture.result-retention-minutes:30}")
private int resultRetentionMinutes = 30;
private final Clock clock;
private final ConcurrentHashMap<String, CaptureSession> sessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, CopyOnWriteArrayList<CaptureSession>> sessionsByDevice =
new ConcurrentHashMap<>();
private final AtomicLong sequence = new AtomicLong();
/** 跨实例同步由独立存储组件完成;单元测试或明确关闭时退化为单实例模式。 */
@Autowired(required = false)
private RawLogCaptureClusterStore clusterStore;
@Value("${syslog.raw-capture.cluster-enabled:true}")
private boolean clusterEnabled = true;
public RawLogCaptureService() {
this(Clock.systemUTC());
}
RawLogCaptureService(Clock clock) {
this.clock = clock;
}
@PostConstruct
public void validateConfiguration() {
if (maxActiveSessions < 1 || maxActiveSessions > 1000) {
throw new IllegalArgumentException("syslog.raw-capture.max-active-sessions 必须在 1~1000 之间");
}
if (maxRetainedSessions < maxActiveSessions || maxRetainedSessions > 5000) {
throw new IllegalArgumentException(
"syslog.raw-capture.max-retained-sessions 必须不小于活动会话上限且不超过 5000");
}
if (settleSeconds < 0 || settleSeconds > 300) {
throw new IllegalArgumentException("syslog.raw-capture.settle-seconds 必须在 0~300 之间");
}
if (resultRetentionMinutes < 1 || resultRetentionMinutes > 1440) {
throw new IllegalArgumentException("syslog.raw-capture.result-retention-minutes 必须在 1~1440 之间");
}
}
public CaptureSnapshot start(long deviceId, int durationSeconds, int messageCount) {
if (!enabled) throw new CaptureDisabledException();
if (deviceId <= 0L) throw new IllegalArgumentException("deviceId 必须大于 0");
if (durationSeconds < 1 || durationSeconds > MAX_DURATION_SECONDS) {
throw new IllegalArgumentException("durationSeconds 必须在 1~600 之间");
}
if (messageCount < 1 || messageCount > MAX_MESSAGE_COUNT) {
throw new IllegalArgumentException("messageCount 必须在 1~50 之间");
}
if (useClusterStore()) {
RawLogCaptureClusterStore.Definition definition = clusterStore.create(deviceId,
durationSeconds, settleSeconds, messageCount, maxActiveSessions,
resultRetentionMinutes);
ensureClusterSession(definition);
return clusterStore.get(definition.getId());
}
cleanup(clock.millis());
synchronized (this) {
long startedAt = clock.millis();
if (activeSessionCount(startedAt) >= maxActiveSessions) {
throw new CaptureCapacityException(maxActiveSessions);
}
makeRoomForRetainedSession(startedAt);
CaptureSession session = new CaptureSession(UUID.randomUUID().toString(), deviceId,
startedAt, startedAt + durationSeconds * 1000L,
startedAt + (durationSeconds + settleSeconds) * 1000L, messageCount);
sessions.put(session.id, session);
sessionsByDevice.computeIfAbsent(deviceId, ignored -> new CopyOnWriteArrayList<>())
.add(session);
return session.snapshot(startedAt);
}
}
public CaptureSnapshot get(String sessionId) {
if (useClusterStore()) return clusterStore.get(sessionId);
long now = clock.millis();
cleanup(now);
CaptureSession session = sessions.get(sessionId);
return session == null ? null : session.snapshot(now);
}
public CaptureSnapshot stop(String sessionId) {
if (useClusterStore()) {
CaptureSnapshot snapshot = clusterStore.stop(sessionId);
CaptureSession local = sessions.get(sessionId);
if (local != null) local.stop(clock.millis());
if (local != null) removeFromActiveIndex(local);
return snapshot;
}
long now = clock.millis();
CaptureSession session = sessions.get(sessionId);
if (session == null) return null;
session.stop(now);
removeFromActiveIndex(session);
return session.snapshot(now);
}
/** 在解密并识别设备后调用;只保存固定容量的最早样本。 */
public void observeReceived(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
String eventId, String topic, LocalDateTime receivedAt,
String rawMessage) {
if (!enabled || deviceId == null) return;
List<CaptureSession> active = sessionsByDevice.get(deviceId);
if (active == null || active.isEmpty()) return;
ReceivedLog received = new ReceivedLog(orderSequence(observedAtEpochMillis), observedAtEpochMillis,
deviceId, deviceCollectId, eventId, topic, receivedAt, rawMessage);
for (CaptureSession session : active) session.received(received);
}
/** 记录规则处理结果;非标结果具有异常优先级。 */
public void observeNormalization(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
String eventId, String topic, LocalDateTime receivedAt,
String rawMessage,
LogNormalProcessor.NormalizationResult result) {
if (result == null) return;
if (!result.getNonNormalMessages().isEmpty()) {
SyslogNonNormalMessage first = result.getNonNormalMessages().get(0);
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
receivedAt, rawMessage, "NON_NORMAL", true,
first.getReason(), first.getReasonDetail());
} else if (result.getOutcome() == LogNormalProcessor.ProcessingOutcome.FILTERED) {
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
receivedAt, rawMessage, "FILTERED", false, "规则过滤", null);
} else {
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
receivedAt, rawMessage, "SUCCESS", false, null, null);
}
}
/** 记录 Retry/DLT、规则执行或持久化异常;异常可替换已有普通样本。 */
public void observeFailure(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
String eventId, String topic, LocalDateTime receivedAt,
String rawMessage, String stage, String terminalState,
Throwable failure) {
String status = terminalState == null || terminalState.trim().isEmpty()
? "ERROR" : terminalState;
String reason = stage == null || stage.trim().isEmpty() ? "处理异常" : stage;
String detail = failure == null ? null : failure.getClass().getName()
+ (failure.getMessage() == null ? "" : ": " + failure.getMessage());
observeOutcome(observedAtEpochMillis, deviceId, deviceCollectId, eventId, topic,
receivedAt, rawMessage, status, true, reason, abbreviate(detail, 2000));
}
private void observeOutcome(long observedAtEpochMillis, Long deviceId, Long deviceCollectId,
String eventId, String topic, LocalDateTime receivedAt,
String rawMessage, String status, boolean anomaly,
String reason, String detail) {
if (!enabled || deviceId == null) return;
List<CaptureSession> active = sessionsByDevice.get(deviceId);
if (active == null || active.isEmpty()) return;
ReceivedLog received = new ReceivedLog(orderSequence(observedAtEpochMillis), observedAtEpochMillis,
deviceId, deviceCollectId, eventId, topic, receivedAt, rawMessage);
long now = clock.millis();
for (CaptureSession session : active) {
session.outcome(received, status, anomaly, reason, detail, now);
}
}
/**
* 多实例每200ms同步一次会话定义和变化过的有界候选集;单实例降级模式用同一定时器
* 主动清理过期结果。API创建时预留1秒激活时间,避免轮询传播丢掉窗口开头的日志。
*/
@Scheduled(fixedDelayString = "${syslog.raw-capture.cluster-sync-interval-ms:200}")
public void synchronizeClusterSessions() {
if (!enabled) return;
if (!useClusterStore()) {
cleanup(clock.millis());
return;
}
try {
long now = clock.millis();
List<RawLogCaptureClusterStore.Definition> definitions = clusterStore.active(now);
Map<String, Boolean> activeIds = new LinkedHashMap<>();
for (RawLogCaptureClusterStore.Definition definition : definitions) {
activeIds.put(definition.getId(), Boolean.TRUE);
CaptureSession session = ensureClusterSession(definition);
CaptureCandidates candidates = session.candidatesIfChanged();
if (candidates != null) {
clusterStore.publish(candidates);
session.markPublished(candidates.getRevision());
}
}
for (CaptureSession session : sessions.values()) {
if (session.clusterSession && !activeIds.containsKey(session.id)) {
clusterStore.publish(session.finalCandidates());
session.stop(now);
removeFromActiveIndex(session);
sessions.remove(session.id, session);
}
}
} catch (RuntimeException failure) {
clusterStore.recordSyncFailure(failure);
}
}
private boolean useClusterStore() {
return clusterEnabled && clusterStore != null;
}
private CaptureSession ensureClusterSession(RawLogCaptureClusterStore.Definition definition) {
CaptureSession existing = sessions.get(definition.getId());
if (existing != null) return existing;
CaptureSession created = new CaptureSession(definition.getId(), definition.getDeviceId(),
definition.getStartedAt(), definition.getCaptureEndsAt(),
definition.getSettleEndsAt(), definition.getMessageCount(), true);
CaptureSession winner = sessions.putIfAbsent(created.id, created);
CaptureSession session = winner == null ? created : winner;
if (winner == null) {
sessionsByDevice.computeIfAbsent(created.deviceId,
ignored -> new CopyOnWriteArrayList<>()).add(created);
}
return session;
}
private synchronized int activeSessionCount(long now) {
int count = 0;
for (CaptureSession session : sessions.values()) {
if (session.isActive(now)) count++;
}
return count;
}
/** 总结果数满时优先淘汰最早完成的会话,活动会话绝不被淘汰。 */
private void makeRoomForRetainedSession(long now) {
while (sessions.size() >= maxRetainedSessions) {
CaptureSession oldestFinished = null;
for (CaptureSession session : sessions.values()) {
if (session.isActive(now)) continue;
if (oldestFinished == null || session.finishedAt() < oldestFinished.finishedAt()) {
oldestFinished = session;
}
}
if (oldestFinished == null) {
throw new CaptureCapacityException(maxRetainedSessions);
}
sessions.remove(oldestFinished.id, oldestFinished);
removeFromActiveIndex(oldestFinished);
}
}
private void cleanup(long now) {
for (CaptureSession session : sessions.values()) {
if (!session.isActive(now)) removeFromActiveIndex(session);
if (session.removableAt(resultRetentionMinutes) < now) sessions.remove(session.id, session);
}
}
private void removeFromActiveIndex(CaptureSession session) {
CopyOnWriteArrayList<CaptureSession> active = sessionsByDevice.get(session.deviceId);
if (active == null) return;
active.remove(session);
if (active.isEmpty()) sessionsByDevice.remove(session.deviceId, active);
}
private static String abbreviate(String value, int maxChars) {
if (value == null || value.length() <= maxChars) return value;
return value.substring(0, maxChars) + "...[truncated]";
}
static String instant(long epochMillis) {
return Instant.ofEpochMilli(epochMillis).toString();
}
private long orderSequence(long observedAtEpochMillis) {
return observedAtEpochMillis * 1_000_000L + sequence.incrementAndGet() % 1_000_000L;
}
static List<CapturedLogSnapshot> mergeCandidates(List<CapturedLogSnapshot> firstCandidates,
List<CapturedLogSnapshot> anomalyCandidates,
int limit) {
Map<String, CapturedLogSnapshot> uniqueFirst = uniqueByEvent(firstCandidates);
List<CapturedLogSnapshot> first = new ArrayList<>(uniqueFirst.values());
first.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
if (first.size() > limit) first = new ArrayList<>(first.subList(0, limit));
Map<String, CapturedLogSnapshot> uniqueAnomalies = uniqueByEvent(anomalyCandidates);
List<CapturedLogSnapshot> anomalies = new ArrayList<>(uniqueAnomalies.values());
anomalies.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
if (anomalies.size() > limit) anomalies = anomalies.subList(0, limit);
Map<String, CapturedLogSnapshot> selected = uniqueByEvent(first);
for (CapturedLogSnapshot anomaly : anomalies) {
String key = eventKey(anomaly);
if (selected.containsKey(key)) {
selected.put(key, anomaly);
continue;
}
if (selected.size() < limit) {
selected.put(key, anomaly);
continue;
}
String oldestNormal = null;
long oldestSequence = Long.MAX_VALUE;
for (Map.Entry<String, CapturedLogSnapshot> entry : selected.entrySet()) {
CapturedLogSnapshot candidate = entry.getValue();
if (!candidate.isAnomaly() && candidate.getSequence() < oldestSequence) {
oldestNormal = entry.getKey();
oldestSequence = candidate.getSequence();
}
}
if (oldestNormal == null) break;
selected.remove(oldestNormal);
selected.put(key, anomaly);
}
List<CapturedLogSnapshot> result = new ArrayList<>(selected.values());
result.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
return result;
}
private static Map<String, CapturedLogSnapshot> uniqueByEvent(
List<CapturedLogSnapshot> candidates) {
Map<String, CapturedLogSnapshot> result = new LinkedHashMap<>();
if (candidates == null) return result;
for (CapturedLogSnapshot candidate : candidates) {
String key = eventKey(candidate);
CapturedLogSnapshot existing = result.get(key);
if (existing == null || (!existing.isAnomaly() && candidate.isAnomaly())) {
result.put(key, candidate);
}
}
return result;
}
private static String eventKey(CapturedLogSnapshot candidate) {
return candidate.getEventId() == null
? "sequence:" + candidate.getSequence() : "event:" + candidate.getEventId();
}
private static List<CapturedLogSnapshot> snapshots(List<CapturedLog> logs) {
List<CapturedLogSnapshot> result = new ArrayList<>(logs.size());
for (CapturedLog log : logs) result.add(log.snapshot());
return result;
}
private static int countAnomalies(List<CapturedLogSnapshot> messages) {
int count = 0;
for (CapturedLogSnapshot message : messages) if (message.isAnomaly()) count++;
return count;
}
private static long replacementCount(List<CapturedLogSnapshot> first,
List<CapturedLogSnapshot> anomalies, int limit) {
Map<String, CapturedLogSnapshot> firstSet = uniqueByEvent(first);
int laterAnomalies = 0;
for (CapturedLogSnapshot anomaly : uniqueByEvent(anomalies).values()) {
if (!firstSet.containsKey(eventKey(anomaly))) laterAnomalies++;
}
int availableNormals = 0;
List<CapturedLogSnapshot> globalFirst = new ArrayList<>(firstSet.values());
globalFirst.sort(Comparator.comparingLong(CapturedLogSnapshot::getSequence));
for (int i = 0; i < Math.min(limit, globalFirst.size()); i++) {
if (!globalFirst.get(i).isAnomaly()) availableNormals++;
}
return Math.min(laterAnomalies, availableNormals);
}
private static final class ReceivedLog {
private final long sequence;
private final long observedAt;
private final Long deviceId;
private final Long deviceCollectId;
private final String eventId;
private final String topic;
private final LocalDateTime receivedAt;
private final String rawMessage;
private ReceivedLog(long sequence, long observedAt, Long deviceId, Long deviceCollectId,
String eventId, String topic, LocalDateTime receivedAt, String rawMessage) {
this.sequence = sequence;
this.observedAt = observedAt;
this.deviceId = deviceId;
this.deviceCollectId = deviceCollectId;
this.eventId = eventId;
this.topic = topic;
this.receivedAt = receivedAt;
this.rawMessage = rawMessage;
}
}
private static final class CaptureSession {
private final String id;
private final long deviceId;
private final long startedAt;
private final long captureEndsAt;
private final long settleEndsAt;
private final int messageCount;
private final List<CapturedLog> firstMessages = new ArrayList<>();
private final List<CapturedLog> firstAnomalies = new ArrayList<>();
private final Map<String, CapturedLog> firstByEventId = new LinkedHashMap<>();
private final Map<String, CapturedLog> anomalyByEventId = new LinkedHashMap<>();
private final boolean clusterSession;
private long revision;
private long publishedRevision = -1L;
private long stoppedAt;
private long receivedCount;
private long processedCount;
private long observedAnomalyCount;
private long replacementCount;
private CaptureSession(String id, long deviceId, long startedAt, long captureEndsAt,
long settleEndsAt, int messageCount) {
this(id, deviceId, startedAt, captureEndsAt, settleEndsAt, messageCount, false);
}
private CaptureSession(String id, long deviceId, long startedAt, long captureEndsAt,
long settleEndsAt, int messageCount, boolean clusterSession) {
this.id = id;
this.deviceId = deviceId;
this.startedAt = startedAt;
this.captureEndsAt = captureEndsAt;
this.settleEndsAt = settleEndsAt;
this.messageCount = messageCount;
this.clusterSession = clusterSession;
}
private synchronized void received(ReceivedLog log) {
if (!accepts(log.observedAt) || stoppedAt > 0L) return;
receivedCount++;
if (findFirst(log.eventId) != null || firstMessages.size() >= messageCount) return;
CapturedLog captured = new CapturedLog(log);
firstMessages.add(captured);
if (captured.eventId != null) firstByEventId.put(captured.eventId, captured);
revision++;
}
private synchronized void outcome(ReceivedLog log, String status, boolean anomaly,
String reason, String detail, long now) {
if (!accepts(log.observedAt) || stoppedAt > 0L || now > settleEndsAt) return;
processedCount++;
if (anomaly) observedAnomalyCount++;
CapturedLog first = findFirst(log.eventId);
if (first != null) {
first.update(status, anomaly, reason, detail, now);
revision++;
}
CapturedLog existingAnomaly = findAnomaly(log.eventId);
if (existingAnomaly != null) {
existingAnomaly.update(status, anomaly, reason, detail, now);
revision++;
}
if (!anomaly || existingAnomaly != null || firstAnomalies.size() >= messageCount) return;
CapturedLog captured = first == null ? new CapturedLog(log) : first.copy();
captured.update(status, true, reason, detail, now);
firstAnomalies.add(captured);
if (captured.eventId != null) anomalyByEventId.put(captured.eventId, captured);
revision++;
}
private boolean accepts(long observedAt) {
return observedAt >= startedAt && observedAt <= captureEndsAt;
}
private CapturedLog findFirst(String eventId) {
return eventId == null ? null : firstByEventId.get(eventId);
}
private CapturedLog findAnomaly(String eventId) {
return eventId == null ? null : anomalyByEventId.get(eventId);
}
private synchronized void stop(long now) {
if (stoppedAt == 0L) stoppedAt = now;
}
private synchronized boolean isActive(long now) {
return stoppedAt == 0L && now <= settleEndsAt;
}
private synchronized long removableAt(int retentionMinutes) {
return finishedAt() + retentionMinutes * 60_000L;
}
private synchronized long finishedAt() {
return stoppedAt > 0L ? stoppedAt : settleEndsAt;
}
private synchronized CaptureSnapshot snapshot(long now) {
List<CapturedLogSnapshot> first = snapshots(firstMessages);
List<CapturedLogSnapshot> anomalies = snapshots(firstAnomalies);
List<CapturedLogSnapshot> logs = mergeCandidates(first, anomalies, messageCount);
int retainedAnomalies = countAnomalies(logs);
replacementCount = replacementCount(first, anomalies, messageCount);
return new CaptureSnapshot(id, deviceId, status(now), instant(startedAt),
instant(captureEndsAt), instant(settleEndsAt), messageCount,
receivedCount, processedCount, observedAnomalyCount,
retainedAnomalies, replacementCount, logs);
}
private synchronized CaptureCandidates candidatesIfChanged() {
if (!clusterSession || revision == publishedRevision) return null;
return candidates();
}
private synchronized CaptureCandidates finalCandidates() {
return candidates();
}
private CaptureCandidates candidates() {
return new CaptureCandidates(id, deviceId, startedAt, captureEndsAt, settleEndsAt,
messageCount, receivedCount, processedCount, observedAnomalyCount,
snapshots(firstMessages), snapshots(firstAnomalies), revision);
}
private synchronized void markPublished(long candidateRevision) {
if (candidateRevision > publishedRevision) publishedRevision = candidateRevision;
}
private String status(long now) {
if (stoppedAt > 0L) return "CANCELLED";
if (now < startedAt) return "SCHEDULED";
if (now <= captureEndsAt) return "RUNNING";
if (now <= settleEndsAt) return "DRAINING";
return "COMPLETED";
}
}
private static final class CapturedLog {
private final long sequence;
private final String eventId;
private final Long deviceId;
private final Long deviceCollectId;
private final String topic;
private final LocalDateTime receivedAt;
private final String observedAt;
private final String rawMessage;
private String processingStatus = "PENDING";
private boolean anomaly;
private String reason;
private String reasonDetail;
private String processedAt;
private CapturedLog(ReceivedLog log) {
this.sequence = log.sequence;
this.eventId = log.eventId;
this.deviceId = log.deviceId;
this.deviceCollectId = log.deviceCollectId;
this.topic = log.topic;
this.receivedAt = log.receivedAt;
this.observedAt = instant(log.observedAt);
this.rawMessage = log.rawMessage;
}
private CapturedLog copy() {
return new CapturedLog(sequence, eventId, deviceId, deviceCollectId, topic,
receivedAt, observedAt, rawMessage, processingStatus, anomaly,
reason, reasonDetail, processedAt);
}
private CapturedLog(long sequence, String eventId, Long deviceId, Long deviceCollectId,
String topic, LocalDateTime receivedAt, String observedAt,
String rawMessage, String processingStatus, boolean anomaly,
String reason, String reasonDetail, String processedAt) {
this.sequence = sequence;
this.eventId = eventId;
this.deviceId = deviceId;
this.deviceCollectId = deviceCollectId;
this.topic = topic;
this.receivedAt = receivedAt;
this.observedAt = observedAt;
this.rawMessage = rawMessage;
this.processingStatus = processingStatus;
this.anomaly = anomaly;
this.reason = reason;
this.reasonDetail = reasonDetail;
this.processedAt = processedAt;
}
private void update(String status, boolean anomaly, String reason, String detail, long now) {
if (this.anomaly && !anomaly) return;
this.processingStatus = status;
this.anomaly = anomaly;
this.reason = reason;
this.reasonDetail = detail;
this.processedAt = instant(now);
}
private CapturedLogSnapshot snapshot() {
return new CapturedLogSnapshot(sequence, eventId, deviceId, deviceCollectId, topic,
receivedAt, observedAt, processingStatus, anomaly, reason, reasonDetail,
processedAt, rawMessage);
}
}
static final class CaptureCandidates {
private final String sessionId;
private final long deviceId;
private final long startedAt;
private final long captureEndsAt;
private final long settleEndsAt;
private final int messageCount;
private final long receivedCount;
private final long processedCount;
private final long observedAnomalyCount;
private final List<CapturedLogSnapshot> firstMessages;
private final List<CapturedLogSnapshot> firstAnomalies;
private final long revision;
CaptureCandidates(String sessionId, long deviceId, long startedAt, long captureEndsAt,
long settleEndsAt, int messageCount, long receivedCount,
long processedCount, long observedAnomalyCount,
List<CapturedLogSnapshot> firstMessages,
List<CapturedLogSnapshot> firstAnomalies, long revision) {
this.sessionId = sessionId;
this.deviceId = deviceId;
this.startedAt = startedAt;
this.captureEndsAt = captureEndsAt;
this.settleEndsAt = settleEndsAt;
this.messageCount = messageCount;
this.receivedCount = receivedCount;
this.processedCount = processedCount;
this.observedAnomalyCount = observedAnomalyCount;
this.firstMessages = firstMessages;
this.firstAnomalies = firstAnomalies;
this.revision = revision;
}
String getSessionId() { return sessionId; }
long getDeviceId() { return deviceId; }
long getStartedAt() { return startedAt; }
long getCaptureEndsAt() { return captureEndsAt; }
long getSettleEndsAt() { return settleEndsAt; }
int getMessageCount() { return messageCount; }
long getReceivedCount() { return receivedCount; }
long getProcessedCount() { return processedCount; }
long getObservedAnomalyCount() { return observedAnomalyCount; }
List<CapturedLogSnapshot> getFirstMessages() { return firstMessages; }
List<CapturedLogSnapshot> getFirstAnomalies() { return firstAnomalies; }
long getRevision() { return revision; }
}
public static final class CaptureSnapshot {
private final String sessionId;
private final long deviceId;
private final String status;
private final String startedAt;
private final String captureEndsAt;
private final String settleEndsAt;
private final int messageCount;
private final long receivedCount;
private final long processedCount;
private final long observedAnomalyCount;
private final int retainedAnomalyCount;
private final long replacementCount;
private final List<CapturedLogSnapshot> messages;
CaptureSnapshot(String sessionId, long deviceId, String status, String startedAt,
String captureEndsAt, String settleEndsAt, int messageCount,
long receivedCount, long processedCount, long observedAnomalyCount,
int retainedAnomalyCount, long replacementCount,
List<CapturedLogSnapshot> messages) {
this.sessionId = sessionId;
this.deviceId = deviceId;
this.status = status;
this.startedAt = startedAt;
this.captureEndsAt = captureEndsAt;
this.settleEndsAt = settleEndsAt;
this.messageCount = messageCount;
this.receivedCount = receivedCount;
this.processedCount = processedCount;
this.observedAnomalyCount = observedAnomalyCount;
this.retainedAnomalyCount = retainedAnomalyCount;
this.replacementCount = replacementCount;
this.messages = Collections.unmodifiableList(messages);
}
public String getSessionId() { return sessionId; }
public long getDeviceId() { return deviceId; }
public String getStatus() { return status; }
public String getStartedAt() { return startedAt; }
public String getCaptureEndsAt() { return captureEndsAt; }
public String getSettleEndsAt() { return settleEndsAt; }
public int getMessageCount() { return messageCount; }
public long getReceivedCount() { return receivedCount; }
public long getProcessedCount() { return processedCount; }
public long getObservedAnomalyCount() { return observedAnomalyCount; }
public int getRetainedAnomalyCount() { return retainedAnomalyCount; }
public long getReplacementCount() { return replacementCount; }
public List<CapturedLogSnapshot> getMessages() { return messages; }
}
public static final class CapturedLogSnapshot {
private final long sequence;
private final String eventId;
private final Long deviceId;
private final Long deviceCollectId;
private final String topic;
private final LocalDateTime receivedAt;
private final String observedAt;
private final String processingStatus;
private final boolean anomaly;
private final String reason;
private final String reasonDetail;
private final String processedAt;
private final String rawMessage;
CapturedLogSnapshot(long sequence, String eventId, Long deviceId,
Long deviceCollectId, String topic, LocalDateTime receivedAt,
String observedAt, String processingStatus, boolean anomaly,
String reason, String reasonDetail, String processedAt,
String rawMessage) {
this.sequence = sequence;
this.eventId = eventId;
this.deviceId = deviceId;
this.deviceCollectId = deviceCollectId;
this.topic = topic;
this.receivedAt = receivedAt;
this.observedAt = observedAt;
this.processingStatus = processingStatus;
this.anomaly = anomaly;
this.reason = reason;
this.reasonDetail = reasonDetail;
this.processedAt = processedAt;
this.rawMessage = rawMessage;
}
public long getSequence() { return sequence; }
public String getEventId() { return eventId; }
public Long getDeviceId() { return deviceId; }
public Long getDeviceCollectId() { return deviceCollectId; }
public String getTopic() { return topic; }
public LocalDateTime getReceivedAt() { return receivedAt; }
public String getObservedAt() { return observedAt; }
public String getProcessingStatus() { return processingStatus; }
public boolean isAnomaly() { return anomaly; }
public String getReason() { return reason; }
public String getReasonDetail() { return reasonDetail; }
public String getProcessedAt() { return processedAt; }
public String getRawMessage() { return rawMessage; }
}
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public static final class CaptureDisabledException extends RuntimeException {
public CaptureDisabledException() { super("现场原始日志采样功能未启用"); }
}
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public static final class CaptureCapacityException extends RuntimeException {
public CaptureCapacityException(int max) { super("采样会话容量已达到上限: " + max); }
}
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public static final class CaptureCoordinationException extends RuntimeException {
public CaptureCoordinationException(Throwable cause) {
super("跨实例原始日志采样暂不可用,请检查 Redis 连接", cause);
}
}
}