Lab 3D:快照与日志压缩
Lab 3D:快照与日志压缩
快照不是“删掉旧日志”这么简单:Raft 必须同时保存快照边界、边界 term 和快照数据,让落后的 Follower 能在旧日志已被删除后继续追上。
TL;DR
- 长期保存完整 Raft 日志会让重启越来越慢,因此状态机定期把已应用状态做成快照。
Snapshot(index, snapshot)保留index之后的日志,并记录lastIncludedIndex与lastIncludedTerm。- 如果 Leader 的
nextIndex已经落到自己的快照边界之前,就发送InstallSnapshot,而不是AppendEntries。 - 快照和 Raft 状态必须一起持久化;重启后先恢复 Raft 状态,再由服务恢复快照中的业务状态。
- 当前实现已通过官方全部 3D 测试,并保持 3A、3B、3C 通过。
目录
| 章节 | 内容 |
|---|---|
| 原文逐行翻译 | MIT Lab 3D 说明的逐行翻译 |
| 快照状态模型 | 截断日志后的全局下标和边界 term |
| 代码实现 | Snapshot、InstallSnapshot 和持久化 |
| 快照应用顺序 | 保证服务状态不倒退 |
| 测试验收 | 3D 官方测试结果 |
原文逐行翻译
<!-- source: lab-raft1.html:565 block=66 -->来源:本地
source/lab-raft1.html。HTML 的排版换行合并成完整句子,每句英文后紧跟中文;源码行号与块编号供核对。命令、代码和终端输出原样保留。下面的 PASS/FAIL 输出均为原文示例,不代表本机测试结果。
3D 部分:日志压缩
<!-- source: lab-raft1.html:567 block=67 -->Part 3D: log compaction
As things stand now, a rebooting server replays the complete Raft log in order to restore its state.
目前,重启的服务器会重放完整 Raft 日志来恢复状态。
However, it's not practical for a long-running service to remember the complete Raft log forever.
但是,对长期运行的服务而言,永远保存全部 Raft 日志并不现实。
Instead, you'll modify Raft to cooperate with services that persistently store a "snapshot" of their state from time to time, at which point Raft discards log entries that precede the snapshot.
因此,你要修改 Raft,让它能与定期持久化自身状态快照的服务配合;服务保存快照后,Raft 就丢弃快照之前的日志条目。
The result is a smaller amount of persistent data and faster restart.
这样可以减少持久化数据量,加快重启。
However, it's now possible for a follower to fall so far behind that the leader has discarded the log entries it needs to catch up; the leader must then send a snapshot plus the log starting at the time of the snapshot.
不过,某个 follower 可能落后得太远,leader 已经丢弃它追赶所需的日志;这时 leader 必须发送快照,以及从快照边界开始的后续日志。
Section 7 of the extended Raft paper outlines the scheme; you will have to design the details.
扩展论文第 7 节概述了这个方案,细节需要你自己设计。
<!-- source: lab-raft1.html:582 block=68 -->Your Raft must provide the following function that the service can call with a serialized snapshot of its state:
Raft 必须提供下面的函数,让服务传入序列化后的状态快照:
<!-- source: lab-raft1.html:586 block=69 -->
Snapshot(index int, snapshot []byte)
Snapshot(index int, snapshot []byte):按给定日志索引保存快照。
In Lab 3D, the tester calls
Snapshot()periodically.
在 Lab 3D 中,测试器会定期调用 Snapshot()。
In Lab 4, you will write a key/value server that calls
Snapshot(); the snapshot will contain the complete table of key/value pairs.
在 Lab 4 中,你会编写调用 Snapshot() 的键值服务器,快照包含完整的键值表。
The service layer calls
Snapshot()on every peer (not just on the leader).
服务层会在每个节点调用 Snapshot(),不只是 leader。
The
indexargument indicates the highest log entry that's reflected in the snapshot.
index 参数表示快照中已经包含的最高日志条目索引。
Raft should discard its log entries before that point.
Raft 应丢弃该边界之前的日志条目。
You'll need to revise your Raft code to operate while storing only the tail of the log.
你需要修改 Raft 代码,使它只保存日志尾部时仍能运行。
<!-- source: lab-raft1.html:600 block=72 -->You'll need to implement the
InstallSnapshotRPC discussed in the paper that allows a Raft leader to tell a lagging Raft peer to replace its state with a snapshot.
你需要实现论文讨论的 InstallSnapshot RPC,使 Raft leader 能让落后的节点用快照替换状态。
You will likely need to think through how InstallSnapshot should interact with the state and rules in Figure 2.
你可能需要仔细思考 InstallSnapshot 如何与 Figure 2 的状态和规则配合。
<!-- source: lab-raft1.html:607 block=73 -->When a follower's Raft code receives an InstallSnapshot RPC, it can use the
applyChto send the snapshot to the service in anApplyMsg.
follower 的 Raft 收到 InstallSnapshot RPC 后,可以用 applyCh 发送携带快照的 ApplyMsg,将快照交给服务。
The
ApplyMsgstruct definition inraftapi/raftapi.goalready contains the fields you will need (and which the tester expects).
raftapi/raftapi.go 中的 ApplyMsg 定义已经包含你需要且测试器期望的字段。
Take care that these snapshots only advance the service's state, and don't cause it to move backwards.
注意:这些快照只能推进服务状态,不能使状态倒退。
<!-- source: lab-raft1.html:616 block=74 -->If a server crashes, it must restart from persisted data.
服务器崩溃后,必须从持久化数据恢复。
Your Raft should persist both Raft state and the corresponding snapshot.
Raft 应持久化 Raft 状态以及与其对应的快照。
Use the second argument to
persister.Save()to save the snapshot.
使用 persister.Save() 的第二个参数保存快照。
If there's no snapshot, pass
nilas the second argument.
如果没有快照,第二个参数传 nil。
When a server restarts, the application layer reads the persisted snapshot and restores its saved application state.
服务器重启时,应用层读取持久化快照,恢复已保存的应用状态。
After a restart, the application layer expects the first message on applyCh to either contain a snapshot with a SnapshotIndex higher than that of the initial restored snapshot, or an ordinary command with CommandIndex immediately following the index of the initial restored snapshot.
重启后,应用层期望 applyCh 的第一条消息,要么包含 SnapshotIndex 高于初始恢复快照的更新快照,要么包含 CommandIndex 紧接初始恢复快照索引的普通命令。
<!-- source: lab-raft1.html:632 block=76 -->Implement
Snapshot()and the InstallSnapshot RPC, as well as the changes to Raft to support these (e.g, operation with a trimmed log).
实现 Snapshot()、InstallSnapshot RPC,以及 Raft 为支持它们所需的修改,例如让截断后的日志仍能正常工作。
Your solution is complete when it passes the 3D tests (and all the previous Lab 3 tests).
通过 3D 测试及之前所有 Lab 3 测试,方案才算完成。
<!-- source: lab-raft1.html:641 block=77 -->
git pullto make sure you have the latest software.
运行 git pull,确保使用最新代码。
A good place to start is to modify your code to so that it is able to store just the part of the log starting at some index X.
可以先修改代码,使其能够只保存从某个索引 X 开始的日志部分。
Initially you can set X to zero and run the 3B/3C tests.
一开始把 X 设为零,运行 3B、3C 测试。
Then make
Snapshot(index)discard the log beforeindex, and set X equal toindex.
随后让 Snapshot(index) 丢弃 index 之前的日志,并将 X 设为 index。
If all goes well you should now pass the first 3D test.
顺利的话,此时应该能通过第一个 3D 测试。
<!-- source: lab-raft1.html:651 block=79 -->A common reason for failing the first 3D test is that followers take too long to catch up to the leader.
第一个 3D 测试失败的常见原因是 follower 追赶 leader 太慢。
<!-- source: lab-raft1.html:655 block=80 -->Next: have the leader send an InstallSnapshot RPC if it doesn't have the log entries required to bring a follower up to date.
下一步:如果 leader 已经没有让 follower 追上最新状态所需的日志条目,就让它发送 InstallSnapshot RPC。
<!-- source: lab-raft1.html:658 block=81 -->Send the entire snapshot in a single InstallSnapshot RPC.
在一次 InstallSnapshot RPC 中发送完整快照。
Don't implement Figure 13's
offsetmechanism for splitting up the snapshot.
不要实现 Figure 13 中用于拆分快照的 offset 机制。
Raft must discard old log entries in a way that allows the Go garbage collector to free and re-use the memory; this requires that there be no reachable references (pointers) to the discarded log entries.
Raft 必须以允许 Go 垃圾回收器释放并复用内存的方式丢弃旧日志;这要求不存在指向被丢弃条目的可达引用或指针。
<!-- source: lab-raft1.html:666 block=83 -->When a Raft peer is re-started, the persister passed to
Make()will contain a snapshot of application state as well as Raft's saved state.
Raft 节点重启时,传给 Make() 的 persister 包含应用状态快照,以及保存的 Raft 状态。
Raft must include a non-nil snapshot with every call to
persister.Save()(if the log has been trimmed), which means that it's a good idea forMake()to callpersister.ReadSnapshot()and save the result.
如果日志已被截断,Raft 每次调用 persister.Save() 都必须携带非 nil 快照,因此最好让 Make() 调用 persister.ReadSnapshot() 并保存结果。
A reasonable amount of time to consume for the full set of Lab 3 tests (3A+3B+3C+3D) without
-raceis 6 minutes of real time and one minute of CPU time.
不开启 -race 时,运行全部 Lab 3 测试(3A、3B、3C、3D)的合理耗时为实际时间 6 分钟、CPU 时间 1 分钟。
When running with
-race, it is about 10 minutes of real time and two minutes of CPU time.
开启 -race 时,大约为实际时间 10 分钟、CPU 时间 2 分钟。
Your code should pass all the 3D tests (as shown below), as well as the 3A, 3B, and 3C tests.
代码应通过下面所示的全部 3D 测试,同时继续通过 3A、3B 和 3C。
<!-- source: lab-raft1.html:685 block=86 -->$ make RUN="-run 3D" raft1
go build -race -o main/raft1d main/raft1d.go
cd raft1 && go test -v -race -run 3D
=== RUN TestSnapshotBasic3D
Test (3D): snapshots basic (reliable network)...
... Passed -- time 8.4s #peers 3 #RPCs 279 #Ops 31
--- PASS: TestSnapshotBasic3D (8.74s)
=== RUN TestSnapshotInstall3D
Test (3D): install snapshots (disconnect) (reliable network)...
... Passed -- time 59.6s #peers 3 #RPCs 919 #Ops 91
--- PASS: TestSnapshotInstall3D (59.99s)
=== RUN TestSnapshotInstallUnreliable3D
Test (3D): install snapshots (disconnect) (unreliable network)...
... Passed -- time 82.1s #peers 3 #RPCs 1083 #Ops 91
--- PASS: TestSnapshotInstallUnreliable3D (82.49s)
=== RUN TestSnapshotInstallCrash3D
Test (3D): install snapshots (crash) (reliable network)...
... Passed -- time 53.6s #peers 3 #RPCs 685 #Ops 91
--- PASS: TestSnapshotInstallCrash3D (53.99s)
=== RUN TestSnapshotInstallUnCrash3D
Test (3D): install snapshots (crash) (unreliable network)...
... Passed -- time 66.2s #peers 3 #RPCs 717 #Ops 91
--- PASS: TestSnapshotInstallUnCrash3D (66.60s)
=== RUN TestSnapshotAllCrash3D
Test (3D): crash and restart all servers (unreliable network)...
... Passed -- time 20.4s #peers 3 #RPCs 244 #Ops 45
--- PASS: TestSnapshotAllCrash3D (20.79s)
=== RUN TestSnapshotInit3D
Test (3D): snapshot initialization after crash (unreliable network)...
... Passed -- time 7.4s #peers 3 #RPCs 79 #Ops 14
--- PASS: TestSnapshotInit3D (7.77s)
PASS
ok 6.5840/raft1 301.406s
$
快照状态模型
flowchart LR
Applied[已应用到 index] --> Snapshot[状态机生成 snapshot]
Snapshot --> Trim[Raft 截断 index 之前的日志]
Trim --> Persist[保存 Raft state + snapshot]
Persist --> Restart[节点重启]
Restart --> Restore[恢复快照边界与日志尾部]
截断后,log[0] 不再代表全局下标 0,而是代表 lastIncludedIndex:
全局下标 = lastIncludedIndex + log 的局部下标
因此每次比较日志时都必须区分全局下标和切片下标;lastIncludedTerm 用来验证快照边界前缀仍与 Leader 一致。
代码实现
Snapshot
Snapshot(index, snapshot) 会:
- 找到
index对应的 term; - 创建新的日志切片,只保留边界 dummy entry 和后缀;
- 更新
lastIncludedIndex、lastIncludedTerm与快照字节; - 调整
commitIndex、lastApplied,并调用persist()。
使用新的切片而不是继续引用旧前缀,才能让 Go 垃圾回收器回收被截断的日志内存。
InstallSnapshot
Leader 发现 nextIndex[peer] <= lastIncludedIndex 时发送:
type InstallSnapshotArgs struct {
Term int
LeaderID int
LastIncludedIndex int
LastIncludedTerm int
Data []byte
}
Follower 收到新快照后,如果本地在相同边界 term 上还有日志尾部,就保留这段尾部;否则用新的 dummy entry 替换整个日志。然后更新提交/应用边界、保存快照,并通过 applyCh 发送 SnapshotValid 消息。
持久化与重启
3D 的 persist() 编码:
currentTerm
votedFor
log
lastIncludedIndex
lastIncludedTerm
并把 snapshot 作为 Persister.Save(raftState, snapshot) 的第二个参数。Make 启动时同时读取 ReadRaftState() 和 ReadSnapshot();服务层先读取快照恢复业务状态,Raft 再从快照边界之后的日志继续发送命令。
快照应用顺序
sequenceDiagram
participant L as Leader
participant F as Follower
participant R as Raft applyCh
participant S as State Machine
L->>F: InstallSnapshot(index, term, data)
F->>F: trim log and persist
F->>R: SnapshotValid(index)
R->>S: restore snapshot
L->>F: AppendEntries after snapshot
F->>R: CommandIndex = index + 1 ...
R->>S: apply in order
实现使用待发送快照和条件变量,让快照消息先于快照边界之后的命令消息进入 applyCh,避免服务收到倒退的状态。
测试验收
cd "/Users/maxingfang/w/w/21 数据库实现/04 分布式共识系统/implementation/6.5840/src"
make RUN='-run 3D' raft1
实际结果:
TestSnapshotBasic3D通过;TestSnapshotInstall3D和TestSnapshotInstallUnreliable3D通过;TestSnapshotInstallCrash3D和TestSnapshotInstallUnCrash3D通过;TestSnapshotAllCrash3D和TestSnapshotInit3D通过;- 全部使用
-race,未报告数据竞争。
下一步
Raft 3A–3D 完成后,下一专栏阶段是 Lab 4:把 Raft 接到容错 KV 服务,处理客户端请求去重、线性一致性和快照中的业务状态。
参考资料
评论 (0)