Files
ai-security-xdr/haobang-security-dm/syslog-serve/src/main/java/com/haobang/apipull/ApiPullRunner.java
T

527 lines
23 KiB
Java
Raw Normal View History

package com.haobang.apipull;
import com.common.mapper.DeviceCollectApiMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.haobang.apipull.adapter.AdapterException;
import com.haobang.apipull.adapter.AdapterRegistry;
import com.haobang.apipull.adapter.ApiPullAdapter;
import com.haobang.apipull.adapter.PullPage;
import com.haobang.apipull.adapter.PullRequest;
import com.haobang.apipull.adapter.PulledEvent;
import com.haobang.apipull.persistence.DeviceCollectApiCheckpoint;
import com.haobang.apipull.persistence.DeviceCollectApiConfig;
import com.haobang.apipull.persistence.DeviceCollectApiRun;
import com.haobang.wal.AdmissionStatus;
import com.haobang.wal.AppendAttempt;
import com.haobang.wal.IngressEvent;
import com.haobang.wal.IngressType;
import com.haobang.wal.SyslogWalService;
import com.haobang.wal.UnifiedIngressService;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* 单个 API 拉取任务的一次运行执行器。
*
* <p>执行顺序固定为:计算已闭合时间窗口、根据第一页 total 自适应拆分超容量窗口、串行分页、
* 逐事件写入 WAL、等待整页 durable,最后以 CAS 推进 checkpoint。只要任一事件尚未通过
* {@code FileChannel.force(true)},本次实际子窗口就不会提交,因此进程崩溃后最多重复拉取,
* 不会因为提前移动游标而丢日志。
*
* <p>同一任务的互斥和数据库租约由 {@link ApiPullScheduler} 建立;本类在耗时 HTTP、WAL 背压
* 和 durable 等待期间持续续租,并在提交前再次验证 fencing token 与配置版本。
*/
@Component
public class ApiPullRunner {
private static final Logger log = LoggerFactory.getLogger(ApiPullRunner.class);
private final DeviceCollectApiMapper mapper;
private final AdapterRegistry adapters;
private final UnifiedIngressService ingress;
private final SyslogWalService wal;
private final ApiPullProperties properties;
private final ObjectMapper json;
public ApiPullRunner(
DeviceCollectApiMapper mapper,
AdapterRegistry adapters,
UnifiedIngressService ingress,
SyslogWalService wal,
ApiPullProperties properties,
ObjectMapper json) {
this.mapper = mapper;
this.adapters = adapters;
this.ingress = ingress;
this.wal = wal;
this.properties = properties;
this.json = json.copy().deactivateDefaultTyping();
}
/**
* 执行调度器已经取得租约的任务快照。
*
* @param config 本次运行不可变的任务配置快照
* @param checkpoint 取得租约后的 checkpoint 与 fencing token
* @param run 已写入数据库的运行审计记录
*/
public void execute(
DeviceCollectApiConfig config,
DeviceCollectApiCheckpoint checkpoint,
DeviceCollectApiRun run) {
ApiPullAdapter adapter = adapters.require(config.getAdapterType());
long fencing = checkpoint.getFencingToken();
long checkpointVersion = checkpoint.getVersion();
Instant lastEvent = null;
String lastExternal = null;
long lastRenewNanos = System.nanoTime();
long lastConfigCheckNanos = 0L;
AtomicBoolean leaseLost = new AtomicBoolean(false);
// 独立心跳避免业务线程阻塞在设备 HTTP 或 durable future 时导致租约自然过期。
ScheduledExecutorService heartbeat =
Executors.newSingleThreadScheduledExecutor(
r -> {
Thread t = new Thread(r, "device-api-lease-heartbeat");
t.setDaemon(true);
return t;
});
long heartbeatSeconds = Math.max(5L, Math.min(40L, properties.getLeaseSeconds() / 3L));
heartbeat.scheduleWithFixedDelay(
() -> {
try {
if (mapper.renewLease(
config.getCollectTaskId(),
properties.getInstanceId(),
fencing,
properties.getLeaseSeconds())
!= 1) leaseLost.set(true);
} catch (Throwable failure) {
leaseLost.set(true);
}
},
heartbeatSeconds,
heartbeatSeconds,
TimeUnit.SECONDS);
try {
// safetyDelay 之后的数据仍可能在设备端持续变化,只处理已经闭合的逻辑窗口。
Instant start = ApiPullTime.toInstant(checkpoint.getCommittedWindowEnd());
Instant now = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
Instant closedAt = now.minusSeconds(config.getSafetyDelaySeconds());
Instant plannedEnd = min(start.plusSeconds(config.getWindowSizeSeconds()), closedAt);
if (!plannedEnd.isAfter(start)) {
finish(run, "SKIPPED", null, null);
mapper.scheduleNext(
config.getCollectTaskId(), config.getConfigVersion(), config.getPollIntervalSeconds());
return;
}
Instant initial = ApiPullTime.toInstant(config.getInitialStartTime());
// lookback 有意重叠查询,用稳定 eventId 将迟到数据转化为下游可幂等的重复数据。
Instant queryStart = max(initial, start.minusSeconds(config.getLookbackSeconds()));
URI base = new URI(config.getBaseUrl());
long hardPageCapacity = calculatePageCapacity(config.getPageSize(), config.getMaxPagesPerRun());
int targetSlicePages = Math.min(config.getMaxPagesPerRun(), properties.getMaxPagesPerSlice());
long slicePageCapacity = calculatePageCapacity(config.getPageSize(), targetSlicePages);
int minimumWindowSeconds = adapter.minimumWindowSeconds();
if (minimumWindowSeconds < 1) {
throw new AdapterException("ADAPTER_CONTRACT_ERROR", "适配器最小窗口必须大于等于 1 秒");
}
Instant end = plannedEnd;
int splitDepth = 0;
PullPage firstPage;
long firstPageStarted;
/*
* 先读取第一页的 total 做容量预判。父窗口超限时不接纳探测页中的事件,
* 因而可以安全缩小窗口,不会先写入一批 WAL 后又从 offset=0 重放。
*/
while (true) {
if (leaseLost.get()) throw new AdapterException("LEASE_LOST", "设备 API 租约心跳失败");
lastConfigCheckNanos = verifyConfigIfDue(config, lastConfigCheckNanos);
lastRenewNanos = renewIfDue(config, fencing, lastRenewNanos);
updateRunWindow(run, start, end, queryStart);
mapper.updateRun(run);
firstPageStarted = System.nanoTime();
firstPage =
adapter.pull(new PullRequest(config, queryStart, end, config.getPageSize(), 0L));
run.setLastHttpStatus(firstPage.getHttpStatus());
if (firstPage.getTotal() <= slicePageCapacity) {
break;
}
// 超限探测页不会进入正常分页循环,因此在此单独保留既有的慢页观测。
logSlowPage(config, run, firstPage, 0L, 0L, firstPageStarted);
if (!canSplitWindow(start, end, minimumWindowSeconds)) {
// 协议已经到达最小时间粒度时不能再安全拆分。如果结果仍在任务的绝对分页上限内,
// 为了不制造永久卡点,本次允许超过公平调度目标并完整提交该最小窗口。
if (firstPage.getTotal() <= hardPageCapacity) {
log.warn(
"设备 API 最小窗口超过分页时间片: taskId={}, runId={}, stream={}, total={},"
+ " sliceCapacity={}, hardCapacity={}, minimumWindowSeconds={}",
config.getCollectTaskId(),
run.getRunId(),
config.getStreamKey(),
firstPage.getTotal(),
slicePageCapacity,
hardPageCapacity,
minimumWindowSeconds);
break;
}
throw new AdapterException(
"MIN_WINDOW_CAPACITY_EXCEEDED",
"最小 "
+ minimumWindowSeconds
+ " 秒窗口仍超过分页容量: total="
+ firstPage.getTotal()
+ ", capacity="
+ hardPageCapacity
+ ", windowStart="
+ start
+ ", windowEnd="
+ end);
}
Instant previousEnd = end;
end = splitWindowEnd(start, end, minimumWindowSeconds);
splitDepth++;
log.info(
"设备 API 高密度窗口自动拆分: taskId={}, runId={}, adapter={}, stream={},"
+ " originalWindowEnd={}, previousWindowEnd={}, splitWindowEnd={}, total={},"
+ " capacity={}, splitDepth={}",
config.getCollectTaskId(),
run.getRunId(),
config.getAdapterType(),
config.getStreamKey(),
plannedEnd,
previousEnd,
end,
firstPage.getTotal(),
slicePageCapacity,
splitDepth);
}
long offset = 0;
Long firstTotal = null;
boolean complete = false;
String datasetFingerprint = firstPage.getDatasetFingerprint();
java.util.Set<String> seenExternalIds = adapter.requiresDistinctExternalIds()
? new java.util.HashSet<>() : null;
// 同一任务严格串行分页,offset 只在整页进入 WAL 后递增。
for (int pageNo = 1; pageNo <= config.getMaxPagesPerRun(); pageNo++) {
PullPage page;
long pageStarted;
long pageOffset = offset;
if (pageNo == 1) {
// 容量可接受时直接复用探测页,正常窗口不会额外增加一次 HTTP 请求。
page = firstPage;
pageStarted = firstPageStarted;
} else {
if (leaseLost.get())
throw new AdapterException("LEASE_LOST", "设备 API 租约心跳失败");
lastConfigCheckNanos = verifyConfigIfDue(config, lastConfigCheckNanos);
lastRenewNanos = renewIfDue(config, fencing, lastRenewNanos);
pageStarted = System.nanoTime();
page =
adapter.pull(
new PullRequest(config, queryStart, end, config.getPageSize(), pageOffset));
}
run.setLastHttpStatus(page.getHttpStatus());
run.setPagesFetched(pageNo);
// offset 分页依赖稳定数据集;total 漂移时继续翻页可能静默漏数或重复。
if (firstTotal == null) firstTotal = page.getTotal();
else if (firstTotal.longValue() != page.getTotal())
throw new AdapterException("PAGINATION_DATASET_CHANGED", "固定窗口内分页 total 发生变化");
if (!java.util.Objects.equals(datasetFingerprint, page.getDatasetFingerprint()))
throw new AdapterException("PAGINATION_DATASET_CHANGED", "固定窗口内分页元数据发生变化");
int sourceRecordCount = page.getSourceRecordCount();
if (sourceRecordCount < 0 || sourceRecordCount > config.getPageSize())
throw new AdapterException("PAGINATION_INCONSISTENT", "设备单页返回条数超出请求 limit");
if (seenExternalIds != null) {
for (PulledEvent event : page.getEvents()) {
if (seenExternalIds.size() >= 100000)
throw new AdapterException("PAGINATION_ID_LIMIT", "分页去重保护上限 100000");
if (!seenExternalIds.add(event.getExternalEventId()))
throw new AdapterException("PAGINATION_DUPLICATE_DOCUMENT", "固定窗口出现重复文档 ID");
}
}
if (sourceRecordCount == 0) {
if (offset >= firstTotal) {
complete = true;
logSlowPage(config, run, page, pageOffset, 0, pageStarted);
break;
}
throw new AdapterException("PAGINATION_INCONSISTENT", "设备在 total 之前返回空页");
}
run.setRecordsFetched(run.getRecordsFetched() + page.getEvents().size());
List<CompletionStage<com.haobang.wal.DurableReceipt>> receipts = new ArrayList<>();
long walStarted = System.nanoTime();
for (PulledEvent e : page.getEvents()) {
if (e.getEventTime().isBefore(start))
run.setDuplicateCandidates(run.getDuplicateCandidates() + 1L);
IngressEvent event =
new IngressEvent(
e.getEventId(),
Instant.now(),
e.getEventTime(),
IngressType.API_PULL,
"HTTPS",
config.getDeviceId(),
config.getCollectTaskId(),
config.getAdapterType(),
e.getExternalEventId(),
base.getHost(),
base.getPort() < 0 ? 443 : base.getPort(),
"JSON",
StandardCharsets.UTF_8,
e.getRawMessage(),
null);
event = wal.prepareIngressEvent(event);
receipts.add(appendWithBackpressure(event, config, fencing));
if (lastEvent == null || e.getEventTime().isAfter(lastEvent)) {
lastEvent = e.getEventTime();
lastExternal = e.getExternalEventId();
}
}
long durableTimeout =
Math.min(600000L, Math.max(120000L, config.getRequestTimeoutMs().longValue()));
// 使用一个页级截止时间,避免 N 个 future 各自拥有完整超时而把总等待放大 N 倍。
long durableDeadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(durableTimeout);
for (CompletionStage<com.haobang.wal.DurableReceipt> receipt : receipts) {
long remaining = durableDeadline - System.nanoTime();
if (remaining <= 0)
throw new java.util.concurrent.TimeoutException("本页 WAL durable 等待超时");
receipt.toCompletableFuture().get(remaining, TimeUnit.NANOSECONDS);
run.setRecordsDurable(run.getRecordsDurable() + 1L);
}
long walMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - walStarted);
// 适配器可能为了把厂商闭区间转换成平台半开区间而过滤边界记录。offset 必须按设备
// 原始返回数推进,不能按过滤后的 WAL 写入数推进,否则会重复请求同一页。
offset += sourceRecordCount;
if (offset > firstTotal)
throw new AdapterException("PAGINATION_INCONSISTENT", "设备返回条数超过首次 total");
mapper.updateRun(run);
logSlowPage(config, run, page, pageOffset, walMs, pageStarted);
if (offset >= firstTotal) {
complete = true;
break;
}
}
if (!complete)
throw new AdapterException("MAX_PAGES_EXCEEDED", "达到 maxPagesPerRun,实际子窗口尚未完成");
ObjectNode cp = json.createObjectNode();
cp.put("schemaVersion", 1);
cp.put(
"committedWindowEnd",
end.atZone(ApiPullTime.DATABASE_ZONE).toOffsetDateTime().toString());
// CAS 同时检查旧版本、持有者、fencing token 和配置版本,防止失租实例覆盖新进度。
if (leaseLost.get()) throw new AdapterException("LEASE_LOST", "提交 checkpoint 前租约心跳失败");
int updated =
mapper.commitCheckpoint(
config.getCollectTaskId(),
checkpointVersion,
properties.getInstanceId(),
fencing,
config.getConfigVersion(),
json.writeValueAsString(cp),
ApiPullTime.toDatabase(end),
ApiPullTime.toDatabase(lastEvent),
lastExternal);
if (updated != 1)
throw new AdapterException("CHECKPOINT_CAS_FAILED", "checkpoint CAS 失败,禁止覆盖提交");
mapper.scheduleNext(
config.getCollectTaskId(), config.getConfigVersion(), config.getPollIntervalSeconds());
finish(run, "SUCCESS", null, null);
} catch (Throwable failure) {
String code = code(failure);
String summary = sanitize(failure);
if (failure instanceof AdapterException
&& ((AdapterException) failure).getHttpStatus() != null)
run.setLastHttpStatus(((AdapterException) failure).getHttpStatus());
finish(run, "FAILED", code, summary);
mapper.scheduleNext(
config.getCollectTaskId(), config.getConfigVersion(), config.getPollIntervalSeconds());
log.warn(
"设备 API 拉取失败: taskId={}, runId={}, adapter={}, stream={}, code={}, error={}",
config.getCollectTaskId(),
run.getRunId(),
config.getAdapterType(),
config.getStreamKey(),
code,
summary);
} finally {
heartbeat.shutdownNow();
if (mapper.releaseLease(config.getCollectTaskId(), properties.getInstanceId(), fencing) != 1)
log.warn(
"设备 API 租约释放失败: taskId={}, runId={}, fencingToken={}",
config.getCollectTaskId(),
run.getRunId(),
fencing);
}
}
/** 使用 long 计算容量,避免两个 Integer 配置相乘时溢出。 */
private long calculatePageCapacity(int pageSize, int pageCount) {
return Math.multiplyExact((long) pageSize, (long) pageCount);
}
/** 到达厂商协议能表达的最小粒度后停止拆分,避免生成等价查询。 */
private boolean canSplitWindow(Instant start, Instant end, int minimumWindowSeconds) {
return Duration.between(start, end).compareTo(Duration.ofSeconds(minimumWindowSeconds)) > 0;
}
/**
* 只保留原窗口左半部分,并将拆分粒度向下取整到整秒。这样下一个 checkpoint
* 仍从原起点连续推进,不会为了降低单次容量而跳过任何时间区间。
*/
private Instant splitWindowEnd(Instant start, Instant end, int minimumWindowSeconds) {
long durationSeconds = Duration.between(start, end).getSeconds();
long halfSeconds = Math.max(minimumWindowSeconds, durationSeconds / 2L);
return start.plusSeconds(halfSeconds);
}
/** 运行审计始终记录最终实际处理的子窗口,而不是拆分前的计划窗口。 */
private void updateRunWindow(
DeviceCollectApiRun run, Instant start, Instant end, Instant queryStart) {
run.setLogicalWindowStart(ApiPullTime.toDatabase(start));
run.setLogicalWindowEnd(ApiPullTime.toDatabase(end));
run.setQueryStart(ApiPullTime.toDatabase(queryStart));
run.setQueryEnd(ApiPullTime.toDatabase(end));
}
private CompletionStage<com.haobang.wal.DurableReceipt> appendWithBackpressure(
IngressEvent event, DeviceCollectApiConfig config, long fencing) throws Exception {
long deadline =
System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(properties.getBackpressureTimeoutMs());
while (true) {
AppendAttempt attempt = ingress.tryAppend(event);
if (attempt.getStatus() == AdmissionStatus.ACCEPTED) return attempt.getDurableStage();
if (attempt.getStatus() == AdmissionStatus.UNAVAILABLE)
throw new AdapterException("WAL_UNAVAILABLE", "WAL 当前不可用");
if (System.nanoTime() >= deadline)
throw new AdapterException("WAL_BACKPRESSURE_TIMEOUT", "等待 WAL 背压超时");
// 背压重试不能成为不可取消的死循环:同时检查暂停/改配并主动维持数据库租约。
DeviceCollectApiConfig current = mapper.selectConfig(config.getCollectTaskId());
if (current == null
|| !current.isEnabled()
|| !current.getConfigVersion().equals(config.getConfigVersion()))
throw new AdapterException("TASK_CONFIGURATION_CHANGED", "任务已暂停或配置版本变化");
if (mapper.renewLease(
config.getCollectTaskId(),
properties.getInstanceId(),
fencing,
properties.getLeaseSeconds())
!= 1) throw new AdapterException("LEASE_LOST", "等待 WAL 时租约已失效");
Thread.sleep(Math.max(1L, wal.getRetryIntervalMs()));
}
}
private long renewIfDue(DeviceCollectApiConfig config, long fencing, long last) {
if (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - last) < 40) return last;
if (mapper.renewLease(
config.getCollectTaskId(),
properties.getInstanceId(),
fencing,
properties.getLeaseSeconds())
!= 1) throw new AdapterException("LEASE_LOST", "设备 API 租约续租失败");
return System.nanoTime();
}
private long verifyConfigIfDue(DeviceCollectApiConfig snapshot, long last) {
long now = System.nanoTime();
if (last != 0L && TimeUnit.NANOSECONDS.toMillis(now - last) < 1000L) return last;
DeviceCollectApiConfig current = mapper.selectConfig(snapshot.getCollectTaskId());
if (current == null
|| !current.isEnabled()
|| !snapshot.getConfigVersion().equals(current.getConfigVersion()))
throw new AdapterException("TASK_CONFIGURATION_CHANGED", "任务已暂停或配置版本变化");
return now;
}
private void logSlowPage(
DeviceCollectApiConfig c,
DeviceCollectApiRun r,
PullPage p,
long offset,
long walMs,
long started) {
long total = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
if (total < properties.getSlowPageThresholdMs()) return;
// 一条结构化日志覆盖网络、解析和 durable 三段耗时,便于定位千万级吞吐瓶颈。
double rate =
p.getEvents().isEmpty() ? 0d : p.getEvents().size() * 1000d / Math.max(1, total);
log.warn(
"设备 API 慢页: taskId={}, runId={}, adapter={}, stream={}, windowStart={}, windowEnd={},"
+ " offset={}, limit={}, sourceCount={}, acceptedCount={}, responseBytes={}, httpMs={}, parseMs={},"
+ " walDurableMs={}, totalMs={}, recordsPerSecond={}",
c.getCollectTaskId(),
r.getRunId(),
c.getAdapterType(),
c.getStreamKey(),
r.getLogicalWindowStart(),
r.getLogicalWindowEnd(),
offset,
c.getPageSize(),
p.getSourceRecordCount(),
p.getEvents().size(),
p.getResponseBytes(),
p.getHttpDurationMs(),
p.getParseDurationMs(),
walMs,
total,
String.format("%.2f", rate));
}
private void finish(DeviceCollectApiRun run, String status, String code, String summary) {
run.setStatus(status);
run.setErrorCode(code);
run.setErrorSummary(summary);
run.setFinishedAt(LocalDateTime.now(ApiPullTime.DATABASE_ZONE));
mapper.updateRun(run);
}
private String code(Throwable e) {
return e instanceof AdapterException
? ((AdapterException) e).getCode()
: e instanceof java.util.concurrent.TimeoutException ? "WAL_DURABLE_TIMEOUT" : "RUN_FAILED";
}
private String sanitize(Throwable e) {
String s = e.getMessage();
if (s == null) s = e.getClass().getSimpleName();
s =
s.replaceAll(
"(?i)(authorization|token|answer|app_secret|app_key)\\s*[:=]\\s*[^,\\s]+",
"$1=[REDACTED]");
s = s.replaceAll("[A-Za-z0-9+/=_-]{32,}", "[REDACTED]");
return s.length() > 2000 ? s.substring(0, 2000) : s;
}
private Instant min(Instant a, Instant b) {
return a.isBefore(b) ? a : b;
}
private Instant max(Instant a, Instant b) {
return a.isAfter(b) ? a : b;
}
}