compaction.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. * Copyright 2017 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package badger
  17. import (
  18. "bytes"
  19. "fmt"
  20. "log"
  21. "math"
  22. "sync"
  23. "golang.org/x/net/trace"
  24. "github.com/dgraph-io/badger/table"
  25. "github.com/dgraph-io/badger/y"
  26. )
  27. type keyRange struct {
  28. left []byte
  29. right []byte
  30. inf bool
  31. }
  32. var infRange = keyRange{inf: true}
  33. func (r keyRange) String() string {
  34. return fmt.Sprintf("[left=%x, right=%x, inf=%v]", r.left, r.right, r.inf)
  35. }
  36. func (r keyRange) equals(dst keyRange) bool {
  37. return bytes.Equal(r.left, dst.left) &&
  38. bytes.Equal(r.right, dst.right) &&
  39. r.inf == dst.inf
  40. }
  41. func (r keyRange) overlapsWith(dst keyRange) bool {
  42. if r.inf || dst.inf {
  43. return true
  44. }
  45. // If my left is greater than dst right, we have no overlap.
  46. if y.CompareKeys(r.left, dst.right) > 0 {
  47. return false
  48. }
  49. // If my right is less than dst left, we have no overlap.
  50. if y.CompareKeys(r.right, dst.left) < 0 {
  51. return false
  52. }
  53. // We have overlap.
  54. return true
  55. }
  56. func getKeyRange(tables []*table.Table) keyRange {
  57. y.AssertTrue(len(tables) > 0)
  58. smallest := tables[0].Smallest()
  59. biggest := tables[0].Biggest()
  60. for i := 1; i < len(tables); i++ {
  61. if y.CompareKeys(tables[i].Smallest(), smallest) < 0 {
  62. smallest = tables[i].Smallest()
  63. }
  64. if y.CompareKeys(tables[i].Biggest(), biggest) > 0 {
  65. biggest = tables[i].Biggest()
  66. }
  67. }
  68. return keyRange{
  69. left: y.KeyWithTs(y.ParseKey(smallest), math.MaxUint64),
  70. right: y.KeyWithTs(y.ParseKey(biggest), 0),
  71. }
  72. }
  73. type levelCompactStatus struct {
  74. ranges []keyRange
  75. delSize int64
  76. }
  77. func (lcs *levelCompactStatus) debug() string {
  78. var b bytes.Buffer
  79. for _, r := range lcs.ranges {
  80. b.WriteString(r.String())
  81. }
  82. return b.String()
  83. }
  84. func (lcs *levelCompactStatus) overlapsWith(dst keyRange) bool {
  85. for _, r := range lcs.ranges {
  86. if r.overlapsWith(dst) {
  87. return true
  88. }
  89. }
  90. return false
  91. }
  92. func (lcs *levelCompactStatus) remove(dst keyRange) bool {
  93. final := lcs.ranges[:0]
  94. var found bool
  95. for _, r := range lcs.ranges {
  96. if !r.equals(dst) {
  97. final = append(final, r)
  98. } else {
  99. found = true
  100. }
  101. }
  102. lcs.ranges = final
  103. return found
  104. }
  105. type compactStatus struct {
  106. sync.RWMutex
  107. levels []*levelCompactStatus
  108. }
  109. func (cs *compactStatus) toLog(tr trace.Trace) {
  110. cs.RLock()
  111. defer cs.RUnlock()
  112. tr.LazyPrintf("Compaction status:")
  113. for i, l := range cs.levels {
  114. if len(l.debug()) == 0 {
  115. continue
  116. }
  117. tr.LazyPrintf("[%d] %s", i, l.debug())
  118. }
  119. }
  120. func (cs *compactStatus) overlapsWith(level int, this keyRange) bool {
  121. cs.RLock()
  122. defer cs.RUnlock()
  123. thisLevel := cs.levels[level]
  124. return thisLevel.overlapsWith(this)
  125. }
  126. func (cs *compactStatus) delSize(l int) int64 {
  127. cs.RLock()
  128. defer cs.RUnlock()
  129. return cs.levels[l].delSize
  130. }
  131. type thisAndNextLevelRLocked struct{}
  132. // compareAndAdd will check whether we can run this compactDef. That it doesn't overlap with any
  133. // other running compaction. If it can be run, it would store this run in the compactStatus state.
  134. func (cs *compactStatus) compareAndAdd(_ thisAndNextLevelRLocked, cd compactDef) bool {
  135. cs.Lock()
  136. defer cs.Unlock()
  137. level := cd.thisLevel.level
  138. y.AssertTruef(level < len(cs.levels)-1, "Got level %d. Max levels: %d", level, len(cs.levels))
  139. thisLevel := cs.levels[level]
  140. nextLevel := cs.levels[level+1]
  141. if thisLevel.overlapsWith(cd.thisRange) {
  142. return false
  143. }
  144. if nextLevel.overlapsWith(cd.nextRange) {
  145. return false
  146. }
  147. // Check whether this level really needs compaction or not. Otherwise, we'll end up
  148. // running parallel compactions for the same level.
  149. // NOTE: We can directly call thisLevel.totalSize, because we already have acquire a read lock
  150. // over this and the next level.
  151. if cd.thisLevel.totalSize-thisLevel.delSize < cd.thisLevel.maxTotalSize {
  152. return false
  153. }
  154. thisLevel.ranges = append(thisLevel.ranges, cd.thisRange)
  155. nextLevel.ranges = append(nextLevel.ranges, cd.nextRange)
  156. thisLevel.delSize += cd.thisSize
  157. return true
  158. }
  159. func (cs *compactStatus) delete(cd compactDef) {
  160. cs.Lock()
  161. defer cs.Unlock()
  162. level := cd.thisLevel.level
  163. y.AssertTruef(level < len(cs.levels)-1, "Got level %d. Max levels: %d", level, len(cs.levels))
  164. thisLevel := cs.levels[level]
  165. nextLevel := cs.levels[level+1]
  166. thisLevel.delSize -= cd.thisSize
  167. found := thisLevel.remove(cd.thisRange)
  168. found = nextLevel.remove(cd.nextRange) && found
  169. if !found {
  170. this := cd.thisRange
  171. next := cd.nextRange
  172. fmt.Printf("Looking for: [%q, %q, %v] in this level.\n", this.left, this.right, this.inf)
  173. fmt.Printf("This Level:\n%s\n", thisLevel.debug())
  174. fmt.Println()
  175. fmt.Printf("Looking for: [%q, %q, %v] in next level.\n", next.left, next.right, next.inf)
  176. fmt.Printf("Next Level:\n%s\n", nextLevel.debug())
  177. log.Fatal("keyRange not found")
  178. }
  179. }