backend_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 backend
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "reflect"
  20. "testing"
  21. "time"
  22. "github.com/boltdb/bolt"
  23. )
  24. func TestBackendClose(t *testing.T) {
  25. b, tmpPath := NewTmpBackend(time.Hour, 10000)
  26. defer os.Remove(tmpPath)
  27. // check close could work
  28. done := make(chan struct{})
  29. go func() {
  30. err := b.Close()
  31. if err != nil {
  32. t.Errorf("close error = %v, want nil", err)
  33. }
  34. done <- struct{}{}
  35. }()
  36. select {
  37. case <-done:
  38. case <-time.After(10 * time.Second):
  39. t.Errorf("failed to close database in 10s")
  40. }
  41. }
  42. func TestBackendSnapshot(t *testing.T) {
  43. b, tmpPath := NewTmpBackend(time.Hour, 10000)
  44. defer cleanup(b, tmpPath)
  45. tx := b.BatchTx()
  46. tx.Lock()
  47. tx.UnsafeCreateBucket([]byte("test"))
  48. tx.UnsafePut([]byte("test"), []byte("foo"), []byte("bar"))
  49. tx.Unlock()
  50. b.ForceCommit()
  51. // write snapshot to a new file
  52. f, err := ioutil.TempFile(os.TempDir(), "etcd_backend_test")
  53. if err != nil {
  54. t.Fatal(err)
  55. }
  56. snap := b.Snapshot()
  57. defer snap.Close()
  58. if _, err := snap.WriteTo(f); err != nil {
  59. t.Fatal(err)
  60. }
  61. f.Close()
  62. // bootstrap new backend from the snapshot
  63. nb := New(f.Name(), time.Hour, 10000)
  64. defer cleanup(nb, f.Name())
  65. newTx := b.BatchTx()
  66. newTx.Lock()
  67. ks, _ := newTx.UnsafeRange([]byte("test"), []byte("foo"), []byte("goo"), 0)
  68. if len(ks) != 1 {
  69. t.Errorf("len(kvs) = %d, want 1", len(ks))
  70. }
  71. newTx.Unlock()
  72. }
  73. func TestBackendBatchIntervalCommit(t *testing.T) {
  74. // start backend with super short batch interval so
  75. // we do not need to wait long before commit to happen.
  76. b, tmpPath := NewTmpBackend(time.Nanosecond, 10000)
  77. defer cleanup(b, tmpPath)
  78. pc := b.Commits()
  79. tx := b.BatchTx()
  80. tx.Lock()
  81. tx.UnsafeCreateBucket([]byte("test"))
  82. tx.UnsafePut([]byte("test"), []byte("foo"), []byte("bar"))
  83. tx.Unlock()
  84. for i := 0; i < 10; i++ {
  85. if b.Commits() >= pc+1 {
  86. break
  87. }
  88. time.Sleep(time.Duration(i*100) * time.Millisecond)
  89. }
  90. // check whether put happens via db view
  91. b.db.View(func(tx *bolt.Tx) error {
  92. bucket := tx.Bucket([]byte("test"))
  93. if bucket == nil {
  94. t.Errorf("bucket test does not exit")
  95. return nil
  96. }
  97. v := bucket.Get([]byte("foo"))
  98. if v == nil {
  99. t.Errorf("foo key failed to written in backend")
  100. }
  101. return nil
  102. })
  103. }
  104. func TestBackendDefrag(t *testing.T) {
  105. b, tmpPath := NewDefaultTmpBackend()
  106. defer cleanup(b, tmpPath)
  107. tx := b.BatchTx()
  108. tx.Lock()
  109. tx.UnsafeCreateBucket([]byte("test"))
  110. for i := 0; i < defragLimit+100; i++ {
  111. tx.UnsafePut([]byte("test"), []byte(fmt.Sprintf("foo_%d", i)), []byte("bar"))
  112. }
  113. tx.Unlock()
  114. b.ForceCommit()
  115. // remove some keys to ensure the disk space will be reclaimed after defrag
  116. tx = b.BatchTx()
  117. tx.Lock()
  118. for i := 0; i < 50; i++ {
  119. tx.UnsafeDelete([]byte("test"), []byte(fmt.Sprintf("foo_%d", i)))
  120. }
  121. tx.Unlock()
  122. b.ForceCommit()
  123. size := b.Size()
  124. // shrink and check hash
  125. oh, err := b.Hash(nil)
  126. if err != nil {
  127. t.Fatal(err)
  128. }
  129. err = b.Defrag()
  130. if err != nil {
  131. t.Fatal(err)
  132. }
  133. nh, err := b.Hash(nil)
  134. if err != nil {
  135. t.Fatal(err)
  136. }
  137. if oh != nh {
  138. t.Errorf("hash = %v, want %v", nh, oh)
  139. }
  140. nsize := b.Size()
  141. if nsize >= size {
  142. t.Errorf("new size = %v, want < %d", nsize, size)
  143. }
  144. // try put more keys after shrink.
  145. tx = b.BatchTx()
  146. tx.Lock()
  147. tx.UnsafeCreateBucket([]byte("test"))
  148. tx.UnsafePut([]byte("test"), []byte("more"), []byte("bar"))
  149. tx.Unlock()
  150. b.ForceCommit()
  151. }
  152. // TestBackendWriteback ensures writes are stored to the read txn on write txn unlock.
  153. func TestBackendWriteback(t *testing.T) {
  154. b, tmpPath := NewDefaultTmpBackend()
  155. defer cleanup(b, tmpPath)
  156. tx := b.BatchTx()
  157. tx.Lock()
  158. tx.UnsafeCreateBucket([]byte("key"))
  159. tx.UnsafePut([]byte("key"), []byte("abc"), []byte("bar"))
  160. tx.UnsafePut([]byte("key"), []byte("def"), []byte("baz"))
  161. tx.UnsafePut([]byte("key"), []byte("overwrite"), []byte("1"))
  162. tx.Unlock()
  163. // overwrites should be propagated too
  164. tx.Lock()
  165. tx.UnsafePut([]byte("key"), []byte("overwrite"), []byte("2"))
  166. tx.Unlock()
  167. keys := []struct {
  168. key []byte
  169. end []byte
  170. limit int64
  171. wkey [][]byte
  172. wval [][]byte
  173. }{
  174. {
  175. key: []byte("abc"),
  176. end: nil,
  177. wkey: [][]byte{[]byte("abc")},
  178. wval: [][]byte{[]byte("bar")},
  179. },
  180. {
  181. key: []byte("abc"),
  182. end: []byte("def"),
  183. wkey: [][]byte{[]byte("abc")},
  184. wval: [][]byte{[]byte("bar")},
  185. },
  186. {
  187. key: []byte("abc"),
  188. end: []byte("deg"),
  189. wkey: [][]byte{[]byte("abc"), []byte("def")},
  190. wval: [][]byte{[]byte("bar"), []byte("baz")},
  191. },
  192. {
  193. key: []byte("abc"),
  194. end: []byte("\xff"),
  195. limit: 1,
  196. wkey: [][]byte{[]byte("abc")},
  197. wval: [][]byte{[]byte("bar")},
  198. },
  199. {
  200. key: []byte("abc"),
  201. end: []byte("\xff"),
  202. wkey: [][]byte{[]byte("abc"), []byte("def"), []byte("overwrite")},
  203. wval: [][]byte{[]byte("bar"), []byte("baz"), []byte("2")},
  204. },
  205. }
  206. rtx := b.ReadTx()
  207. for i, tt := range keys {
  208. rtx.Lock()
  209. k, v := rtx.UnsafeRange([]byte("key"), tt.key, tt.end, tt.limit)
  210. rtx.Unlock()
  211. if !reflect.DeepEqual(tt.wkey, k) || !reflect.DeepEqual(tt.wval, v) {
  212. t.Errorf("#%d: want k=%+v, v=%+v; got k=%+v, v=%+v", i, tt.wkey, tt.wval, k, v)
  213. }
  214. }
  215. }
  216. func cleanup(b Backend, path string) {
  217. b.Close()
  218. os.Remove(path)
  219. }