storage.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package raft
  15. import (
  16. "errors"
  17. "sync"
  18. pb "github.com/coreos/etcd/raft/raftpb"
  19. )
  20. // ErrCompacted is returned by Storage.Entries/Compact when a requested
  21. // index is unavailable because it predates the last snapshot.
  22. var ErrCompacted = errors.New("requested index is unavailable due to compaction")
  23. // ErrOutOfDataSnap is returned by Storage.CreateSnapshot when a requested
  24. // index is older than the existing snapshot.
  25. var ErrSnapOutOfDate = errors.New("requested index is older than the existing snapshot")
  26. var ErrUnavailable = errors.New("requested entry at index is unavailable")
  27. // Storage is an interface that may be implemented by the application
  28. // to retrieve log entries from storage.
  29. //
  30. // If any Storage method returns an error, the raft instance will
  31. // become inoperable and refuse to participate in elections; the
  32. // application is responsible for cleanup and recovery in this case.
  33. type Storage interface {
  34. // InitialState returns the saved HardState and ConfState information.
  35. InitialState() (pb.HardState, pb.ConfState, error)
  36. // Entries returns a slice of log entries in the range [lo,hi).
  37. Entries(lo, hi uint64) ([]pb.Entry, error)
  38. // Term returns the term of entry i, which must be in the range
  39. // [FirstIndex()-1, LastIndex()]. The term of the entry before
  40. // FirstIndex is retained for matching purposes even though the
  41. // rest of that entry may not be available.
  42. Term(i uint64) (uint64, error)
  43. // LastIndex returns the index of the last entry in the log.
  44. LastIndex() (uint64, error)
  45. // FirstIndex returns the index of the first log entry that is
  46. // possibly available via Entries (older entries have been incorporated
  47. // into the latest Snapshot; if storage only contains the dummy entry the
  48. // first log entry is not available).
  49. FirstIndex() (uint64, error)
  50. // Snapshot returns the most recent snapshot.
  51. Snapshot() (pb.Snapshot, error)
  52. }
  53. // MemoryStorage implements the Storage interface backed by an
  54. // in-memory array.
  55. type MemoryStorage struct {
  56. // Protects access to all fields. Most methods of MemoryStorage are
  57. // run on the raft goroutine, but Append() is run on an application
  58. // goroutine.
  59. sync.Mutex
  60. hardState pb.HardState
  61. snapshot pb.Snapshot
  62. // ents[i] has raft log position i+snapshot.Metadata.Index
  63. ents []pb.Entry
  64. }
  65. // NewMemoryStorage creates an empty MemoryStorage.
  66. func NewMemoryStorage() *MemoryStorage {
  67. return &MemoryStorage{
  68. // When starting from scratch populate the list with a dummy entry at term zero.
  69. ents: make([]pb.Entry, 1),
  70. }
  71. }
  72. // InitialState implements the Storage interface.
  73. func (ms *MemoryStorage) InitialState() (pb.HardState, pb.ConfState, error) {
  74. return ms.hardState, ms.snapshot.Metadata.ConfState, nil
  75. }
  76. // SetHardState saves the current HardState.
  77. func (ms *MemoryStorage) SetHardState(st pb.HardState) error {
  78. ms.hardState = st
  79. return nil
  80. }
  81. // Entries implements the Storage interface.
  82. func (ms *MemoryStorage) Entries(lo, hi uint64) ([]pb.Entry, error) {
  83. ms.Lock()
  84. defer ms.Unlock()
  85. offset := ms.ents[0].Index
  86. if lo <= offset {
  87. return nil, ErrCompacted
  88. }
  89. if hi > ms.lastIndex()+1 {
  90. raftLogger.Panicf("entries's hi(%d) is out of bound lastindex(%d)", hi, ms.lastIndex())
  91. }
  92. // only contains dummy entries.
  93. if len(ms.ents) == 1 {
  94. return nil, ErrUnavailable
  95. }
  96. return ms.ents[lo-offset : hi-offset], nil
  97. }
  98. // Term implements the Storage interface.
  99. func (ms *MemoryStorage) Term(i uint64) (uint64, error) {
  100. ms.Lock()
  101. defer ms.Unlock()
  102. offset := ms.ents[0].Index
  103. if i < offset {
  104. return 0, ErrCompacted
  105. }
  106. return ms.ents[i-offset].Term, nil
  107. }
  108. // LastIndex implements the Storage interface.
  109. func (ms *MemoryStorage) LastIndex() (uint64, error) {
  110. ms.Lock()
  111. defer ms.Unlock()
  112. return ms.lastIndex(), nil
  113. }
  114. func (ms *MemoryStorage) lastIndex() uint64 {
  115. return ms.ents[0].Index + uint64(len(ms.ents)) - 1
  116. }
  117. // FirstIndex implements the Storage interface.
  118. func (ms *MemoryStorage) FirstIndex() (uint64, error) {
  119. ms.Lock()
  120. defer ms.Unlock()
  121. return ms.firstIndex(), nil
  122. }
  123. func (ms *MemoryStorage) firstIndex() uint64 {
  124. return ms.ents[0].Index + 1
  125. }
  126. // Snapshot implements the Storage interface.
  127. func (ms *MemoryStorage) Snapshot() (pb.Snapshot, error) {
  128. ms.Lock()
  129. defer ms.Unlock()
  130. return ms.snapshot, nil
  131. }
  132. // ApplySnapshot overwrites the contents of this Storage object with
  133. // those of the given snapshot.
  134. func (ms *MemoryStorage) ApplySnapshot(snap pb.Snapshot) error {
  135. ms.Lock()
  136. defer ms.Unlock()
  137. // TODO: return snapOutOfDate?
  138. ms.snapshot = snap
  139. ms.ents = []pb.Entry{{Term: snap.Metadata.Term, Index: snap.Metadata.Index}}
  140. return nil
  141. }
  142. // Creates a snapshot which can be retrieved with the Snapshot() method and
  143. // can be used to reconstruct the state at that point.
  144. // If any configuration changes have been made since the last compaction,
  145. // the result of the last ApplyConfChange must be passed in.
  146. func (ms *MemoryStorage) CreateSnapshot(i uint64, cs *pb.ConfState, data []byte) (pb.Snapshot, error) {
  147. ms.Lock()
  148. defer ms.Unlock()
  149. if i <= ms.snapshot.Metadata.Index {
  150. return pb.Snapshot{}, ErrSnapOutOfDate
  151. }
  152. offset := ms.ents[0].Index
  153. if i > ms.lastIndex() {
  154. raftLogger.Panicf("snapshot %d is out of bound lastindex(%d)", i, ms.lastIndex())
  155. }
  156. ms.snapshot.Metadata.Index = i
  157. ms.snapshot.Metadata.Term = ms.ents[i-offset].Term
  158. if cs != nil {
  159. ms.snapshot.Metadata.ConfState = *cs
  160. }
  161. ms.snapshot.Data = data
  162. return ms.snapshot, nil
  163. }
  164. // Compact discards all log entries prior to i.
  165. // It is the application's responsibility to not attempt to compact an index
  166. // greater than raftLog.applied.
  167. func (ms *MemoryStorage) Compact(compactIndex uint64) error {
  168. offset := ms.ents[0].Index
  169. if compactIndex <= offset {
  170. return ErrCompacted
  171. }
  172. if compactIndex > ms.lastIndex() {
  173. raftLogger.Panicf("compact %d is out of bound lastindex(%d)", compactIndex, ms.lastIndex())
  174. }
  175. i := compactIndex - offset
  176. ents := make([]pb.Entry, 1, 1+uint64(len(ms.ents))-i)
  177. ents[0].Index = ms.ents[i].Index
  178. ents[0].Term = ms.ents[i].Term
  179. ents = append(ents, ms.ents[i+1:]...)
  180. ms.ents = ents
  181. return nil
  182. }
  183. // Append the new entries to storage.
  184. // TODO (xiangli): ensure the entries are continuous and
  185. // entries[0].Index > ms.entries[0].Index
  186. func (ms *MemoryStorage) Append(entries []pb.Entry) error {
  187. ms.Lock()
  188. defer ms.Unlock()
  189. if len(entries) == 0 {
  190. return nil
  191. }
  192. first := ms.ents[0].Index + 1
  193. last := entries[0].Index + uint64(len(entries)) - 1
  194. // shortcut if there is no new entry.
  195. if last < first {
  196. return nil
  197. }
  198. // truncate compacted entries
  199. if first > entries[0].Index {
  200. entries = entries[first-entries[0].Index:]
  201. }
  202. offset := entries[0].Index - ms.ents[0].Index
  203. switch {
  204. case uint64(len(ms.ents)) > offset:
  205. ms.ents = append([]pb.Entry{}, ms.ents[:offset]...)
  206. ms.ents = append(ms.ents, entries...)
  207. case uint64(len(ms.ents)) == offset:
  208. ms.ents = append(ms.ents, entries...)
  209. default:
  210. raftLogger.Panicf("missing log entry [last: %d, append at: %d]",
  211. ms.lastIndex(), entries[0].Index)
  212. }
  213. return nil
  214. }