log.go 9.1 KB

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