backend.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 backend
  15. import (
  16. "fmt"
  17. "hash/crc32"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "os"
  22. "path"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/boltdb/bolt"
  27. )
  28. var (
  29. defaultBatchLimit = 10000
  30. defaultBatchInterval = 100 * time.Millisecond
  31. defragLimit = 10000
  32. // InitialMmapSize is the initial size of the mmapped region. Setting this larger than
  33. // the potential max db size can prevent writer from blocking reader.
  34. // This only works for linux.
  35. InitialMmapSize = int64(10 * 1024 * 1024 * 1024)
  36. )
  37. type Backend interface {
  38. BatchTx() BatchTx
  39. Snapshot() Snapshot
  40. Hash() (uint32, error)
  41. // Size returns the current size of the backend.
  42. Size() int64
  43. Defrag() error
  44. ForceCommit()
  45. Close() error
  46. }
  47. type Snapshot interface {
  48. // Size gets the size of the snapshot.
  49. Size() int64
  50. // WriteTo writes the snapshot into the given writer.
  51. WriteTo(w io.Writer) (n int64, err error)
  52. // Close closes the snapshot.
  53. Close() error
  54. }
  55. type backend struct {
  56. // size and commits are used with atomic operations so they must be
  57. // 64-bit aligned, otherwise 32-bit tests will crash
  58. // size is the number of bytes in the backend
  59. size int64
  60. // commits counts number of commits since start
  61. commits int64
  62. mu sync.RWMutex
  63. db *bolt.DB
  64. batchInterval time.Duration
  65. batchLimit int
  66. batchTx *batchTx
  67. stopc chan struct{}
  68. donec chan struct{}
  69. }
  70. func New(path string, d time.Duration, limit int) Backend {
  71. return newBackend(path, d, limit)
  72. }
  73. func NewDefaultBackend(path string) Backend {
  74. return newBackend(path, defaultBatchInterval, defaultBatchLimit)
  75. }
  76. func newBackend(path string, d time.Duration, limit int) *backend {
  77. db, err := bolt.Open(path, 0600, boltOpenOptions)
  78. if err != nil {
  79. log.Panicf("backend: cannot open database at %s (%v)", path, err)
  80. }
  81. b := &backend{
  82. db: db,
  83. batchInterval: d,
  84. batchLimit: limit,
  85. stopc: make(chan struct{}),
  86. donec: make(chan struct{}),
  87. }
  88. b.batchTx = newBatchTx(b)
  89. go b.run()
  90. return b
  91. }
  92. // BatchTx returns the current batch tx in coalescer. The tx can be used for read and
  93. // write operations. The write result can be retrieved within the same tx immediately.
  94. // The write result is isolated with other txs until the current one get committed.
  95. func (b *backend) BatchTx() BatchTx {
  96. return b.batchTx
  97. }
  98. // ForceCommit forces the current batching tx to commit.
  99. func (b *backend) ForceCommit() {
  100. b.batchTx.Commit()
  101. }
  102. func (b *backend) Snapshot() Snapshot {
  103. b.batchTx.Commit()
  104. b.mu.RLock()
  105. defer b.mu.RUnlock()
  106. tx, err := b.db.Begin(false)
  107. if err != nil {
  108. log.Fatalf("backend: cannot begin tx (%s)", err)
  109. }
  110. return &snapshot{tx}
  111. }
  112. func (b *backend) Hash() (uint32, error) {
  113. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  114. b.mu.RLock()
  115. defer b.mu.RUnlock()
  116. err := b.db.View(func(tx *bolt.Tx) error {
  117. c := tx.Cursor()
  118. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  119. b := tx.Bucket(next)
  120. if b == nil {
  121. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  122. }
  123. h.Write(next)
  124. b.ForEach(func(k, v []byte) error {
  125. h.Write(k)
  126. h.Write(v)
  127. return nil
  128. })
  129. }
  130. return nil
  131. })
  132. if err != nil {
  133. return 0, err
  134. }
  135. return h.Sum32(), nil
  136. }
  137. func (b *backend) Size() int64 {
  138. return atomic.LoadInt64(&b.size)
  139. }
  140. func (b *backend) run() {
  141. defer close(b.donec)
  142. for {
  143. select {
  144. case <-time.After(b.batchInterval):
  145. case <-b.stopc:
  146. b.batchTx.CommitAndStop()
  147. return
  148. }
  149. b.batchTx.Commit()
  150. }
  151. }
  152. func (b *backend) Close() error {
  153. close(b.stopc)
  154. <-b.donec
  155. return b.db.Close()
  156. }
  157. // Commits returns total number of commits since start
  158. func (b *backend) Commits() int64 {
  159. return atomic.LoadInt64(&b.commits)
  160. }
  161. func (b *backend) Defrag() error {
  162. // TODO: make this non-blocking?
  163. // lock batchTx to ensure nobody is using previous tx, and then
  164. // close previous ongoing tx.
  165. b.batchTx.Lock()
  166. defer b.batchTx.Unlock()
  167. // lock database after lock tx to avoid deadlock.
  168. b.mu.Lock()
  169. defer b.mu.Unlock()
  170. b.batchTx.commit(true)
  171. b.batchTx.tx = nil
  172. tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
  173. if err != nil {
  174. return err
  175. }
  176. err = defragdb(b.db, tmpdb, defragLimit)
  177. if err != nil {
  178. tmpdb.Close()
  179. os.RemoveAll(tmpdb.Path())
  180. return err
  181. }
  182. dbp := b.db.Path()
  183. tdbp := tmpdb.Path()
  184. err = b.db.Close()
  185. if err != nil {
  186. log.Fatalf("backend: cannot close database (%s)", err)
  187. }
  188. err = tmpdb.Close()
  189. if err != nil {
  190. log.Fatalf("backend: cannot close database (%s)", err)
  191. }
  192. err = os.Rename(tdbp, dbp)
  193. if err != nil {
  194. log.Fatalf("backend: cannot rename database (%s)", err)
  195. }
  196. b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
  197. if err != nil {
  198. log.Panicf("backend: cannot open database at %s (%v)", dbp, err)
  199. }
  200. b.batchTx.tx, err = b.db.Begin(true)
  201. if err != nil {
  202. log.Fatalf("backend: cannot begin tx (%s)", err)
  203. }
  204. return nil
  205. }
  206. func defragdb(odb, tmpdb *bolt.DB, limit int) error {
  207. // open a tx on tmpdb for writes
  208. tmptx, err := tmpdb.Begin(true)
  209. if err != nil {
  210. return err
  211. }
  212. // open a tx on old db for read
  213. tx, err := odb.Begin(false)
  214. if err != nil {
  215. return err
  216. }
  217. defer tx.Rollback()
  218. c := tx.Cursor()
  219. count := 0
  220. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  221. b := tx.Bucket(next)
  222. if b == nil {
  223. return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
  224. }
  225. tmpb, berr := tmptx.CreateBucketIfNotExists(next)
  226. if berr != nil {
  227. return berr
  228. }
  229. b.ForEach(func(k, v []byte) error {
  230. count++
  231. if count > limit {
  232. err = tmptx.Commit()
  233. if err != nil {
  234. return err
  235. }
  236. tmptx, err = tmpdb.Begin(true)
  237. if err != nil {
  238. return err
  239. }
  240. tmpb = tmptx.Bucket(next)
  241. }
  242. err = tmpb.Put(k, v)
  243. if err != nil {
  244. return err
  245. }
  246. return nil
  247. })
  248. }
  249. return tmptx.Commit()
  250. }
  251. // NewTmpBackend creates a backend implementation for testing.
  252. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  253. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  254. if err != nil {
  255. log.Fatal(err)
  256. }
  257. tmpPath := path.Join(dir, "database")
  258. return newBackend(tmpPath, batchInterval, batchLimit), tmpPath
  259. }
  260. func NewDefaultTmpBackend() (*backend, string) {
  261. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  262. }
  263. type snapshot struct {
  264. *bolt.Tx
  265. }
  266. func (s *snapshot) Close() error { return s.Tx.Rollback() }