kvstore.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. "github.com/coreos/etcd/lease"
  26. "github.com/coreos/etcd/mvcc/backend"
  27. "github.com/coreos/etcd/mvcc/mvccpb"
  28. "github.com/coreos/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("github.com/coreos/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. if err := s.restore(); err != nil {
  113. // TODO: return the error instead of panic here?
  114. panic("failed to recover store from backend")
  115. }
  116. return s
  117. }
  118. func (s *store) compactBarrier(ctx context.Context, ch chan struct{}) {
  119. if ctx == nil || ctx.Err() != nil {
  120. s.mu.Lock()
  121. select {
  122. case <-s.stopc:
  123. default:
  124. f := func(ctx context.Context) { s.compactBarrier(ctx, ch) }
  125. s.fifoSched.Schedule(f)
  126. }
  127. s.mu.Unlock()
  128. return
  129. }
  130. close(ch)
  131. }
  132. func (s *store) Hash() (hash uint32, revision int64, err error) {
  133. s.b.ForceCommit()
  134. h, err := s.b.Hash(DefaultIgnores)
  135. return h, s.currentRev, err
  136. }
  137. func (s *store) HashByRev(rev int64) (hash uint32, currentRev int64, compactRev int64, err error) {
  138. s.mu.RLock()
  139. s.revMu.RLock()
  140. compactRev, currentRev = s.compactMainRev, s.currentRev
  141. s.revMu.RUnlock()
  142. if rev > 0 && rev <= compactRev {
  143. s.mu.RUnlock()
  144. return 0, 0, compactRev, ErrCompacted
  145. } else if rev > 0 && rev > currentRev {
  146. s.mu.RUnlock()
  147. return 0, currentRev, 0, ErrFutureRev
  148. }
  149. if rev == 0 {
  150. rev = currentRev
  151. }
  152. keep := s.kvindex.Keep(rev)
  153. tx := s.b.ReadTx()
  154. tx.Lock()
  155. defer tx.Unlock()
  156. s.mu.RUnlock()
  157. upper := revision{main: rev + 1}
  158. lower := revision{main: compactRev + 1}
  159. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  160. h.Write(keyBucketName)
  161. err = tx.UnsafeForEach(keyBucketName, func(k, v []byte) error {
  162. kr := bytesToRev(k)
  163. if !upper.GreaterThan(kr) {
  164. return nil
  165. }
  166. // skip revisions that are scheduled for deletion
  167. // due to compacting; don't skip if there isn't one.
  168. if lower.GreaterThan(kr) && len(keep) > 0 {
  169. if _, ok := keep[kr]; !ok {
  170. return nil
  171. }
  172. }
  173. h.Write(k)
  174. h.Write(v)
  175. return nil
  176. })
  177. return h.Sum32(), currentRev, compactRev, err
  178. }
  179. func (s *store) Compact(rev int64) (<-chan struct{}, error) {
  180. s.mu.Lock()
  181. s.revMu.Lock()
  182. if rev <= s.compactMainRev {
  183. ch := make(chan struct{})
  184. f := func(ctx context.Context) { s.compactBarrier(ctx, ch) }
  185. s.fifoSched.Schedule(f)
  186. s.mu.Unlock()
  187. s.revMu.Unlock()
  188. return ch, ErrCompacted
  189. }
  190. if rev > s.currentRev {
  191. s.mu.Unlock()
  192. s.revMu.Unlock()
  193. return nil, ErrFutureRev
  194. }
  195. start := time.Now()
  196. s.compactMainRev = rev
  197. rbytes := newRevBytes()
  198. revToBytes(revision{main: rev}, rbytes)
  199. tx := s.b.BatchTx()
  200. tx.Lock()
  201. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  202. tx.Unlock()
  203. // ensure that desired compaction is persisted
  204. s.b.ForceCommit()
  205. s.mu.Unlock()
  206. s.revMu.Unlock()
  207. keep := s.kvindex.Compact(rev)
  208. ch := make(chan struct{})
  209. var j = func(ctx context.Context) {
  210. if ctx.Err() != nil {
  211. s.compactBarrier(ctx, ch)
  212. return
  213. }
  214. if !s.scheduleCompaction(rev, keep) {
  215. s.compactBarrier(nil, ch)
  216. return
  217. }
  218. close(ch)
  219. }
  220. s.fifoSched.Schedule(j)
  221. indexCompactionPauseDurations.Observe(float64(time.Since(start) / time.Millisecond))
  222. return ch, nil
  223. }
  224. // DefaultIgnores is a map of keys to ignore in hash checking.
  225. var DefaultIgnores map[backend.IgnoreKey]struct{}
  226. func init() {
  227. DefaultIgnores = map[backend.IgnoreKey]struct{}{
  228. // consistent index might be changed due to v2 internal sync, which
  229. // is not controllable by the user.
  230. {Bucket: string(metaBucketName), Key: string(consistentIndexKeyName)}: {},
  231. }
  232. }
  233. func (s *store) Commit() {
  234. s.mu.Lock()
  235. defer s.mu.Unlock()
  236. tx := s.b.BatchTx()
  237. tx.Lock()
  238. s.saveIndex(tx)
  239. tx.Unlock()
  240. s.b.ForceCommit()
  241. }
  242. func (s *store) Restore(b backend.Backend) error {
  243. s.mu.Lock()
  244. defer s.mu.Unlock()
  245. close(s.stopc)
  246. s.fifoSched.Stop()
  247. atomic.StoreUint64(&s.consistentIndex, 0)
  248. s.b = b
  249. s.kvindex = newTreeIndex(s.lg)
  250. s.currentRev = 1
  251. s.compactMainRev = -1
  252. s.fifoSched = schedule.NewFIFOScheduler()
  253. s.stopc = make(chan struct{})
  254. return s.restore()
  255. }
  256. func (s *store) restore() error {
  257. b := s.b
  258. reportDbTotalSizeInBytesMu.Lock()
  259. reportDbTotalSizeInBytes = func() float64 { return float64(b.Size()) }
  260. reportDbTotalSizeInBytesMu.Unlock()
  261. reportDbTotalSizeInUseInBytesMu.Lock()
  262. reportDbTotalSizeInUseInBytes = func() float64 { return float64(b.SizeInUse()) }
  263. reportDbTotalSizeInUseInBytesMu.Unlock()
  264. min, max := newRevBytes(), newRevBytes()
  265. revToBytes(revision{main: 1}, min)
  266. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  267. keyToLease := make(map[string]lease.LeaseID)
  268. // restore index
  269. tx := s.b.BatchTx()
  270. tx.Lock()
  271. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  272. if len(finishedCompactBytes) != 0 {
  273. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  274. if s.lg != nil {
  275. s.lg.Info(
  276. "restored last compact revision",
  277. zap.String("meta-bucket-name", string(metaBucketName)),
  278. zap.String("meta-bucket-name-key", string(finishedCompactKeyName)),
  279. zap.Int64("restored-compact-revision", s.compactMainRev),
  280. )
  281. } else {
  282. plog.Printf("restore compact to %d", s.compactMainRev)
  283. }
  284. }
  285. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  286. scheduledCompact := int64(0)
  287. if len(scheduledCompactBytes) != 0 {
  288. scheduledCompact = bytesToRev(scheduledCompactBytes[0]).main
  289. }
  290. // index keys concurrently as they're loaded in from tx
  291. keysGauge.Set(0)
  292. rkvc, revc := restoreIntoIndex(s.kvindex)
  293. for {
  294. keys, vals := tx.UnsafeRange(keyBucketName, min, max, int64(restoreChunkKeys))
  295. if len(keys) == 0 {
  296. break
  297. }
  298. // rkvc blocks if the total pending keys exceeds the restore
  299. // chunk size to keep keys from consuming too much memory.
  300. restoreChunk(rkvc, keys, vals, keyToLease)
  301. if len(keys) < restoreChunkKeys {
  302. // partial set implies final set
  303. break
  304. }
  305. // next set begins after where this one ended
  306. newMin := bytesToRev(keys[len(keys)-1][:revBytesLen])
  307. newMin.sub++
  308. revToBytes(newMin, min)
  309. }
  310. close(rkvc)
  311. s.currentRev = <-revc
  312. // keys in the range [compacted revision -N, compaction] might all be deleted due to compaction.
  313. // the correct revision should be set to compaction revision in the case, not the largest revision
  314. // we have seen.
  315. if s.currentRev < s.compactMainRev {
  316. s.currentRev = s.compactMainRev
  317. }
  318. if scheduledCompact <= s.compactMainRev {
  319. scheduledCompact = 0
  320. }
  321. for key, lid := range keyToLease {
  322. if s.le == nil {
  323. panic("no lessor to attach lease")
  324. }
  325. err := s.le.Attach(lid, []lease.LeaseItem{{Key: key}})
  326. if err != nil {
  327. if s.lg != nil {
  328. s.lg.Warn(
  329. "failed to attach a lease",
  330. zap.String("lease-id", fmt.Sprintf("%016x", lid)),
  331. zap.Error(err),
  332. )
  333. } else {
  334. plog.Errorf("unexpected Attach error: %v", err)
  335. }
  336. }
  337. }
  338. tx.Unlock()
  339. if scheduledCompact != 0 {
  340. s.Compact(scheduledCompact)
  341. if s.lg != nil {
  342. s.lg.Info(
  343. "resume scheduled compaction",
  344. zap.String("meta-bucket-name", string(metaBucketName)),
  345. zap.String("meta-bucket-name-key", string(scheduledCompactKeyName)),
  346. zap.Int64("scheduled-compact-revision", scheduledCompact),
  347. )
  348. } else {
  349. plog.Printf("resume scheduled compaction at %d", scheduledCompact)
  350. }
  351. }
  352. return nil
  353. }
  354. type revKeyValue struct {
  355. key []byte
  356. kv mvccpb.KeyValue
  357. kstr string
  358. }
  359. func restoreIntoIndex(idx index) (chan<- revKeyValue, <-chan int64) {
  360. rkvc, revc := make(chan revKeyValue, restoreChunkKeys), make(chan int64, 1)
  361. go func() {
  362. currentRev := int64(1)
  363. defer func() { revc <- currentRev }()
  364. // restore the tree index from streaming the unordered index.
  365. kiCache := make(map[string]*keyIndex, restoreChunkKeys)
  366. for rkv := range rkvc {
  367. ki, ok := kiCache[rkv.kstr]
  368. // purge kiCache if many keys but still missing in the cache
  369. if !ok && len(kiCache) >= restoreChunkKeys {
  370. i := 10
  371. for k := range kiCache {
  372. delete(kiCache, k)
  373. if i--; i == 0 {
  374. break
  375. }
  376. }
  377. }
  378. // cache miss, fetch from tree index if there
  379. if !ok {
  380. ki = &keyIndex{key: rkv.kv.Key}
  381. if idxKey := idx.KeyIndex(ki); idxKey != nil {
  382. kiCache[rkv.kstr], ki = idxKey, idxKey
  383. ok = true
  384. }
  385. }
  386. rev := bytesToRev(rkv.key)
  387. currentRev = rev.main
  388. if ok {
  389. if isTombstone(rkv.key) {
  390. ki.tombstone(rev.main, rev.sub)
  391. continue
  392. }
  393. ki.put(rev.main, rev.sub)
  394. } else if !isTombstone(rkv.key) {
  395. ki.restore(revision{rkv.kv.CreateRevision, 0}, rev, rkv.kv.Version)
  396. idx.Insert(ki)
  397. kiCache[rkv.kstr] = ki
  398. }
  399. }
  400. }()
  401. return rkvc, revc
  402. }
  403. func restoreChunk(kvc chan<- revKeyValue, keys, vals [][]byte, keyToLease map[string]lease.LeaseID) {
  404. for i, key := range keys {
  405. rkv := revKeyValue{key: key}
  406. if err := rkv.kv.Unmarshal(vals[i]); err != nil {
  407. plog.Fatalf("cannot unmarshal event: %v", err)
  408. }
  409. rkv.kstr = string(rkv.kv.Key)
  410. if isTombstone(key) {
  411. delete(keyToLease, rkv.kstr)
  412. } else if lid := lease.LeaseID(rkv.kv.Lease); lid != lease.NoLease {
  413. keyToLease[rkv.kstr] = lid
  414. } else {
  415. delete(keyToLease, rkv.kstr)
  416. }
  417. kvc <- rkv
  418. }
  419. }
  420. func (s *store) Close() error {
  421. close(s.stopc)
  422. s.fifoSched.Stop()
  423. return nil
  424. }
  425. func (s *store) saveIndex(tx backend.BatchTx) {
  426. if s.ig == nil {
  427. return
  428. }
  429. bs := s.bytesBuf8
  430. ci := s.ig.ConsistentIndex()
  431. binary.BigEndian.PutUint64(bs, ci)
  432. // put the index into the underlying backend
  433. // tx has been locked in TxnBegin, so there is no need to lock it again
  434. tx.UnsafePut(metaBucketName, consistentIndexKeyName, bs)
  435. atomic.StoreUint64(&s.consistentIndex, ci)
  436. }
  437. func (s *store) ConsistentIndex() uint64 {
  438. if ci := atomic.LoadUint64(&s.consistentIndex); ci > 0 {
  439. return ci
  440. }
  441. tx := s.b.BatchTx()
  442. tx.Lock()
  443. defer tx.Unlock()
  444. _, vs := tx.UnsafeRange(metaBucketName, consistentIndexKeyName, nil, 0)
  445. if len(vs) == 0 {
  446. return 0
  447. }
  448. v := binary.BigEndian.Uint64(vs[0])
  449. atomic.StoreUint64(&s.consistentIndex, v)
  450. return v
  451. }
  452. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  453. func appendMarkTombstone(b []byte) []byte {
  454. if len(b) != revBytesLen {
  455. plog.Panicf("cannot append mark to non normal revision bytes")
  456. }
  457. return append(b, markTombstone)
  458. }
  459. // isTombstone checks whether the revision bytes is a tombstone.
  460. func isTombstone(b []byte) bool {
  461. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  462. }