backend.go 8.5 KB

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