storage.go 7.8 KB

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