kvstore.go 16 KB

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