tracker.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // Copyright 2019 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package tracker
  15. import (
  16. "fmt"
  17. "sort"
  18. "go.etcd.io/etcd/raft/quorum"
  19. )
  20. // Config reflects the configuration tracked in a ProgressTracker.
  21. type Config struct {
  22. Voters quorum.JointConfig
  23. // Learners is a set of IDs corresponding to the learners active in the
  24. // current configuration.
  25. //
  26. // Invariant: Learners and Voters does not intersect, i.e. if a peer is in
  27. // either half of the joint config, it can't be a learner; if it is a
  28. // learner it can't be in either half of the joint config. This invariant
  29. // simplifies the implementation since it allows peers to have clarity about
  30. // its current role without taking into account joint consensus.
  31. Learners map[uint64]struct{}
  32. // TODO(tbg): when we actually carry out joint consensus changes and turn a
  33. // voter into a learner, we cannot add the learner when entering the joint
  34. // state. This is because this would violate the invariant that the inter-
  35. // section of voters and learners is empty. For example, assume a Voter is
  36. // removed and immediately re-added as a learner (or in other words, it is
  37. // demoted).
  38. //
  39. // Initially, the configuration will be
  40. //
  41. // voters: {1 2 3}
  42. // learners: {}
  43. //
  44. // and we want to demote 3. Entering the joint configuration, we naively get
  45. //
  46. // voters: {1 2} & {1 2 3}
  47. // learners: {3}
  48. //
  49. // but this violates the invariant (3 is both voter and learner). Instead,
  50. // we have
  51. //
  52. // voters: {1 2} & {1 2 3}
  53. // learners: {}
  54. // next_learners: {3}
  55. //
  56. // Where 3 is now still purely a voter, but we are remembering the intention
  57. // to make it a learner upon transitioning into the final configuration:
  58. //
  59. // voters: {1 2}
  60. // learners: {3}
  61. // next_learners: {}
  62. //
  63. // Note that next_learners is not used while adding a learner that is not
  64. // also a voter in the joint config. In this case, the learner is added
  65. // to Learners right away when entering the joint configuration, so that it
  66. // is caught up as soon as possible.
  67. //
  68. // NextLearners map[uint64]struct{}
  69. }
  70. func (c *Config) String() string {
  71. if len(c.Learners) == 0 {
  72. return fmt.Sprintf("voters=%s", c.Voters)
  73. }
  74. return fmt.Sprintf(
  75. "voters=%s learners=%s",
  76. c.Voters, quorum.MajorityConfig(c.Learners).String(),
  77. )
  78. }
  79. // ProgressTracker tracks the currently active configuration and the information
  80. // known about the nodes and learners in it. In particular, it tracks the match
  81. // index for each peer which in turn allows reasoning about the committed index.
  82. type ProgressTracker struct {
  83. Config
  84. Progress map[uint64]*Progress
  85. Votes map[uint64]bool
  86. MaxInflight int
  87. }
  88. // MakeProgressTracker initializes a ProgressTracker.
  89. func MakeProgressTracker(maxInflight int) ProgressTracker {
  90. p := ProgressTracker{
  91. MaxInflight: maxInflight,
  92. Config: Config{
  93. Voters: quorum.JointConfig{
  94. quorum.MajorityConfig{},
  95. // TODO(tbg): this will be mostly empty, so make it a nil pointer
  96. // in the common case.
  97. quorum.MajorityConfig{},
  98. },
  99. Learners: map[uint64]struct{}{},
  100. },
  101. Votes: map[uint64]bool{},
  102. Progress: map[uint64]*Progress{},
  103. }
  104. return p
  105. }
  106. // IsSingleton returns true if (and only if) there is only one voting member
  107. // (i.e. the leader) in the current configuration.
  108. func (p *ProgressTracker) IsSingleton() bool {
  109. return len(p.Voters[0]) == 1 && len(p.Voters[1]) == 0
  110. }
  111. type matchAckIndexer map[uint64]*Progress
  112. var _ quorum.AckedIndexer = matchAckIndexer(nil)
  113. // AckedIndex implements IndexLookuper.
  114. func (l matchAckIndexer) AckedIndex(id uint64) (quorum.Index, bool) {
  115. pr, ok := l[id]
  116. if !ok {
  117. return 0, false
  118. }
  119. return quorum.Index(pr.Match), true
  120. }
  121. // Committed returns the largest log index known to be committed based on what
  122. // the voting members of the group have acknowledged.
  123. func (p *ProgressTracker) Committed() uint64 {
  124. return uint64(p.Voters.CommittedIndex(matchAckIndexer(p.Progress)))
  125. }
  126. // RemoveAny removes this peer, which *must* be tracked as a voter or learner,
  127. // from the tracker.
  128. func (p *ProgressTracker) RemoveAny(id uint64) {
  129. _, okPR := p.Progress[id]
  130. _, okV1 := p.Voters[0][id]
  131. _, okV2 := p.Voters[1][id]
  132. _, okL := p.Learners[id]
  133. okV := okV1 || okV2
  134. if !okPR {
  135. panic("attempting to remove unknown peer %x")
  136. } else if !okV && !okL {
  137. panic("attempting to remove unknown peer %x")
  138. } else if okV && okL {
  139. panic(fmt.Sprintf("peer %x is both voter and learner", id))
  140. }
  141. delete(p.Voters[0], id)
  142. delete(p.Voters[1], id)
  143. delete(p.Learners, id)
  144. delete(p.Progress, id)
  145. }
  146. // InitProgress initializes a new progress for the given node or learner. The
  147. // node may not exist yet in either form or a panic will ensue.
  148. func (p *ProgressTracker) InitProgress(id, match, next uint64, isLearner bool) {
  149. if pr := p.Progress[id]; pr != nil {
  150. panic(fmt.Sprintf("peer %x already tracked as node %v", id, pr))
  151. }
  152. if !isLearner {
  153. p.Voters[0][id] = struct{}{}
  154. } else {
  155. p.Learners[id] = struct{}{}
  156. }
  157. p.Progress[id] = &Progress{Next: next, Match: match, Inflights: NewInflights(p.MaxInflight), IsLearner: isLearner}
  158. }
  159. // Visit invokes the supplied closure for all tracked progresses.
  160. func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
  161. for id, pr := range p.Progress {
  162. f(id, pr)
  163. }
  164. }
  165. // QuorumActive returns true if the quorum is active from the view of the local
  166. // raft state machine. Otherwise, it returns false.
  167. func (p *ProgressTracker) QuorumActive() bool {
  168. votes := map[uint64]bool{}
  169. p.Visit(func(id uint64, pr *Progress) {
  170. if pr.IsLearner {
  171. return
  172. }
  173. votes[id] = pr.RecentActive
  174. })
  175. return p.Voters.VoteResult(votes) == quorum.VoteWon
  176. }
  177. // VoterNodes returns a sorted slice of voters.
  178. func (p *ProgressTracker) VoterNodes() []uint64 {
  179. m := p.Voters.IDs()
  180. nodes := make([]uint64, 0, len(m))
  181. for id := range m {
  182. nodes = append(nodes, id)
  183. }
  184. sort.Slice(nodes, func(i, j int) bool { return nodes[i] < nodes[j] })
  185. return nodes
  186. }
  187. // LearnerNodes returns a sorted slice of learners.
  188. func (p *ProgressTracker) LearnerNodes() []uint64 {
  189. nodes := make([]uint64, 0, len(p.Learners))
  190. for id := range p.Learners {
  191. nodes = append(nodes, id)
  192. }
  193. sort.Slice(nodes, func(i, j int) bool { return nodes[i] < nodes[j] })
  194. return nodes
  195. }
  196. // ResetVotes prepares for a new round of vote counting via recordVote.
  197. func (p *ProgressTracker) ResetVotes() {
  198. p.Votes = map[uint64]bool{}
  199. }
  200. // RecordVote records that the node with the given id voted for this Raft
  201. // instance if v == true (and declined it otherwise).
  202. func (p *ProgressTracker) RecordVote(id uint64, v bool) {
  203. _, ok := p.Votes[id]
  204. if !ok {
  205. p.Votes[id] = v
  206. }
  207. }
  208. // TallyVotes returns the number of granted and rejected Votes, and whether the
  209. // election outcome is known.
  210. func (p *ProgressTracker) TallyVotes() (granted int, rejected int, _ quorum.VoteResult) {
  211. // Make sure to populate granted/rejected correctly even if the Votes slice
  212. // contains members no longer part of the configuration. This doesn't really
  213. // matter in the way the numbers are used (they're informational), but might
  214. // as well get it right.
  215. for id, pr := range p.Progress {
  216. if pr.IsLearner {
  217. continue
  218. }
  219. v, voted := p.Votes[id]
  220. if !voted {
  221. continue
  222. }
  223. if v {
  224. granted++
  225. } else {
  226. rejected++
  227. }
  228. }
  229. result := p.Voters.VoteResult(p.Votes)
  230. return granted, rejected, result
  231. }