tracker.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. "strings"
  19. "go.etcd.io/etcd/raft/quorum"
  20. )
  21. // Config reflects the configuration tracked in a ProgressTracker.
  22. type Config struct {
  23. Voters quorum.JointConfig
  24. // Learners is a set of IDs corresponding to the learners active in the
  25. // current configuration.
  26. //
  27. // Invariant: Learners and Voters does not intersect, i.e. if a peer is in
  28. // either half of the joint config, it can't be a learner; if it is a
  29. // learner it can't be in either half of the joint config. This invariant
  30. // simplifies the implementation since it allows peers to have clarity about
  31. // its current role without taking into account joint consensus.
  32. Learners map[uint64]struct{}
  33. // When we turn a voter into a learner during a joint consensus transition,
  34. // we cannot add the learner directly when entering the joint state. This is
  35. // because this would violate the invariant that the intersection of
  36. // voters and learners is empty. For example, assume a Voter is removed and
  37. // immediately re-added as a learner (or in other words, it is 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 get
  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. // right away when entering the joint configuration, so that it is caught up
  66. // as soon as possible.
  67. LearnersNext map[uint64]struct{}
  68. }
  69. func (c Config) String() string {
  70. var buf strings.Builder
  71. fmt.Fprintf(&buf, "voters=%s", c.Voters)
  72. if c.Learners != nil {
  73. fmt.Fprintf(&buf, " learners=%s", quorum.MajorityConfig(c.Learners).String())
  74. }
  75. if c.LearnersNext != nil {
  76. fmt.Fprintf(&buf, " learners_next=%s", quorum.MajorityConfig(c.LearnersNext).String())
  77. }
  78. return buf.String()
  79. }
  80. // Clone returns a copy of the Config that shares no memory with the original.
  81. func (c *Config) Clone() Config {
  82. clone := func(m map[uint64]struct{}) map[uint64]struct{} {
  83. if m == nil {
  84. return nil
  85. }
  86. mm := make(map[uint64]struct{}, len(m))
  87. for k := range m {
  88. mm[k] = struct{}{}
  89. }
  90. return mm
  91. }
  92. return Config{
  93. Voters: quorum.JointConfig{clone(c.Voters[0]), clone(c.Voters[1])},
  94. Learners: clone(c.Learners),
  95. LearnersNext: clone(c.LearnersNext),
  96. }
  97. }
  98. // ProgressTracker tracks the currently active configuration and the information
  99. // known about the nodes and learners in it. In particular, it tracks the match
  100. // index for each peer which in turn allows reasoning about the committed index.
  101. type ProgressTracker struct {
  102. Config
  103. Progress ProgressMap
  104. Votes map[uint64]bool
  105. MaxInflight int
  106. }
  107. // MakeProgressTracker initializes a ProgressTracker.
  108. func MakeProgressTracker(maxInflight int) ProgressTracker {
  109. p := ProgressTracker{
  110. MaxInflight: maxInflight,
  111. Config: Config{
  112. Voters: quorum.JointConfig{
  113. quorum.MajorityConfig{},
  114. nil, // only populated when used
  115. },
  116. Learners: nil, // only populated when used
  117. LearnersNext: nil, // only populated when used
  118. },
  119. Votes: map[uint64]bool{},
  120. Progress: map[uint64]*Progress{},
  121. }
  122. return p
  123. }
  124. // IsSingleton returns true if (and only if) there is only one voting member
  125. // (i.e. the leader) in the current configuration.
  126. func (p *ProgressTracker) IsSingleton() bool {
  127. return len(p.Voters[0]) == 1 && len(p.Voters[1]) == 0
  128. }
  129. type matchAckIndexer map[uint64]*Progress
  130. var _ quorum.AckedIndexer = matchAckIndexer(nil)
  131. // AckedIndex implements IndexLookuper.
  132. func (l matchAckIndexer) AckedIndex(id uint64) (quorum.Index, bool) {
  133. pr, ok := l[id]
  134. if !ok {
  135. return 0, false
  136. }
  137. return quorum.Index(pr.Match), true
  138. }
  139. // Committed returns the largest log index known to be committed based on what
  140. // the voting members of the group have acknowledged.
  141. func (p *ProgressTracker) Committed() uint64 {
  142. return uint64(p.Voters.CommittedIndex(matchAckIndexer(p.Progress)))
  143. }
  144. // Visit invokes the supplied closure for all tracked progresses.
  145. func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
  146. for id, pr := range p.Progress {
  147. f(id, pr)
  148. }
  149. }
  150. // QuorumActive returns true if the quorum is active from the view of the local
  151. // raft state machine. Otherwise, it returns false.
  152. func (p *ProgressTracker) QuorumActive() bool {
  153. votes := map[uint64]bool{}
  154. p.Visit(func(id uint64, pr *Progress) {
  155. if pr.IsLearner {
  156. return
  157. }
  158. votes[id] = pr.RecentActive
  159. })
  160. return p.Voters.VoteResult(votes) == quorum.VoteWon
  161. }
  162. // VoterNodes returns a sorted slice of voters.
  163. func (p *ProgressTracker) VoterNodes() []uint64 {
  164. m := p.Voters.IDs()
  165. nodes := make([]uint64, 0, len(m))
  166. for id := range m {
  167. nodes = append(nodes, id)
  168. }
  169. sort.Slice(nodes, func(i, j int) bool { return nodes[i] < nodes[j] })
  170. return nodes
  171. }
  172. // LearnerNodes returns a sorted slice of learners.
  173. func (p *ProgressTracker) LearnerNodes() []uint64 {
  174. nodes := make([]uint64, 0, len(p.Learners))
  175. for id := range p.Learners {
  176. nodes = append(nodes, id)
  177. }
  178. sort.Slice(nodes, func(i, j int) bool { return nodes[i] < nodes[j] })
  179. return nodes
  180. }
  181. // ResetVotes prepares for a new round of vote counting via recordVote.
  182. func (p *ProgressTracker) ResetVotes() {
  183. p.Votes = map[uint64]bool{}
  184. }
  185. // RecordVote records that the node with the given id voted for this Raft
  186. // instance if v == true (and declined it otherwise).
  187. func (p *ProgressTracker) RecordVote(id uint64, v bool) {
  188. _, ok := p.Votes[id]
  189. if !ok {
  190. p.Votes[id] = v
  191. }
  192. }
  193. // TallyVotes returns the number of granted and rejected Votes, and whether the
  194. // election outcome is known.
  195. func (p *ProgressTracker) TallyVotes() (granted int, rejected int, _ quorum.VoteResult) {
  196. // Make sure to populate granted/rejected correctly even if the Votes slice
  197. // contains members no longer part of the configuration. This doesn't really
  198. // matter in the way the numbers are used (they're informational), but might
  199. // as well get it right.
  200. for id, pr := range p.Progress {
  201. if pr.IsLearner {
  202. continue
  203. }
  204. v, voted := p.Votes[id]
  205. if !voted {
  206. continue
  207. }
  208. if v {
  209. granted++
  210. } else {
  211. rejected++
  212. }
  213. }
  214. result := p.Voters.VoteResult(p.Votes)
  215. return granted, rejected, result
  216. }