log.go 17 KB

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