log.go 9.5 KB

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