log.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. package raft
  2. import (
  3. "bufio"
  4. "code.google.com/p/goprotobuf/proto"
  5. "errors"
  6. "fmt"
  7. "github.com/benbjohnson/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. debugln("open.log.append log index ", entry.Index)
  160. readBytes += int64(n)
  161. }
  162. l.results = make([]*logResult, len(l.entries))
  163. l.compact(l.startIndex, l.startTerm)
  164. debugln("open.log.recovery number of log ", len(l.entries))
  165. return nil
  166. }
  167. // Closes the log file.
  168. func (l *Log) close() {
  169. l.mutex.Lock()
  170. defer l.mutex.Unlock()
  171. if l.file != nil {
  172. l.file.Close()
  173. l.file = nil
  174. }
  175. l.entries = make([]*LogEntry, 0)
  176. l.results = make([]*logResult, 0)
  177. }
  178. //--------------------------------------
  179. // Entries
  180. //--------------------------------------
  181. // Creates a log entry associated with this log.
  182. func (l *Log) createEntry(term uint64, command Command) (*LogEntry, error) {
  183. return newLogEntry(l, l.nextIndex(), term, command)
  184. }
  185. // Retrieves an entry from the log. If the entry has been eliminated because
  186. // of a snapshot then nil is returned.
  187. func (l *Log) getEntry(index uint64) *LogEntry {
  188. l.mutex.RLock()
  189. defer l.mutex.RUnlock()
  190. if index <= l.startIndex || index > (l.startIndex+uint64(len(l.entries))) {
  191. return nil
  192. }
  193. return l.entries[index-l.startIndex-1]
  194. }
  195. // Checks if the log contains a given index/term combination.
  196. func (l *Log) containsEntry(index uint64, term uint64) bool {
  197. entry := l.getEntry(index)
  198. return (entry != nil && entry.Term == term)
  199. }
  200. // Retrieves a list of entries after a given index as well as the term of the
  201. // index provided. A nil list of entries is returned if the index no longer
  202. // exists because a snapshot was made.
  203. func (l *Log) getEntriesAfter(index uint64, maxLogEntriesPerRequest uint64) ([]*LogEntry, uint64) {
  204. l.mutex.Lock()
  205. defer l.mutex.Unlock()
  206. // Return nil if index is before the start of the log.
  207. if index < l.startIndex {
  208. traceln("log.entriesAfter.before: ", index, " ", l.startIndex)
  209. return nil, 0
  210. }
  211. // Return an error if the index doesn't exist.
  212. if index > (uint64(len(l.entries)) + l.startIndex) {
  213. panic(fmt.Sprintf("raft: Index is beyond end of log: %v %v", len(l.entries), index))
  214. }
  215. // If we're going from the beginning of the log then return the whole log.
  216. if index == l.startIndex {
  217. traceln("log.entriesAfter.beginning: ", index, " ", l.startIndex)
  218. return l.entries, l.startTerm
  219. }
  220. traceln("log.entriesAfter.partial: ", index, " ", l.entries[len(l.entries)-1].Index)
  221. entries := l.entries[index-l.startIndex:]
  222. length := len(entries)
  223. if uint64(length) < maxLogEntriesPerRequest {
  224. // Determine the term at the given entry and return a subslice.
  225. return entries, l.entries[index-1-l.startIndex].Term
  226. } else {
  227. return entries[:maxLogEntriesPerRequest], l.entries[index-1-l.startIndex].Term
  228. }
  229. }
  230. // Retrieves the return value and error for an entry. The result can only exist
  231. // after the entry has been committed.
  232. func (l *Log) getEntryResult(entry *LogEntry, clear bool) (interface{}, error) {
  233. l.mutex.RLock()
  234. defer l.mutex.RUnlock()
  235. if entry == nil {
  236. panic("raft: Log entry required for error retrieval")
  237. }
  238. debugln("getEntryResult.result index: ", entry.Index-l.startIndex-1)
  239. // If a result exists for the entry then return it with its error.
  240. if entry.Index > l.startIndex && entry.Index <= l.startIndex+uint64(len(l.results)) {
  241. if result := l.results[entry.Index-l.startIndex-1]; result != nil {
  242. // keep the records before remove it
  243. returnValue, err := result.returnValue, result.err
  244. // Remove reference to result if it's being cleared after retrieval.
  245. if clear {
  246. result.returnValue = nil
  247. }
  248. return returnValue, err
  249. }
  250. }
  251. return nil, nil
  252. }
  253. //--------------------------------------
  254. // Commit
  255. //--------------------------------------
  256. // Retrieves the last index and term that has been committed to the log.
  257. func (l *Log) commitInfo() (index uint64, term uint64) {
  258. l.mutex.RLock()
  259. defer l.mutex.RUnlock()
  260. // If we don't have any committed entries then just return zeros.
  261. if l.commitIndex == 0 {
  262. return 0, 0
  263. }
  264. // No new commit log after snapshot
  265. if l.commitIndex == l.startIndex {
  266. return l.startIndex, l.startTerm
  267. }
  268. // Return the last index & term from the last committed entry.
  269. debugln("commitInfo.get.[", l.commitIndex, "/", l.startIndex, "]")
  270. entry := l.entries[l.commitIndex-1-l.startIndex]
  271. return entry.Index, entry.Term
  272. }
  273. // Retrieves the last index and term that has been committed to the log.
  274. func (l *Log) lastInfo() (index uint64, term uint64) {
  275. l.mutex.RLock()
  276. defer l.mutex.RUnlock()
  277. // If we don't have any entries then just return zeros.
  278. if len(l.entries) == 0 {
  279. return l.startIndex, l.startTerm
  280. }
  281. // Return the last index & term
  282. entry := l.entries[len(l.entries)-1]
  283. return entry.Index, entry.Term
  284. }
  285. // Updates the commit index
  286. func (l *Log) updateCommitIndex(index uint64) {
  287. l.mutex.Lock()
  288. defer l.mutex.Unlock()
  289. l.commitIndex = index
  290. }
  291. // Updates the commit index and writes entries after that index to the stable storage.
  292. func (l *Log) setCommitIndex(index uint64) error {
  293. l.mutex.Lock()
  294. defer l.mutex.Unlock()
  295. // this is not error any more after limited the number of sending entries
  296. // commit up to what we already have
  297. if index > l.startIndex+uint64(len(l.entries)) {
  298. debugln("raft.Log: Commit index", index, "set back to ", len(l.entries))
  299. index = l.startIndex + uint64(len(l.entries))
  300. }
  301. // Do not allow previous indices to be committed again.
  302. // This could happens, since the guarantee is that the new leader has up-to-dated
  303. // log entires rather than has most up-to-dated committed index
  304. // For example, Leader 1 send log 80 to follower 2 and follower 3
  305. // follower 2 and follow 3 all got the new entries and reply
  306. // leader 1 committed entry 80 and send reply to follower 2 and follower3
  307. // follower 2 receive the new committed index and update committed index to 80
  308. // leader 1 fail to send the committed index to follower 3
  309. // follower 3 promote to leader (server 1 and server 2 will vote, since leader 3
  310. // has up-to-dated the entries)
  311. // when new leader 3 send heartbeat with committed index = 0 to follower 2,
  312. // follower 2 should reply success and let leader 3 update the committed index to 80
  313. if index < l.commitIndex {
  314. return nil
  315. }
  316. // Find all entries whose index is between the previous index and the current index.
  317. for i := l.commitIndex + 1; i <= index; i++ {
  318. entryIndex := i - 1 - l.startIndex
  319. entry := l.entries[entryIndex]
  320. // Update commit index.
  321. l.commitIndex = entry.Index
  322. // Decode the command.
  323. command, err := newCommand(entry.CommandName, entry.Command)
  324. if err != nil {
  325. return err
  326. }
  327. // Apply the changes to the state machine and store the error code.
  328. returnValue, err := l.ApplyFunc(command)
  329. debugln("setCommitIndex.set.result index: ", entryIndex)
  330. l.results[entryIndex] = &logResult{returnValue: returnValue, err: err}
  331. }
  332. return nil
  333. }
  334. // Set the commitIndex at the head of the log file to the current
  335. // commit Index. This should be called after obtained a log lock
  336. func (l *Log) flushCommitIndex() {
  337. l.file.Seek(0, os.SEEK_SET)
  338. fmt.Fprintf(l.file, "%8x\n", l.commitIndex)
  339. l.file.Seek(0, os.SEEK_END)
  340. }
  341. //--------------------------------------
  342. // Truncation
  343. //--------------------------------------
  344. // Truncates the log to the given index and term. This only works if the log
  345. // at the index has not been committed.
  346. func (l *Log) truncate(index uint64, term uint64) error {
  347. l.mutex.Lock()
  348. defer l.mutex.Unlock()
  349. debugln("log.truncate: ", index)
  350. // Do not allow committed entries to be truncated.
  351. if index < l.commitIndex {
  352. debugln("log.truncate.before")
  353. return fmt.Errorf("raft.Log: Index is already committed (%v): (IDX=%v, TERM=%v)", l.commitIndex, index, term)
  354. }
  355. // Do not truncate past end of entries.
  356. if index > l.startIndex+uint64(len(l.entries)) {
  357. debugln("log.truncate.after")
  358. return fmt.Errorf("raft.Log: Entry index does not exist (MAX=%v): (IDX=%v, TERM=%v)", len(l.entries), index, term)
  359. }
  360. // If we're truncating everything then just clear the entries.
  361. if index == l.startIndex {
  362. debugln("log.truncate.clear")
  363. l.file.Truncate(0)
  364. l.file.Seek(0, os.SEEK_SET)
  365. l.entries = []*LogEntry{}
  366. } else {
  367. // Do not truncate if the entry at index does not have the matching term.
  368. entry := l.entries[index-l.startIndex-1]
  369. if len(l.entries) > 0 && entry.Term != term {
  370. debugln("log.truncate.termMismatch")
  371. return fmt.Errorf("raft.Log: Entry at index does not have matching term (%v): (IDX=%v, TERM=%v)", entry.Term, index, term)
  372. }
  373. // Otherwise truncate up to the desired entry.
  374. if index < l.startIndex+uint64(len(l.entries)) {
  375. debugln("log.truncate.finish")
  376. position := l.entries[index-l.startIndex].Position
  377. l.file.Truncate(position)
  378. l.file.Seek(position, os.SEEK_SET)
  379. l.entries = l.entries[0 : index-l.startIndex]
  380. }
  381. }
  382. return nil
  383. }
  384. //--------------------------------------
  385. // Append
  386. //--------------------------------------
  387. // Appends a series of entries to the log. These entries are not written to
  388. // disk until setCommitIndex() is called.
  389. func (l *Log) appendEntries(entries []*LogEntry) error {
  390. l.mutex.Lock()
  391. defer l.mutex.Unlock()
  392. startPosition, _ := l.file.Seek(0, os.SEEK_CUR)
  393. w := bufio.NewWriter(l.file)
  394. var size int64
  395. var err error
  396. // Append each entry but exit if we hit an error.
  397. for _, entry := range entries {
  398. entry.log = l
  399. if size, err = l.writeEntry(entry, w); err != nil {
  400. return err
  401. }
  402. entry.Position = startPosition
  403. startPosition += size
  404. }
  405. w.Flush()
  406. return nil
  407. }
  408. // Writes a single log entry to the end of the log. This function does not
  409. // obtain a lock and should only be used internally. Use AppendEntries() and
  410. // AppendEntry() to use it externally.
  411. func (l *Log) appendEntry(entry *LogEntry) error {
  412. if l.file == nil {
  413. return errors.New("raft.Log: Log is not open")
  414. }
  415. // Make sure the term and index are greater than the previous.
  416. if len(l.entries) > 0 {
  417. lastEntry := l.entries[len(l.entries)-1]
  418. if entry.Term < lastEntry.Term {
  419. return fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  420. } else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
  421. 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)
  422. }
  423. }
  424. position, _ := l.file.Seek(0, os.SEEK_CUR)
  425. entry.Position = position
  426. // Write to storage.
  427. if _, err := entry.encode(l.file); err != nil {
  428. return err
  429. }
  430. // Append to entries list if stored on disk.
  431. l.entries = append(l.entries, entry)
  432. l.results = append(l.results, nil)
  433. return nil
  434. }
  435. // appendEntry with Buffered io
  436. func (l *Log) writeEntry(entry *LogEntry, w io.Writer) (int64, error) {
  437. if l.file == nil {
  438. return -1, errors.New("raft.Log: Log is not open")
  439. }
  440. // Make sure the term and index are greater than the previous.
  441. if len(l.entries) > 0 {
  442. lastEntry := l.entries[len(l.entries)-1]
  443. if entry.Term < lastEntry.Term {
  444. return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  445. } else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
  446. 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)
  447. }
  448. }
  449. // Write to storage.
  450. size, err := entry.encode(w)
  451. if err != nil {
  452. return -1, err
  453. }
  454. // Append to entries list if stored on disk.
  455. l.entries = append(l.entries, entry)
  456. l.results = append(l.results, nil)
  457. return int64(size), nil
  458. }
  459. //--------------------------------------
  460. // Log compaction
  461. //--------------------------------------
  462. // compact the log before index (including index)
  463. func (l *Log) compact(index uint64, term uint64) error {
  464. var entries []*LogEntry
  465. var results []*logResult
  466. l.mutex.Lock()
  467. defer l.mutex.Unlock()
  468. if index == 0 {
  469. return nil
  470. }
  471. // nothing to compaction
  472. // the index may be greater than the current index if
  473. // we just recovery from on snapshot
  474. if index >= l.internalCurrentIndex() {
  475. entries = make([]*LogEntry, 0)
  476. results = make([]*logResult, 0)
  477. } else {
  478. // get all log entries after index
  479. entries = l.entries[index-l.startIndex:]
  480. results = l.results[index-l.startIndex:]
  481. }
  482. // create a new log file and add all the entries
  483. file, err := os.OpenFile(l.path+".new", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
  484. if err != nil {
  485. return err
  486. }
  487. for _, entry := range entries {
  488. position, _ := l.file.Seek(0, os.SEEK_CUR)
  489. entry.Position = position
  490. if _, err = entry.encode(file); err != nil {
  491. return err
  492. }
  493. }
  494. // close the current log file
  495. l.file.Close()
  496. // remove the current log file to .bak
  497. err = os.Remove(l.path)
  498. if err != nil {
  499. return err
  500. }
  501. // rename the new log file
  502. err = os.Rename(l.path+".new", l.path)
  503. if err != nil {
  504. return err
  505. }
  506. l.file = file
  507. // compaction the in memory log
  508. l.entries = entries
  509. l.results = results
  510. l.startIndex = index
  511. l.startTerm = term
  512. return nil
  513. }