log.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. // unstable contains all unstable entries and snapshot.
  23. // they will be saved into storage.
  24. unstable unstable
  25. // committed is the highest log position that is known to be in
  26. // stable storage on a quorum of nodes.
  27. // Invariant: committed < unstable
  28. committed uint64
  29. // applied is the highest log position that the application has
  30. // been instructed to apply to its state machine.
  31. // Invariant: applied <= committed
  32. applied uint64
  33. }
  34. // newLog returns log using the given storage. It recovers the log to the state
  35. // that it just commits and applies the lastest snapshot.
  36. func newLog(storage Storage) *raftLog {
  37. if storage == nil {
  38. log.Panic("storage must not be nil")
  39. }
  40. log := &raftLog{
  41. storage: storage,
  42. }
  43. firstIndex, err := storage.FirstIndex()
  44. if err != nil {
  45. panic(err) // TODO(bdarnell)
  46. }
  47. lastIndex, err := storage.LastIndex()
  48. if err != nil {
  49. panic(err) // TODO(bdarnell)
  50. }
  51. log.unstable.offset = lastIndex + 1
  52. // Initialize our committed and applied pointers to the time of the last compaction.
  53. log.committed = firstIndex - 1
  54. log.applied = firstIndex - 1
  55. return log
  56. }
  57. func (l *raftLog) String() string {
  58. return fmt.Sprintf("committed=%d, applied=%d, unstable.offset=%d, len(unstable.Entries)=%d", l.unstable.offset, l.committed, l.applied, len(l.unstable.entries))
  59. }
  60. // maybeAppend returns (0, false) if the entries cannot be appended. Otherwise,
  61. // it returns (last index of new entries, true).
  62. func (l *raftLog) maybeAppend(index, logTerm, committed uint64, ents ...pb.Entry) (lastnewi uint64, ok bool) {
  63. lastnewi = index + uint64(len(ents))
  64. if l.matchTerm(index, logTerm) {
  65. from := index + 1
  66. ci := l.findConflict(from, ents)
  67. switch {
  68. case ci == 0:
  69. case ci <= l.committed:
  70. log.Panicf("entry %d conflict with committed entry [committed(%d)]", ci, l.committed)
  71. default:
  72. l.append(ci-1, ents[ci-from:]...)
  73. }
  74. l.commitTo(min(committed, lastnewi))
  75. return lastnewi, true
  76. }
  77. return 0, false
  78. }
  79. func (l *raftLog) append(after uint64, ents ...pb.Entry) uint64 {
  80. if after < l.committed {
  81. log.Panicf("after(%d) is out of range [committed(%d)]", after, l.committed)
  82. }
  83. l.unstable.truncateAndAppend(after, ents)
  84. return l.lastIndex()
  85. }
  86. // findConflict finds the index of the conflict.
  87. // It returns the first pair of conflicting entries between the existing
  88. // entries and the given entries, if there are any.
  89. // If there is no conflicting entries, and the existing entries contains
  90. // all the given entries, zero will be returned.
  91. // If there is no conflicting entries, but the given entries contains new
  92. // entries, the index of the first new entry will be returned.
  93. // An entry is considered to be conflicting if it has the same index but
  94. // a different term.
  95. // The first entry MUST have an index equal to the argument 'from'.
  96. // The index of the given entries MUST be continuously increasing.
  97. func (l *raftLog) findConflict(from uint64, ents []pb.Entry) uint64 {
  98. // TODO(xiangli): validate the index of ents
  99. for offset, ne := range ents {
  100. if i := from + uint64(offset); !l.matchTerm(ne.Index, ne.Term) {
  101. if i <= l.lastIndex() {
  102. log.Printf("raftlog: found conflict at index %d [existing term: %d, conflicting term: %d]",
  103. i, l.term(i), ne.Term)
  104. }
  105. return i
  106. }
  107. }
  108. return 0
  109. }
  110. func (l *raftLog) unstableEntries() []pb.Entry {
  111. if len(l.unstable.entries) == 0 {
  112. return nil
  113. }
  114. return l.unstable.entries
  115. }
  116. // nextEnts returns all the available entries for execution.
  117. // If applied is smaller than the index of snapshot, it returns all committed
  118. // entries after the index of snapshot.
  119. func (l *raftLog) nextEnts() (ents []pb.Entry) {
  120. off := max(l.applied+1, l.firstIndex())
  121. if l.committed+1 > off {
  122. return l.slice(off, l.committed+1)
  123. }
  124. return nil
  125. }
  126. func (l *raftLog) snapshot() (pb.Snapshot, error) {
  127. if l.unstable.snapshot != nil {
  128. return *l.unstable.snapshot, nil
  129. }
  130. return l.storage.Snapshot()
  131. }
  132. func (l *raftLog) firstIndex() uint64 {
  133. if i, ok := l.unstable.maybeFirstIndex(); ok {
  134. return i
  135. }
  136. index, err := l.storage.FirstIndex()
  137. if err != nil {
  138. panic(err) // TODO(bdarnell)
  139. }
  140. return index
  141. }
  142. func (l *raftLog) lastIndex() uint64 {
  143. if i, ok := l.unstable.maybeLastIndex(); ok {
  144. return i
  145. }
  146. i, err := l.storage.LastIndex()
  147. if err != nil {
  148. panic(err) // TODO(bdarnell)
  149. }
  150. return i
  151. }
  152. func (l *raftLog) commitTo(tocommit uint64) {
  153. // never decrease commit
  154. if l.committed < tocommit {
  155. if l.lastIndex() < tocommit {
  156. log.Panicf("tocommit(%d) is out of range [lastIndex(%d)]", tocommit, l.lastIndex())
  157. }
  158. l.committed = tocommit
  159. }
  160. }
  161. func (l *raftLog) appliedTo(i uint64) {
  162. if i == 0 {
  163. return
  164. }
  165. if l.committed < i || i < l.applied {
  166. log.Panicf("applied(%d) is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
  167. }
  168. l.applied = i
  169. }
  170. func (l *raftLog) stableTo(i, t uint64) { l.unstable.stableTo(i, t) }
  171. func (l *raftLog) stableSnapTo(i uint64) { l.unstable.stableSnapTo(i) }
  172. func (l *raftLog) lastTerm() uint64 { return l.term(l.lastIndex()) }
  173. func (l *raftLog) term(i uint64) uint64 {
  174. if i > l.lastIndex() {
  175. return 0
  176. }
  177. if t, ok := l.unstable.maybeTerm(i); ok {
  178. return t
  179. }
  180. t, err := l.storage.Term(i)
  181. if err == nil {
  182. return t
  183. }
  184. if err == ErrCompacted {
  185. return 0
  186. }
  187. panic(err) // TODO(bdarnell)
  188. }
  189. func (l *raftLog) entries(i uint64) []pb.Entry { return l.slice(i, l.lastIndex()+1) }
  190. // allEntries returns all entries in the log.
  191. func (l *raftLog) allEntries() []pb.Entry { return l.entries(l.firstIndex()) }
  192. // isUpToDate determines if the given (lastIndex,term) log is more up-to-date
  193. // by comparing the index and term of the last entries in the existing logs.
  194. // If the logs have last entries with different terms, then the log with the
  195. // later term is more up-to-date. If the logs end with the same term, then
  196. // whichever log has the larger lastIndex is more up-to-date. If the logs are
  197. // the same, the given log is up-to-date.
  198. func (l *raftLog) isUpToDate(lasti, term uint64) bool {
  199. return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
  200. }
  201. func (l *raftLog) matchTerm(i, term uint64) bool { return l.term(i) == term }
  202. func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
  203. if maxIndex > l.committed && l.term(maxIndex) == term {
  204. l.commitTo(maxIndex)
  205. return true
  206. }
  207. return false
  208. }
  209. func (l *raftLog) restore(s pb.Snapshot) {
  210. log.Printf("raftlog: log [%s] starts to restore snapshot [index: %d, term: %d]", l, s.Metadata.Index, s.Metadata.Term)
  211. l.committed = s.Metadata.Index
  212. l.unstable.restore(s)
  213. }
  214. // slice returns a slice of log entries from lo through hi-1, inclusive.
  215. func (l *raftLog) slice(lo uint64, hi uint64) []pb.Entry {
  216. if lo >= hi {
  217. return nil
  218. }
  219. if l.isOutOfBounds(lo) || l.isOutOfBounds(hi-1) {
  220. return nil
  221. }
  222. var ents []pb.Entry
  223. if lo < l.unstable.offset {
  224. storedEnts, err := l.storage.Entries(lo, min(hi, l.unstable.offset))
  225. if err == ErrCompacted {
  226. // This should never fail because it has been checked before.
  227. log.Panicf("entries[%d:%d) from storage is out of bound", lo, min(hi, l.unstable.offset))
  228. return nil
  229. } else if err == ErrUnavailable {
  230. return nil
  231. } else if err != nil {
  232. panic(err) // TODO(bdarnell)
  233. }
  234. ents = append(ents, storedEnts...)
  235. }
  236. if hi > l.unstable.offset {
  237. unstable := l.unstable.slice(max(lo, l.unstable.offset), hi)
  238. ents = append(ents, unstable...)
  239. }
  240. return ents
  241. }
  242. func (l *raftLog) isOutOfBounds(i uint64) bool {
  243. if i < l.firstIndex() || i > l.lastIndex() {
  244. return true
  245. }
  246. return false
  247. }