storage.go 8.1 KB

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