kvstore.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. "context"
  17. "encoding/binary"
  18. "errors"
  19. "hash/crc32"
  20. "math"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/coreos/etcd/internal/lease"
  25. "github.com/coreos/etcd/internal/mvcc/backend"
  26. "github.com/coreos/etcd/internal/mvcc/mvccpb"
  27. "github.com/coreos/etcd/pkg/schedule"
  28. "github.com/coreos/pkg/capnslog"
  29. )
  30. var (
  31. keyBucketName = []byte("key")
  32. metaBucketName = []byte("meta")
  33. consistentIndexKeyName = []byte("consistent_index")
  34. scheduledCompactKeyName = []byte("scheduledCompactRev")
  35. finishedCompactKeyName = []byte("finishedCompactRev")
  36. ErrCompacted = errors.New("mvcc: required revision has been compacted")
  37. ErrFutureRev = errors.New("mvcc: required revision is a future revision")
  38. ErrCanceled = errors.New("mvcc: watcher is canceled")
  39. ErrClosed = errors.New("mvcc: closed")
  40. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "mvcc")
  41. )
  42. const (
  43. // markedRevBytesLen is the byte length of marked revision.
  44. // The first `revBytesLen` bytes represents a normal revision. The last
  45. // one byte is the mark.
  46. markedRevBytesLen = revBytesLen + 1
  47. markBytePosition = markedRevBytesLen - 1
  48. markTombstone byte = 't'
  49. )
  50. var restoreChunkKeys = 10000 // non-const for testing
  51. // ConsistentIndexGetter is an interface that wraps the Get method.
  52. // Consistent index is the offset of an entry in a consistent replicated log.
  53. type ConsistentIndexGetter interface {
  54. // ConsistentIndex returns the consistent index of current executing entry.
  55. ConsistentIndex() uint64
  56. }
  57. type store struct {
  58. ReadView
  59. WriteView
  60. // consistentIndex caches the "consistent_index" key's value. Accessed
  61. // through atomics so must be 64-bit aligned.
  62. consistentIndex uint64
  63. // mu read locks for txns and write locks for non-txn store changes.
  64. mu sync.RWMutex
  65. ig ConsistentIndexGetter
  66. b backend.Backend
  67. kvindex index
  68. le lease.Lessor
  69. // revMuLock protects currentRev and compactMainRev.
  70. // Locked at end of write txn and released after write txn unlock lock.
  71. // Locked before locking read txn and released after locking.
  72. revMu sync.RWMutex
  73. // currentRev is the revision of the last completed transaction.
  74. currentRev int64
  75. // compactMainRev is the main revision of the last compaction.
  76. compactMainRev int64
  77. // bytesBuf8 is a byte slice of length 8
  78. // to avoid a repetitive allocation in saveIndex.
  79. bytesBuf8 []byte
  80. fifoSched schedule.Scheduler
  81. stopc chan struct{}
  82. }
  83. // NewStore returns a new store. It is useful to create a store inside
  84. // mvcc pkg. It should only be used for testing externally.
  85. func NewStore(b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) *store {
  86. s := &store{
  87. b: b,
  88. ig: ig,
  89. kvindex: newTreeIndex(),
  90. le: le,
  91. currentRev: 1,
  92. compactMainRev: -1,
  93. bytesBuf8: make([]byte, 8),
  94. fifoSched: schedule.NewFIFOScheduler(),
  95. stopc: make(chan struct{}),
  96. }
  97. s.ReadView = &readView{s}
  98. s.WriteView = &writeView{s}
  99. if s.le != nil {
  100. s.le.SetRangeDeleter(func() lease.TxnDelete { return s.Write() })
  101. }
  102. tx := s.b.BatchTx()
  103. tx.Lock()
  104. tx.UnsafeCreateBucket(keyBucketName)
  105. tx.UnsafeCreateBucket(metaBucketName)
  106. tx.Unlock()
  107. s.b.ForceCommit()
  108. if err := s.restore(); err != nil {
  109. // TODO: return the error instead of panic here?
  110. panic("failed to recover store from backend")
  111. }
  112. return s
  113. }
  114. func (s *store) compactBarrier(ctx context.Context, ch chan struct{}) {
  115. if ctx == nil || ctx.Err() != nil {
  116. s.mu.Lock()
  117. select {
  118. case <-s.stopc:
  119. default:
  120. f := func(ctx context.Context) { s.compactBarrier(ctx, ch) }
  121. s.fifoSched.Schedule(f)
  122. }
  123. s.mu.Unlock()
  124. return
  125. }
  126. close(ch)
  127. }
  128. func (s *store) Hash() (hash uint32, revision int64, err error) {
  129. s.b.ForceCommit()
  130. h, err := s.b.Hash(DefaultIgnores)
  131. return h, s.currentRev, err
  132. }
  133. func (s *store) HashByRev(rev int64) (hash uint32, currentRev int64, compactRev int64, err error) {
  134. s.mu.RLock()
  135. s.revMu.RLock()
  136. compactRev, currentRev = s.compactMainRev, s.currentRev
  137. s.revMu.RUnlock()
  138. if rev > 0 && rev <= compactRev {
  139. s.mu.RUnlock()
  140. return 0, 0, compactRev, ErrCompacted
  141. } else if rev > 0 && rev > currentRev {
  142. s.mu.RUnlock()
  143. return 0, currentRev, 0, ErrFutureRev
  144. }
  145. if rev == 0 {
  146. rev = currentRev
  147. }
  148. keep := s.kvindex.Keep(rev)
  149. tx := s.b.ReadTx()
  150. tx.Lock()
  151. defer tx.Unlock()
  152. s.mu.RUnlock()
  153. upper := revision{main: rev + 1}
  154. lower := revision{main: compactRev + 1}
  155. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  156. h.Write(keyBucketName)
  157. err = tx.UnsafeForEach(keyBucketName, func(k, v []byte) error {
  158. kr := bytesToRev(k)
  159. if !upper.GreaterThan(kr) {
  160. return nil
  161. }
  162. // skip revisions that are scheduled for deletion
  163. // due to compacting; don't skip if there isn't one.
  164. if lower.GreaterThan(kr) && len(keep) > 0 {
  165. if _, ok := keep[kr]; !ok {
  166. return nil
  167. }
  168. }
  169. h.Write(k)
  170. h.Write(v)
  171. return nil
  172. })
  173. return h.Sum32(), currentRev, compactRev, err
  174. }
  175. func (s *store) Compact(rev int64) (<-chan struct{}, error) {
  176. s.mu.Lock()
  177. defer s.mu.Unlock()
  178. s.revMu.Lock()
  179. defer s.revMu.Unlock()
  180. if rev <= s.compactMainRev {
  181. ch := make(chan struct{})
  182. f := func(ctx context.Context) { s.compactBarrier(ctx, ch) }
  183. s.fifoSched.Schedule(f)
  184. return ch, ErrCompacted
  185. }
  186. if rev > s.currentRev {
  187. return nil, ErrFutureRev
  188. }
  189. start := time.Now()
  190. s.compactMainRev = rev
  191. rbytes := newRevBytes()
  192. revToBytes(revision{main: rev}, rbytes)
  193. tx := s.b.BatchTx()
  194. tx.Lock()
  195. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  196. tx.Unlock()
  197. // ensure that desired compaction is persisted
  198. s.b.ForceCommit()
  199. keep := s.kvindex.Compact(rev)
  200. ch := make(chan struct{})
  201. var j = func(ctx context.Context) {
  202. if ctx.Err() != nil {
  203. s.compactBarrier(ctx, ch)
  204. return
  205. }
  206. if !s.scheduleCompaction(rev, keep) {
  207. s.compactBarrier(nil, ch)
  208. return
  209. }
  210. close(ch)
  211. }
  212. s.fifoSched.Schedule(j)
  213. indexCompactionPauseDurations.Observe(float64(time.Since(start) / time.Millisecond))
  214. return ch, nil
  215. }
  216. // DefaultIgnores is a map of keys to ignore in hash checking.
  217. var DefaultIgnores map[backend.IgnoreKey]struct{}
  218. func init() {
  219. DefaultIgnores = map[backend.IgnoreKey]struct{}{
  220. // consistent index might be changed due to v2 internal sync, which
  221. // is not controllable by the user.
  222. {Bucket: string(metaBucketName), Key: string(consistentIndexKeyName)}: {},
  223. }
  224. }
  225. func (s *store) Commit() {
  226. s.mu.Lock()
  227. defer s.mu.Unlock()
  228. tx := s.b.BatchTx()
  229. tx.Lock()
  230. s.saveIndex(tx)
  231. tx.Unlock()
  232. s.b.ForceCommit()
  233. }
  234. func (s *store) Restore(b backend.Backend) error {
  235. s.mu.Lock()
  236. defer s.mu.Unlock()
  237. close(s.stopc)
  238. s.fifoSched.Stop()
  239. atomic.StoreUint64(&s.consistentIndex, 0)
  240. s.b = b
  241. s.kvindex = newTreeIndex()
  242. s.currentRev = 1
  243. s.compactMainRev = -1
  244. s.fifoSched = schedule.NewFIFOScheduler()
  245. s.stopc = make(chan struct{})
  246. return s.restore()
  247. }
  248. func (s *store) restore() error {
  249. b := s.b
  250. reportDbTotalSizeInBytesMu.Lock()
  251. reportDbTotalSizeInBytes = func() float64 { return float64(b.Size()) }
  252. reportDbTotalSizeInBytesMu.Unlock()
  253. reportDbTotalSizeInUseInBytesMu.Lock()
  254. reportDbTotalSizeInUseInBytes = func() float64 { return float64(b.SizeInUse()) }
  255. reportDbTotalSizeInUseInBytesMu.Unlock()
  256. min, max := newRevBytes(), newRevBytes()
  257. revToBytes(revision{main: 1}, min)
  258. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  259. keyToLease := make(map[string]lease.LeaseID)
  260. // restore index
  261. tx := s.b.BatchTx()
  262. tx.Lock()
  263. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  264. if len(finishedCompactBytes) != 0 {
  265. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  266. plog.Printf("restore compact to %d", s.compactMainRev)
  267. }
  268. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  269. scheduledCompact := int64(0)
  270. if len(scheduledCompactBytes) != 0 {
  271. scheduledCompact = bytesToRev(scheduledCompactBytes[0]).main
  272. }
  273. // index keys concurrently as they're loaded in from tx
  274. keysGauge.Set(0)
  275. rkvc, revc := restoreIntoIndex(s.kvindex)
  276. for {
  277. keys, vals := tx.UnsafeRange(keyBucketName, min, max, int64(restoreChunkKeys))
  278. if len(keys) == 0 {
  279. break
  280. }
  281. // rkvc blocks if the total pending keys exceeds the restore
  282. // chunk size to keep keys from consuming too much memory.
  283. restoreChunk(rkvc, keys, vals, keyToLease)
  284. if len(keys) < restoreChunkKeys {
  285. // partial set implies final set
  286. break
  287. }
  288. // next set begins after where this one ended
  289. newMin := bytesToRev(keys[len(keys)-1][:revBytesLen])
  290. newMin.sub++
  291. revToBytes(newMin, min)
  292. }
  293. close(rkvc)
  294. s.currentRev = <-revc
  295. // keys in the range [compacted revision -N, compaction] might all be deleted due to compaction.
  296. // the correct revision should be set to compaction revision in the case, not the largest revision
  297. // we have seen.
  298. if s.currentRev < s.compactMainRev {
  299. s.currentRev = s.compactMainRev
  300. }
  301. if scheduledCompact <= s.compactMainRev {
  302. scheduledCompact = 0
  303. }
  304. for key, lid := range keyToLease {
  305. if s.le == nil {
  306. panic("no lessor to attach lease")
  307. }
  308. err := s.le.Attach(lid, []lease.LeaseItem{{Key: key}})
  309. if err != nil {
  310. plog.Errorf("unexpected Attach error: %v", err)
  311. }
  312. }
  313. tx.Unlock()
  314. if scheduledCompact != 0 {
  315. s.Compact(scheduledCompact)
  316. plog.Printf("resume scheduled compaction at %d", scheduledCompact)
  317. }
  318. return nil
  319. }
  320. type revKeyValue struct {
  321. key []byte
  322. kv mvccpb.KeyValue
  323. kstr string
  324. }
  325. func restoreIntoIndex(idx index) (chan<- revKeyValue, <-chan int64) {
  326. rkvc, revc := make(chan revKeyValue, restoreChunkKeys), make(chan int64, 1)
  327. go func() {
  328. currentRev := int64(1)
  329. defer func() { revc <- currentRev }()
  330. // restore the tree index from streaming the unordered index.
  331. kiCache := make(map[string]*keyIndex, restoreChunkKeys)
  332. for rkv := range rkvc {
  333. ki, ok := kiCache[rkv.kstr]
  334. // purge kiCache if many keys but still missing in the cache
  335. if !ok && len(kiCache) >= restoreChunkKeys {
  336. i := 10
  337. for k := range kiCache {
  338. delete(kiCache, k)
  339. if i--; i == 0 {
  340. break
  341. }
  342. }
  343. }
  344. // cache miss, fetch from tree index if there
  345. if !ok {
  346. ki = &keyIndex{key: rkv.kv.Key}
  347. if idxKey := idx.KeyIndex(ki); idxKey != nil {
  348. kiCache[rkv.kstr], ki = idxKey, idxKey
  349. ok = true
  350. }
  351. }
  352. rev := bytesToRev(rkv.key)
  353. currentRev = rev.main
  354. if ok {
  355. if isTombstone(rkv.key) {
  356. ki.tombstone(rev.main, rev.sub)
  357. continue
  358. }
  359. ki.put(rev.main, rev.sub)
  360. } else if !isTombstone(rkv.key) {
  361. ki.restore(revision{rkv.kv.CreateRevision, 0}, rev, rkv.kv.Version)
  362. idx.Insert(ki)
  363. kiCache[rkv.kstr] = ki
  364. }
  365. }
  366. }()
  367. return rkvc, revc
  368. }
  369. func restoreChunk(kvc chan<- revKeyValue, keys, vals [][]byte, keyToLease map[string]lease.LeaseID) {
  370. for i, key := range keys {
  371. rkv := revKeyValue{key: key}
  372. if err := rkv.kv.Unmarshal(vals[i]); err != nil {
  373. plog.Fatalf("cannot unmarshal event: %v", err)
  374. }
  375. rkv.kstr = string(rkv.kv.Key)
  376. if isTombstone(key) {
  377. delete(keyToLease, rkv.kstr)
  378. } else if lid := lease.LeaseID(rkv.kv.Lease); lid != lease.NoLease {
  379. keyToLease[rkv.kstr] = lid
  380. } else {
  381. delete(keyToLease, rkv.kstr)
  382. }
  383. kvc <- rkv
  384. }
  385. }
  386. func (s *store) Close() error {
  387. close(s.stopc)
  388. s.fifoSched.Stop()
  389. return nil
  390. }
  391. func (s *store) saveIndex(tx backend.BatchTx) {
  392. if s.ig == nil {
  393. return
  394. }
  395. bs := s.bytesBuf8
  396. ci := s.ig.ConsistentIndex()
  397. binary.BigEndian.PutUint64(bs, ci)
  398. // put the index into the underlying backend
  399. // tx has been locked in TxnBegin, so there is no need to lock it again
  400. tx.UnsafePut(metaBucketName, consistentIndexKeyName, bs)
  401. atomic.StoreUint64(&s.consistentIndex, ci)
  402. }
  403. func (s *store) ConsistentIndex() uint64 {
  404. if ci := atomic.LoadUint64(&s.consistentIndex); ci > 0 {
  405. return ci
  406. }
  407. tx := s.b.BatchTx()
  408. tx.Lock()
  409. defer tx.Unlock()
  410. _, vs := tx.UnsafeRange(metaBucketName, consistentIndexKeyName, nil, 0)
  411. if len(vs) == 0 {
  412. return 0
  413. }
  414. v := binary.BigEndian.Uint64(vs[0])
  415. atomic.StoreUint64(&s.consistentIndex, v)
  416. return v
  417. }
  418. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  419. func appendMarkTombstone(b []byte) []byte {
  420. if len(b) != revBytesLen {
  421. plog.Panicf("cannot append mark to non normal revision bytes")
  422. }
  423. return append(b, markTombstone)
  424. }
  425. // isTombstone checks whether the revision bytes is a tombstone.
  426. func isTombstone(b []byte) bool {
  427. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  428. }