log.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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.GetLastIndex()
  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.unstable {
  86. // The log is being truncated to before our current unstable
  87. // portion, so discard it and reset unstable.
  88. l.unstableEnts = nil
  89. l.unstable = after + 1
  90. }
  91. // Truncate any unstable entries that are being replaced, then
  92. // append the new ones.
  93. l.unstableEnts = append(l.unstableEnts[0:1+after-l.unstable], ents...)
  94. l.unstable = min(l.unstable, after+1)
  95. return l.lastIndex()
  96. }
  97. // findConflict finds the index of the conflict.
  98. // It returns the first pair of conflicting entries between the existing
  99. // entries and the given entries, if there are any.
  100. // If there is no conflicting entries, and the existing entries contains
  101. // all the given entries, zero will be returned.
  102. // If there is no conflicting entries, but the given entries contains new
  103. // entries, the index of the first new entry will be returned.
  104. // An entry is considered to be conflicting if it has the same index but
  105. // a different term.
  106. // The first entry MUST have an index equal to the argument 'from'.
  107. // The index of the given entries MUST be continuously increasing.
  108. func (l *raftLog) findConflict(from uint64, ents []pb.Entry) uint64 {
  109. // TODO(xiangli): validate the index of ents
  110. for i, ne := range ents {
  111. if oe := l.at(from + uint64(i)); oe == nil || oe.Term != ne.Term {
  112. return from + uint64(i)
  113. }
  114. }
  115. return 0
  116. }
  117. func (l *raftLog) unstableEntries() []pb.Entry {
  118. if len(l.unstableEnts) == 0 {
  119. return nil
  120. }
  121. cpy := make([]pb.Entry, len(l.unstableEnts))
  122. copy(cpy, l.unstableEnts)
  123. return cpy
  124. }
  125. // nextEnts returns all the available entries for execution.
  126. // all the returned entries will be marked as applied.
  127. func (l *raftLog) nextEnts() (ents []pb.Entry) {
  128. if l.committed > l.applied {
  129. return l.slice(l.applied+1, l.committed+1)
  130. }
  131. return nil
  132. }
  133. func (l *raftLog) firstIndex() uint64 {
  134. index, err := l.storage.GetFirstIndex()
  135. if err != nil {
  136. panic(err) // TODO(bdarnell)
  137. }
  138. return index
  139. }
  140. func (l *raftLog) lastIndex() uint64 {
  141. if len(l.unstableEnts) > 0 {
  142. return l.unstable + uint64(len(l.unstableEnts)) - 1
  143. }
  144. index, err := l.storage.GetLastIndex()
  145. if err != nil {
  146. panic(err) // TODO(bdarnell)
  147. }
  148. return index
  149. }
  150. func (l *raftLog) appliedTo(i uint64) {
  151. if i == 0 {
  152. return
  153. }
  154. if l.committed < i || i < l.applied {
  155. log.Panicf("applied[%d] is out of range [prevApplied(%d), committed(%d)]", i, l.applied, l.committed)
  156. }
  157. l.applied = i
  158. }
  159. func (l *raftLog) stableTo(i uint64) {
  160. l.unstableEnts = l.unstableEnts[i+1-l.unstable:]
  161. l.unstable = i + 1
  162. }
  163. func (l *raftLog) lastTerm() uint64 {
  164. return l.term(l.lastIndex())
  165. }
  166. func (l *raftLog) term(i uint64) uint64 {
  167. if e := l.at(i); e != nil {
  168. return e.Term
  169. }
  170. return 0
  171. }
  172. func (l *raftLog) entries(i uint64) []pb.Entry {
  173. // never send out the first entry
  174. // first entry is only used for matching
  175. // prevLogTerm
  176. if i == 0 {
  177. panic("cannot return the first entry in log")
  178. }
  179. return l.slice(i, l.lastIndex()+1)
  180. }
  181. // allEntries returns all entries in the log, including the initial
  182. // entry that is only used for prevLogTerm validation. This method
  183. // should only be used for testing.
  184. func (l *raftLog) allEntries() []pb.Entry {
  185. return l.slice(l.firstIndex(), l.lastIndex()+1)
  186. }
  187. // isUpToDate determines if the given (lastIndex,term) log is more up-to-date
  188. // by comparing the index and term of the last entries in the existing logs.
  189. // If the logs have last entries with different terms, then the log with the
  190. // later term is more up-to-date. If the logs end with the same term, then
  191. // whichever log has the larger lastIndex is more up-to-date. If the logs are
  192. // the same, the given log is up-to-date.
  193. func (l *raftLog) isUpToDate(lasti, term uint64) bool {
  194. return term > l.lastTerm() || (term == l.lastTerm() && lasti >= l.lastIndex())
  195. }
  196. func (l *raftLog) matchTerm(i, term uint64) bool {
  197. if e := l.at(i); e != nil {
  198. return e.Term == term
  199. }
  200. return false
  201. }
  202. func (l *raftLog) maybeCommit(maxIndex, term uint64) bool {
  203. if maxIndex > l.committed && l.term(maxIndex) == term {
  204. l.committed = maxIndex
  205. return true
  206. }
  207. return false
  208. }
  209. // compact compacts all log entries until i.
  210. // It removes the log entries before i, exclusive.
  211. // i must be not smaller than the index of the first entry
  212. // and not greater than the index of the last entry.
  213. // the number of entries after compaction will be returned.
  214. func (l *raftLog) compact(i uint64) uint64 {
  215. if l.isOutOfAppliedBounds(i) {
  216. panic(fmt.Sprintf("compact %d out of bounds (applied up to %d)", i, l.applied))
  217. }
  218. err := l.storage.Compact(i)
  219. if err != nil {
  220. panic(err) // TODO(bdarnell)
  221. }
  222. l.unstable = max(i+1, l.unstable)
  223. firstIndex, err := l.storage.GetFirstIndex()
  224. if err != nil {
  225. panic(err) // TODO(bdarnell)
  226. }
  227. lastIndex, err := l.storage.GetLastIndex()
  228. if err != nil {
  229. panic(err) // TODO(bdarnell)
  230. }
  231. return lastIndex - firstIndex
  232. }
  233. func (l *raftLog) snap(d []byte, index, term uint64, nodes []uint64) {
  234. l.snapshot = pb.Snapshot{
  235. Data: d,
  236. Nodes: nodes,
  237. Index: index,
  238. Term: term,
  239. }
  240. }
  241. func (l *raftLog) restore(s pb.Snapshot) {
  242. l.storage = &MemoryStorage{
  243. ents: []pb.Entry{{Term: s.Term}},
  244. offset: s.Index,
  245. }
  246. l.unstable = s.Index + 1
  247. l.unstableEnts = nil
  248. l.committed = s.Index
  249. l.applied = s.Index
  250. l.snapshot = s
  251. }
  252. func (l *raftLog) at(i uint64) *pb.Entry {
  253. ents := l.slice(i, i+1)
  254. if len(ents) == 0 {
  255. return nil
  256. }
  257. return &ents[0]
  258. }
  259. // slice returns a slice of log entries from lo through hi-1, inclusive.
  260. func (l *raftLog) slice(lo uint64, hi uint64) []pb.Entry {
  261. if lo >= hi {
  262. return nil
  263. }
  264. if l.isOutOfBounds(lo) || l.isOutOfBounds(hi-1) {
  265. return nil
  266. }
  267. var ents []pb.Entry
  268. if lo < l.unstable {
  269. storedEnts, err := l.storage.GetEntries(lo, min(hi, l.unstable))
  270. if err != nil {
  271. panic(err) // TODO(bdarnell)
  272. }
  273. ents = append(ents, storedEnts...)
  274. }
  275. if len(l.unstableEnts) > 0 && hi > l.unstable {
  276. var firstUnstable uint64
  277. if lo < l.unstable {
  278. firstUnstable = l.unstable
  279. } else {
  280. firstUnstable = lo
  281. }
  282. ents = append(ents, l.unstableEnts[firstUnstable-l.unstable:hi-l.unstable]...)
  283. }
  284. return ents
  285. }
  286. func (l *raftLog) isOutOfBounds(i uint64) bool {
  287. if i < l.firstIndex() || i > l.lastIndex() {
  288. return true
  289. }
  290. return false
  291. }
  292. func (l *raftLog) isOutOfAppliedBounds(i uint64) bool {
  293. if i < l.firstIndex() || i > l.applied {
  294. return true
  295. }
  296. return false
  297. }
  298. func min(a, b uint64) uint64 {
  299. if a > b {
  300. return b
  301. }
  302. return a
  303. }
  304. func max(a, b uint64) uint64 {
  305. if a > b {
  306. return a
  307. }
  308. return b
  309. }