kvstore.go 13 KB

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