log.go 9.0 KB

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