如何断点 Raft 提交?
解读
“断点 Raft 提交”在国内 Consul 面试里通常有两层含义:
- 在源码调试阶段,把断点打在 Raft 日志真正被**提交(commit)**的那一行,确认一条日志何时被 Leader 标记为 committed、何时被 FSM apply;
- 在运行时诊断阶段,不重启进程的前提下,人为卡住某一条日志的提交,模拟“半同步”场景,验证多数据中心、ACL、Intentions 等上层逻辑对延迟的容错能力。
面试官想听的是:你不仅知道 Raft 论文里的 commit 定义,还能在 **Consul 源码(hashicorp/raft 库 + consul/agent/consul/fsm.go)**里快速定位关键函数,并给出可落地的调试/干预手段。
知识点
- hashicorp/raft 三层提交模型
- Leader 本地 append → 复制到 follower → 收到多数派成功响应 → 更新
commitIndex→ 下一轮 AppendEntries 带新commitIndex→ follower 更新自身commitIndex→ FSM goroutine 把 ≤commitIndex的日志 apply。
- Leader 本地 append → 复制到 follower → 收到多数派成功响应 → 更新
- Consul FSM 路径
raftNode.Apply(log, timeout)→fsm.Apply(log)→consul/fsm.go:apply()→ type switch 分发到RegisterNode、KVS、Session等具体命令。
- 调试锚点
- Leader 侧标记 commit:
hashicorp/raft/raft.go:handleAppendEntriesResponse()里r.setCommitIndex(toCommit)这一行。 - FSM apply 入口:
hashicorp/raft/fsm.go:commitPipeline()调用的fsm.Apply(log)。
- Leader 侧标记 commit:
- 运行时干预手段
- 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。
- dlv 条件断点:
答案
要在 Consul 里“断点”Raft 提交,分三步:
- 源码定位:
把 dlv 断点打在hashicorp/raft.(*Raft).setCommitIndex函数入口,这是 Leader 侧真正把日志索引标记为 committed 的唯一地方;同时在下层consul/fsm.go:apply()函数第一行再下一个断点,用来观察 FSM 何时消费这条日志。 - 条件触发:
启动 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。 - 运行时干预(不重启):
若生产环境不允许源码级调试,可用 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 回退造成集群不可用。
拓展思考
- 只阻塞 FSM 不阻塞 commit 能否做到?
可以。把断点从setCommitIndex后移到fsm.applyLogs()的for log := range commitCh循环里,让 commitIndex 继续推进,但 FSM goroutine 暂停,此时集群对外表现为“写成功但读不到”,可用来测试 线性读(consistent read) 的降级策略。 - 多数据中心 WAN Federation 场景下如何断点?
WAN 池里每个数据中心有自己的 Raft 集,日志不会跨数据中心提交。要模拟“二级提交”延迟,需在 consul-replicate 或 consul-enterprise 的 Area 机制里打断点,观察replicate.go:waitForRemoteCommit(),确认二级 DC 的replicatedIndex何时追上主 DC 的commitIndex。 - 断点期间客户端请求会不会无限重试?
默认raft_apply_timeout=10s,超过后 Leader 会给客户端返回raft.ErrEnqueueTimeout,但不会回滚日志。若你在断点里把 commit 卡住 15 s,客户端收到 500 后会按retry_max=2重试,结果集群最终会出现重复日志,需要在上层业务做幂等(KV 用 ModifyIndex、Session 用 TTL)。