backend.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 writter.
  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. stopc chan struct{}
  55. donec chan struct{}
  56. }
  57. func New(path string, d time.Duration, limit int) Backend {
  58. return newBackend(path, d, limit)
  59. }
  60. func NewDefaultBackend(path string) Backend {
  61. return newBackend(path, defaultBatchInterval, defaultBatchLimit)
  62. }
  63. func newBackend(path string, d time.Duration, limit int) *backend {
  64. db, err := bolt.Open(path, 0600, boltOpenOptions)
  65. if err != nil {
  66. log.Panicf("backend: cannot open database at %s (%v)", path, err)
  67. }
  68. b := &backend{
  69. db: db,
  70. batchInterval: d,
  71. batchLimit: limit,
  72. stopc: make(chan struct{}),
  73. donec: make(chan struct{}),
  74. }
  75. b.batchTx = newBatchTx(b)
  76. go b.run()
  77. return b
  78. }
  79. // BatchTx returns the current batch tx in coalescer. The tx can be used for read and
  80. // write operations. The write result can be retrieved within the same tx immediately.
  81. // The write result is isolated with other txs until the current one get committed.
  82. func (b *backend) BatchTx() BatchTx {
  83. return b.batchTx
  84. }
  85. // force commit the current batching tx.
  86. func (b *backend) ForceCommit() {
  87. b.batchTx.Commit()
  88. }
  89. func (b *backend) Snapshot() Snapshot {
  90. b.batchTx.Commit()
  91. tx, err := b.db.Begin(false)
  92. if err != nil {
  93. log.Fatalf("storage: cannot begin tx (%s)", err)
  94. }
  95. return &snapshot{tx}
  96. }
  97. func (b *backend) Hash() (uint32, error) {
  98. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  99. err := b.db.View(func(tx *bolt.Tx) error {
  100. c := tx.Cursor()
  101. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  102. b := tx.Bucket(next)
  103. if b == nil {
  104. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  105. }
  106. h.Write(next)
  107. b.ForEach(func(k, v []byte) error {
  108. h.Write(k)
  109. h.Write(v)
  110. return nil
  111. })
  112. }
  113. return nil
  114. })
  115. if err != nil {
  116. return 0, err
  117. }
  118. return h.Sum32(), nil
  119. }
  120. func (b *backend) Size() int64 {
  121. return atomic.LoadInt64(&b.size)
  122. }
  123. func (b *backend) run() {
  124. defer close(b.donec)
  125. for {
  126. select {
  127. case <-time.After(b.batchInterval):
  128. case <-b.stopc:
  129. b.batchTx.CommitAndStop()
  130. return
  131. }
  132. b.batchTx.Commit()
  133. }
  134. }
  135. func (b *backend) Close() error {
  136. close(b.stopc)
  137. <-b.donec
  138. return b.db.Close()
  139. }
  140. // NewTmpBackend creates a backend implementation for testing.
  141. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  142. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  143. if err != nil {
  144. log.Fatal(err)
  145. }
  146. tmpPath := path.Join(dir, "database")
  147. return newBackend(tmpPath, batchInterval, batchLimit), tmpPath
  148. }
  149. func NewDefaultTmpBackend() (*backend, string) {
  150. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  151. }
  152. type snapshot struct {
  153. *bolt.Tx
  154. }
  155. func (s *snapshot) Close() error { return s.Tx.Rollback() }