log.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. snapshot pb.Snapshot
  39. }
  40. func newLog(storage Storage) *raftLog {
  41. if storage == nil {
  42. panic("storage must not be nil")
  43. }
  44. log := &raftLog{
  45. storage: storage,
  46. }
  47. lastIndex, err := storage.LastIndex()
  48. if err == ErrStorageEmpty {
  49. // When starting from scratch populate the list with a dummy entry at term zero.
  50. log.unstableEnts = make([]pb.Entry, 1)
  51. } else if err == nil {
  52. log.unstable = lastIndex + 1
  53. } else {
  54. panic(err) // TODO(bdarnell)
  55. }
  56. return log
  57. }
  58. func (l *raftLog) String() string {
  59. return fmt.Sprintf("unstable=%d committed=%d applied=%d", l.unstable, l.committed, l.applied)
  60. }
  61. // maybeAppend returns (0, false) if the entries cannot be appended. Otherwise,
  62. // it returns (last index of new entries, true).
  63. func (l *raftLog) maybeAppend(index, logTerm, committed uint64, ents ...pb.Entry) (lastnewi uint64, ok bool) {
  64. lastnewi = index + uint64(len(ents))
  65. if l.matchTerm(index, logTerm) {
  66. from := index + 1
  67. ci := l.findConflict(from, ents)
  68. switch {
  69. case ci == 0:
  70. case ci <= l.committed:
  71. panic("conflict with committed entry")
  72. default:
  73. l.append(ci-1, ents[ci-from:]...)
  74. }
  75. tocommit := min(committed, lastnewi)
  76. // if toCommit > commitIndex, set commitIndex = toCommit
  77. if l.committed < tocommit {
  78. l.committed = tocommit
  79. }
  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("appending after %d, but already committed through %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[0:1+after-l.unstable], ents...)
  97. l.unstable = min(l.unstable, after+1)
  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(from uint64, ents []pb.Entry) uint64 {
  112. // TODO(xiangli): validate the index of ents
  113. for i, ne := range ents {
  114. if oe := l.at(from + uint64(i)); oe == nil || oe.Term != ne.Term {
  115. return from + uint64(i)
  116. }
  117. }
  118. return 0
  119. }
  120. func (l *raftLog) unstableEntries() []pb.Entry {
  121. if len(l.unstableEnts) == 0 {
  122. return nil
  123. }
  124. return append([]pb.Entry(nil), l.unstableEnts...)
  125. }
  126. // nextEnts returns all the available entries for execution.
  127. // all the returned entries will be marked as applied.
  128. func (l *raftLog) nextEnts() (ents []pb.Entry) {
  129. if l.committed > l.applied {
  130. return l.slice(l.applied+1, l.committed+1)
  131. }
  132. return nil
  133. }
  134. func (l *raftLog) firstIndex() uint64 {
  135. index, err := l.storage.FirstIndex()
  136. if err != nil {
  137. panic(err) // TODO(bdarnell)
  138. }
  139. return index
  140. }
  141. func (l *raftLog) lastIndex() uint64 {
  142. if len(l.unstableEnts) > 0 {
  143. return l.unstable + uint64(len(l.unstableEnts)) - 1
  144. }
  145. index, err := l.storage.LastIndex()
  146. if err != nil {
  147. panic(err) // TODO(bdarnell)
  148. }
  149. return index
  150. }
  151. func (l *raftLog) appliedTo(i uint64) {
  152. if i == 0 {
  153. return
  154. }
  155. if l.committed < i || i < l.applied {
  156. log.Panicf("applied[%d] is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
  157. }
  158. l.applied = i
  159. }
  160. func (l *raftLog) stableTo(i uint64) {
  161. if i < l.unstable || i+1-l.unstable > uint64(len(l.unstableEnts)) {
  162. log.Panicf("stableTo(%d) is out of range (unstable=%d, len(unstableEnts)=%d)",
  163. i, l.unstable, len(l.unstableEnts))
  164. }
  165. l.unstableEnts = l.unstableEnts[i+1-l.unstable:]
  166. l.unstable = i + 1
  167. }
  168. func (l *raftLog) lastTerm() uint64 {
  169. return l.term(l.lastIndex())
  170. }
  171. func (l *raftLog) term(i uint64) uint64 {
  172. if e := l.at(i); e != nil {
  173. return e.Term
  174. }
  175. return 0
  176. }
  177. func (l *raftLog) entries(i uint64) []pb.Entry {
  178. // never send out the first entry
  179. // first entry is only used for matching
  180. // prevLogTerm
  181. if i == 0 {
  182. panic("cannot return the first entry in log")
  183. }
  184. return l.slice(i, l.lastIndex()+1)
  185. }
  186. // allEntries returns all entries in the log, including the initial
  187. // entry that is only used for prevLogTerm validation. This method
  188. // should only be used for testing.
  189. func (l *raftLog) allEntries() []pb.Entry {
  190. return l.slice(l.firstIndex(), l.lastIndex()+1)
  191. }
  192. // isUpToDate determines if the given (lastIndex,term) log is more up-to-date
  193. // by comparing the index and term of the last entries in the existing logs.
  194. // If the logs have last entries with different terms, then the log with the
  195. // later term is more up-to-date. If the logs end with the same term, then
  196. // whichever log has the larger lastIndex is more up-to-date. If the logs are
  197. // the same, the given log is up-to-date.
  198. func (l *raftLog) isUpToDate(lasti, term uint64) bool {
  199. return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
  200. }
  201. func (l *raftLog) matchTerm(i, term uint64) bool {
  202. if e := l.at(i); e != nil {
  203. return e.Term == term
  204. }
  205. return false
  206. }
  207. func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
  208. if maxIndex > l.committed && l.term(maxIndex) == term {
  209. l.committed = maxIndex
  210. return true
  211. }
  212. return false
  213. }
  214. // compact compacts all log entries until i.
  215. // It removes the log entries before i, exclusive.
  216. // i must be not smaller than the index of the first entry
  217. // and not greater than the index of the last entry.
  218. // the number of entries after compaction will be returned.
  219. func (l *raftLog) compact(i uint64) uint64 {
  220. if l.isOutOfAppliedBounds(i) {
  221. panic(fmt.Sprintf("compact %d out of bounds (applied up to %d)", i, l.applied))
  222. }
  223. err := l.storage.Compact(i)
  224. if err != nil {
  225. panic(err) // TODO(bdarnell)
  226. }
  227. l.unstable = max(i+1, l.unstable)
  228. firstIndex, err := l.storage.FirstIndex()
  229. if err != nil {
  230. panic(err) // TODO(bdarnell)
  231. }
  232. lastIndex, err := l.storage.LastIndex()
  233. if err != nil {
  234. panic(err) // TODO(bdarnell)
  235. }
  236. return lastIndex - firstIndex
  237. }
  238. func (l *raftLog) snap(d []byte, index, term uint64, nodes []uint64) {
  239. l.snapshot = pb.Snapshot{
  240. Data: d,
  241. Nodes: nodes,
  242. Index: index,
  243. Term: term,
  244. }
  245. }
  246. func (l *raftLog) restore(s pb.Snapshot) {
  247. l.storage = &MemoryStorage{
  248. ents: []pb.Entry{{Term: s.Term}},
  249. offset: s.Index,
  250. }
  251. l.unstable = s.Index + 1
  252. l.unstableEnts = nil
  253. l.committed = s.Index
  254. l.applied = s.Index
  255. l.snapshot = s
  256. }
  257. func (l *raftLog) at(i uint64) *pb.Entry {
  258. ents := l.slice(i, i+1)
  259. if len(ents) == 0 {
  260. return nil
  261. }
  262. return &ents[0]
  263. }
  264. // slice returns a slice of log entries from lo through hi-1, inclusive.
  265. func (l *raftLog) slice(lo uint64, hi uint64) []pb.Entry {
  266. if lo >= hi {
  267. return nil
  268. }
  269. if l.isOutOfBounds(lo) || l.isOutOfBounds(hi-1) {
  270. return nil
  271. }
  272. var ents []pb.Entry
  273. if lo < l.unstable {
  274. storedEnts, err := l.storage.Entries(lo, min(hi, l.unstable))
  275. if err != nil {
  276. panic(err) // TODO(bdarnell)
  277. }
  278. ents = append(ents, storedEnts...)
  279. }
  280. if len(l.unstableEnts) > 0 && hi > l.unstable {
  281. var firstUnstable uint64
  282. if lo < l.unstable {
  283. firstUnstable = l.unstable
  284. } else {
  285. firstUnstable = lo
  286. }
  287. ents = append(ents, l.unstableEnts[firstUnstable-l.unstable:hi-l.unstable]...)
  288. }
  289. return ents
  290. }
  291. func (l *raftLog) isOutOfBounds(i uint64) bool {
  292. if i < l.firstIndex() || i > l.lastIndex() {
  293. return true
  294. }
  295. return false
  296. }
  297. func (l *raftLog) isOutOfAppliedBounds(i uint64) bool {
  298. if i < l.firstIndex() || i > l.applied {
  299. return true
  300. }
  301. return false
  302. }
  303. func min(a, b uint64) uint64 {
  304. if a > b {
  305. return b
  306. }
  307. return a
  308. }
  309. func max(a, b uint64) uint64 {
  310. if a > b {
  311. return a
  312. }
  313. return b
  314. }