log.go 10 KB

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