log.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package raft
  15. import (
  16. "fmt"
  17. "log"
  18. pb "github.com/coreos/etcd/raft/raftpb"
  19. )
  20. type raftLog struct {
  21. // storage contains all stable entries since the last snapshot.
  22. storage Storage
  23. // unstable contains all unstable entries and snapshot.
  24. // they will be saved into storage.
  25. unstable unstable
  26. // committed is the highest log position that is known to be in
  27. // stable storage on a quorum of nodes.
  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. logger Logger
  34. }
  35. // newLog returns log using the given storage. It recovers the log to the state
  36. // that it just commits and applies the latest snapshot.
  37. func newLog(storage Storage, logger Logger) *raftLog {
  38. if storage == nil {
  39. log.Panic("storage must not be nil")
  40. }
  41. log := &raftLog{
  42. storage: storage,
  43. logger: logger,
  44. }
  45. firstIndex, err := storage.FirstIndex()
  46. if err != nil {
  47. panic(err) // TODO(bdarnell)
  48. }
  49. lastIndex, err := storage.LastIndex()
  50. if err != nil {
  51. panic(err) // TODO(bdarnell)
  52. }
  53. log.unstable.offset = lastIndex + 1
  54. log.unstable.logger = logger
  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("committed=%d, applied=%d, unstable.offset=%d, len(unstable.Entries)=%d", l.committed, l.applied, l.unstable.offset, len(l.unstable.entries))
  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. ci := l.findConflict(ents)
  69. switch {
  70. case ci == 0:
  71. case ci <= l.committed:
  72. l.logger.Panicf("entry %d conflict with committed entry [committed(%d)]", ci, l.committed)
  73. default:
  74. offset := index + 1
  75. l.append(ents[ci-offset:]...)
  76. }
  77. l.commitTo(min(committed, lastnewi))
  78. return lastnewi, true
  79. }
  80. return 0, false
  81. }
  82. func (l *raftLog) append(ents ...pb.Entry) uint64 {
  83. if len(ents) == 0 {
  84. return l.lastIndex()
  85. }
  86. if after := ents[0].Index - 1; after < l.committed {
  87. l.logger.Panicf("after(%d) is out of range [committed(%d)]", after, l.committed)
  88. }
  89. l.unstable.truncateAndAppend(ents)
  90. return l.lastIndex()
  91. }
  92. // findConflict finds the index of the conflict.
  93. // It returns the first pair of conflicting entries between the existing
  94. // entries and the given entries, if there are any.
  95. // If there is no conflicting entries, and the existing entries contains
  96. // all the given entries, zero will be returned.
  97. // If there is no conflicting entries, but the given entries contains new
  98. // entries, the index of the first new entry will be returned.
  99. // An entry is considered to be conflicting if it has the same index but
  100. // a different term.
  101. // The first entry MUST have an index equal to the argument 'from'.
  102. // The index of the given entries MUST be continuously increasing.
  103. func (l *raftLog) findConflict(ents []pb.Entry) uint64 {
  104. for _, ne := range ents {
  105. if !l.matchTerm(ne.Index, ne.Term) {
  106. if ne.Index <= l.lastIndex() {
  107. l.logger.Infof("found conflict at index %d [existing term: %d, conflicting term: %d]",
  108. ne.Index, l.zeroTermOnErrCompacted(l.term(ne.Index)), ne.Term)
  109. }
  110. return ne.Index
  111. }
  112. }
  113. return 0
  114. }
  115. func (l *raftLog) unstableEntries() []pb.Entry {
  116. if len(l.unstable.entries) == 0 {
  117. return nil
  118. }
  119. return l.unstable.entries
  120. }
  121. // nextEnts returns all the available entries for execution.
  122. // If applied is smaller than the index of snapshot, it returns all committed
  123. // entries after the index of snapshot.
  124. func (l *raftLog) nextEnts() (ents []pb.Entry) {
  125. off := max(l.applied+1, l.firstIndex())
  126. if l.committed+1 > off {
  127. ents, err := l.slice(off, l.committed+1, noLimit)
  128. if err != nil {
  129. l.logger.Panicf("unexpected error when getting unapplied entries (%v)", err)
  130. }
  131. return ents
  132. }
  133. return nil
  134. }
  135. // hasNextEnts returns if there is any available entries for execution. This
  136. // is a fast check without heavy raftLog.slice() in raftLog.nextEnts().
  137. func (l *raftLog) hasNextEnts() bool {
  138. off := max(l.applied+1, l.firstIndex())
  139. if l.committed+1 > off {
  140. return true
  141. }
  142. return false
  143. }
  144. func (l *raftLog) snapshot() (pb.Snapshot, error) {
  145. if l.unstable.snapshot != nil {
  146. return *l.unstable.snapshot, nil
  147. }
  148. return l.storage.Snapshot()
  149. }
  150. func (l *raftLog) firstIndex() uint64 {
  151. if i, ok := l.unstable.maybeFirstIndex(); ok {
  152. return i
  153. }
  154. index, err := l.storage.FirstIndex()
  155. if err != nil {
  156. panic(err) // TODO(bdarnell)
  157. }
  158. return index
  159. }
  160. func (l *raftLog) lastIndex() uint64 {
  161. if i, ok := l.unstable.maybeLastIndex(); ok {
  162. return i
  163. }
  164. i, err := l.storage.LastIndex()
  165. if err != nil {
  166. panic(err) // TODO(bdarnell)
  167. }
  168. return i
  169. }
  170. func (l *raftLog) commitTo(tocommit uint64) {
  171. // never decrease commit
  172. if l.committed < tocommit {
  173. if l.lastIndex() < tocommit {
  174. l.logger.Panicf("tocommit(%d) is out of range [lastIndex(%d)]. Was the raft log corrupted, truncated, or lost?", tocommit, l.lastIndex())
  175. }
  176. l.committed = tocommit
  177. }
  178. }
  179. func (l *raftLog) appliedTo(i uint64) {
  180. if i == 0 {
  181. return
  182. }
  183. if l.committed < i || i < l.applied {
  184. l.logger.Panicf("applied(%d) is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
  185. }
  186. l.applied = i
  187. }
  188. func (l *raftLog) stableTo(i, t uint64) { l.unstable.stableTo(i, t) }
  189. func (l *raftLog) stableSnapTo(i uint64) { l.unstable.stableSnapTo(i) }
  190. func (l *raftLog) lastTerm() uint64 {
  191. t, err := l.term(l.lastIndex())
  192. if err != nil {
  193. l.logger.Panicf("unexpected error when getting the last term (%v)", err)
  194. }
  195. return t
  196. }
  197. func (l *raftLog) term(i uint64) (uint64, error) {
  198. // the valid term range is [index of dummy entry, last index]
  199. dummyIndex := l.firstIndex() - 1
  200. if i < dummyIndex || i > l.lastIndex() {
  201. // TODO: return an error instead?
  202. return 0, nil
  203. }
  204. if t, ok := l.unstable.maybeTerm(i); ok {
  205. return t, nil
  206. }
  207. t, err := l.storage.Term(i)
  208. if err == nil {
  209. return t, nil
  210. }
  211. if err == ErrCompacted {
  212. return 0, err
  213. }
  214. panic(err) // TODO(bdarnell)
  215. }
  216. func (l *raftLog) entries(i, maxsize uint64) ([]pb.Entry, error) {
  217. if i > l.lastIndex() {
  218. return nil, nil
  219. }
  220. return l.slice(i, l.lastIndex()+1, maxsize)
  221. }
  222. // allEntries returns all entries in the log.
  223. func (l *raftLog) allEntries() []pb.Entry {
  224. ents, err := l.entries(l.firstIndex(), noLimit)
  225. if err == nil {
  226. return ents
  227. }
  228. if err == ErrCompacted { // try again if there was a racing compaction
  229. return l.allEntries()
  230. }
  231. // TODO (xiangli): handle error?
  232. panic(err)
  233. }
  234. // isUpToDate determines if the given (lastIndex,term) log is more up-to-date
  235. // by comparing the index and term of the last entries in the existing logs.
  236. // If the logs have last entries with different terms, then the log with the
  237. // later term is more up-to-date. If the logs end with the same term, then
  238. // whichever log has the larger lastIndex is more up-to-date. If the logs are
  239. // the same, the given log is up-to-date.
  240. func (l *raftLog) isUpToDate(lasti, term uint64) bool {
  241. return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
  242. }
  243. func (l *raftLog) matchTerm(i, term uint64) bool {
  244. t, err := l.term(i)
  245. if err != nil {
  246. return false
  247. }
  248. return t == term
  249. }
  250. func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
  251. if maxIndex > l.committed && l.zeroTermOnErrCompacted(l.term(maxIndex)) == term {
  252. l.commitTo(maxIndex)
  253. return true
  254. }
  255. return false
  256. }
  257. func (l *raftLog) restore(s pb.Snapshot) {
  258. l.logger.Infof("log [%s] starts to restore snapshot [index: %d, term: %d]", l, s.Metadata.Index, s.Metadata.Term)
  259. l.committed = s.Metadata.Index
  260. l.unstable.restore(s)
  261. }
  262. // slice returns a slice of log entries from lo through hi-1, inclusive.
  263. func (l *raftLog) slice(lo, hi, maxSize uint64) ([]pb.Entry, error) {
  264. err := l.mustCheckOutOfBounds(lo, hi)
  265. if err != nil {
  266. return nil, err
  267. }
  268. if lo == hi {
  269. return nil, nil
  270. }
  271. var ents []pb.Entry
  272. if lo < l.unstable.offset {
  273. storedEnts, err := l.storage.Entries(lo, min(hi, l.unstable.offset), maxSize)
  274. if err == ErrCompacted {
  275. return nil, err
  276. } else if err == ErrUnavailable {
  277. l.logger.Panicf("entries[%d:%d) is unavailable from storage", lo, min(hi, l.unstable.offset))
  278. } else if err != nil {
  279. panic(err) // TODO(bdarnell)
  280. }
  281. // check if ents has reached the size limitation
  282. if uint64(len(storedEnts)) < min(hi, l.unstable.offset)-lo {
  283. return storedEnts, nil
  284. }
  285. ents = storedEnts
  286. }
  287. if hi > l.unstable.offset {
  288. unstable := l.unstable.slice(max(lo, l.unstable.offset), hi)
  289. if len(ents) > 0 {
  290. ents = append([]pb.Entry{}, ents...)
  291. ents = append(ents, unstable...)
  292. } else {
  293. ents = unstable
  294. }
  295. }
  296. return limitSize(ents, maxSize), nil
  297. }
  298. // l.firstIndex <= lo <= hi <= l.firstIndex + len(l.entries)
  299. func (l *raftLog) mustCheckOutOfBounds(lo, hi uint64) error {
  300. if lo > hi {
  301. l.logger.Panicf("invalid slice %d > %d", lo, hi)
  302. }
  303. fi := l.firstIndex()
  304. if lo < fi {
  305. return ErrCompacted
  306. }
  307. length := l.lastIndex() - fi + 1
  308. if lo < fi || hi > fi+length {
  309. l.logger.Panicf("slice[%d,%d) out of bound [%d,%d]", lo, hi, fi, l.lastIndex())
  310. }
  311. return nil
  312. }
  313. func (l *raftLog) zeroTermOnErrCompacted(t uint64, err error) uint64 {
  314. if err == nil {
  315. return t
  316. }
  317. if err == ErrCompacted {
  318. return 0
  319. }
  320. l.logger.Panicf("unexpected error (%v)", err)
  321. return 0
  322. }