kvstore_compaction.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2015 CoreOS, Inc.
  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 storage
  15. import (
  16. "encoding/binary"
  17. "time"
  18. )
  19. func (s *store) scheduleCompaction(compactMainRev int64, keep map[revision]struct{}) {
  20. defer s.wg.Done()
  21. totalStart := time.Now()
  22. defer dbCompactionTotalDurations.Observe(float64(time.Now().Sub(totalStart) / time.Millisecond))
  23. end := make([]byte, 8)
  24. binary.BigEndian.PutUint64(end, uint64(compactMainRev+1))
  25. batchsize := int64(10000)
  26. last := make([]byte, 8+1+8)
  27. for {
  28. var rev revision
  29. start := time.Now()
  30. tx := s.b.BatchTx()
  31. tx.Lock()
  32. keys, _ := tx.UnsafeRange(keyBucketName, last, end, batchsize)
  33. for _, key := range keys {
  34. rev = bytesToRev(key)
  35. if _, ok := keep[rev]; !ok {
  36. tx.UnsafeDelete(keyBucketName, key)
  37. }
  38. }
  39. if len(keys) < int(batchsize) {
  40. rbytes := make([]byte, 8+1+8)
  41. revToBytes(revision{main: compactMainRev}, rbytes)
  42. tx.UnsafePut(metaBucketName, finishedCompactKeyName, rbytes)
  43. tx.Unlock()
  44. return
  45. }
  46. // update last
  47. revToBytes(revision{main: rev.main, sub: rev.sub + 1}, last)
  48. tx.Unlock()
  49. dbCompactionPauseDurations.Observe(float64(time.Now().Sub(start) / time.Millisecond))
  50. select {
  51. case <-time.After(100 * time.Millisecond):
  52. case <-s.stopc:
  53. return
  54. }
  55. }
  56. }