storage.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.Lock()
  89. defer ms.Unlock()
  90. ms.hardState = st
  91. return nil
  92. }
  93. // Entries implements the Storage interface.
  94. func (ms *MemoryStorage) Entries(lo, hi, maxSize uint64) ([]pb.Entry, error) {
  95. ms.Lock()
  96. defer ms.Unlock()
  97. offset := ms.ents[0].Index
  98. if lo <= offset {
  99. return nil, ErrCompacted
  100. }
  101. if hi > ms.lastIndex()+1 {
  102. raftLogger.Panicf("entries' hi(%d) is out of bound lastindex(%d)", hi, ms.lastIndex())
  103. }
  104. // only contains dummy entries.
  105. if len(ms.ents) == 1 {
  106. return nil, ErrUnavailable
  107. }
  108. ents := ms.ents[lo-offset : hi-offset]
  109. return limitSize(ents, maxSize), nil
  110. }
  111. // Term implements the Storage interface.
  112. func (ms *MemoryStorage) Term(i uint64) (uint64, error) {
  113. ms.Lock()
  114. defer ms.Unlock()
  115. offset := ms.ents[0].Index
  116. if i < offset {
  117. return 0, ErrCompacted
  118. }
  119. if int(i-offset) >= len(ms.ents) {
  120. return 0, ErrUnavailable
  121. }
  122. return ms.ents[i-offset].Term, nil
  123. }
  124. // LastIndex implements the Storage interface.
  125. func (ms *MemoryStorage) LastIndex() (uint64, error) {
  126. ms.Lock()
  127. defer ms.Unlock()
  128. return ms.lastIndex(), nil
  129. }
  130. func (ms *MemoryStorage) lastIndex() uint64 {
  131. return ms.ents[0].Index + uint64(len(ms.ents)) - 1
  132. }
  133. // FirstIndex implements the Storage interface.
  134. func (ms *MemoryStorage) FirstIndex() (uint64, error) {
  135. ms.Lock()
  136. defer ms.Unlock()
  137. return ms.firstIndex(), nil
  138. }
  139. func (ms *MemoryStorage) firstIndex() uint64 {
  140. return ms.ents[0].Index + 1
  141. }
  142. // Snapshot implements the Storage interface.
  143. func (ms *MemoryStorage) Snapshot() (pb.Snapshot, error) {
  144. ms.Lock()
  145. defer ms.Unlock()
  146. return ms.snapshot, nil
  147. }
  148. // ApplySnapshot overwrites the contents of this Storage object with
  149. // those of the given snapshot.
  150. func (ms *MemoryStorage) ApplySnapshot(snap pb.Snapshot) error {
  151. ms.Lock()
  152. defer ms.Unlock()
  153. //handle check for old snapshot being applied
  154. msIndex := ms.snapshot.Metadata.Index
  155. snapIndex := snap.Metadata.Index
  156. if msIndex >= snapIndex {
  157. return ErrSnapOutOfDate
  158. }
  159. ms.snapshot = snap
  160. ms.ents = []pb.Entry{{Term: snap.Metadata.Term, Index: snap.Metadata.Index}}
  161. return nil
  162. }
  163. // CreateSnapshot makes a snapshot which can be retrieved with Snapshot() and
  164. // can be used to reconstruct the state at that point.
  165. // If any configuration changes have been made since the last compaction,
  166. // the result of the last ApplyConfChange must be passed in.
  167. func (ms *MemoryStorage) CreateSnapshot(i uint64, cs *pb.ConfState, data []byte) (pb.Snapshot, error) {
  168. ms.Lock()
  169. defer ms.Unlock()
  170. if i <= ms.snapshot.Metadata.Index {
  171. return pb.Snapshot{}, ErrSnapOutOfDate
  172. }
  173. offset := ms.ents[0].Index
  174. if i > ms.lastIndex() {
  175. raftLogger.Panicf("snapshot %d is out of bound lastindex(%d)", i, ms.lastIndex())
  176. }
  177. ms.snapshot.Metadata.Index = i
  178. ms.snapshot.Metadata.Term = ms.ents[i-offset].Term
  179. if cs != nil {
  180. ms.snapshot.Metadata.ConfState = *cs
  181. }
  182. ms.snapshot.Data = data
  183. return ms.snapshot, nil
  184. }
  185. // Compact discards all log entries prior to compactIndex.
  186. // It is the application's responsibility to not attempt to compact an index
  187. // greater than raftLog.applied.
  188. func (ms *MemoryStorage) Compact(compactIndex uint64) error {
  189. ms.Lock()
  190. defer ms.Unlock()
  191. offset := ms.ents[0].Index
  192. if compactIndex <= offset {
  193. return ErrCompacted
  194. }
  195. if compactIndex > ms.lastIndex() {
  196. raftLogger.Panicf("compact %d is out of bound lastindex(%d)", compactIndex, ms.lastIndex())
  197. }
  198. i := compactIndex - offset
  199. ents := make([]pb.Entry, 1, 1+uint64(len(ms.ents))-i)
  200. ents[0].Index = ms.ents[i].Index
  201. ents[0].Term = ms.ents[i].Term
  202. ents = append(ents, ms.ents[i+1:]...)
  203. ms.ents = ents
  204. return nil
  205. }
  206. // Append the new entries to storage.
  207. // TODO (xiangli): ensure the entries are continuous and
  208. // entries[0].Index > ms.entries[0].Index
  209. func (ms *MemoryStorage) Append(entries []pb.Entry) error {
  210. if len(entries) == 0 {
  211. return nil
  212. }
  213. ms.Lock()
  214. defer ms.Unlock()
  215. first := ms.firstIndex()
  216. last := entries[0].Index + uint64(len(entries)) - 1
  217. // shortcut if there is no new entry.
  218. if last < first {
  219. return nil
  220. }
  221. // truncate compacted entries
  222. if first > entries[0].Index {
  223. entries = entries[first-entries[0].Index:]
  224. }
  225. offset := entries[0].Index - ms.ents[0].Index
  226. switch {
  227. case uint64(len(ms.ents)) > offset:
  228. ms.ents = append([]pb.Entry{}, ms.ents[:offset]...)
  229. ms.ents = append(ms.ents, entries...)
  230. case uint64(len(ms.ents)) == offset:
  231. ms.ents = append(ms.ents, entries...)
  232. default:
  233. raftLogger.Panicf("missing log entry [last: %d, append at: %d]",
  234. ms.lastIndex(), entries[0].Index)
  235. }
  236. return nil
  237. }