如何断点 Raft 提交?

解读

“断点 Raft 提交”在国内 Consul 面试里通常有两层含义:

  1. 在源码调试阶段,把断点打在 Raft 日志真正被**提交(commit)**的那一行,确认一条日志何时被 Leader 标记为 committed、何时被 FSM apply;
  2. 在运行时诊断阶段,不重启进程的前提下,人为卡住某一条日志的提交,模拟“半同步”场景,验证多数据中心、ACL、Intentions 等上层逻辑对延迟的容错能力。
    面试官想听的是:你不仅知道 Raft 论文里的 commit 定义,还能在 **Consul 源码(hashicorp/raft 库 + consul/agent/consul/fsm.go)**里快速定位关键函数,并给出可落地的调试/干预手段。

知识点

  1. hashicorp/raft 三层提交模型
    • Leader 本地 append → 复制到 follower → 收到多数派成功响应 → 更新 commitIndex → 下一轮 AppendEntries 带新 commitIndex → follower 更新自身 commitIndex → FSM goroutine 把 ≤commitIndex 的日志 apply。
  2. Consul FSM 路径
    • raftNode.Apply(log, timeout) → fsm.Apply(log) → consul/fsm.go:apply() → type switch 分发到 RegisterNode、KVS、Session 等具体命令。
  3. 调试锚点
    • Leader 侧标记 commit:hashicorp/raft/raft.go:handleAppendEntriesResponse() 里 r.setCommitIndex(toCommit) 这一行。
    • FSM apply 入口:hashicorp/raft/fsm.go:commitPipeline() 调用的 fsm.Apply(log)。
  4. 运行时干预手段
    • dlv 条件断点:b raft.go:1234 if log.Index==目标索引;
    • failpoint 注入:在 setCommitIndex 前加 time.Sleep 或 select {} 阻塞;
    • 网络分区模拟:用 iptables -A INPUT -p tcp --dport 8300 -s followerIP -j DROP 让 Leader 永远收不到多数派回复,日志停留在“已复制未提交”状态;
    • consul debug 接口:curl -X PUT localhost:8500/v1/agent/self/debug/pprof/goroutine 观察 FSM goroutine 是否卡在 commitCh。

答案

要在 Consul 里“断点”Raft 提交,分三步:

  1. 源码定位:
    把 dlv 断点打在 hashicorp/raft.(*Raft).setCommitIndex 函数入口,这是 Leader 侧真正把日志索引标记为 committed 的唯一地方;同时在下层 consul/fsm.go:apply() 函数第一行再下一个断点,用来观察 FSM 何时消费这条日志。
  2. 条件触发:
    启动 consul 时用 dlv debug 带 --allow-non-terminal-interactive 参数,在 dlv 里执行 b setCommitIndex if commitIndex==1234,当测试请求刚好产生 index=1234 的日志时,进程会停住,此时在 Leader 的 /var/consul/raft/raft.db 中该日志仍为“未提交”状态,可通过 consul operator raft list-peers 看到 commit_index 停在 1233。
  3. 运行时干预(不重启):
    若生产环境不允许源码级调试,可用 failpoint 热补丁:在 setCommitIndex 前注入 select { case <-time.After(10 * time.Minute): },重新编译出 consul-failpoint 二进制,替换后向 Leader 发一条 KV PUT,即可把提交卡住 10 分钟;期间用 consul monitor --log-level=TRACE 能看到 raft: waiting for logs to be applied 持续打印,验证断点生效。
    注意:干预结束后务必通过 consul leave 平滑退出,避免 commitIndex 回退造成集群不可用。

拓展思考

  1. 只阻塞 FSM 不阻塞 commit 能否做到?
    可以。把断点从 setCommitIndex 后移到 fsm.applyLogs() 的 for log := range commitCh 循环里,让 commitIndex 继续推进,但 FSM goroutine 暂停,此时集群对外表现为“写成功但读不到”,可用来测试 线性读(consistent read) 的降级策略。
  2. 多数据中心 WAN Federation 场景下如何断点?
    WAN 池里每个数据中心有自己的 Raft 集,日志不会跨数据中心提交。要模拟“二级提交”延迟,需在 consul-replicate 或 consul-enterprise 的 Area 机制里打断点,观察 replicate.go:waitForRemoteCommit(),确认二级 DC 的 replicatedIndex 何时追上主 DC 的 commitIndex。
  3. 断点期间客户端请求会不会无限重试?
    默认 raft_apply_timeout=10s,超过后 Leader 会给客户端返回 raft.ErrEnqueueTimeout,但不会回滚日志。若你在断点里把 commit 卡住 15 s,客户端收到 500 后会按 retry_max=2 重试,结果集群最终会出现重复日志,需要在上层业务做幂等(KV 用 ModifyIndex、Session 用 TTL)。