key_index.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. "bytes"
  17. "errors"
  18. "fmt"
  19. "github.com/google/btree"
  20. )
  21. var (
  22. ErrRevisionNotFound = errors.New("mvcc: revision not found")
  23. )
  24. // keyIndex stores the revisions of a key in the backend.
  25. // Each keyIndex has at least one key generation.
  26. // Each generation might have several key versions.
  27. // Tombstone on a key appends an tombstone version at the end
  28. // of the current generation and creates a new empty generation.
  29. // Each version of a key has an index pointing to the backend.
  30. //
  31. // For example: put(1.0);put(2.0);tombstone(3.0);put(4.0);tombstone(5.0) on key "foo"
  32. // generate a keyIndex:
  33. // key: "foo"
  34. // rev: 5
  35. // generations:
  36. // {empty}
  37. // {4.0, 5.0(t)}
  38. // {1.0, 2.0, 3.0(t)}
  39. //
  40. // Compact a keyIndex removes the versions with smaller or equal to
  41. // rev except the largest one. If the generation becomes empty
  42. // during compaction, it will be removed. if all the generations get
  43. // removed, the keyIndex should be removed.
  44. // For example:
  45. // compact(2) on the previous example
  46. // generations:
  47. // {empty}
  48. // {4.0, 5.0(t)}
  49. // {2.0, 3.0(t)}
  50. //
  51. // compact(4)
  52. // generations:
  53. // {empty}
  54. // {4.0, 5.0(t)}
  55. //
  56. // compact(5):
  57. // generations:
  58. // {empty} -> key SHOULD be removed.
  59. //
  60. // compact(6):
  61. // generations:
  62. // {empty} -> key SHOULD be removed.
  63. type keyIndex struct {
  64. key []byte
  65. modified revision // the main rev of the last modification
  66. generations []generation
  67. }
  68. // put puts a revision to the keyIndex.
  69. func (ki *keyIndex) put(main int64, sub int64) {
  70. rev := revision{main: main, sub: sub}
  71. if !rev.GreaterThan(ki.modified) {
  72. plog.Panicf("store.keyindex: put with unexpected smaller revision [%v / %v]", rev, ki.modified)
  73. }
  74. if len(ki.generations) == 0 {
  75. ki.generations = append(ki.generations, generation{})
  76. }
  77. g := &ki.generations[len(ki.generations)-1]
  78. if len(g.revs) == 0 { // create a new key
  79. keysGauge.Inc()
  80. g.created = rev
  81. }
  82. g.revs = append(g.revs, rev)
  83. g.ver++
  84. ki.modified = rev
  85. }
  86. func (ki *keyIndex) restore(created, modified revision, ver int64) {
  87. if len(ki.generations) != 0 {
  88. plog.Panicf("store.keyindex: cannot restore non-empty keyIndex")
  89. }
  90. ki.modified = modified
  91. g := generation{created: created, ver: ver, revs: []revision{modified}}
  92. ki.generations = append(ki.generations, g)
  93. keysGauge.Inc()
  94. }
  95. // tombstone puts a revision, pointing to a tombstone, to the keyIndex.
  96. // It also creates a new empty generation in the keyIndex.
  97. // It returns ErrRevisionNotFound when tombstone on an empty generation.
  98. func (ki *keyIndex) tombstone(main int64, sub int64) error {
  99. if ki.isEmpty() {
  100. plog.Panicf("store.keyindex: unexpected tombstone on empty keyIndex %s", string(ki.key))
  101. }
  102. if ki.generations[len(ki.generations)-1].isEmpty() {
  103. return ErrRevisionNotFound
  104. }
  105. ki.put(main, sub)
  106. ki.generations = append(ki.generations, generation{})
  107. keysGauge.Dec()
  108. return nil
  109. }
  110. // get gets the modified, created revision and version of the key that satisfies the given atRev.
  111. // Rev must be higher than or equal to the given atRev.
  112. func (ki *keyIndex) get(atRev int64) (modified, created revision, ver int64, err error) {
  113. if ki.isEmpty() {
  114. plog.Panicf("store.keyindex: unexpected get on empty keyIndex %s", string(ki.key))
  115. }
  116. g := ki.findGeneration(atRev)
  117. if g.isEmpty() {
  118. return revision{}, revision{}, 0, ErrRevisionNotFound
  119. }
  120. n := g.walk(func(rev revision) bool { return rev.main > atRev })
  121. if n != -1 {
  122. return g.revs[n], g.created, g.ver - int64(len(g.revs)-n-1), nil
  123. }
  124. return revision{}, revision{}, 0, ErrRevisionNotFound
  125. }
  126. // since returns revisions since the given rev. Only the revision with the
  127. // largest sub revision will be returned if multiple revisions have the same
  128. // main revision.
  129. func (ki *keyIndex) since(rev int64) []revision {
  130. if ki.isEmpty() {
  131. plog.Panicf("store.keyindex: unexpected get on empty keyIndex %s", string(ki.key))
  132. }
  133. since := revision{rev, 0}
  134. var gi int
  135. // find the generations to start checking
  136. for gi = len(ki.generations) - 1; gi > 0; gi-- {
  137. g := ki.generations[gi]
  138. if g.isEmpty() {
  139. continue
  140. }
  141. if since.GreaterThan(g.created) {
  142. break
  143. }
  144. }
  145. var revs []revision
  146. var last int64
  147. for ; gi < len(ki.generations); gi++ {
  148. for _, r := range ki.generations[gi].revs {
  149. if since.GreaterThan(r) {
  150. continue
  151. }
  152. if r.main == last {
  153. // replace the revision with a new one that has higher sub value,
  154. // because the original one should not be seen by external
  155. revs[len(revs)-1] = r
  156. continue
  157. }
  158. revs = append(revs, r)
  159. last = r.main
  160. }
  161. }
  162. return revs
  163. }
  164. // compact compacts a keyIndex by removing the versions with smaller or equal
  165. // revision than the given atRev except the largest one (If the largest one is
  166. // a tombstone, it will not be kept).
  167. // If a generation becomes empty during compaction, it will be removed.
  168. func (ki *keyIndex) compact(atRev int64, available map[revision]struct{}) {
  169. if ki.isEmpty() {
  170. plog.Panicf("store.keyindex: unexpected compact on empty keyIndex %s", string(ki.key))
  171. }
  172. // walk until reaching the first revision that has an revision smaller or equal to
  173. // the atRev.
  174. // add it to the available map
  175. f := func(rev revision) bool {
  176. if rev.main <= atRev {
  177. available[rev] = struct{}{}
  178. return false
  179. }
  180. return true
  181. }
  182. i, g := 0, &ki.generations[0]
  183. // find first generation includes atRev or created after atRev
  184. for i < len(ki.generations)-1 {
  185. if tomb := g.revs[len(g.revs)-1].main; tomb > atRev {
  186. break
  187. }
  188. i++
  189. g = &ki.generations[i]
  190. }
  191. if !g.isEmpty() {
  192. n := g.walk(f)
  193. // remove the previous contents.
  194. if n != -1 {
  195. g.revs = g.revs[n:]
  196. }
  197. // remove any tombstone
  198. if len(g.revs) == 1 && i != len(ki.generations)-1 {
  199. delete(available, g.revs[0])
  200. i++
  201. }
  202. }
  203. // remove the previous generations.
  204. ki.generations = ki.generations[i:]
  205. return
  206. }
  207. func (ki *keyIndex) isEmpty() bool {
  208. return len(ki.generations) == 1 && ki.generations[0].isEmpty()
  209. }
  210. // findGeneration finds out the generation of the keyIndex that the
  211. // given rev belongs to. If the given rev is at the gap of two generations,
  212. // which means that the key does not exist at the given rev, it returns nil.
  213. func (ki *keyIndex) findGeneration(rev int64) *generation {
  214. lastg := len(ki.generations) - 1
  215. cg := lastg
  216. for cg >= 0 {
  217. if len(ki.generations[cg].revs) == 0 {
  218. cg--
  219. continue
  220. }
  221. g := ki.generations[cg]
  222. if cg != lastg {
  223. if tomb := g.revs[len(g.revs)-1].main; tomb <= rev {
  224. return nil
  225. }
  226. }
  227. if g.revs[0].main <= rev {
  228. return &ki.generations[cg]
  229. }
  230. cg--
  231. }
  232. return nil
  233. }
  234. func (a *keyIndex) Less(b btree.Item) bool {
  235. return bytes.Compare(a.key, b.(*keyIndex).key) == -1
  236. }
  237. func (a *keyIndex) equal(b *keyIndex) bool {
  238. if !bytes.Equal(a.key, b.key) {
  239. return false
  240. }
  241. if a.modified != b.modified {
  242. return false
  243. }
  244. if len(a.generations) != len(b.generations) {
  245. return false
  246. }
  247. for i := range a.generations {
  248. ag, bg := a.generations[i], b.generations[i]
  249. if !ag.equal(bg) {
  250. return false
  251. }
  252. }
  253. return true
  254. }
  255. func (ki *keyIndex) String() string {
  256. var s string
  257. for _, g := range ki.generations {
  258. s += g.String()
  259. }
  260. return s
  261. }
  262. // generation contains multiple revisions of a key.
  263. type generation struct {
  264. ver int64
  265. created revision // when the generation is created (put in first revision).
  266. revs []revision
  267. }
  268. func (g *generation) isEmpty() bool { return g == nil || len(g.revs) == 0 }
  269. // walk walks through the revisions in the generation in descending order.
  270. // It passes the revision to the given function.
  271. // walk returns until: 1. it finishes walking all pairs 2. the function returns false.
  272. // walk returns the position at where it stopped. If it stopped after
  273. // finishing walking, -1 will be returned.
  274. func (g *generation) walk(f func(rev revision) bool) int {
  275. l := len(g.revs)
  276. for i := range g.revs {
  277. ok := f(g.revs[l-i-1])
  278. if !ok {
  279. return l - i - 1
  280. }
  281. }
  282. return -1
  283. }
  284. func (g *generation) String() string {
  285. return fmt.Sprintf("g: created[%d] ver[%d], revs %#v\n", g.created, g.ver, g.revs)
  286. }
  287. func (a generation) equal(b generation) bool {
  288. if a.ver != b.ver {
  289. return false
  290. }
  291. if len(a.revs) != len(b.revs) {
  292. return false
  293. }
  294. for i := range a.revs {
  295. ar, br := a.revs[i], b.revs[i]
  296. if ar != br {
  297. return false
  298. }
  299. }
  300. return true
  301. }