log.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package raft
  14. import (
  15. "fmt"
  16. "log"
  17. pb "github.com/coreos/etcd/raft/raftpb"
  18. )
  19. type raftLog struct {
  20. // storage contains all stable entries since the last snapshot.
  21. storage Storage
  22. // the incoming unstable snapshot, if any.
  23. unstableSnapshot *pb.Snapshot
  24. // unstableEnts contains all entries that have not yet been written
  25. // to storage.
  26. unstableEnts []pb.Entry
  27. // unstableEnts[i] has raft log position i+unstable. Note that
  28. // unstable may be less than the highest log position in storage;
  29. // this means that the next write to storage will truncate the log
  30. // before persisting unstableEnts.
  31. unstable uint64
  32. // committed is the highest log position that is known to be in
  33. // stable storage on a quorum of nodes.
  34. // Invariant: committed < unstable
  35. committed uint64
  36. // applied is the highest log position that the application has
  37. // been instructed to apply to its state machine.
  38. // Invariant: applied <= committed
  39. applied uint64
  40. }
  41. // newLog returns log using the given storage. It recovers the log to the state
  42. // that it just commits and applies the lastest snapshot.
  43. func newLog(storage Storage) *raftLog {
  44. if storage == nil {
  45. log.Panic("storage must not be nil")
  46. }
  47. log := &raftLog{
  48. storage: storage,
  49. }
  50. firstIndex, err := storage.FirstIndex()
  51. if err != nil {
  52. panic(err) // TODO(bdarnell)
  53. }
  54. lastIndex, err := storage.LastIndex()
  55. if err != nil {
  56. panic(err) // TODO(bdarnell)
  57. }
  58. log.unstable = lastIndex + 1
  59. // Initialize our committed and applied pointers to the time of the last compaction.
  60. log.committed = firstIndex - 1
  61. log.applied = firstIndex - 1
  62. return log
  63. }
  64. func (l *raftLog) String() string {
  65. return fmt.Sprintf("unstable=%d committed=%d applied=%d len(unstableEntries)=%d", l.unstable, l.committed, l.applied, len(l.unstableEnts))
  66. }
  67. // maybeAppend returns (0, false) if the entries cannot be appended. Otherwise,
  68. // it returns (last index of new entries, true).
  69. func (l *raftLog) maybeAppend(index, logTerm, committed uint64, ents ...pb.Entry) (lastnewi uint64, ok bool) {
  70. lastnewi = index + uint64(len(ents))
  71. if l.matchTerm(index, logTerm) {
  72. from := index + 1
  73. ci := l.findConflict(from, ents)
  74. switch {
  75. case ci == 0:
  76. case ci <= l.committed:
  77. log.Panicf("entry %d conflict with committed entry [committed(%d)]", ci, l.committed)
  78. default:
  79. l.append(ci-1, ents[ci-from:]...)
  80. }
  81. l.commitTo(min(committed, lastnewi))
  82. return lastnewi, true
  83. }
  84. return 0, false
  85. }
  86. func (l *raftLog) append(after uint64, ents ...pb.Entry) uint64 {
  87. if after < l.committed {
  88. log.Panicf("after(%d) is out of range [committed(%d)]", after, l.committed)
  89. }
  90. if after < l.unstable {
  91. // The log is being truncated to before our current unstable
  92. // portion, so discard it and reset unstable.
  93. l.unstableEnts = nil
  94. l.unstable = after + 1
  95. }
  96. // Truncate any unstable entries that are being replaced, then
  97. // append the new ones.
  98. l.unstableEnts = append(l.unstableEnts[:after+1-l.unstable], ents...)
  99. return l.lastIndex()
  100. }
  101. // findConflict finds the index of the conflict.
  102. // It returns the first pair of conflicting entries between the existing
  103. // entries and the given entries, if there are any.
  104. // If there is no conflicting entries, and the existing entries contains
  105. // all the given entries, zero will be returned.
  106. // If there is no conflicting entries, but the given entries contains new
  107. // entries, the index of the first new entry will be returned.
  108. // An entry is considered to be conflicting if it has the same index but
  109. // a different term.
  110. // The first entry MUST have an index equal to the argument 'from'.
  111. // The index of the given entries MUST be continuously increasing.
  112. func (l *raftLog) findConflict(from uint64, ents []pb.Entry) uint64 {
  113. // TODO(xiangli): validate the index of ents
  114. for i, ne := range ents {
  115. if !l.matchTerm(from+uint64(i), ne.Term) {
  116. return from + uint64(i)
  117. }
  118. }
  119. return 0
  120. }
  121. func (l *raftLog) unstableEntries() []pb.Entry {
  122. if len(l.unstableEnts) == 0 {
  123. return nil
  124. }
  125. // copy unstable entries to an empty slice
  126. return append([]pb.Entry{}, l.unstableEnts...)
  127. }
  128. // nextEnts returns all the available entries for execution.
  129. // If applied is smaller than the index of snapshot, it returns all committed
  130. // entries after the index of snapshot.
  131. func (l *raftLog) nextEnts() (ents []pb.Entry) {
  132. off := max(l.applied+1, l.firstIndex())
  133. if l.committed+1 > off {
  134. return l.slice(off, l.committed+1)
  135. }
  136. return nil
  137. }
  138. func (l *raftLog) snapshot() (pb.Snapshot, error) {
  139. if l.unstableSnapshot != nil {
  140. return *l.unstableSnapshot, nil
  141. }
  142. return l.storage.Snapshot()
  143. }
  144. func (l *raftLog) firstIndex() uint64 {
  145. if l.unstableSnapshot != nil {
  146. return l.unstableSnapshot.Metadata.Index + 1
  147. }
  148. index, err := l.storage.FirstIndex()
  149. if err != nil {
  150. panic(err) // TODO(bdarnell)
  151. }
  152. return index
  153. }
  154. func (l *raftLog) lastIndex() uint64 {
  155. return l.unstable + uint64(len(l.unstableEnts)) - 1
  156. }
  157. func (l *raftLog) commitTo(tocommit uint64) {
  158. // never decrease commit
  159. if l.committed < tocommit {
  160. if l.lastIndex() < tocommit {
  161. log.Panicf("tocommit(%d) is out of range [lastIndex(%d)]", tocommit, l.lastIndex())
  162. }
  163. l.committed = tocommit
  164. }
  165. }
  166. func (l *raftLog) appliedTo(i uint64) {
  167. if i == 0 {
  168. return
  169. }
  170. if l.committed < i || i < l.applied {
  171. log.Panicf("applied(%d) is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
  172. }
  173. l.applied = i
  174. }
  175. func (l *raftLog) stableTo(i uint64) {
  176. if i < l.unstable || i+1-l.unstable > uint64(len(l.unstableEnts)) {
  177. log.Panicf("stableTo(%d) is out of range [unstable(%d), len(unstableEnts)(%d)]",
  178. i, l.unstable, len(l.unstableEnts))
  179. }
  180. l.unstableEnts = l.unstableEnts[i+1-l.unstable:]
  181. l.unstable = i + 1
  182. }
  183. func (l *raftLog) lastTerm() uint64 {
  184. return l.term(l.lastIndex())
  185. }
  186. func (l *raftLog) term(i uint64) uint64 {
  187. switch {
  188. case i > l.lastIndex():
  189. return 0
  190. case i < l.unstable:
  191. if snap := l.unstableSnapshot; snap != nil {
  192. if i == snap.Metadata.Index {
  193. return snap.Metadata.Term
  194. }
  195. return 0
  196. }
  197. t, err := l.storage.Term(i)
  198. switch err {
  199. case nil:
  200. return t
  201. case ErrCompacted:
  202. return 0
  203. default:
  204. panic(err) // TODO(bdarnell)
  205. }
  206. default:
  207. return l.unstableEnts[i-l.unstable].Term
  208. }
  209. }
  210. func (l *raftLog) entries(i uint64) []pb.Entry {
  211. return l.slice(i, l.lastIndex()+1)
  212. }
  213. // allEntries returns all entries in the log.
  214. func (l *raftLog) allEntries() []pb.Entry {
  215. return l.entries(l.firstIndex())
  216. }
  217. // isUpToDate determines if the given (lastIndex,term) log is more up-to-date
  218. // by comparing the index and term of the last entries in the existing logs.
  219. // If the logs have last entries with different terms, then the log with the
  220. // later term is more up-to-date. If the logs end with the same term, then
  221. // whichever log has the larger lastIndex is more up-to-date. If the logs are
  222. // the same, the given log is up-to-date.
  223. func (l *raftLog) isUpToDate(lasti, term uint64) bool {
  224. return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
  225. }
  226. func (l *raftLog) matchTerm(i, term uint64) bool {
  227. return l.term(i) == term
  228. }
  229. func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
  230. if maxIndex > l.committed && l.term(maxIndex) == term {
  231. l.commitTo(maxIndex)
  232. return true
  233. }
  234. return false
  235. }
  236. func (l *raftLog) restore(s pb.Snapshot) {
  237. l.committed = s.Metadata.Index
  238. l.unstable = l.committed
  239. l.unstableEnts = []pb.Entry{{Index: s.Metadata.Index, Term: s.Metadata.Term}}
  240. l.unstableSnapshot = &s
  241. }
  242. // slice returns a slice of log entries from lo through hi-1, inclusive.
  243. func (l *raftLog) slice(lo uint64, hi uint64) []pb.Entry {
  244. if lo >= hi {
  245. return nil
  246. }
  247. if l.isOutOfBounds(lo) || l.isOutOfBounds(hi-1) {
  248. return nil
  249. }
  250. var ents []pb.Entry
  251. if lo < l.unstable {
  252. storedEnts, err := l.storage.Entries(lo, min(hi, l.unstable))
  253. if err == ErrCompacted {
  254. // This should never fail because it has been checked before.
  255. log.Panicf("entries[%d:%d) from storage is out of bound", lo, min(hi, l.unstable))
  256. return nil
  257. } else if err != nil {
  258. panic(err) // TODO(bdarnell)
  259. }
  260. ents = append(ents, storedEnts...)
  261. }
  262. if hi > l.unstable {
  263. firstUnstable := max(lo, l.unstable)
  264. ents = append(ents, l.unstableEnts[firstUnstable-l.unstable:hi-l.unstable]...)
  265. }
  266. return ents
  267. }
  268. func (l *raftLog) isOutOfBounds(i uint64) bool {
  269. if i < l.firstIndex() || i > l.lastIndex() {
  270. return true
  271. }
  272. return false
  273. }