backend.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. humanize "github.com/dustin/go-humanize"
  28. "go.uber.org/zap"
  29. )
  30. var (
  31. defaultBatchLimit = 10000
  32. defaultBatchInterval = 100 * time.Millisecond
  33. defragLimit = 10000
  34. // initialMmapSize is the initial size of the mmapped region. Setting this larger than
  35. // the potential max db size can prevent writer from blocking reader.
  36. // This only works for linux.
  37. initialMmapSize = uint64(10 * 1024 * 1024 * 1024)
  38. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "mvcc/backend")
  39. // minSnapshotWarningTimeout is the minimum threshold to trigger a long running snapshot warning.
  40. minSnapshotWarningTimeout = 30 * time.Second
  41. )
  42. type Backend interface {
  43. ReadTx() ReadTx
  44. BatchTx() BatchTx
  45. Snapshot() Snapshot
  46. Hash(ignores map[IgnoreKey]struct{}) (uint32, error)
  47. // Size returns the current size of the backend physically allocated.
  48. // The backend can hold DB space that is not utilized at the moment,
  49. // since it can conduct pre-allocation or spare unused space for recycling.
  50. // Use SizeInUse() instead for the actual DB size.
  51. Size() int64
  52. // SizeInUse returns the current size of the backend logically in use.
  53. // Since the backend can manage free space in a non-byte unit such as
  54. // number of pages, the returned value can be not exactly accurate in bytes.
  55. SizeInUse() int64
  56. Defrag() error
  57. ForceCommit()
  58. Close() error
  59. }
  60. type Snapshot interface {
  61. // Size gets the size of the snapshot.
  62. Size() int64
  63. // WriteTo writes the snapshot into the given writer.
  64. WriteTo(w io.Writer) (n int64, err error)
  65. // Close closes the snapshot.
  66. Close() error
  67. }
  68. type backend struct {
  69. // size and commits are used with atomic operations so they must be
  70. // 64-bit aligned, otherwise 32-bit tests will crash
  71. // size is the number of bytes allocated in the backend
  72. size int64
  73. // sizeInUse is the number of bytes actually used in the backend
  74. sizeInUse int64
  75. // commits counts number of commits since start
  76. commits int64
  77. mu sync.RWMutex
  78. db *bolt.DB
  79. batchInterval time.Duration
  80. batchLimit int
  81. batchTx *batchTxBuffered
  82. readTx *readTx
  83. stopc chan struct{}
  84. donec chan struct{}
  85. lg *zap.Logger
  86. }
  87. type BackendConfig struct {
  88. // Path is the file path to the backend file.
  89. Path string
  90. // BatchInterval is the maximum time before flushing the BatchTx.
  91. BatchInterval time.Duration
  92. // BatchLimit is the maximum puts before flushing the BatchTx.
  93. BatchLimit int
  94. // MmapSize is the number of bytes to mmap for the backend.
  95. MmapSize uint64
  96. // Logger logs backend-side operations.
  97. Logger *zap.Logger
  98. }
  99. func DefaultBackendConfig() BackendConfig {
  100. return BackendConfig{
  101. BatchInterval: defaultBatchInterval,
  102. BatchLimit: defaultBatchLimit,
  103. MmapSize: initialMmapSize,
  104. }
  105. }
  106. func New(bcfg BackendConfig) Backend {
  107. return newBackend(bcfg)
  108. }
  109. func NewDefaultBackend(path string) Backend {
  110. bcfg := DefaultBackendConfig()
  111. bcfg.Path = path
  112. return newBackend(bcfg)
  113. }
  114. func newBackend(bcfg BackendConfig) *backend {
  115. bopts := &bolt.Options{}
  116. if boltOpenOptions != nil {
  117. *bopts = *boltOpenOptions
  118. }
  119. bopts.InitialMmapSize = bcfg.mmapSize()
  120. db, err := bolt.Open(bcfg.Path, 0600, bopts)
  121. if err != nil {
  122. if bcfg.Logger != nil {
  123. bcfg.Logger.Panic("failed to open database", zap.String("path", bcfg.Path), zap.Error(err))
  124. } else {
  125. plog.Panicf("cannot open database at %s (%v)", bcfg.Path, err)
  126. }
  127. }
  128. // In future, may want to make buffering optional for low-concurrency systems
  129. // or dynamically swap between buffered/non-buffered depending on workload.
  130. b := &backend{
  131. db: db,
  132. batchInterval: bcfg.BatchInterval,
  133. batchLimit: bcfg.BatchLimit,
  134. readTx: &readTx{
  135. buf: txReadBuffer{
  136. txBuffer: txBuffer{make(map[string]*bucketBuffer)},
  137. },
  138. buckets: make(map[string]*bolt.Bucket),
  139. },
  140. stopc: make(chan struct{}),
  141. donec: make(chan struct{}),
  142. lg: bcfg.Logger,
  143. }
  144. b.batchTx = newBatchTxBuffered(b)
  145. go b.run()
  146. return b
  147. }
  148. // BatchTx returns the current batch tx in coalescer. The tx can be used for read and
  149. // write operations. The write result can be retrieved within the same tx immediately.
  150. // The write result is isolated with other txs until the current one get committed.
  151. func (b *backend) BatchTx() BatchTx {
  152. return b.batchTx
  153. }
  154. func (b *backend) ReadTx() ReadTx { return b.readTx }
  155. // ForceCommit forces the current batching tx to commit.
  156. func (b *backend) ForceCommit() {
  157. b.batchTx.Commit()
  158. }
  159. func (b *backend) Snapshot() Snapshot {
  160. b.batchTx.Commit()
  161. b.mu.RLock()
  162. defer b.mu.RUnlock()
  163. tx, err := b.db.Begin(false)
  164. if err != nil {
  165. plog.Fatalf("cannot begin tx (%s)", err)
  166. }
  167. stopc, donec := make(chan struct{}), make(chan struct{})
  168. dbBytes := tx.Size()
  169. go func() {
  170. defer close(donec)
  171. // sendRateBytes is based on transferring snapshot data over a 1 gigabit/s connection
  172. // assuming a min tcp throughput of 100MB/s.
  173. var sendRateBytes int64 = 100 * 1024 * 1014
  174. warningTimeout := time.Duration(int64((float64(dbBytes) / float64(sendRateBytes)) * float64(time.Second)))
  175. if warningTimeout < minSnapshotWarningTimeout {
  176. warningTimeout = minSnapshotWarningTimeout
  177. }
  178. start := time.Now()
  179. ticker := time.NewTicker(warningTimeout)
  180. defer ticker.Stop()
  181. for {
  182. select {
  183. case <-ticker.C:
  184. if b.lg != nil {
  185. b.lg.Warn(
  186. "snapshotting taking too long to transfer",
  187. zap.Duration("taking", time.Since(start)),
  188. zap.Int64("bytes", dbBytes),
  189. zap.String("size", humanize.Bytes(uint64(dbBytes))),
  190. )
  191. } else {
  192. 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)
  193. }
  194. case <-stopc:
  195. snapshotDurations.Observe(time.Since(start).Seconds())
  196. return
  197. }
  198. }
  199. }()
  200. return &snapshot{tx, stopc, donec}
  201. }
  202. type IgnoreKey struct {
  203. Bucket string
  204. Key string
  205. }
  206. func (b *backend) Hash(ignores map[IgnoreKey]struct{}) (uint32, error) {
  207. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  208. b.mu.RLock()
  209. defer b.mu.RUnlock()
  210. err := b.db.View(func(tx *bolt.Tx) error {
  211. c := tx.Cursor()
  212. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  213. b := tx.Bucket(next)
  214. if b == nil {
  215. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  216. }
  217. h.Write(next)
  218. b.ForEach(func(k, v []byte) error {
  219. bk := IgnoreKey{Bucket: string(next), Key: string(k)}
  220. if _, ok := ignores[bk]; !ok {
  221. h.Write(k)
  222. h.Write(v)
  223. }
  224. return nil
  225. })
  226. }
  227. return nil
  228. })
  229. if err != nil {
  230. return 0, err
  231. }
  232. return h.Sum32(), nil
  233. }
  234. func (b *backend) Size() int64 {
  235. return atomic.LoadInt64(&b.size)
  236. }
  237. func (b *backend) SizeInUse() int64 {
  238. return atomic.LoadInt64(&b.sizeInUse)
  239. }
  240. func (b *backend) run() {
  241. defer close(b.donec)
  242. t := time.NewTimer(b.batchInterval)
  243. defer t.Stop()
  244. for {
  245. select {
  246. case <-t.C:
  247. case <-b.stopc:
  248. b.batchTx.CommitAndStop()
  249. return
  250. }
  251. if b.batchTx.safePending() != 0 {
  252. b.batchTx.Commit()
  253. }
  254. t.Reset(b.batchInterval)
  255. }
  256. }
  257. func (b *backend) Close() error {
  258. close(b.stopc)
  259. <-b.donec
  260. return b.db.Close()
  261. }
  262. // Commits returns total number of commits since start
  263. func (b *backend) Commits() int64 {
  264. return atomic.LoadInt64(&b.commits)
  265. }
  266. func (b *backend) Defrag() error {
  267. return b.defrag()
  268. }
  269. func (b *backend) defrag() error {
  270. now := time.Now()
  271. // TODO: make this non-blocking?
  272. // lock batchTx to ensure nobody is using previous tx, and then
  273. // close previous ongoing tx.
  274. b.batchTx.Lock()
  275. defer b.batchTx.Unlock()
  276. // lock database after lock tx to avoid deadlock.
  277. b.mu.Lock()
  278. defer b.mu.Unlock()
  279. // block concurrent read requests while resetting tx
  280. b.readTx.mu.Lock()
  281. defer b.readTx.mu.Unlock()
  282. b.batchTx.unsafeCommit(true)
  283. b.batchTx.tx = nil
  284. tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
  285. if err != nil {
  286. return err
  287. }
  288. dbp := b.db.Path()
  289. tdbp := tmpdb.Path()
  290. size1, sizeInUse1 := b.Size(), b.SizeInUse()
  291. if b.lg != nil {
  292. b.lg.Info(
  293. "defragmenting",
  294. zap.String("path", dbp),
  295. zap.Int64("current-db-size-bytes", size1),
  296. zap.String("current-db-size", humanize.Bytes(uint64(size1))),
  297. zap.Int64("current-db-size-in-use-bytes", sizeInUse1),
  298. zap.String("current-db-size-in-use", humanize.Bytes(uint64(sizeInUse1))),
  299. )
  300. }
  301. err = defragdb(b.db, tmpdb, defragLimit)
  302. if err != nil {
  303. tmpdb.Close()
  304. os.RemoveAll(tmpdb.Path())
  305. return err
  306. }
  307. err = b.db.Close()
  308. if err != nil {
  309. if b.lg != nil {
  310. b.lg.Fatal("failed to close database", zap.Error(err))
  311. } else {
  312. plog.Fatalf("cannot close database (%s)", err)
  313. }
  314. }
  315. err = tmpdb.Close()
  316. if err != nil {
  317. if b.lg != nil {
  318. b.lg.Fatal("failed to close tmp database", zap.Error(err))
  319. } else {
  320. plog.Fatalf("cannot close database (%s)", err)
  321. }
  322. }
  323. err = os.Rename(tdbp, dbp)
  324. if err != nil {
  325. if b.lg != nil {
  326. b.lg.Fatal("failed to rename tmp database", zap.Error(err))
  327. } else {
  328. plog.Fatalf("cannot rename database (%s)", err)
  329. }
  330. }
  331. b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
  332. if err != nil {
  333. if b.lg != nil {
  334. b.lg.Fatal("failed to open database", zap.String("path", dbp), zap.Error(err))
  335. } else {
  336. plog.Panicf("cannot open database at %s (%v)", dbp, err)
  337. }
  338. }
  339. b.batchTx.tx, err = b.db.Begin(true)
  340. if err != nil {
  341. if b.lg != nil {
  342. b.lg.Fatal("failed to begin tx", zap.Error(err))
  343. } else {
  344. plog.Fatalf("cannot begin tx (%s)", err)
  345. }
  346. }
  347. b.readTx.reset()
  348. b.readTx.tx = b.unsafeBegin(false)
  349. size := b.readTx.tx.Size()
  350. db := b.readTx.tx.DB()
  351. atomic.StoreInt64(&b.size, size)
  352. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  353. size2, sizeInUse2 := b.Size(), b.SizeInUse()
  354. if b.lg != nil {
  355. b.lg.Info(
  356. "defragmented",
  357. zap.String("path", dbp),
  358. zap.Int64("current-db-size-bytes-diff", size2-size1),
  359. zap.Int64("current-db-size-bytes", size2),
  360. zap.String("current-db-size", humanize.Bytes(uint64(size2))),
  361. zap.Int64("current-db-size-in-use-bytes-diff", sizeInUse2-sizeInUse1),
  362. zap.Int64("current-db-size-in-use-bytes", sizeInUse2),
  363. zap.String("current-db-size-in-use", humanize.Bytes(uint64(sizeInUse2))),
  364. zap.Duration("took", time.Since(now)),
  365. )
  366. }
  367. return nil
  368. }
  369. func defragdb(odb, tmpdb *bolt.DB, limit int) error {
  370. // open a tx on tmpdb for writes
  371. tmptx, err := tmpdb.Begin(true)
  372. if err != nil {
  373. return err
  374. }
  375. // open a tx on old db for read
  376. tx, err := odb.Begin(false)
  377. if err != nil {
  378. return err
  379. }
  380. defer tx.Rollback()
  381. c := tx.Cursor()
  382. count := 0
  383. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  384. b := tx.Bucket(next)
  385. if b == nil {
  386. return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
  387. }
  388. tmpb, berr := tmptx.CreateBucketIfNotExists(next)
  389. if berr != nil {
  390. return berr
  391. }
  392. tmpb.FillPercent = 0.9 // for seq write in for each
  393. b.ForEach(func(k, v []byte) error {
  394. count++
  395. if count > limit {
  396. err = tmptx.Commit()
  397. if err != nil {
  398. return err
  399. }
  400. tmptx, err = tmpdb.Begin(true)
  401. if err != nil {
  402. return err
  403. }
  404. tmpb = tmptx.Bucket(next)
  405. tmpb.FillPercent = 0.9 // for seq write in for each
  406. count = 0
  407. }
  408. return tmpb.Put(k, v)
  409. })
  410. }
  411. return tmptx.Commit()
  412. }
  413. func (b *backend) begin(write bool) *bolt.Tx {
  414. b.mu.RLock()
  415. tx := b.unsafeBegin(write)
  416. b.mu.RUnlock()
  417. size := tx.Size()
  418. db := tx.DB()
  419. atomic.StoreInt64(&b.size, size)
  420. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  421. return tx
  422. }
  423. func (b *backend) unsafeBegin(write bool) *bolt.Tx {
  424. tx, err := b.db.Begin(write)
  425. if err != nil {
  426. if b.lg != nil {
  427. b.lg.Fatal("failed to begin tx", zap.Error(err))
  428. } else {
  429. plog.Fatalf("cannot begin tx (%s)", err)
  430. }
  431. }
  432. return tx
  433. }
  434. // NewTmpBackend creates a backend implementation for testing.
  435. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  436. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  437. if err != nil {
  438. panic(err)
  439. }
  440. tmpPath := filepath.Join(dir, "database")
  441. bcfg := DefaultBackendConfig()
  442. bcfg.Path, bcfg.BatchInterval, bcfg.BatchLimit = tmpPath, batchInterval, batchLimit
  443. return newBackend(bcfg), tmpPath
  444. }
  445. func NewDefaultTmpBackend() (*backend, string) {
  446. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  447. }
  448. type snapshot struct {
  449. *bolt.Tx
  450. stopc chan struct{}
  451. donec chan struct{}
  452. }
  453. func (s *snapshot) Close() error {
  454. close(s.stopc)
  455. <-s.donec
  456. return s.Tx.Rollback()
  457. }