MIT6.824-Raft-index含义
nextIndex
- 官方描述:for each server, index of the next log entry to send to that server (initialized to leader last log index + 1)
- leader保存该数组变量,由leader更新。
nextIndex[i]
代表着对第i个follower发起Append Entries RPC时尝试replicated log的位置,仅仅是猜测并不是真实的,并且出现log inconsistency
会将该值回退。所以nextIndex[i]
需要比matchIndex[i]
要大。- leader收到Append Entries RPC回复后只有是因为
log inconsistency
才能更新nextIndex。 - 更新nextIndex的三个时机
- leader election成功时候,需要更新nextIndex为
leader last log index + 1
- AppendEntries RPC返回success,代表已经成功replicated log
log inconsistency
时候回退nextIndex
- leader election成功时候,需要更新nextIndex为
matchIndex
- 官方描述:for each server, index of highest log entry known to be replicated on server (initialized to 0, increases monotonically)
- leader保存该数组变量,由leader更新。
- 更新matchIndex时候,应该取自args的值,因为nextIndex和raft中的logEntries的值可能已经发生了变化。
matchIndex = prevLogIndex + len(args.entries)
- 更新matchIndex的三个时机
- leader election成功,更新matchIndex为lastLogIndex
- AppendEntries RPC返回success,代表已经成功replicated log
- leader接收到新的command时候,主要用于配合该规则更新commitIndex,然后触发apply操作:
If there exists an N such that N > commitIndex, a majority of matchIndex[i] ≥ N, and log[N].term == currentTerm: set commitIndex = N
commitIndex
- 官方描述:index of highest log entry known to be committed (initialized to 0, increases monotonically)
- commitIndex并不是只有leader才有的,所有server的commitIndex应该是一致的。
- If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry)
- leader发送带有log的Append Entries RPC给follower,append log的follower达到majority后,leader commit该log,并更新commitIndex
- 第二次发送RPC时候,因为leaderCommit大于follower的commitIndex,代表着leader已经commit了新的log,所以follower根据上述规则更新自己的commitIndex
- 根据commitIndex > lastApplied,leader(如果已经达到majority的话)/follower就会apply
[lastApplied+1, commitIndex]
的log到state machine。这里apply的是上一次的log。因为leader commit后,follower才能commit,本次log leader还没有commit
- apply时候需要注意Figure8的条件,leader只能apply currentTerm的log时候顺便apply了之前的term的log,而不能直接apply之前term的log
lastApplied
- highest applied log index,和commitIndex配合使用,标明要apply log的区间
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 GreenHatHGのBlog!
评论