storage.go 7.4 KB

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