log.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. package raft
  2. import (
  3. "bufio"
  4. "code.google.com/p/goprotobuf/proto"
  5. "errors"
  6. "fmt"
  7. "github.com/coreos/go-raft/protobuf"
  8. "io"
  9. "os"
  10. "sync"
  11. )
  12. //------------------------------------------------------------------------------
  13. //
  14. // Typedefs
  15. //
  16. //------------------------------------------------------------------------------
  17. // A log is a collection of log entries that are persisted to durable storage.
  18. type Log struct {
  19. ApplyFunc func(Command) (interface{}, error)
  20. file *os.File
  21. path string
  22. entries []*LogEntry
  23. results []*logResult
  24. commitIndex uint64
  25. mutex sync.RWMutex
  26. startIndex uint64 // the index before the first entry in the Log entries
  27. startTerm uint64
  28. pBuffer *proto.Buffer
  29. pLogEntry *protobuf.ProtoLogEntry
  30. }
  31. // The results of the applying a log entry.
  32. type logResult struct {
  33. returnValue interface{}
  34. err error
  35. }
  36. //------------------------------------------------------------------------------
  37. //
  38. // Constructor
  39. //
  40. //------------------------------------------------------------------------------
  41. // Creates a new log.
  42. func newLog() *Log {
  43. return &Log{
  44. entries: make([]*LogEntry, 0),
  45. pBuffer: proto.NewBuffer(nil),
  46. pLogEntry: &protobuf.ProtoLogEntry{},
  47. }
  48. }
  49. //------------------------------------------------------------------------------
  50. //
  51. // Accessors
  52. //
  53. //------------------------------------------------------------------------------
  54. //--------------------------------------
  55. // Log Indices
  56. //--------------------------------------
  57. // The last committed index in the log.
  58. func (l *Log) CommitIndex() uint64 {
  59. l.mutex.RLock()
  60. defer l.mutex.RUnlock()
  61. return l.commitIndex
  62. }
  63. // The current index in the log.
  64. func (l *Log) currentIndex() uint64 {
  65. l.mutex.RLock()
  66. defer l.mutex.RUnlock()
  67. if len(l.entries) == 0 {
  68. return l.startIndex
  69. }
  70. return l.entries[len(l.entries)-1].Index
  71. }
  72. // The current index in the log without locking
  73. func (l *Log) internalCurrentIndex() uint64 {
  74. if len(l.entries) == 0 {
  75. return l.startIndex
  76. }
  77. return l.entries[len(l.entries)-1].Index
  78. }
  79. // The next index in the log.
  80. func (l *Log) nextIndex() uint64 {
  81. return l.currentIndex() + 1
  82. }
  83. // Determines if the log contains zero entries.
  84. func (l *Log) isEmpty() bool {
  85. l.mutex.RLock()
  86. defer l.mutex.RUnlock()
  87. return (len(l.entries) == 0) && (l.startIndex == 0)
  88. }
  89. // The name of the last command in the log.
  90. func (l *Log) lastCommandName() string {
  91. l.mutex.RLock()
  92. defer l.mutex.RUnlock()
  93. if len(l.entries) > 0 {
  94. if entry := l.entries[len(l.entries)-1]; entry != nil {
  95. return entry.CommandName
  96. }
  97. }
  98. return ""
  99. }
  100. //--------------------------------------
  101. // Log Terms
  102. //--------------------------------------
  103. // The current term in the log.
  104. func (l *Log) currentTerm() uint64 {
  105. l.mutex.RLock()
  106. defer l.mutex.RUnlock()
  107. if len(l.entries) == 0 {
  108. return l.startTerm
  109. }
  110. return l.entries[len(l.entries)-1].Term
  111. }
  112. //------------------------------------------------------------------------------
  113. //
  114. // Methods
  115. //
  116. //------------------------------------------------------------------------------
  117. //--------------------------------------
  118. // State
  119. //--------------------------------------
  120. // Opens the log file and reads existing entries. The log can remain open and
  121. // continue to append entries to the end of the log.
  122. func (l *Log) open(path string) error {
  123. // Read all the entries from the log if one exists.
  124. var readBytes int64
  125. var err error
  126. debugln("log.open.open ", path)
  127. // open log file
  128. l.file, err = os.OpenFile(path, os.O_RDWR, 0600)
  129. l.path = path
  130. if err != nil {
  131. // if the log file does not exist before
  132. // we create the log file and set commitIndex to 0
  133. if os.IsNotExist(err) {
  134. l.file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600)
  135. debugln("log.open.create ", path)
  136. return err
  137. }
  138. return err
  139. }
  140. debugln("log.open.exist ", path)
  141. // Read the file and decode entries.
  142. for {
  143. // Instantiate log entry and decode into it.
  144. entry, _ := newLogEntry(l, 0, 0, nil)
  145. entry.Position, _ = l.file.Seek(0, os.SEEK_CUR)
  146. n, err := entry.decode(l.file)
  147. if err != nil {
  148. if err == io.EOF {
  149. debugln("open.log.append: finish ")
  150. } else {
  151. if err = os.Truncate(path, readBytes); err != nil {
  152. return fmt.Errorf("raft.Log: Unable to recover: %v", err)
  153. }
  154. }
  155. break
  156. }
  157. // Append entry.
  158. l.entries = append(l.entries, entry)
  159. if entry.Index <= l.commitIndex {
  160. command, err := newCommand(entry.CommandName, entry.Command)
  161. if err != nil {
  162. continue
  163. }
  164. l.ApplyFunc(command)
  165. }
  166. debugln("open.log.append log index ", entry.Index)
  167. readBytes += int64(n)
  168. }
  169. l.results = make([]*logResult, len(l.entries))
  170. l.compact(l.startIndex, l.startTerm)
  171. debugln("open.log.recovery number of log ", len(l.entries))
  172. return nil
  173. }
  174. // Closes the log file.
  175. func (l *Log) close() {
  176. l.mutex.Lock()
  177. defer l.mutex.Unlock()
  178. if l.file != nil {
  179. l.file.Close()
  180. l.file = nil
  181. }
  182. l.entries = make([]*LogEntry, 0)
  183. l.results = make([]*logResult, 0)
  184. }
  185. //--------------------------------------
  186. // Entries
  187. //--------------------------------------
  188. // Creates a log entry associated with this log.
  189. func (l *Log) createEntry(term uint64, command Command) (*LogEntry, error) {
  190. return newLogEntry(l, l.nextIndex(), term, command)
  191. }
  192. // Retrieves an entry from the log. If the entry has been eliminated because
  193. // of a snapshot then nil is returned.
  194. func (l *Log) getEntry(index uint64) *LogEntry {
  195. l.mutex.RLock()
  196. defer l.mutex.RUnlock()
  197. if index <= l.startIndex || index > (l.startIndex+uint64(len(l.entries))) {
  198. return nil
  199. }
  200. return l.entries[index-l.startIndex-1]
  201. }
  202. // Checks if the log contains a given index/term combination.
  203. func (l *Log) containsEntry(index uint64, term uint64) bool {
  204. entry := l.getEntry(index)
  205. return (entry != nil && entry.Term == term)
  206. }
  207. // Retrieves a list of entries after a given index as well as the term of the
  208. // index provided. A nil list of entries is returned if the index no longer
  209. // exists because a snapshot was made.
  210. func (l *Log) getEntriesAfter(index uint64, maxLogEntriesPerRequest uint64) ([]*LogEntry, uint64) {
  211. l.mutex.Lock()
  212. defer l.mutex.Unlock()
  213. // Return nil if index is before the start of the log.
  214. if index < l.startIndex {
  215. traceln("log.entriesAfter.before: ", index, " ", l.startIndex)
  216. return nil, 0
  217. }
  218. // Return an error if the index doesn't exist.
  219. if index > (uint64(len(l.entries)) + l.startIndex) {
  220. panic(fmt.Sprintf("raft: Index is beyond end of log: %v %v", len(l.entries), index))
  221. }
  222. // If we're going from the beginning of the log then return the whole log.
  223. if index == l.startIndex {
  224. traceln("log.entriesAfter.beginning: ", index, " ", l.startIndex)
  225. return l.entries, l.startTerm
  226. }
  227. traceln("log.entriesAfter.partial: ", index, " ", l.entries[len(l.entries)-1].Index)
  228. entries := l.entries[index-l.startIndex:]
  229. length := len(entries)
  230. if uint64(length) < maxLogEntriesPerRequest {
  231. // Determine the term at the given entry and return a subslice.
  232. return entries, l.entries[index-1-l.startIndex].Term
  233. } else {
  234. return entries[:maxLogEntriesPerRequest], l.entries[index-1-l.startIndex].Term
  235. }
  236. }
  237. // Retrieves the return value and error for an entry. The result can only exist
  238. // after the entry has been committed.
  239. func (l *Log) getEntryResult(entry *LogEntry, clear bool) (interface{}, error) {
  240. l.mutex.RLock()
  241. defer l.mutex.RUnlock()
  242. if entry == nil {
  243. panic("raft: Log entry required for error retrieval")
  244. }
  245. debugln("getEntryResult.result index: ", entry.Index-l.startIndex-1)
  246. // If a result exists for the entry then return it with its error.
  247. if entry.Index > l.startIndex && entry.Index <= l.startIndex+uint64(len(l.results)) {
  248. if result := l.results[entry.Index-l.startIndex-1]; result != nil {
  249. // keep the records before remove it
  250. returnValue, err := result.returnValue, result.err
  251. // Remove reference to result if it's being cleared after retrieval.
  252. if clear {
  253. result.returnValue = nil
  254. }
  255. return returnValue, err
  256. }
  257. }
  258. return nil, nil
  259. }
  260. //--------------------------------------
  261. // Commit
  262. //--------------------------------------
  263. // Retrieves the last index and term that has been committed to the log.
  264. func (l *Log) commitInfo() (index uint64, term uint64) {
  265. l.mutex.RLock()
  266. defer l.mutex.RUnlock()
  267. // If we don't have any committed entries then just return zeros.
  268. if l.commitIndex == 0 {
  269. return 0, 0
  270. }
  271. // No new commit log after snapshot
  272. if l.commitIndex == l.startIndex {
  273. return l.startIndex, l.startTerm
  274. }
  275. // Return the last index & term from the last committed entry.
  276. debugln("commitInfo.get.[", l.commitIndex, "/", l.startIndex, "]")
  277. entry := l.entries[l.commitIndex-1-l.startIndex]
  278. return entry.Index, entry.Term
  279. }
  280. // Retrieves the last index and term that has been committed to the log.
  281. func (l *Log) lastInfo() (index uint64, term uint64) {
  282. l.mutex.RLock()
  283. defer l.mutex.RUnlock()
  284. // If we don't have any entries then just return zeros.
  285. if len(l.entries) == 0 {
  286. return l.startIndex, l.startTerm
  287. }
  288. // Return the last index & term
  289. entry := l.entries[len(l.entries)-1]
  290. return entry.Index, entry.Term
  291. }
  292. // Updates the commit index
  293. func (l *Log) updateCommitIndex(index uint64) {
  294. l.mutex.Lock()
  295. defer l.mutex.Unlock()
  296. l.commitIndex = index
  297. }
  298. // Updates the commit index and writes entries after that index to the stable storage.
  299. func (l *Log) setCommitIndex(index uint64) error {
  300. l.mutex.Lock()
  301. defer l.mutex.Unlock()
  302. // this is not error any more after limited the number of sending entries
  303. // commit up to what we already have
  304. if index > l.startIndex+uint64(len(l.entries)) {
  305. debugln("raft.Log: Commit index", index, "set back to ", len(l.entries))
  306. index = l.startIndex + uint64(len(l.entries))
  307. }
  308. // Do not allow previous indices to be committed again.
  309. // This could happens, since the guarantee is that the new leader has up-to-dated
  310. // log entires rather than has most up-to-dated committed index
  311. // For example, Leader 1 send log 80 to follower 2 and follower 3
  312. // follower 2 and follow 3 all got the new entries and reply
  313. // leader 1 committed entry 80 and send reply to follower 2 and follower3
  314. // follower 2 receive the new committed index and update committed index to 80
  315. // leader 1 fail to send the committed index to follower 3
  316. // follower 3 promote to leader (server 1 and server 2 will vote, since leader 3
  317. // has up-to-dated the entries)
  318. // when new leader 3 send heartbeat with committed index = 0 to follower 2,
  319. // follower 2 should reply success and let leader 3 update the committed index to 80
  320. if index < l.commitIndex {
  321. return nil
  322. }
  323. // Find all entries whose index is between the previous index and the current index.
  324. for i := l.commitIndex + 1; i <= index; i++ {
  325. entryIndex := i - 1 - l.startIndex
  326. entry := l.entries[entryIndex]
  327. // Update commit index.
  328. l.commitIndex = entry.Index
  329. // Decode the command.
  330. command, err := newCommand(entry.CommandName, entry.Command)
  331. if err != nil {
  332. return err
  333. }
  334. // Apply the changes to the state machine and store the error code.
  335. returnValue, err := l.ApplyFunc(command)
  336. debugln("setCommitIndex.set.result index: ", entryIndex)
  337. l.results[entryIndex] = &logResult{returnValue: returnValue, err: err}
  338. }
  339. return nil
  340. }
  341. // Set the commitIndex at the head of the log file to the current
  342. // commit Index. This should be called after obtained a log lock
  343. func (l *Log) flushCommitIndex() {
  344. l.file.Seek(0, os.SEEK_SET)
  345. fmt.Fprintf(l.file, "%8x\n", l.commitIndex)
  346. l.file.Seek(0, os.SEEK_END)
  347. }
  348. //--------------------------------------
  349. // Truncation
  350. //--------------------------------------
  351. // Truncates the log to the given index and term. This only works if the log
  352. // at the index has not been committed.
  353. func (l *Log) truncate(index uint64, term uint64) error {
  354. l.mutex.Lock()
  355. defer l.mutex.Unlock()
  356. debugln("log.truncate: ", index)
  357. // Do not allow committed entries to be truncated.
  358. if index < l.commitIndex {
  359. debugln("log.truncate.before")
  360. return fmt.Errorf("raft.Log: Index is already committed (%v): (IDX=%v, TERM=%v)", l.commitIndex, index, term)
  361. }
  362. // Do not truncate past end of entries.
  363. if index > l.startIndex+uint64(len(l.entries)) {
  364. debugln("log.truncate.after")
  365. return fmt.Errorf("raft.Log: Entry index does not exist (MAX=%v): (IDX=%v, TERM=%v)", len(l.entries), index, term)
  366. }
  367. // If we're truncating everything then just clear the entries.
  368. if index == l.startIndex {
  369. debugln("log.truncate.clear")
  370. l.file.Truncate(0)
  371. l.file.Seek(0, os.SEEK_SET)
  372. l.entries = []*LogEntry{}
  373. } else {
  374. // Do not truncate if the entry at index does not have the matching term.
  375. entry := l.entries[index-l.startIndex-1]
  376. if len(l.entries) > 0 && entry.Term != term {
  377. debugln("log.truncate.termMismatch")
  378. return fmt.Errorf("raft.Log: Entry at index does not have matching term (%v): (IDX=%v, TERM=%v)", entry.Term, index, term)
  379. }
  380. // Otherwise truncate up to the desired entry.
  381. if index < l.startIndex+uint64(len(l.entries)) {
  382. debugln("log.truncate.finish")
  383. position := l.entries[index-l.startIndex].Position
  384. l.file.Truncate(position)
  385. l.file.Seek(position, os.SEEK_SET)
  386. l.entries = l.entries[0 : index-l.startIndex]
  387. }
  388. }
  389. return nil
  390. }
  391. //--------------------------------------
  392. // Append
  393. //--------------------------------------
  394. // Appends a series of entries to the log. These entries are not written to
  395. // disk until setCommitIndex() is called.
  396. func (l *Log) appendEntries(entries []*LogEntry) error {
  397. l.mutex.Lock()
  398. defer l.mutex.Unlock()
  399. startPosition, _ := l.file.Seek(0, os.SEEK_CUR)
  400. w := bufio.NewWriter(l.file)
  401. var size int64
  402. var err error
  403. // Append each entry but exit if we hit an error.
  404. for _, entry := range entries {
  405. entry.log = l
  406. if size, err = l.writeEntry(entry, w); err != nil {
  407. return err
  408. }
  409. entry.Position = startPosition
  410. startPosition += size
  411. }
  412. w.Flush()
  413. return nil
  414. }
  415. // Writes a single log entry to the end of the log. This function does not
  416. // obtain a lock and should only be used internally. Use AppendEntries() and
  417. // AppendEntry() to use it externally.
  418. func (l *Log) appendEntry(entry *LogEntry) error {
  419. if l.file == nil {
  420. return errors.New("raft.Log: Log is not open")
  421. }
  422. // Make sure the term and index are greater than the previous.
  423. if len(l.entries) > 0 {
  424. lastEntry := l.entries[len(l.entries)-1]
  425. if entry.Term < lastEntry.Term {
  426. return fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  427. } else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
  428. return fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  429. }
  430. }
  431. position, _ := l.file.Seek(0, os.SEEK_CUR)
  432. entry.Position = position
  433. // Write to storage.
  434. if _, err := entry.encode(l.file); err != nil {
  435. return err
  436. }
  437. // Append to entries list if stored on disk.
  438. l.entries = append(l.entries, entry)
  439. l.results = append(l.results, nil)
  440. return nil
  441. }
  442. // appendEntry with Buffered io
  443. func (l *Log) writeEntry(entry *LogEntry, w io.Writer) (int64, error) {
  444. if l.file == nil {
  445. return -1, errors.New("raft.Log: Log is not open")
  446. }
  447. // Make sure the term and index are greater than the previous.
  448. if len(l.entries) > 0 {
  449. lastEntry := l.entries[len(l.entries)-1]
  450. if entry.Term < lastEntry.Term {
  451. return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  452. } else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
  453. return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  454. }
  455. }
  456. // Write to storage.
  457. size, err := entry.encode(w)
  458. if err != nil {
  459. return -1, err
  460. }
  461. // Append to entries list if stored on disk.
  462. l.entries = append(l.entries, entry)
  463. l.results = append(l.results, nil)
  464. return int64(size), nil
  465. }
  466. //--------------------------------------
  467. // Log compaction
  468. //--------------------------------------
  469. // compact the log before index (including index)
  470. func (l *Log) compact(index uint64, term uint64) error {
  471. var entries []*LogEntry
  472. var results []*logResult
  473. l.mutex.Lock()
  474. defer l.mutex.Unlock()
  475. if index == 0 {
  476. return nil
  477. }
  478. // nothing to compaction
  479. // the index may be greater than the current index if
  480. // we just recovery from on snapshot
  481. if index >= l.internalCurrentIndex() {
  482. entries = make([]*LogEntry, 0)
  483. results = make([]*logResult, 0)
  484. } else {
  485. // get all log entries after index
  486. entries = l.entries[index-l.startIndex:]
  487. results = l.results[index-l.startIndex:]
  488. }
  489. // create a new log file and add all the entries
  490. file, err := os.OpenFile(l.path+".new", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
  491. if err != nil {
  492. return err
  493. }
  494. for _, entry := range entries {
  495. position, _ := l.file.Seek(0, os.SEEK_CUR)
  496. entry.Position = position
  497. if _, err = entry.encode(file); err != nil {
  498. return err
  499. }
  500. }
  501. // close the current log file
  502. l.file.Close()
  503. // remove the current log file to .bak
  504. err = os.Remove(l.path)
  505. if err != nil {
  506. return err
  507. }
  508. // rename the new log file
  509. err = os.Rename(l.path+".new", l.path)
  510. if err != nil {
  511. return err
  512. }
  513. l.file = file
  514. // compaction the in memory log
  515. l.entries = entries
  516. l.results = results
  517. l.startIndex = index
  518. l.startTerm = term
  519. return nil
  520. }