kvstore.go 16 KB

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