backend.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. "io"
  17. "log"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/boltdb/bolt"
  20. )
  21. type Backend interface {
  22. BatchTx() BatchTx
  23. Snapshot(w io.Writer) (n int64, err error)
  24. ForceCommit()
  25. Close() error
  26. }
  27. type backend struct {
  28. db *bolt.DB
  29. batchInterval time.Duration
  30. batchLimit int
  31. batchTx *batchTx
  32. stopc chan struct{}
  33. donec chan struct{}
  34. }
  35. func New(path string, d time.Duration, limit int) Backend {
  36. return newBackend(path, d, limit)
  37. }
  38. func newBackend(path string, d time.Duration, limit int) *backend {
  39. db, err := bolt.Open(path, 0600, nil)
  40. if err != nil {
  41. log.Panicf("backend: cannot open database at %s (%v)", path, err)
  42. }
  43. b := &backend{
  44. db: db,
  45. batchInterval: d,
  46. batchLimit: limit,
  47. stopc: make(chan struct{}),
  48. donec: make(chan struct{}),
  49. }
  50. b.batchTx = newBatchTx(b)
  51. go b.run()
  52. return b
  53. }
  54. // BatchTx returns the current batch tx in coalescer. The tx can be used for read and
  55. // write operations. The write result can be retrieved within the same tx immediately.
  56. // The write result is isolated with other txs until the current one get committed.
  57. func (b *backend) BatchTx() BatchTx {
  58. return b.batchTx
  59. }
  60. // force commit the current batching tx.
  61. func (b *backend) ForceCommit() {
  62. b.batchTx.Commit()
  63. }
  64. func (b *backend) Snapshot(w io.Writer) (n int64, err error) {
  65. b.db.View(func(tx *bolt.Tx) error {
  66. n, err = tx.WriteTo(w)
  67. return nil
  68. })
  69. return n, err
  70. }
  71. func (b *backend) run() {
  72. defer close(b.donec)
  73. for {
  74. select {
  75. case <-time.After(b.batchInterval):
  76. case <-b.stopc:
  77. b.batchTx.CommitAndStop()
  78. return
  79. }
  80. b.batchTx.Commit()
  81. }
  82. }
  83. func (b *backend) Close() error {
  84. close(b.stopc)
  85. <-b.donec
  86. return b.db.Close()
  87. }