backend.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. // SizeInUse returns the current size of the backend logically in use.
  48. // Since the backend can manage free space in a non-byte unit such as
  49. // number of pages, the returned value can be not exactly accurate in bytes.
  50. SizeInUse() int64
  51. Defrag() error
  52. ForceCommit()
  53. Close() error
  54. }
  55. type Snapshot interface {
  56. // Size gets the size of the snapshot.
  57. Size() int64
  58. // WriteTo writes the snapshot into the given writer.
  59. WriteTo(w io.Writer) (n int64, err error)
  60. // Close closes the snapshot.
  61. Close() error
  62. }
  63. type backend struct {
  64. // size and commits are used with atomic operations so they must be
  65. // 64-bit aligned, otherwise 32-bit tests will crash
  66. // size is the number of bytes in the backend
  67. size int64
  68. // sizeInUse is the number of bytes actually used in the backend
  69. sizeInUse 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 = 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{
  123. buf: txReadBuffer{
  124. txBuffer: txBuffer{make(map[string]*bucketBuffer)},
  125. },
  126. buckets: make(map[string]*bolt.Bucket),
  127. },
  128. stopc: make(chan struct{}),
  129. donec: make(chan struct{}),
  130. }
  131. b.batchTx = newBatchTxBuffered(b)
  132. go b.run()
  133. return b
  134. }
  135. // BatchTx returns the current batch tx in coalescer. The tx can be used for read and
  136. // write operations. The write result can be retrieved within the same tx immediately.
  137. // The write result is isolated with other txs until the current one get committed.
  138. func (b *backend) BatchTx() BatchTx {
  139. return b.batchTx
  140. }
  141. func (b *backend) ReadTx() ReadTx { return b.readTx }
  142. // ForceCommit forces the current batching tx to commit.
  143. func (b *backend) ForceCommit() {
  144. b.batchTx.Commit()
  145. }
  146. func (b *backend) Snapshot() Snapshot {
  147. b.batchTx.Commit()
  148. b.mu.RLock()
  149. defer b.mu.RUnlock()
  150. tx, err := b.db.Begin(false)
  151. if err != nil {
  152. plog.Fatalf("cannot begin tx (%s)", err)
  153. }
  154. stopc, donec := make(chan struct{}), make(chan struct{})
  155. dbBytes := tx.Size()
  156. go func() {
  157. defer close(donec)
  158. // sendRateBytes is based on transferring snapshot data over a 1 gigabit/s connection
  159. // assuming a min tcp throughput of 100MB/s.
  160. var sendRateBytes int64 = 100 * 1024 * 1014
  161. warningTimeout := time.Duration(int64((float64(dbBytes) / float64(sendRateBytes)) * float64(time.Second)))
  162. if warningTimeout < minSnapshotWarningTimeout {
  163. warningTimeout = minSnapshotWarningTimeout
  164. }
  165. start := time.Now()
  166. ticker := time.NewTicker(warningTimeout)
  167. defer ticker.Stop()
  168. for {
  169. select {
  170. case <-ticker.C:
  171. 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)
  172. case <-stopc:
  173. snapshotDurations.Observe(time.Since(start).Seconds())
  174. return
  175. }
  176. }
  177. }()
  178. return &snapshot{tx, stopc, donec}
  179. }
  180. type IgnoreKey struct {
  181. Bucket string
  182. Key string
  183. }
  184. func (b *backend) Hash(ignores map[IgnoreKey]struct{}) (uint32, error) {
  185. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  186. b.mu.RLock()
  187. defer b.mu.RUnlock()
  188. err := b.db.View(func(tx *bolt.Tx) error {
  189. c := tx.Cursor()
  190. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  191. b := tx.Bucket(next)
  192. if b == nil {
  193. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  194. }
  195. h.Write(next)
  196. b.ForEach(func(k, v []byte) error {
  197. bk := IgnoreKey{Bucket: string(next), Key: string(k)}
  198. if _, ok := ignores[bk]; !ok {
  199. h.Write(k)
  200. h.Write(v)
  201. }
  202. return nil
  203. })
  204. }
  205. return nil
  206. })
  207. if err != nil {
  208. return 0, err
  209. }
  210. return h.Sum32(), nil
  211. }
  212. func (b *backend) Size() int64 {
  213. return atomic.LoadInt64(&b.size)
  214. }
  215. func (b *backend) SizeInUse() int64 {
  216. return atomic.LoadInt64(&b.sizeInUse)
  217. }
  218. func (b *backend) run() {
  219. defer close(b.donec)
  220. t := time.NewTimer(b.batchInterval)
  221. defer t.Stop()
  222. for {
  223. select {
  224. case <-t.C:
  225. case <-b.stopc:
  226. b.batchTx.CommitAndStop()
  227. return
  228. }
  229. b.batchTx.Commit()
  230. t.Reset(b.batchInterval)
  231. }
  232. }
  233. func (b *backend) Close() error {
  234. close(b.stopc)
  235. <-b.donec
  236. return b.db.Close()
  237. }
  238. // Commits returns total number of commits since start
  239. func (b *backend) Commits() int64 {
  240. return atomic.LoadInt64(&b.commits)
  241. }
  242. func (b *backend) Defrag() error {
  243. return b.defrag()
  244. }
  245. func (b *backend) defrag() error {
  246. // TODO: make this non-blocking?
  247. // lock batchTx to ensure nobody is using previous tx, and then
  248. // close previous ongoing tx.
  249. b.batchTx.Lock()
  250. defer b.batchTx.Unlock()
  251. // lock database after lock tx to avoid deadlock.
  252. b.mu.Lock()
  253. defer b.mu.Unlock()
  254. // block concurrent read requests while resetting tx
  255. b.readTx.mu.Lock()
  256. defer b.readTx.mu.Unlock()
  257. b.batchTx.unsafeCommit(true)
  258. b.batchTx.tx = nil
  259. tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
  260. if err != nil {
  261. return err
  262. }
  263. err = defragdb(b.db, tmpdb, defragLimit)
  264. if err != nil {
  265. tmpdb.Close()
  266. os.RemoveAll(tmpdb.Path())
  267. return err
  268. }
  269. dbp := b.db.Path()
  270. tdbp := tmpdb.Path()
  271. err = b.db.Close()
  272. if err != nil {
  273. plog.Fatalf("cannot close database (%s)", err)
  274. }
  275. err = tmpdb.Close()
  276. if err != nil {
  277. plog.Fatalf("cannot close database (%s)", err)
  278. }
  279. err = os.Rename(tdbp, dbp)
  280. if err != nil {
  281. plog.Fatalf("cannot rename database (%s)", err)
  282. }
  283. b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
  284. if err != nil {
  285. plog.Panicf("cannot open database at %s (%v)", dbp, err)
  286. }
  287. b.batchTx.tx, err = b.db.Begin(true)
  288. if err != nil {
  289. plog.Fatalf("cannot begin tx (%s)", err)
  290. }
  291. b.readTx.reset()
  292. b.readTx.tx = b.unsafeBegin(false)
  293. size := b.readTx.tx.Size()
  294. db := b.db
  295. atomic.StoreInt64(&b.size, size)
  296. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  297. took := time.Since(now)
  298. defragDurations.Observe(took.Seconds())
  299. return nil
  300. }
  301. func defragdb(odb, tmpdb *bolt.DB, limit int) error {
  302. // open a tx on tmpdb for writes
  303. tmptx, err := tmpdb.Begin(true)
  304. if err != nil {
  305. return err
  306. }
  307. // open a tx on old db for read
  308. tx, err := odb.Begin(false)
  309. if err != nil {
  310. return err
  311. }
  312. defer tx.Rollback()
  313. c := tx.Cursor()
  314. count := 0
  315. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  316. b := tx.Bucket(next)
  317. if b == nil {
  318. return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
  319. }
  320. tmpb, berr := tmptx.CreateBucketIfNotExists(next)
  321. if berr != nil {
  322. return berr
  323. }
  324. tmpb.FillPercent = 0.9 // for seq write in for each
  325. b.ForEach(func(k, v []byte) error {
  326. count++
  327. if count > limit {
  328. err = tmptx.Commit()
  329. if err != nil {
  330. return err
  331. }
  332. tmptx, err = tmpdb.Begin(true)
  333. if err != nil {
  334. return err
  335. }
  336. tmpb = tmptx.Bucket(next)
  337. tmpb.FillPercent = 0.9 // for seq write in for each
  338. count = 0
  339. }
  340. return tmpb.Put(k, v)
  341. })
  342. }
  343. return tmptx.Commit()
  344. }
  345. func (b *backend) begin(write bool) *bolt.Tx {
  346. b.mu.RLock()
  347. tx := b.unsafeBegin(write)
  348. b.mu.RUnlock()
  349. size := tx.Size()
  350. db := tx.DB()
  351. atomic.StoreInt64(&b.size, size)
  352. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  353. return tx
  354. }
  355. func (b *backend) unsafeBegin(write bool) *bolt.Tx {
  356. tx, err := b.db.Begin(write)
  357. if err != nil {
  358. plog.Fatalf("cannot begin tx (%s)", err)
  359. }
  360. return tx
  361. }
  362. // NewTmpBackend creates a backend implementation for testing.
  363. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  364. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  365. if err != nil {
  366. plog.Fatal(err)
  367. }
  368. tmpPath := filepath.Join(dir, "database")
  369. bcfg := DefaultBackendConfig()
  370. bcfg.Path, bcfg.BatchInterval, bcfg.BatchLimit = tmpPath, batchInterval, batchLimit
  371. return newBackend(bcfg), tmpPath
  372. }
  373. func NewDefaultTmpBackend() (*backend, string) {
  374. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  375. }
  376. type snapshot struct {
  377. *bolt.Tx
  378. stopc chan struct{}
  379. donec chan struct{}
  380. }
  381. func (s *snapshot) Close() error {
  382. close(s.stopc)
  383. <-s.donec
  384. return s.Tx.Rollback()
  385. }