log.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. package raft
  2. import (
  3. "bufio"
  4. "github.com/coreos/etcd/third_party/code.google.com/p/goprotobuf/proto"
  5. "errors"
  6. "fmt"
  7. "github.com/coreos/etcd/third_party/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. commitIndex uint64
  24. mutex sync.RWMutex
  25. startIndex uint64 // the index before the first entry in the Log entries
  26. startTerm uint64
  27. pBuffer *proto.Buffer
  28. pLogEntry *protobuf.ProtoLogEntry
  29. }
  30. // The results of the applying a log entry.
  31. type logResult struct {
  32. returnValue interface{}
  33. err error
  34. }
  35. //------------------------------------------------------------------------------
  36. //
  37. // Constructor
  38. //
  39. //------------------------------------------------------------------------------
  40. // Creates a new log.
  41. func newLog() *Log {
  42. return &Log{
  43. entries: make([]*LogEntry, 0),
  44. pBuffer: proto.NewBuffer(nil),
  45. pLogEntry: &protobuf.ProtoLogEntry{},
  46. }
  47. }
  48. //------------------------------------------------------------------------------
  49. //
  50. // Accessors
  51. //
  52. //------------------------------------------------------------------------------
  53. //--------------------------------------
  54. // Log Indices
  55. //--------------------------------------
  56. // The last committed index in the log.
  57. func (l *Log) CommitIndex() uint64 {
  58. l.mutex.RLock()
  59. defer l.mutex.RUnlock()
  60. return l.commitIndex
  61. }
  62. // The current index in the log.
  63. func (l *Log) currentIndex() uint64 {
  64. l.mutex.RLock()
  65. defer l.mutex.RUnlock()
  66. return l.internalCurrentIndex()
  67. }
  68. // The current index in the log without locking
  69. func (l *Log) internalCurrentIndex() uint64 {
  70. if len(l.entries) == 0 {
  71. return l.startIndex
  72. }
  73. return l.entries[len(l.entries)-1].Index
  74. }
  75. // The next index in the log.
  76. func (l *Log) nextIndex() uint64 {
  77. return l.currentIndex() + 1
  78. }
  79. // Determines if the log contains zero entries.
  80. func (l *Log) isEmpty() bool {
  81. l.mutex.RLock()
  82. defer l.mutex.RUnlock()
  83. return (len(l.entries) == 0) && (l.startIndex == 0)
  84. }
  85. // The name of the last command in the log.
  86. func (l *Log) lastCommandName() string {
  87. l.mutex.RLock()
  88. defer l.mutex.RUnlock()
  89. if len(l.entries) > 0 {
  90. if entry := l.entries[len(l.entries)-1]; entry != nil {
  91. return entry.CommandName
  92. }
  93. }
  94. return ""
  95. }
  96. //--------------------------------------
  97. // Log Terms
  98. //--------------------------------------
  99. // The current term in the log.
  100. func (l *Log) currentTerm() uint64 {
  101. l.mutex.RLock()
  102. defer l.mutex.RUnlock()
  103. if len(l.entries) == 0 {
  104. return l.startTerm
  105. }
  106. return l.entries[len(l.entries)-1].Term
  107. }
  108. //------------------------------------------------------------------------------
  109. //
  110. // Methods
  111. //
  112. //------------------------------------------------------------------------------
  113. //--------------------------------------
  114. // State
  115. //--------------------------------------
  116. // Opens the log file and reads existing entries. The log can remain open and
  117. // continue to append entries to the end of the log.
  118. func (l *Log) open(path string) error {
  119. // Read all the entries from the log if one exists.
  120. var readBytes int64
  121. var err error
  122. debugln("log.open.open ", path)
  123. // open log file
  124. l.file, err = os.OpenFile(path, os.O_RDWR, 0600)
  125. l.path = path
  126. if err != nil {
  127. // if the log file does not exist before
  128. // we create the log file and set commitIndex to 0
  129. if os.IsNotExist(err) {
  130. l.file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600)
  131. debugln("log.open.create ", path)
  132. return err
  133. }
  134. return err
  135. }
  136. debugln("log.open.exist ", path)
  137. // Read the file and decode entries.
  138. for {
  139. // Instantiate log entry and decode into it.
  140. entry, _ := newLogEntry(l, nil, 0, 0, nil)
  141. entry.Position, _ = l.file.Seek(0, os.SEEK_CUR)
  142. n, err := entry.decode(l.file)
  143. if err != nil {
  144. if err == io.EOF {
  145. debugln("open.log.append: finish ")
  146. } else {
  147. if err = os.Truncate(path, readBytes); err != nil {
  148. return fmt.Errorf("raft.Log: Unable to recover: %v", err)
  149. }
  150. }
  151. break
  152. }
  153. if entry.Index > l.startIndex {
  154. // Append entry.
  155. l.entries = append(l.entries, entry)
  156. if entry.Index <= l.commitIndex {
  157. command, err := newCommand(entry.CommandName, entry.Command)
  158. if err != nil {
  159. continue
  160. }
  161. l.ApplyFunc(command)
  162. }
  163. debugln("open.log.append log index ", entry.Index)
  164. }
  165. readBytes += int64(n)
  166. }
  167. debugln("open.log.recovery number of log ", len(l.entries))
  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.Lock()
  211. defer l.mutex.Unlock()
  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(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 []*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 _, entry := range entries {
  400. entry.log = l
  401. if size, err = l.writeEntry(entry, w); err != nil {
  402. return err
  403. }
  404. entry.Position = startPosition
  405. startPosition += size
  406. }
  407. w.Flush()
  408. err = l.sync()
  409. if err != nil {
  410. panic(err)
  411. }
  412. return nil
  413. }
  414. // Writes a single log entry to the end of the log.
  415. func (l *Log) appendEntry(entry *LogEntry) error {
  416. l.mutex.Lock()
  417. defer l.mutex.Unlock()
  418. if l.file == nil {
  419. return errors.New("raft.Log: Log is not open")
  420. }
  421. // Make sure the term and index are greater than the previous.
  422. if len(l.entries) > 0 {
  423. lastEntry := l.entries[len(l.entries)-1]
  424. if entry.Term < lastEntry.Term {
  425. return fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  426. } else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
  427. 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)
  428. }
  429. }
  430. position, _ := l.file.Seek(0, os.SEEK_CUR)
  431. entry.Position = position
  432. // Write to storage.
  433. if _, err := entry.encode(l.file); err != nil {
  434. return err
  435. }
  436. // Append to entries list if stored on disk.
  437. l.entries = append(l.entries, entry)
  438. return nil
  439. }
  440. // appendEntry with Buffered io
  441. func (l *Log) writeEntry(entry *LogEntry, w io.Writer) (int64, error) {
  442. if l.file == nil {
  443. return -1, errors.New("raft.Log: Log is not open")
  444. }
  445. // Make sure the term and index are greater than the previous.
  446. if len(l.entries) > 0 {
  447. lastEntry := l.entries[len(l.entries)-1]
  448. if entry.Term < lastEntry.Term {
  449. return -1, fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
  450. } else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
  451. 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)
  452. }
  453. }
  454. // Write to storage.
  455. size, err := entry.encode(w)
  456. if err != nil {
  457. return -1, err
  458. }
  459. // Append to entries list if stored on disk.
  460. l.entries = append(l.entries, entry)
  461. return int64(size), nil
  462. }
  463. //--------------------------------------
  464. // Log compaction
  465. //--------------------------------------
  466. // compact the log before index (including index)
  467. func (l *Log) compact(index uint64, term uint64) error {
  468. var entries []*LogEntry
  469. l.mutex.Lock()
  470. defer l.mutex.Unlock()
  471. if index == 0 {
  472. return nil
  473. }
  474. // nothing to compaction
  475. // the index may be greater than the current index if
  476. // we just recovery from on snapshot
  477. if index >= l.internalCurrentIndex() {
  478. entries = make([]*LogEntry, 0)
  479. } else {
  480. // get all log entries after index
  481. entries = l.entries[index-l.startIndex:]
  482. }
  483. // create a new log file and add all the entries
  484. new_file_path := l.path + ".new"
  485. file, err := os.OpenFile(new_file_path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
  486. if err != nil {
  487. return err
  488. }
  489. for _, entry := range entries {
  490. position, _ := l.file.Seek(0, os.SEEK_CUR)
  491. entry.Position = position
  492. if _, err = entry.encode(file); err != nil {
  493. file.Close()
  494. os.Remove(new_file_path)
  495. return err
  496. }
  497. }
  498. file.Sync()
  499. old_file := l.file
  500. // rename the new log file
  501. err = os.Rename(new_file_path, l.path)
  502. if err != nil {
  503. file.Close()
  504. os.Remove(new_file_path)
  505. return err
  506. }
  507. l.file = file
  508. // close the old log file
  509. old_file.Close()
  510. // compaction the in memory log
  511. l.entries = entries
  512. l.startIndex = index
  513. l.startTerm = term
  514. return nil
  515. }