kvstore_compaction.go 2.2 KB

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