backend.go 10 KB

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