backend.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. now := time.Now()
  247. // TODO: make this non-blocking?
  248. // lock batchTx to ensure nobody is using previous tx, and then
  249. // close previous ongoing tx.
  250. b.batchTx.Lock()
  251. defer b.batchTx.Unlock()
  252. // lock database after lock tx to avoid deadlock.
  253. b.mu.Lock()
  254. defer b.mu.Unlock()
  255. // block concurrent read requests while resetting tx
  256. b.readTx.mu.Lock()
  257. defer b.readTx.mu.Unlock()
  258. b.batchTx.unsafeCommit(true)
  259. b.batchTx.tx = nil
  260. tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
  261. if err != nil {
  262. return err
  263. }
  264. err = defragdb(b.db, tmpdb, defragLimit)
  265. if err != nil {
  266. tmpdb.Close()
  267. os.RemoveAll(tmpdb.Path())
  268. return err
  269. }
  270. dbp := b.db.Path()
  271. tdbp := tmpdb.Path()
  272. err = b.db.Close()
  273. if err != nil {
  274. plog.Fatalf("cannot close database (%s)", err)
  275. }
  276. err = tmpdb.Close()
  277. if err != nil {
  278. plog.Fatalf("cannot close database (%s)", err)
  279. }
  280. err = os.Rename(tdbp, dbp)
  281. if err != nil {
  282. plog.Fatalf("cannot rename database (%s)", err)
  283. }
  284. b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
  285. if err != nil {
  286. plog.Panicf("cannot open database at %s (%v)", dbp, err)
  287. }
  288. b.batchTx.tx, err = b.db.Begin(true)
  289. if err != nil {
  290. plog.Fatalf("cannot begin tx (%s)", err)
  291. }
  292. b.readTx.reset()
  293. b.readTx.tx = b.unsafeBegin(false)
  294. size := b.readTx.tx.Size()
  295. db := b.db
  296. atomic.StoreInt64(&b.size, size)
  297. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  298. took := time.Since(now)
  299. defragDurations.Observe(took.Seconds())
  300. return nil
  301. }
  302. func defragdb(odb, tmpdb *bolt.DB, limit int) error {
  303. // open a tx on tmpdb for writes
  304. tmptx, err := tmpdb.Begin(true)
  305. if err != nil {
  306. return err
  307. }
  308. // open a tx on old db for read
  309. tx, err := odb.Begin(false)
  310. if err != nil {
  311. return err
  312. }
  313. defer tx.Rollback()
  314. c := tx.Cursor()
  315. count := 0
  316. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  317. b := tx.Bucket(next)
  318. if b == nil {
  319. return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
  320. }
  321. tmpb, berr := tmptx.CreateBucketIfNotExists(next)
  322. if berr != nil {
  323. return berr
  324. }
  325. tmpb.FillPercent = 0.9 // for seq write in for each
  326. b.ForEach(func(k, v []byte) error {
  327. count++
  328. if count > limit {
  329. err = tmptx.Commit()
  330. if err != nil {
  331. return err
  332. }
  333. tmptx, err = tmpdb.Begin(true)
  334. if err != nil {
  335. return err
  336. }
  337. tmpb = tmptx.Bucket(next)
  338. tmpb.FillPercent = 0.9 // for seq write in for each
  339. count = 0
  340. }
  341. return tmpb.Put(k, v)
  342. })
  343. }
  344. return tmptx.Commit()
  345. }
  346. func (b *backend) begin(write bool) *bolt.Tx {
  347. b.mu.RLock()
  348. tx := b.unsafeBegin(write)
  349. b.mu.RUnlock()
  350. size := tx.Size()
  351. db := tx.DB()
  352. atomic.StoreInt64(&b.size, size)
  353. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  354. return tx
  355. }
  356. func (b *backend) unsafeBegin(write bool) *bolt.Tx {
  357. tx, err := b.db.Begin(write)
  358. if err != nil {
  359. plog.Fatalf("cannot begin tx (%s)", err)
  360. }
  361. return tx
  362. }
  363. // NewTmpBackend creates a backend implementation for testing.
  364. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  365. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  366. if err != nil {
  367. plog.Fatal(err)
  368. }
  369. tmpPath := filepath.Join(dir, "database")
  370. bcfg := DefaultBackendConfig()
  371. bcfg.Path, bcfg.BatchInterval, bcfg.BatchLimit = tmpPath, batchInterval, batchLimit
  372. return newBackend(bcfg), tmpPath
  373. }
  374. func NewDefaultTmpBackend() (*backend, string) {
  375. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  376. }
  377. type snapshot struct {
  378. *bolt.Tx
  379. stopc chan struct{}
  380. donec chan struct{}
  381. }
  382. func (s *snapshot) Close() error {
  383. close(s.stopc)
  384. <-s.donec
  385. return s.Tx.Rollback()
  386. }