log.go 17 KB

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