log.go 8.6 KB

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