编辑
2023-10-20
数据结构与算法
00
请注意,本文编写于 567 天前,最后修改于 567 天前,其中某些信息可能已经过时。
go
// CommitEntry 是 Raft 用来向 commit 通道报告的数据。每个 commit 条目通知客户端一致性已经在一个命令上达成,并且它可以应用于客户端的状态机。 type CommitEntry struct { // Command 是正在提交的客户端命令。 Command interface{} // Index 是客户端命令被提交的日志索引。 Index int // Term 是客户端命令被提交的 Raft 任期。 Term int } // CMState 表示 Raft 一致性模块的状态。 type CMState int const ( Follower CMState = iota // 跟随者状态 Candidate // 候选人状态 Leader // 领导者状态 Dead // 无效状态 ) func (s CMState) String() string { switch s { case Follower: return "跟随者" case Candidate: return "候选人" case Leader: return "领导者" case Dead: return "无效状态" default: panic("不可达的状态") } } // LogEntry 表示 Raft 日志条目。 type LogEntry struct { Command interface{} // 日志条目中的命令 Term int // 日志条目所属的 Raft 任期 } // ConsensusModule (CM) 实现 Raft 一致性的单个节点。 type ConsensusModule struct { // mu 保护对 CM 的并发访问。 mu sync.Mutex // id 是此 CM 的服务器 ID。 id int // peerIds 列出了集群中同伴的 ID。 peerIds []int // server 是包含此 CM 的服务器。它用于向同伴发出 RPC 调用。 server *Server // storage 用于持久化状态。 storage Storage // commitChan 是此 CM 将报告提交的日志条目的通道。在构建过程中由客户端传递。 commitChan chan<- CommitEntry // newCommitReadyChan 是内部通知通道,用于通知提交新条目的 goroutines 可能会发送到 commitChan。 newCommitReadyChan chan struct{} // triggerAEChan 是内部通知通道,用于在发生重要更改时触发向跟随者发送新 AEs。 triggerAEChan chan struct{} // 持久化在所有服务器上的 Raft 状态 currentTerm int votedFor int log []LogEntry // 所有服务器上的易失性 Raft 状态 commitIndex int lastApplied int state CMState electionResetEvent time.Time // 领导者的 Raft 状态 nextIndex map[int]int matchIndex map[int]int } // RequestVoteArgs 表示 RequestVote RPC 的参数。 type RequestVoteArgs struct { Term int // 请求方的当前任期 CandidateId int // 请求方的候选人 ID LastLogIndex int // 请求方的最后日志索引 LastLogTerm int // 请求方的最后日志的任期 } // RequestVoteReply 表示 RequestVote RPC 的回复。 type RequestVoteReply struct { Term int // 接收方的当前任期 VoteGranted bool // 是否授予投票 } // AppendEntriesArgs 表示 AppendEntries RPC 的参数。 type AppendEntriesArgs struct { Term int // 领导者的当前任期 LeaderId int // 领导者的 ID PrevLogIndex int // 先前日志条目的索引 PrevLogTerm int // 先前日志条目的任期 Entries []LogEntry // 要附加到日志的条目 LeaderCommit int // 领导者的提交索引 } // AppendEntriesReply 表示 AppendEntries RPC 的回复。 type AppendEntriesReply struct { Term int // 接收方的当前任期 Success bool // 是否成功 // 更快的冲突解决优化(在文档第 5.3 节末尾有描述) ConflictIndex int // 冲突索引 ConflictTerm int // 冲突任期 }

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!