tracker.go 7.5 KB

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