backend.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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/atomic"
  24. "time"
  25. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/boltdb/bolt"
  26. )
  27. var (
  28. defaultBatchLimit = 10000
  29. defaultBatchInterval = 100 * time.Millisecond
  30. )
  31. type Backend interface {
  32. BatchTx() BatchTx
  33. Snapshot() Snapshot
  34. Hash() (uint32, error)
  35. // Size returns the current size of the backend.
  36. Size() int64
  37. ForceCommit()
  38. Close() error
  39. }
  40. type Snapshot interface {
  41. // Size gets the size of the snapshot.
  42. Size() int64
  43. // WriteTo writes the snapshot into the given writer.
  44. WriteTo(w io.Writer) (n int64, err error)
  45. // Close closes the snapshot.
  46. Close() error
  47. }
  48. type backend struct {
  49. db *bolt.DB
  50. batchInterval time.Duration
  51. batchLimit int
  52. batchTx *batchTx
  53. size int64
  54. // number of commits since start
  55. commits int64
  56. stopc chan struct{}
  57. donec chan struct{}
  58. }
  59. func New(path string, d time.Duration, limit int) Backend {
  60. return newBackend(path, d, limit)
  61. }
  62. func NewDefaultBackend(path string) Backend {
  63. return newBackend(path, defaultBatchInterval, defaultBatchLimit)
  64. }
  65. func newBackend(path string, d time.Duration, limit int) *backend {
  66. db, err := bolt.Open(path, 0600, boltOpenOptions)
  67. if err != nil {
  68. log.Panicf("backend: cannot open database at %s (%v)", path, err)
  69. }
  70. b := &backend{
  71. db: db,
  72. batchInterval: d,
  73. batchLimit: limit,
  74. stopc: make(chan struct{}),
  75. donec: make(chan struct{}),
  76. }
  77. b.batchTx = newBatchTx(b)
  78. go b.run()
  79. return b
  80. }
  81. // BatchTx returns the current batch tx in coalescer. The tx can be used for read and
  82. // write operations. The write result can be retrieved within the same tx immediately.
  83. // The write result is isolated with other txs until the current one get committed.
  84. func (b *backend) BatchTx() BatchTx {
  85. return b.batchTx
  86. }
  87. // force commit the current batching tx.
  88. func (b *backend) ForceCommit() {
  89. b.batchTx.Commit()
  90. }
  91. func (b *backend) Snapshot() Snapshot {
  92. b.batchTx.Commit()
  93. tx, err := b.db.Begin(false)
  94. if err != nil {
  95. log.Fatalf("storage: cannot begin tx (%s)", err)
  96. }
  97. return &snapshot{tx}
  98. }
  99. func (b *backend) Hash() (uint32, error) {
  100. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  101. err := b.db.View(func(tx *bolt.Tx) error {
  102. c := tx.Cursor()
  103. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  104. b := tx.Bucket(next)
  105. if b == nil {
  106. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  107. }
  108. h.Write(next)
  109. b.ForEach(func(k, v []byte) error {
  110. h.Write(k)
  111. h.Write(v)
  112. return nil
  113. })
  114. }
  115. return nil
  116. })
  117. if err != nil {
  118. return 0, err
  119. }
  120. return h.Sum32(), nil
  121. }
  122. func (b *backend) Size() int64 {
  123. return atomic.LoadInt64(&b.size)
  124. }
  125. func (b *backend) run() {
  126. defer close(b.donec)
  127. for {
  128. select {
  129. case <-time.After(b.batchInterval):
  130. case <-b.stopc:
  131. b.batchTx.CommitAndStop()
  132. return
  133. }
  134. b.batchTx.Commit()
  135. }
  136. }
  137. func (b *backend) Close() error {
  138. close(b.stopc)
  139. <-b.donec
  140. return b.db.Close()
  141. }
  142. // Commits returns total number of commits since start
  143. func (b *backend) Commits() int64 {
  144. return atomic.LoadInt64(&b.commits)
  145. }
  146. // NewTmpBackend creates a backend implementation for testing.
  147. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  148. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  149. if err != nil {
  150. log.Fatal(err)
  151. }
  152. tmpPath := path.Join(dir, "database")
  153. return newBackend(tmpPath, batchInterval, batchLimit), tmpPath
  154. }
  155. func NewDefaultTmpBackend() (*backend, string) {
  156. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  157. }
  158. type snapshot struct {
  159. *bolt.Tx
  160. }
  161. func (s *snapshot) Close() error { return s.Tx.Rollback() }