storage.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Copyright 2015 The etcd Authors
  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. // ErrSnapOutOfDate 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. // ErrUnavailable is returned by Storage interface when the requested log entries
  27. // are unavailable.
  28. var ErrUnavailable = errors.New("requested entry at index is unavailable")
  29. // ErrSnapshotTemporarilyUnavailable is returned by the Storage interface when the required
  30. // snapshot is temporarily unavailable.
  31. var ErrSnapshotTemporarilyUnavailable = errors.New("snapshot is temporarily unavailable")
  32. // Storage is an interface that may be implemented by the application
  33. // to retrieve log entries from storage.
  34. //
  35. // If any Storage method returns an error, the raft instance will
  36. // become inoperable and refuse to participate in elections; the
  37. // application is responsible for cleanup and recovery in this case.
  38. type Storage interface {
  39. // InitialState returns the saved HardState and ConfState information.
  40. InitialState() (pb.HardState, pb.ConfState, error)
  41. // Entries returns a slice of log entries in the range [lo,hi).
  42. // MaxSize limits the total size of the log entries returned, but
  43. // Entries returns at least one entry if any.
  44. Entries(lo, hi, maxSize uint64) ([]pb.Entry, error)
  45. // Term returns the term of entry i, which must be in the range
  46. // [FirstIndex()-1, LastIndex()]. The term of the entry before
  47. // FirstIndex is retained for matching purposes even though the
  48. // rest of that entry may not be available.
  49. Term(i uint64) (uint64, error)
  50. // LastIndex returns the index of the last entry in the log.
  51. LastIndex() (uint64, error)
  52. // FirstIndex returns the index of the first log entry that is
  53. // possibly available via Entries (older entries have been incorporated
  54. // into the latest Snapshot; if storage only contains the dummy entry the
  55. // first log entry is not available).
  56. FirstIndex() (uint64, error)
  57. // Snapshot returns the most recent snapshot.
  58. // If snapshot is temporarily unavailable, it should return ErrSnapshotTemporarilyUnavailable,
  59. // so raft state machine could know that Storage needs some time to prepare
  60. // snapshot and call Snapshot later.
  61. Snapshot() (pb.Snapshot, error)
  62. }
  63. // MemoryStorage implements the Storage interface backed by an
  64. // in-memory array.
  65. type MemoryStorage struct {
  66. // Protects access to all fields. Most methods of MemoryStorage are
  67. // run on the raft goroutine, but Append() is run on an application
  68. // goroutine.
  69. sync.Mutex
  70. hardState pb.HardState
  71. snapshot pb.Snapshot
  72. // ents[i] has raft log position i+snapshot.Metadata.Index
  73. ents []pb.Entry
  74. }
  75. // NewMemoryStorage creates an empty MemoryStorage.
  76. func NewMemoryStorage() *MemoryStorage {
  77. return &MemoryStorage{
  78. // When starting from scratch populate the list with a dummy entry at term zero.
  79. ents: make([]pb.Entry, 1),
  80. }
  81. }
  82. // InitialState implements the Storage interface.
  83. func (ms *MemoryStorage) InitialState() (pb.HardState, pb.ConfState, error) {
  84. return ms.hardState, ms.snapshot.Metadata.ConfState, nil
  85. }
  86. // SetHardState saves the current HardState.
  87. func (ms *MemoryStorage) SetHardState(st pb.HardState) error {
  88. ms.hardState = st
  89. return nil
  90. }
  91. // Entries implements the Storage interface.
  92. func (ms *MemoryStorage) Entries(lo, hi, maxSize uint64) ([]pb.Entry, error) {
  93. ms.Lock()
  94. defer ms.Unlock()
  95. offset := ms.ents[0].Index
  96. if lo <= offset {
  97. return nil, ErrCompacted
  98. }
  99. if hi > ms.lastIndex()+1 {
  100. raftLogger.Panicf("entries' hi(%d) is out of bound lastindex(%d)", hi, ms.lastIndex())
  101. }
  102. // only contains dummy entries.
  103. if len(ms.ents) == 1 {
  104. return nil, ErrUnavailable
  105. }
  106. ents := ms.ents[lo-offset : hi-offset]
  107. return limitSize(ents, maxSize), nil
  108. }
  109. // Term implements the Storage interface.
  110. func (ms *MemoryStorage) Term(i uint64) (uint64, error) {
  111. ms.Lock()
  112. defer ms.Unlock()
  113. offset := ms.ents[0].Index
  114. if i < offset {
  115. return 0, ErrCompacted
  116. }
  117. if int(i-offset) >= len(ms.ents) {
  118. return 0, ErrUnavailable
  119. }
  120. return ms.ents[i-offset].Term, nil
  121. }
  122. // LastIndex implements the Storage interface.
  123. func (ms *MemoryStorage) LastIndex() (uint64, error) {
  124. ms.Lock()
  125. defer ms.Unlock()
  126. return ms.lastIndex(), nil
  127. }
  128. func (ms *MemoryStorage) lastIndex() uint64 {
  129. return ms.ents[0].Index + uint64(len(ms.ents)) - 1
  130. }
  131. // FirstIndex implements the Storage interface.
  132. func (ms *MemoryStorage) FirstIndex() (uint64, error) {
  133. ms.Lock()
  134. defer ms.Unlock()
  135. return ms.firstIndex(), nil
  136. }
  137. func (ms *MemoryStorage) firstIndex() uint64 {
  138. return ms.ents[0].Index + 1
  139. }
  140. // Snapshot implements the Storage interface.
  141. func (ms *MemoryStorage) Snapshot() (pb.Snapshot, error) {
  142. ms.Lock()
  143. defer ms.Unlock()
  144. return ms.snapshot, nil
  145. }
  146. // ApplySnapshot overwrites the contents of this Storage object with
  147. // those of the given snapshot.
  148. func (ms *MemoryStorage) ApplySnapshot(snap pb.Snapshot) error {
  149. ms.Lock()
  150. defer ms.Unlock()
  151. //handle check for old snapshot being applied
  152. msIndex := ms.snapshot.Metadata.Index
  153. snapIndex := snap.Metadata.Index
  154. if msIndex >= snapIndex {
  155. return ErrSnapOutOfDate
  156. }
  157. ms.snapshot = snap
  158. ms.ents = []pb.Entry{{Term: snap.Metadata.Term, Index: snap.Metadata.Index}}
  159. return nil
  160. }
  161. // CreateSnapshot makes a snapshot which can be retrieved with Snapshot() and
  162. // can be used to reconstruct the state at that point.
  163. // If any configuration changes have been made since the last compaction,
  164. // the result of the last ApplyConfChange must be passed in.
  165. func (ms *MemoryStorage) CreateSnapshot(i uint64, cs *pb.ConfState, data []byte) (pb.Snapshot, error) {
  166. ms.Lock()
  167. defer ms.Unlock()
  168. if i <= ms.snapshot.Metadata.Index {
  169. return pb.Snapshot{}, ErrSnapOutOfDate
  170. }
  171. offset := ms.ents[0].Index
  172. if i > ms.lastIndex() {
  173. raftLogger.Panicf("snapshot %d is out of bound lastindex(%d)", i, ms.lastIndex())
  174. }
  175. ms.snapshot.Metadata.Index = i
  176. ms.snapshot.Metadata.Term = ms.ents[i-offset].Term
  177. if cs != nil {
  178. ms.snapshot.Metadata.ConfState = *cs
  179. }
  180. ms.snapshot.Data = data
  181. return ms.snapshot, nil
  182. }
  183. // Compact discards all log entries prior to compactIndex.
  184. // It is the application's responsibility to not attempt to compact an index
  185. // greater than raftLog.applied.
  186. func (ms *MemoryStorage) Compact(compactIndex uint64) error {
  187. ms.Lock()
  188. defer ms.Unlock()
  189. offset := ms.ents[0].Index
  190. if compactIndex <= offset {
  191. return ErrCompacted
  192. }
  193. if compactIndex > ms.lastIndex() {
  194. raftLogger.Panicf("compact %d is out of bound lastindex(%d)", compactIndex, ms.lastIndex())
  195. }
  196. i := compactIndex - offset
  197. ents := make([]pb.Entry, 1, 1+uint64(len(ms.ents))-i)
  198. ents[0].Index = ms.ents[i].Index
  199. ents[0].Term = ms.ents[i].Term
  200. ents = append(ents, ms.ents[i+1:]...)
  201. ms.ents = ents
  202. return nil
  203. }
  204. // Append the new entries to storage.
  205. // TODO (xiangli): ensure the entries are continuous and
  206. // entries[0].Index > ms.entries[0].Index
  207. func (ms *MemoryStorage) Append(entries []pb.Entry) error {
  208. if len(entries) == 0 {
  209. return nil
  210. }
  211. ms.Lock()
  212. defer ms.Unlock()
  213. first := ms.firstIndex()
  214. last := entries[0].Index + uint64(len(entries)) - 1
  215. // shortcut if there is no new entry.
  216. if last < first {
  217. return nil
  218. }
  219. // truncate compacted entries
  220. if first > entries[0].Index {
  221. entries = entries[first-entries[0].Index:]
  222. }
  223. offset := entries[0].Index - ms.ents[0].Index
  224. switch {
  225. case uint64(len(ms.ents)) > offset:
  226. ms.ents = append([]pb.Entry{}, ms.ents[:offset]...)
  227. ms.ents = append(ms.ents, entries...)
  228. case uint64(len(ms.ents)) == offset:
  229. ms.ents = append(ms.ents, entries...)
  230. default:
  231. raftLogger.Panicf("missing log entry [last: %d, append at: %d]",
  232. ms.lastIndex(), entries[0].Index)
  233. }
  234. return nil
  235. }