log.go 8.6 KB

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