storage.go 7.6 KB

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