raft study

2019-09-30  本文已影响0人  帆子_8c3a

Paper

名词

和其他一致性算法的区别

其他replicated state machine例子

一致性算法需要满足的特点

raft从3个角度分解一致性问题

三个状态

Term

image.png

Term起到了logical clock的作用

Timeout

RPC

Leader election

Follower赢得选票

Majority rule保证在某一个term中,最多有一个candidate赢得竞选

其他人赢得竞选

  1. Follower接到>=的term的AppendEntries,立刻从candidate=>Follower
  2. Follower接到<的term的AppendEntries,立刻reject请求

没有人赢得竞选

  1. Election timout后,会开启新的一轮term,并发起竞选
  2. Election timout对于每个server是随机值,避免冲突(150~300ms)

Raft guarantees

image.png

Log内容

  1. 状态机的更新值
  2. Term号(用来检测是否一致)
  3. 每条Log以log index标识


    image.png

Log replication

  1. Client发到Leader端,leader先自己写log
  2. Leader发送带log的AppendEntries
  3. the leader applies the entry to its state machine and returns the result of that execution to the client

Leader决定何时apply log entry

  1. 这个log entry的状态被称作committed。
  2. committed过的log entry,一定会反应到所有状态机上。
  3. Leader创建的log entry一旦有majority的数量的复制,就可以commit了。
  4. 上图中log1~7都已经commmited了
  5. leader记录着下一条要被commit的log entry,在以后的AppendEntries会带上这个值。
  6. follower会根据这个值,来apply相应的log entry
  7. commit会保证前面log entry也commit,如果不满足,先commit前面的log entry

Leader端保存的变量

Log Matching Property

  1. 有相同的index和term的两个log entry,存储相同命令
  2. 有相同的index和term的两个log entry,这之前内容一定一样


    image.png

AppendEntries Consistency Check

AppendEntries发送log的同时,会带着上一条log的index和term,如果follower不能找到index和term相同的log,则reject。reject后,Lead会试图发一个带着前一个log的AppendEntries,如果再失败,就再找更前一个log

image.png
Leader向follower发送AppendEntries返回成功,一定说明这个append操作log entry(包括之前的)一定严格和Leader的log一致。

如何解决log不一致

  1. 当leader没有复制完所有log entry时候,其他follower竞选成新的leader后,会产生log 不一致问题
  2. Leader端为每个follower维护一个position,nextIndex。初始时候,每个follower的这个值设置为Leader的最新log entry position。每次发送AppendEntries的时候,用这个position的log entry。如果被reject了,则减一再试。
  3. AppendEntries Consistency Check会保证AppendEntries的log entry(包括之前)一定和leader一致
  4. Leader一定不会删除、修改自己的log,只会append log

Leader Completeness Property

Election restriction

如何commit

结论

具体规则

image.png image.png image.png image.png

动画演示

https://raft.github.io/
http://thesecretlivesofdata.com/raft/
http://kanaka.github.io/raft.js/

https://www.zhihu.com/question/54997169
https://www.zhihu.com/question/29597104/answer/128443409

上一篇下一篇

猜你喜欢

热点阅读