feat(syslog): 增加普通通道字段截断并完善慢写诊断
- 新增普通通道字段上限配置,默认2048个UTF-8字节,截断尾部保留标记 - 规则计算后执行截断,告警不应用新增2KB限制,原有256KB策略不变 - 非标原文、头部及详细原因应用新增限制,大日志通道和InfluxDB策略不变 - Retry/Replay按原始Topic识别通道,启动日志输出生效上限 - 补充达梦实际写入内容大小、最大行及最大字段诊断 - 慢日志默认阈值统一调整为1000毫秒,异常和失败仍记录 - 更新v4配置说明及回归测试 验证:JDK 8构建成功,250项测试通过 升级:替换JAR并重启,无需数据库或Kafka脚本
This commit is contained in:
+14
-1
@@ -46,20 +46,33 @@ public class DmPreparedBatchInserter {
|
||||
|
||||
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));
|
||||
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;
|
||||
|
||||
+9
-8
@@ -36,7 +36,7 @@ public class DmStandardizedBatchExecutor {
|
||||
@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:500}")
|
||||
@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}")
|
||||
@@ -118,7 +118,7 @@ public class DmStandardizedBatchExecutor {
|
||||
// 事实表使用一个固定 PreparedStatement 直接 addBatch,彻底绕开逐行 OGNL 动态 SQL。
|
||||
timing.phase("JDBC_FACT_WRITE");
|
||||
timing.batchExecution = preparedBatchInserter.insert(
|
||||
alarmTable, rows, transactionTimeoutSeconds);
|
||||
alarmTable, rows, transactionTimeoutSeconds, timing.writeSize);
|
||||
|
||||
// 兼容期变更日志仍与事实行共用当前事务;默认关闭时完全不创建 MyBatis BatchSession。
|
||||
if (statsChangeCaptureService.isEnabled()) {
|
||||
@@ -145,11 +145,11 @@ public class DmStandardizedBatchExecutor {
|
||||
} catch (RuntimeException failure) {
|
||||
log.error("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=FAILED, "
|
||||
+ "failureStage={}, phaseElapsedMs={}, transactionMs={}, connectionBeginMs={}, "
|
||||
+ "jdbcExecuteMs={}, lateAlarmBucketMs={}, retry={}, errorType={}",
|
||||
+ "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());
|
||||
failure.getClass().getName(), timing.writeSize);
|
||||
throw failure;
|
||||
}
|
||||
long transactionMs = elapsedMs(transactionStarted);
|
||||
@@ -159,22 +159,22 @@ public class DmStandardizedBatchExecutor {
|
||||
if (slowTransactionThresholdMs > 0 && transactionMs >= slowTransactionThresholdMs) {
|
||||
log.warn("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=SUCCESS, connectionBeginMs={}, jdbcPlanMs={}, "
|
||||
+ "jdbcBindMs={}, jdbcExecuteMs={}, lateAlarmBucketMs={}, statsProjectionStageMs={}, "
|
||||
+ "commitMs={}, transactionMs={}, retry={}",
|
||||
+ "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.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={}",
|
||||
+ "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.commitMs, transactionMs, retries, timing.writeSize);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,6 +189,7 @@ public class DmStandardizedBatchExecutor {
|
||||
}
|
||||
|
||||
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(); }
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ public class DmStandardizedBatchWriter {
|
||||
@Value("${dm.standardized-write.batch-size:500}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${syslog.slow-batch.threshold-ms:500}")
|
||||
@Value("${syslog.slow-batch.threshold-ms:1000}")
|
||||
private long slowQueueThresholdMs;
|
||||
|
||||
@Value("${dm.standardized-write.transaction-timeout-seconds:45}")
|
||||
|
||||
+107
@@ -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;
|
||||
}
|
||||
}
|
||||
+62
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user