kvstore.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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.Lock()
  160. defer tx.Unlock()
  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. min, max := newRevBytes(), newRevBytes()
  291. revToBytes(revision{main: 1}, min)
  292. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  293. keyToLease := make(map[string]lease.LeaseID)
  294. // restore index
  295. tx := s.b.BatchTx()
  296. tx.Lock()
  297. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  298. if len(finishedCompactBytes) != 0 {
  299. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  300. if s.lg != nil {
  301. s.lg.Info(
  302. "restored last compact revision",
  303. zap.String("meta-bucket-name", string(metaBucketName)),
  304. zap.String("meta-bucket-name-key", string(finishedCompactKeyName)),
  305. zap.Int64("restored-compact-revision", s.compactMainRev),
  306. )
  307. } else {
  308. plog.Printf("restore compact to %d", s.compactMainRev)
  309. }
  310. }
  311. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  312. scheduledCompact := int64(0)
  313. if len(scheduledCompactBytes) != 0 {
  314. scheduledCompact = bytesToRev(scheduledCompactBytes[0]).main
  315. }
  316. // index keys concurrently as they're loaded in from tx
  317. keysGauge.Set(0)
  318. rkvc, revc := restoreIntoIndex(s.lg, s.kvindex)
  319. for {
  320. keys, vals := tx.UnsafeRange(keyBucketName, min, max, int64(restoreChunkKeys))
  321. if len(keys) == 0 {
  322. break
  323. }
  324. // rkvc blocks if the total pending keys exceeds the restore
  325. // chunk size to keep keys from consuming too much memory.
  326. restoreChunk(s.lg, rkvc, keys, vals, keyToLease)
  327. if len(keys) < restoreChunkKeys {
  328. // partial set implies final set
  329. break
  330. }
  331. // next set begins after where this one ended
  332. newMin := bytesToRev(keys[len(keys)-1][:revBytesLen])
  333. newMin.sub++
  334. revToBytes(newMin, min)
  335. }
  336. close(rkvc)
  337. s.currentRev = <-revc
  338. // keys in the range [compacted revision -N, compaction] might all be deleted due to compaction.
  339. // the correct revision should be set to compaction revision in the case, not the largest revision
  340. // we have seen.
  341. if s.currentRev < s.compactMainRev {
  342. s.currentRev = s.compactMainRev
  343. }
  344. if scheduledCompact <= s.compactMainRev {
  345. scheduledCompact = 0
  346. }
  347. for key, lid := range keyToLease {
  348. if s.le == nil {
  349. panic("no lessor to attach lease")
  350. }
  351. err := s.le.Attach(lid, []lease.LeaseItem{{Key: key}})
  352. if err != nil {
  353. if s.lg != nil {
  354. s.lg.Warn(
  355. "failed to attach a lease",
  356. zap.String("lease-id", fmt.Sprintf("%016x", lid)),
  357. zap.Error(err),
  358. )
  359. } else {
  360. plog.Errorf("unexpected Attach error: %v", err)
  361. }
  362. }
  363. }
  364. tx.Unlock()
  365. if scheduledCompact != 0 {
  366. s.compactLockfree(scheduledCompact)
  367. if s.lg != nil {
  368. s.lg.Info(
  369. "resume scheduled compaction",
  370. zap.String("meta-bucket-name", string(metaBucketName)),
  371. zap.String("meta-bucket-name-key", string(scheduledCompactKeyName)),
  372. zap.Int64("scheduled-compact-revision", scheduledCompact),
  373. )
  374. } else {
  375. plog.Printf("resume scheduled compaction at %d", scheduledCompact)
  376. }
  377. }
  378. return nil
  379. }
  380. type revKeyValue struct {
  381. key []byte
  382. kv mvccpb.KeyValue
  383. kstr string
  384. }
  385. func restoreIntoIndex(lg *zap.Logger, idx index) (chan<- revKeyValue, <-chan int64) {
  386. rkvc, revc := make(chan revKeyValue, restoreChunkKeys), make(chan int64, 1)
  387. go func() {
  388. currentRev := int64(1)
  389. defer func() { revc <- currentRev }()
  390. // restore the tree index from streaming the unordered index.
  391. kiCache := make(map[string]*keyIndex, restoreChunkKeys)
  392. for rkv := range rkvc {
  393. ki, ok := kiCache[rkv.kstr]
  394. // purge kiCache if many keys but still missing in the cache
  395. if !ok && len(kiCache) >= restoreChunkKeys {
  396. i := 10
  397. for k := range kiCache {
  398. delete(kiCache, k)
  399. if i--; i == 0 {
  400. break
  401. }
  402. }
  403. }
  404. // cache miss, fetch from tree index if there
  405. if !ok {
  406. ki = &keyIndex{key: rkv.kv.Key}
  407. if idxKey := idx.KeyIndex(ki); idxKey != nil {
  408. kiCache[rkv.kstr], ki = idxKey, idxKey
  409. ok = true
  410. }
  411. }
  412. rev := bytesToRev(rkv.key)
  413. currentRev = rev.main
  414. if ok {
  415. if isTombstone(rkv.key) {
  416. ki.tombstone(lg, rev.main, rev.sub)
  417. continue
  418. }
  419. ki.put(lg, rev.main, rev.sub)
  420. } else if !isTombstone(rkv.key) {
  421. ki.restore(lg, revision{rkv.kv.CreateRevision, 0}, rev, rkv.kv.Version)
  422. idx.Insert(ki)
  423. kiCache[rkv.kstr] = ki
  424. }
  425. }
  426. }()
  427. return rkvc, revc
  428. }
  429. func restoreChunk(lg *zap.Logger, kvc chan<- revKeyValue, keys, vals [][]byte, keyToLease map[string]lease.LeaseID) {
  430. for i, key := range keys {
  431. rkv := revKeyValue{key: key}
  432. if err := rkv.kv.Unmarshal(vals[i]); err != nil {
  433. if lg != nil {
  434. lg.Fatal("failed to unmarshal mvccpb.KeyValue", zap.Error(err))
  435. } else {
  436. plog.Fatalf("cannot unmarshal event: %v", err)
  437. }
  438. }
  439. rkv.kstr = string(rkv.kv.Key)
  440. if isTombstone(key) {
  441. delete(keyToLease, rkv.kstr)
  442. } else if lid := lease.LeaseID(rkv.kv.Lease); lid != lease.NoLease {
  443. keyToLease[rkv.kstr] = lid
  444. } else {
  445. delete(keyToLease, rkv.kstr)
  446. }
  447. kvc <- rkv
  448. }
  449. }
  450. func (s *store) Close() error {
  451. close(s.stopc)
  452. s.fifoSched.Stop()
  453. return nil
  454. }
  455. func (s *store) saveIndex(tx backend.BatchTx) {
  456. if s.ig == nil {
  457. return
  458. }
  459. bs := s.bytesBuf8
  460. ci := s.ig.ConsistentIndex()
  461. binary.BigEndian.PutUint64(bs, ci)
  462. // put the index into the underlying backend
  463. // tx has been locked in TxnBegin, so there is no need to lock it again
  464. tx.UnsafePut(metaBucketName, consistentIndexKeyName, bs)
  465. atomic.StoreUint64(&s.consistentIndex, ci)
  466. }
  467. func (s *store) ConsistentIndex() uint64 {
  468. if ci := atomic.LoadUint64(&s.consistentIndex); ci > 0 {
  469. return ci
  470. }
  471. tx := s.b.BatchTx()
  472. tx.Lock()
  473. defer tx.Unlock()
  474. _, vs := tx.UnsafeRange(metaBucketName, consistentIndexKeyName, nil, 0)
  475. if len(vs) == 0 {
  476. return 0
  477. }
  478. v := binary.BigEndian.Uint64(vs[0])
  479. atomic.StoreUint64(&s.consistentIndex, v)
  480. return v
  481. }
  482. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  483. func appendMarkTombstone(lg *zap.Logger, b []byte) []byte {
  484. if len(b) != revBytesLen {
  485. if lg != nil {
  486. lg.Panic(
  487. "cannot append tombstone mark to non-normal revision bytes",
  488. zap.Int("expected-revision-bytes-size", revBytesLen),
  489. zap.Int("given-revision-bytes-size", len(b)),
  490. )
  491. } else {
  492. plog.Panicf("cannot append mark to non normal revision bytes")
  493. }
  494. }
  495. return append(b, markTombstone)
  496. }
  497. // isTombstone checks whether the revision bytes is a tombstone.
  498. func isTombstone(b []byte) bool {
  499. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  500. }