log.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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("unstable=%d committed=%d applied=%d len(unstableEntries)=%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 i, ne := range ents {
  100. if !l.matchTerm(from+uint64(i), ne.Term) {
  101. return from + uint64(i)
  102. }
  103. }
  104. return 0
  105. }
  106. func (l *raftLog) unstableEntries() []pb.Entry {
  107. if len(l.unstable.entries) == 0 {
  108. return nil
  109. }
  110. // copy unstable entries to an empty slice
  111. return append([]pb.Entry{}, l.unstable.entries...)
  112. }
  113. // nextEnts returns all the available entries for execution.
  114. // If applied is smaller than the index of snapshot, it returns all committed
  115. // entries after the index of snapshot.
  116. func (l *raftLog) nextEnts() (ents []pb.Entry) {
  117. off := max(l.applied+1, l.firstIndex())
  118. if l.committed+1 > off {
  119. return l.slice(off, l.committed+1)
  120. }
  121. return nil
  122. }
  123. func (l *raftLog) snapshot() (pb.Snapshot, error) {
  124. if l.unstable.snapshot != nil {
  125. return *l.unstable.snapshot, nil
  126. }
  127. return l.storage.Snapshot()
  128. }
  129. func (l *raftLog) firstIndex() uint64 {
  130. if i, ok := l.unstable.maybeFirstIndex(); ok {
  131. return i
  132. }
  133. index, err := l.storage.FirstIndex()
  134. if err != nil {
  135. panic(err) // TODO(bdarnell)
  136. }
  137. return index
  138. }
  139. func (l *raftLog) lastIndex() uint64 {
  140. if i, ok := l.unstable.maybeLastIndex(); ok {
  141. return i
  142. }
  143. i, err := l.storage.LastIndex()
  144. if err != nil {
  145. panic(err) // TODO(bdarnell)
  146. }
  147. return i
  148. }
  149. func (l *raftLog) commitTo(tocommit uint64) {
  150. // never decrease commit
  151. if l.committed < tocommit {
  152. if l.lastIndex() < tocommit {
  153. log.Panicf("tocommit(%d) is out of range [lastIndex(%d)]", tocommit, l.lastIndex())
  154. }
  155. l.committed = tocommit
  156. }
  157. }
  158. func (l *raftLog) appliedTo(i uint64) {
  159. if i == 0 {
  160. return
  161. }
  162. if l.committed < i || i < l.applied {
  163. log.Panicf("applied(%d) is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
  164. }
  165. l.applied = i
  166. }
  167. func (l *raftLog) stableTo(i, t uint64) { l.unstable.stableTo(i, t) }
  168. func (l *raftLog) stableSnapTo(i uint64) { l.unstable.stableSnapTo(i) }
  169. func (l *raftLog) lastTerm() uint64 { return l.term(l.lastIndex()) }
  170. func (l *raftLog) term(i uint64) uint64 {
  171. if i > l.lastIndex() {
  172. return 0
  173. }
  174. if t, ok := l.unstable.maybeTerm(i); ok {
  175. return t
  176. }
  177. t, err := l.storage.Term(i)
  178. if err == nil {
  179. return t
  180. }
  181. if err == ErrCompacted {
  182. return 0
  183. }
  184. panic(err) // TODO(bdarnell)
  185. }
  186. func (l *raftLog) entries(i uint64) []pb.Entry { return l.slice(i, l.lastIndex()+1) }
  187. // allEntries returns all entries in the log.
  188. func (l *raftLog) allEntries() []pb.Entry { return l.entries(l.firstIndex()) }
  189. // isUpToDate determines if the given (lastIndex,term) log is more up-to-date
  190. // by comparing the index and term of the last entries in the existing logs.
  191. // If the logs have last entries with different terms, then the log with the
  192. // later term is more up-to-date. If the logs end with the same term, then
  193. // whichever log has the larger lastIndex is more up-to-date. If the logs are
  194. // the same, the given log is up-to-date.
  195. func (l *raftLog) isUpToDate(lasti, term uint64) bool {
  196. return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
  197. }
  198. func (l *raftLog) matchTerm(i, term uint64) bool { return l.term(i) == term }
  199. func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
  200. if maxIndex > l.committed && l.term(maxIndex) == term {
  201. l.commitTo(maxIndex)
  202. return true
  203. }
  204. return false
  205. }
  206. func (l *raftLog) restore(s pb.Snapshot) {
  207. l.committed = s.Metadata.Index
  208. l.unstable.restore(s)
  209. }
  210. // slice returns a slice of log entries from lo through hi-1, inclusive.
  211. func (l *raftLog) slice(lo uint64, hi uint64) []pb.Entry {
  212. if lo >= hi {
  213. return nil
  214. }
  215. if l.isOutOfBounds(lo) || l.isOutOfBounds(hi-1) {
  216. return nil
  217. }
  218. var ents []pb.Entry
  219. if lo < l.unstable.offset {
  220. storedEnts, err := l.storage.Entries(lo, min(hi, l.unstable.offset))
  221. if err == ErrCompacted {
  222. // This should never fail because it has been checked before.
  223. log.Panicf("entries[%d:%d) from storage is out of bound", lo, min(hi, l.unstable.offset))
  224. return nil
  225. } else if err != nil {
  226. panic(err) // TODO(bdarnell)
  227. }
  228. ents = append(ents, storedEnts...)
  229. }
  230. if hi > l.unstable.offset {
  231. unstable := l.unstable.slice(max(lo, l.unstable.offset), hi)
  232. ents = append(ents, unstable...)
  233. }
  234. return ents
  235. }
  236. func (l *raftLog) isOutOfBounds(i uint64) bool {
  237. if i < l.firstIndex() || i > l.lastIndex() {
  238. return true
  239. }
  240. return false
  241. }