kvstore_compaction.go 2.3 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 func() { dbCompactionTotalMs.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. 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, int64(s.cfg.CompactionBatchLimit))
  34. for _, key := range keys {
  35. rev = bytesToRev(key)
  36. if _, ok := keep[rev]; !ok {
  37. tx.UnsafeDelete(keyBucketName, key)
  38. }
  39. }
  40. if len(keys) < s.cfg.CompactionBatchLimit {
  41. rbytes := make([]byte, 8+1+8)
  42. revToBytes(revision{main: compactMainRev}, rbytes)
  43. tx.UnsafePut(metaBucketName, finishedCompactKeyName, rbytes)
  44. tx.Unlock()
  45. if s.lg != nil {
  46. s.lg.Info(
  47. "finished scheduled compaction",
  48. zap.Int64("compact-revision", compactMainRev),
  49. zap.Duration("took", time.Since(totalStart)),
  50. )
  51. } else {
  52. plog.Infof("finished scheduled compaction at %d (took %v)", compactMainRev, time.Since(totalStart))
  53. }
  54. return true
  55. }
  56. // update last
  57. revToBytes(revision{main: rev.main, sub: rev.sub + 1}, last)
  58. tx.Unlock()
  59. // Immediately commit the compaction deletes instead of letting them accumulate in the write buffer
  60. s.b.ForceCommit()
  61. dbCompactionPauseMs.Observe(float64(time.Since(start) / time.Millisecond))
  62. select {
  63. case <-time.After(10 * time.Millisecond):
  64. case <-s.stopc:
  65. return false
  66. }
  67. }
  68. }