kvstore.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 mvcc
  15. import (
  16. "encoding/binary"
  17. "errors"
  18. "math"
  19. "sync"
  20. "time"
  21. "github.com/coreos/etcd/lease"
  22. "github.com/coreos/etcd/mvcc/backend"
  23. "github.com/coreos/etcd/mvcc/mvccpb"
  24. "github.com/coreos/etcd/pkg/schedule"
  25. "github.com/coreos/pkg/capnslog"
  26. "golang.org/x/net/context"
  27. )
  28. var (
  29. keyBucketName = []byte("key")
  30. metaBucketName = []byte("meta")
  31. // markedRevBytesLen is the byte length of marked revision.
  32. // The first `revBytesLen` bytes represents a normal revision. The last
  33. // one byte is the mark.
  34. markedRevBytesLen = revBytesLen + 1
  35. markBytePosition = markedRevBytesLen - 1
  36. markTombstone byte = 't'
  37. consistentIndexKeyName = []byte("consistent_index")
  38. scheduledCompactKeyName = []byte("scheduledCompactRev")
  39. finishedCompactKeyName = []byte("finishedCompactRev")
  40. ErrCompacted = errors.New("mvcc: required revision has been compacted")
  41. ErrFutureRev = errors.New("mvcc: required revision is a future revision")
  42. ErrCanceled = errors.New("mvcc: watcher is canceled")
  43. ErrClosed = errors.New("mvcc: closed")
  44. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "mvcc")
  45. )
  46. // ConsistentIndexGetter is an interface that wraps the Get method.
  47. // Consistent index is the offset of an entry in a consistent replicated log.
  48. type ConsistentIndexGetter interface {
  49. // ConsistentIndex returns the consistent index of current executing entry.
  50. ConsistentIndex() uint64
  51. }
  52. type store struct {
  53. ReadView
  54. WriteView
  55. // mu read locks for txns and write locks for non-txn store changes.
  56. mu sync.RWMutex
  57. ig ConsistentIndexGetter
  58. b backend.Backend
  59. kvindex index
  60. le lease.Lessor
  61. // revMuLock protects currentRev and compactMainRev.
  62. // Locked at end of write txn and released after write txn unlock lock.
  63. // Locked before locking read txn and released after locking.
  64. revMu sync.RWMutex
  65. // currentRev is the revision of the last completed transaction.
  66. currentRev int64
  67. // compactMainRev is the main revision of the last compaction.
  68. compactMainRev int64
  69. // bytesBuf8 is a byte slice of length 8
  70. // to avoid a repetitive allocation in saveIndex.
  71. bytesBuf8 []byte
  72. fifoSched schedule.Scheduler
  73. stopc chan struct{}
  74. }
  75. // NewStore returns a new store. It is useful to create a store inside
  76. // mvcc pkg. It should only be used for testing externally.
  77. func NewStore(b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) *store {
  78. s := &store{
  79. b: b,
  80. ig: ig,
  81. kvindex: newTreeIndex(),
  82. le: le,
  83. currentRev: 1,
  84. compactMainRev: -1,
  85. bytesBuf8: make([]byte, 8),
  86. fifoSched: schedule.NewFIFOScheduler(),
  87. stopc: make(chan struct{}),
  88. }
  89. s.ReadView = &readView{s}
  90. s.WriteView = &writeView{s}
  91. if s.le != nil {
  92. s.le.SetRangeDeleter(func() lease.TxnDelete { return s.Write() })
  93. }
  94. tx := s.b.BatchTx()
  95. tx.Lock()
  96. tx.UnsafeCreateBucket(keyBucketName)
  97. tx.UnsafeCreateBucket(metaBucketName)
  98. tx.Unlock()
  99. s.b.ForceCommit()
  100. if err := s.restore(); err != nil {
  101. // TODO: return the error instead of panic here?
  102. panic("failed to recover store from backend")
  103. }
  104. return s
  105. }
  106. func (s *store) compactBarrier(ctx context.Context, ch chan struct{}) {
  107. if ctx == nil || ctx.Err() != nil {
  108. s.mu.Lock()
  109. select {
  110. case <-s.stopc:
  111. default:
  112. f := func(ctx context.Context) { s.compactBarrier(ctx, ch) }
  113. s.fifoSched.Schedule(f)
  114. }
  115. s.mu.Unlock()
  116. return
  117. }
  118. close(ch)
  119. }
  120. func (s *store) Hash() (hash uint32, revision int64, err error) {
  121. s.b.ForceCommit()
  122. h, err := s.b.Hash(DefaultIgnores)
  123. return h, s.currentRev, err
  124. }
  125. func (s *store) Compact(rev int64) (<-chan struct{}, error) {
  126. s.mu.Lock()
  127. defer s.mu.Unlock()
  128. s.revMu.Lock()
  129. defer s.revMu.Unlock()
  130. if rev <= s.compactMainRev {
  131. ch := make(chan struct{})
  132. f := func(ctx context.Context) { s.compactBarrier(ctx, ch) }
  133. s.fifoSched.Schedule(f)
  134. return ch, ErrCompacted
  135. }
  136. if rev > s.currentRev {
  137. return nil, ErrFutureRev
  138. }
  139. start := time.Now()
  140. s.compactMainRev = rev
  141. rbytes := newRevBytes()
  142. revToBytes(revision{main: rev}, rbytes)
  143. tx := s.b.BatchTx()
  144. tx.Lock()
  145. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  146. tx.Unlock()
  147. // ensure that desired compaction is persisted
  148. s.b.ForceCommit()
  149. keep := s.kvindex.Compact(rev)
  150. ch := make(chan struct{})
  151. var j = func(ctx context.Context) {
  152. if ctx.Err() != nil {
  153. s.compactBarrier(ctx, ch)
  154. return
  155. }
  156. if !s.scheduleCompaction(rev, keep) {
  157. s.compactBarrier(nil, ch)
  158. return
  159. }
  160. close(ch)
  161. }
  162. s.fifoSched.Schedule(j)
  163. indexCompactionPauseDurations.Observe(float64(time.Since(start) / time.Millisecond))
  164. return ch, nil
  165. }
  166. // DefaultIgnores is a map of keys to ignore in hash checking.
  167. var DefaultIgnores map[backend.IgnoreKey]struct{}
  168. func init() {
  169. DefaultIgnores = map[backend.IgnoreKey]struct{}{
  170. // consistent index might be changed due to v2 internal sync, which
  171. // is not controllable by the user.
  172. {Bucket: string(metaBucketName), Key: string(consistentIndexKeyName)}: {},
  173. }
  174. }
  175. func (s *store) Commit() {
  176. s.mu.Lock()
  177. defer s.mu.Unlock()
  178. tx := s.b.BatchTx()
  179. tx.Lock()
  180. s.saveIndex(tx)
  181. tx.Unlock()
  182. s.b.ForceCommit()
  183. }
  184. func (s *store) Restore(b backend.Backend) error {
  185. s.mu.Lock()
  186. defer s.mu.Unlock()
  187. close(s.stopc)
  188. s.fifoSched.Stop()
  189. s.b = b
  190. s.kvindex = newTreeIndex()
  191. s.currentRev = 1
  192. s.compactMainRev = -1
  193. s.fifoSched = schedule.NewFIFOScheduler()
  194. s.stopc = make(chan struct{})
  195. return s.restore()
  196. }
  197. func (s *store) restore() error {
  198. min, max := newRevBytes(), newRevBytes()
  199. revToBytes(revision{main: 1}, min)
  200. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  201. keyToLease := make(map[string]lease.LeaseID)
  202. // use an unordered map to hold the temp index data to speed up
  203. // the initial key index recovery.
  204. // we will convert this unordered map into the tree index later.
  205. unordered := make(map[string]*keyIndex, 100000)
  206. // restore index
  207. tx := s.b.BatchTx()
  208. tx.Lock()
  209. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  210. if len(finishedCompactBytes) != 0 {
  211. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  212. plog.Printf("restore compact to %d", s.compactMainRev)
  213. }
  214. // TODO: limit N to reduce max memory usage
  215. keys, vals := tx.UnsafeRange(keyBucketName, min, max, 0)
  216. for i, key := range keys {
  217. var kv mvccpb.KeyValue
  218. if err := kv.Unmarshal(vals[i]); err != nil {
  219. plog.Fatalf("cannot unmarshal event: %v", err)
  220. }
  221. rev := bytesToRev(key[:revBytesLen])
  222. s.currentRev = rev.main
  223. // restore index
  224. switch {
  225. case isTombstone(key):
  226. if ki, ok := unordered[string(kv.Key)]; ok {
  227. ki.tombstone(rev.main, rev.sub)
  228. }
  229. delete(keyToLease, string(kv.Key))
  230. default:
  231. ki, ok := unordered[string(kv.Key)]
  232. if ok {
  233. ki.put(rev.main, rev.sub)
  234. } else {
  235. ki = &keyIndex{key: kv.Key}
  236. ki.restore(revision{kv.CreateRevision, 0}, rev, kv.Version)
  237. unordered[string(kv.Key)] = ki
  238. }
  239. if lid := lease.LeaseID(kv.Lease); lid != lease.NoLease {
  240. keyToLease[string(kv.Key)] = lid
  241. } else {
  242. delete(keyToLease, string(kv.Key))
  243. }
  244. }
  245. }
  246. // restore the tree index from the unordered index.
  247. for _, v := range unordered {
  248. s.kvindex.Insert(v)
  249. }
  250. // keys in the range [compacted revision -N, compaction] might all be deleted due to compaction.
  251. // the correct revision should be set to compaction revision in the case, not the largest revision
  252. // we have seen.
  253. if s.currentRev < s.compactMainRev {
  254. s.currentRev = s.compactMainRev
  255. }
  256. for key, lid := range keyToLease {
  257. if s.le == nil {
  258. panic("no lessor to attach lease")
  259. }
  260. err := s.le.Attach(lid, []lease.LeaseItem{{Key: key}})
  261. if err != nil {
  262. plog.Errorf("unexpected Attach error: %v", err)
  263. }
  264. }
  265. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  266. scheduledCompact := int64(0)
  267. if len(scheduledCompactBytes) != 0 {
  268. scheduledCompact = bytesToRev(scheduledCompactBytes[0]).main
  269. if scheduledCompact <= s.compactMainRev {
  270. scheduledCompact = 0
  271. }
  272. }
  273. tx.Unlock()
  274. if scheduledCompact != 0 {
  275. s.Compact(scheduledCompact)
  276. plog.Printf("resume scheduled compaction at %d", scheduledCompact)
  277. }
  278. return nil
  279. }
  280. func (s *store) Close() error {
  281. close(s.stopc)
  282. s.fifoSched.Stop()
  283. return nil
  284. }
  285. func (a *store) Equal(b *store) bool {
  286. if a.currentRev != b.currentRev {
  287. return false
  288. }
  289. if a.compactMainRev != b.compactMainRev {
  290. return false
  291. }
  292. return a.kvindex.Equal(b.kvindex)
  293. }
  294. func (s *store) saveIndex(tx backend.BatchTx) {
  295. if s.ig == nil {
  296. return
  297. }
  298. bs := s.bytesBuf8
  299. binary.BigEndian.PutUint64(bs, s.ig.ConsistentIndex())
  300. // put the index into the underlying backend
  301. // tx has been locked in TxnBegin, so there is no need to lock it again
  302. tx.UnsafePut(metaBucketName, consistentIndexKeyName, bs)
  303. }
  304. func (s *store) ConsistentIndex() uint64 {
  305. // TODO: cache index in a uint64 field?
  306. tx := s.b.BatchTx()
  307. tx.Lock()
  308. defer tx.Unlock()
  309. _, vs := tx.UnsafeRange(metaBucketName, consistentIndexKeyName, nil, 0)
  310. if len(vs) == 0 {
  311. return 0
  312. }
  313. return binary.BigEndian.Uint64(vs[0])
  314. }
  315. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  316. func appendMarkTombstone(b []byte) []byte {
  317. if len(b) != revBytesLen {
  318. plog.Panicf("cannot append mark to non normal revision bytes")
  319. }
  320. return append(b, markTombstone)
  321. }
  322. // isTombstone checks whether the revision bytes is a tombstone.
  323. func isTombstone(b []byte) bool {
  324. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  325. }
  326. // revBytesRange returns the range of revision bytes at
  327. // the given revision.
  328. func revBytesRange(rev revision) (start, end []byte) {
  329. start = newRevBytes()
  330. revToBytes(rev, start)
  331. end = newRevBytes()
  332. endRev := revision{main: rev.main, sub: rev.sub + 1}
  333. revToBytes(endRev, end)
  334. return start, end
  335. }