backend.go 8.8 KB

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