kvstore.go 15 KB

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