backend.go 7.5 KB

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