progress.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. )
  20. // Progress represents a follower’s progress in the view of the leader. Leader
  21. // maintains progresses of all followers, and sends entries to the follower
  22. // based on its progress.
  23. //
  24. // NB(tbg): Progress is basically a state machine whose transitions are mostly
  25. // strewn around `*raft.raft`. Additionally, some fields are only used when in a
  26. // certain State. All of this isn't ideal.
  27. type Progress struct {
  28. Match, Next uint64
  29. // State defines how the leader should interact with the follower.
  30. //
  31. // When in StateProbe, leader sends at most one replication message
  32. // per heartbeat interval. It also probes actual progress of the follower.
  33. //
  34. // When in StateReplicate, leader optimistically increases next
  35. // to the latest entry sent after sending replication message. This is
  36. // an optimized state for fast replicating log entries to the follower.
  37. //
  38. // When in StateSnapshot, leader should have sent out snapshot
  39. // before and stops sending any replication message.
  40. State StateType
  41. // PendingSnapshot is used in StateSnapshot.
  42. // If there is a pending snapshot, the pendingSnapshot will be set to the
  43. // index of the snapshot. If pendingSnapshot is set, the replication process of
  44. // this Progress will be paused. raft will not resend snapshot until the pending one
  45. // is reported to be failed.
  46. PendingSnapshot uint64
  47. // RecentActive is true if the progress is recently active. Receiving any messages
  48. // from the corresponding follower indicates the progress is active.
  49. // RecentActive can be reset to false after an election timeout.
  50. RecentActive bool
  51. // ProbeSent is used while this follower is in StateProbe. When ProbeSent is
  52. // true, raft should pause sending replication message to this peer until
  53. // ProbeSent is reset. See ProbeAcked() and IsPaused().
  54. ProbeSent bool
  55. // Inflights is a sliding window for the inflight messages.
  56. // Each inflight message contains one or more log entries.
  57. // The max number of entries per message is defined in raft config as MaxSizePerMsg.
  58. // Thus inflight effectively limits both the number of inflight messages
  59. // and the bandwidth each Progress can use.
  60. // When inflights is Full, no more message should be sent.
  61. // When a leader sends out a message, the index of the last
  62. // entry should be added to inflights. The index MUST be added
  63. // into inflights in order.
  64. // When a leader receives a reply, the previous inflights should
  65. // be freed by calling inflights.FreeLE with the index of the last
  66. // received entry.
  67. Inflights *Inflights
  68. // IsLearner is true if this progress is tracked for a learner.
  69. IsLearner bool
  70. }
  71. // ResetState moves the Progress into the specified State, resetting ProbeSent,
  72. // PendingSnapshot, and Inflights.
  73. func (pr *Progress) ResetState(state StateType) {
  74. pr.ProbeSent = false
  75. pr.PendingSnapshot = 0
  76. pr.State = state
  77. pr.Inflights.reset()
  78. }
  79. func max(a, b uint64) uint64 {
  80. if a > b {
  81. return a
  82. }
  83. return b
  84. }
  85. func min(a, b uint64) uint64 {
  86. if a > b {
  87. return b
  88. }
  89. return a
  90. }
  91. // ProbeAcked is called when this peer has accepted an append. It resets
  92. // ProbeSent to signal that additional append messages should be sent without
  93. // further delay.
  94. func (pr *Progress) ProbeAcked() {
  95. pr.ProbeSent = false
  96. }
  97. // BecomeProbe transitions into StateProbe. Next is reset to Match+1 or,
  98. // optionally and if larger, the index of the pending snapshot.
  99. func (pr *Progress) BecomeProbe() {
  100. // If the original state is StateSnapshot, progress knows that
  101. // the pending snapshot has been sent to this peer successfully, then
  102. // probes from pendingSnapshot + 1.
  103. if pr.State == StateSnapshot {
  104. pendingSnapshot := pr.PendingSnapshot
  105. pr.ResetState(StateProbe)
  106. pr.Next = max(pr.Match+1, pendingSnapshot+1)
  107. } else {
  108. pr.ResetState(StateProbe)
  109. pr.Next = pr.Match + 1
  110. }
  111. }
  112. // BecomeReplicate transitions into StateReplicate, resetting Next to Match+1.
  113. func (pr *Progress) BecomeReplicate() {
  114. pr.ResetState(StateReplicate)
  115. pr.Next = pr.Match + 1
  116. }
  117. // BecomeSnapshot moves the Progress to StateSnapshot with the specified pending
  118. // snapshot index.
  119. func (pr *Progress) BecomeSnapshot(snapshoti uint64) {
  120. pr.ResetState(StateSnapshot)
  121. pr.PendingSnapshot = snapshoti
  122. }
  123. // MaybeUpdate is called when an MsgAppResp arrives from the follower, with the
  124. // index acked by it. The method returns false if the given n index comes from
  125. // an outdated message. Otherwise it updates the progress and returns true.
  126. func (pr *Progress) MaybeUpdate(n uint64) bool {
  127. var updated bool
  128. if pr.Match < n {
  129. pr.Match = n
  130. updated = true
  131. pr.ProbeAcked()
  132. }
  133. if pr.Next < n+1 {
  134. pr.Next = n + 1
  135. }
  136. return updated
  137. }
  138. // OptimisticUpdate signals that appends all the way up to and including index n
  139. // are in-flight. As a result, Next is increased to n+1.
  140. func (pr *Progress) OptimisticUpdate(n uint64) { pr.Next = n + 1 }
  141. // MaybeDecrTo adjusts the Progress to the receipt of a MsgApp rejection. The
  142. // arguments are the index the follower rejected to append to its log, and its
  143. // last index.
  144. //
  145. // Rejections can happen spuriously as messages are sent out of order or
  146. // duplicated. In such cases, the rejection pertains to an index that the
  147. // Progress already knows were previously acknowledged, and false is returned
  148. // without changing the Progress.
  149. //
  150. // If the rejection is genuine, Next is lowered sensibly, and the Progress is
  151. // cleared for sending log entries.
  152. func (pr *Progress) MaybeDecrTo(rejected, last uint64) bool {
  153. if pr.State == StateReplicate {
  154. // The rejection must be stale if the progress has matched and "rejected"
  155. // is smaller than "match".
  156. if rejected <= pr.Match {
  157. return false
  158. }
  159. // Directly decrease next to match + 1.
  160. //
  161. // TODO(tbg): why not use last if it's larger?
  162. pr.Next = pr.Match + 1
  163. return true
  164. }
  165. // The rejection must be stale if "rejected" does not match next - 1. This
  166. // is because non-replicating followers are probed one entry at a time.
  167. if pr.Next-1 != rejected {
  168. return false
  169. }
  170. if pr.Next = min(rejected, last+1); pr.Next < 1 {
  171. pr.Next = 1
  172. }
  173. pr.ProbeSent = false
  174. return true
  175. }
  176. // IsPaused returns whether sending log entries to this node has been throttled.
  177. // This is done when a node has rejected recent MsgApps, is currently waiting
  178. // for a snapshot, or has reached the MaxInflightMsgs limit. In normal
  179. // operation, this is false. A throttled node will be contacted less frequently
  180. // until it has reached a state in which it's able to accept a steady stream of
  181. // log entries again.
  182. func (pr *Progress) IsPaused() bool {
  183. switch pr.State {
  184. case StateProbe:
  185. return pr.ProbeSent
  186. case StateReplicate:
  187. return pr.Inflights.Full()
  188. case StateSnapshot:
  189. return true
  190. default:
  191. panic("unexpected state")
  192. }
  193. }
  194. func (pr *Progress) String() string {
  195. var buf strings.Builder
  196. fmt.Fprintf(&buf, "%s match=%d next=%d", pr.State, pr.Match, pr.Next)
  197. if pr.IsLearner {
  198. fmt.Fprint(&buf, " learner")
  199. }
  200. if pr.IsPaused() {
  201. fmt.Fprint(&buf, " paused")
  202. }
  203. if pr.PendingSnapshot > 0 {
  204. fmt.Fprintf(&buf, " pendingSnap=%d", pr.PendingSnapshot)
  205. }
  206. if !pr.RecentActive {
  207. fmt.Fprintf(&buf, " inactive")
  208. }
  209. if n := pr.Inflights.Count(); n > 0 {
  210. fmt.Fprintf(&buf, " inflight=%d", n)
  211. if pr.Inflights.Full() {
  212. fmt.Fprint(&buf, "[full]")
  213. }
  214. }
  215. return buf.String()
  216. }
  217. // ProgressMap is a map of *Progress.
  218. type ProgressMap map[uint64]*Progress
  219. // String prints the ProgressMap in sorted key order, one Progress per line.
  220. func (m ProgressMap) String() string {
  221. ids := make([]uint64, 0, len(m))
  222. for k := range m {
  223. ids = append(ids, k)
  224. }
  225. sort.Slice(ids, func(i, j int) bool {
  226. return ids[i] < ids[j]
  227. })
  228. var buf strings.Builder
  229. for _, id := range ids {
  230. fmt.Fprintf(&buf, "%d: %s\n", id, m[id])
  231. }
  232. return buf.String()
  233. }