kvstore_compaction.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "encoding/binary"
  17. "time"
  18. )
  19. func (s *store) scheduleCompaction(compactMainRev int64, keep map[revision]struct{}) bool {
  20. totalStart := time.Now()
  21. defer func() { dbCompactionTotalDurations.Observe(float64(time.Since(totalStart) / time.Millisecond)) }()
  22. keyCompactions := 0
  23. defer func() { dbCompactionKeysCounter.Add(float64(keyCompactions)) }()
  24. end := make([]byte, 8)
  25. binary.BigEndian.PutUint64(end, uint64(compactMainRev+1))
  26. batchsize := int64(10000)
  27. last := make([]byte, 8+1+8)
  28. for {
  29. var rev revision
  30. start := time.Now()
  31. tx := s.b.BatchTx()
  32. tx.Lock()
  33. keys, _ := tx.UnsafeRange(keyBucketName, last, end, batchsize)
  34. for _, key := range keys {
  35. rev = bytesToRev(key)
  36. if _, ok := keep[rev]; !ok {
  37. tx.UnsafeDelete(keyBucketName, key)
  38. keyCompactions++
  39. }
  40. }
  41. if len(keys) < int(batchsize) {
  42. rbytes := make([]byte, 8+1+8)
  43. revToBytes(revision{main: compactMainRev}, rbytes)
  44. tx.UnsafePut(metaBucketName, finishedCompactKeyName, rbytes)
  45. tx.Unlock()
  46. plog.Printf("finished scheduled compaction at %d (took %v)", compactMainRev, time.Since(totalStart))
  47. return true
  48. }
  49. // update last
  50. revToBytes(revision{main: rev.main, sub: rev.sub + 1}, last)
  51. tx.Unlock()
  52. dbCompactionPauseDurations.Observe(float64(time.Since(start) / time.Millisecond))
  53. select {
  54. case <-time.After(100 * time.Millisecond):
  55. case <-s.stopc:
  56. return false
  57. }
  58. }
  59. }