kvstore_compaction.go 1.8 KB

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