backend.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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("go.etcd.io/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. if b.lg != nil {
  166. b.lg.Fatal("failed to begin tx", zap.Error(err))
  167. } else {
  168. plog.Fatalf("cannot begin tx (%s)", err)
  169. }
  170. }
  171. stopc, donec := make(chan struct{}), make(chan struct{})
  172. dbBytes := tx.Size()
  173. go func() {
  174. defer close(donec)
  175. // sendRateBytes is based on transferring snapshot data over a 1 gigabit/s connection
  176. // assuming a min tcp throughput of 100MB/s.
  177. var sendRateBytes int64 = 100 * 1024 * 1014
  178. warningTimeout := time.Duration(int64((float64(dbBytes) / float64(sendRateBytes)) * float64(time.Second)))
  179. if warningTimeout < minSnapshotWarningTimeout {
  180. warningTimeout = minSnapshotWarningTimeout
  181. }
  182. start := time.Now()
  183. ticker := time.NewTicker(warningTimeout)
  184. defer ticker.Stop()
  185. for {
  186. select {
  187. case <-ticker.C:
  188. if b.lg != nil {
  189. b.lg.Warn(
  190. "snapshotting taking too long to transfer",
  191. zap.Duration("taking", time.Since(start)),
  192. zap.Int64("bytes", dbBytes),
  193. zap.String("size", humanize.Bytes(uint64(dbBytes))),
  194. )
  195. } else {
  196. 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)
  197. }
  198. case <-stopc:
  199. snapshotTransferSec.Observe(time.Since(start).Seconds())
  200. return
  201. }
  202. }
  203. }()
  204. return &snapshot{tx, stopc, donec}
  205. }
  206. type IgnoreKey struct {
  207. Bucket string
  208. Key string
  209. }
  210. func (b *backend) Hash(ignores map[IgnoreKey]struct{}) (uint32, error) {
  211. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  212. b.mu.RLock()
  213. defer b.mu.RUnlock()
  214. err := b.db.View(func(tx *bolt.Tx) error {
  215. c := tx.Cursor()
  216. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  217. b := tx.Bucket(next)
  218. if b == nil {
  219. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  220. }
  221. h.Write(next)
  222. b.ForEach(func(k, v []byte) error {
  223. bk := IgnoreKey{Bucket: string(next), Key: string(k)}
  224. if _, ok := ignores[bk]; !ok {
  225. h.Write(k)
  226. h.Write(v)
  227. }
  228. return nil
  229. })
  230. }
  231. return nil
  232. })
  233. if err != nil {
  234. return 0, err
  235. }
  236. return h.Sum32(), nil
  237. }
  238. func (b *backend) Size() int64 {
  239. return atomic.LoadInt64(&b.size)
  240. }
  241. func (b *backend) SizeInUse() int64 {
  242. return atomic.LoadInt64(&b.sizeInUse)
  243. }
  244. func (b *backend) run() {
  245. defer close(b.donec)
  246. t := time.NewTimer(b.batchInterval)
  247. defer t.Stop()
  248. for {
  249. select {
  250. case <-t.C:
  251. case <-b.stopc:
  252. b.batchTx.CommitAndStop()
  253. return
  254. }
  255. if b.batchTx.safePending() != 0 {
  256. b.batchTx.Commit()
  257. }
  258. t.Reset(b.batchInterval)
  259. }
  260. }
  261. func (b *backend) Close() error {
  262. close(b.stopc)
  263. <-b.donec
  264. return b.db.Close()
  265. }
  266. // Commits returns total number of commits since start
  267. func (b *backend) Commits() int64 {
  268. return atomic.LoadInt64(&b.commits)
  269. }
  270. func (b *backend) Defrag() error {
  271. return b.defrag()
  272. }
  273. func (b *backend) defrag() error {
  274. now := time.Now()
  275. // TODO: make this non-blocking?
  276. // lock batchTx to ensure nobody is using previous tx, and then
  277. // close previous ongoing tx.
  278. b.batchTx.Lock()
  279. defer b.batchTx.Unlock()
  280. // lock database after lock tx to avoid deadlock.
  281. b.mu.Lock()
  282. defer b.mu.Unlock()
  283. // block concurrent read requests while resetting tx
  284. b.readTx.mu.Lock()
  285. defer b.readTx.mu.Unlock()
  286. b.batchTx.unsafeCommit(true)
  287. b.batchTx.tx = nil
  288. tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
  289. if err != nil {
  290. return err
  291. }
  292. dbp := b.db.Path()
  293. tdbp := tmpdb.Path()
  294. size1, sizeInUse1 := b.Size(), b.SizeInUse()
  295. if b.lg != nil {
  296. b.lg.Info(
  297. "defragmenting",
  298. zap.String("path", dbp),
  299. zap.Int64("current-db-size-bytes", size1),
  300. zap.String("current-db-size", humanize.Bytes(uint64(size1))),
  301. zap.Int64("current-db-size-in-use-bytes", sizeInUse1),
  302. zap.String("current-db-size-in-use", humanize.Bytes(uint64(sizeInUse1))),
  303. )
  304. }
  305. err = defragdb(b.db, tmpdb, defragLimit)
  306. if err != nil {
  307. tmpdb.Close()
  308. os.RemoveAll(tmpdb.Path())
  309. return err
  310. }
  311. err = b.db.Close()
  312. if err != nil {
  313. if b.lg != nil {
  314. b.lg.Fatal("failed to close database", zap.Error(err))
  315. } else {
  316. plog.Fatalf("cannot close database (%s)", err)
  317. }
  318. }
  319. err = tmpdb.Close()
  320. if err != nil {
  321. if b.lg != nil {
  322. b.lg.Fatal("failed to close tmp database", zap.Error(err))
  323. } else {
  324. plog.Fatalf("cannot close database (%s)", err)
  325. }
  326. }
  327. err = os.Rename(tdbp, dbp)
  328. if err != nil {
  329. if b.lg != nil {
  330. b.lg.Fatal("failed to rename tmp database", zap.Error(err))
  331. } else {
  332. plog.Fatalf("cannot rename database (%s)", err)
  333. }
  334. }
  335. b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
  336. if err != nil {
  337. if b.lg != nil {
  338. b.lg.Fatal("failed to open database", zap.String("path", dbp), zap.Error(err))
  339. } else {
  340. plog.Panicf("cannot open database at %s (%v)", dbp, err)
  341. }
  342. }
  343. b.batchTx.tx, err = b.db.Begin(true)
  344. if err != nil {
  345. if b.lg != nil {
  346. b.lg.Fatal("failed to begin tx", zap.Error(err))
  347. } else {
  348. plog.Fatalf("cannot begin tx (%s)", err)
  349. }
  350. }
  351. b.readTx.reset()
  352. b.readTx.tx = b.unsafeBegin(false)
  353. size := b.readTx.tx.Size()
  354. db := b.readTx.tx.DB()
  355. atomic.StoreInt64(&b.size, size)
  356. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  357. took := time.Since(now)
  358. defragSec.Observe(took.Seconds())
  359. size2, sizeInUse2 := b.Size(), b.SizeInUse()
  360. if b.lg != nil {
  361. b.lg.Info(
  362. "defragmented",
  363. zap.String("path", dbp),
  364. zap.Int64("current-db-size-bytes-diff", size2-size1),
  365. zap.Int64("current-db-size-bytes", size2),
  366. zap.String("current-db-size", humanize.Bytes(uint64(size2))),
  367. zap.Int64("current-db-size-in-use-bytes-diff", sizeInUse2-sizeInUse1),
  368. zap.Int64("current-db-size-in-use-bytes", sizeInUse2),
  369. zap.String("current-db-size-in-use", humanize.Bytes(uint64(sizeInUse2))),
  370. zap.Duration("took", took),
  371. )
  372. }
  373. return nil
  374. }
  375. func defragdb(odb, tmpdb *bolt.DB, limit int) error {
  376. // open a tx on tmpdb for writes
  377. tmptx, err := tmpdb.Begin(true)
  378. if err != nil {
  379. return err
  380. }
  381. // open a tx on old db for read
  382. tx, err := odb.Begin(false)
  383. if err != nil {
  384. return err
  385. }
  386. defer tx.Rollback()
  387. c := tx.Cursor()
  388. count := 0
  389. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  390. b := tx.Bucket(next)
  391. if b == nil {
  392. return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
  393. }
  394. tmpb, berr := tmptx.CreateBucketIfNotExists(next)
  395. if berr != nil {
  396. return berr
  397. }
  398. tmpb.FillPercent = 0.9 // for seq write in for each
  399. b.ForEach(func(k, v []byte) error {
  400. count++
  401. if count > limit {
  402. err = tmptx.Commit()
  403. if err != nil {
  404. return err
  405. }
  406. tmptx, err = tmpdb.Begin(true)
  407. if err != nil {
  408. return err
  409. }
  410. tmpb = tmptx.Bucket(next)
  411. tmpb.FillPercent = 0.9 // for seq write in for each
  412. count = 0
  413. }
  414. return tmpb.Put(k, v)
  415. })
  416. }
  417. return tmptx.Commit()
  418. }
  419. func (b *backend) begin(write bool) *bolt.Tx {
  420. b.mu.RLock()
  421. tx := b.unsafeBegin(write)
  422. b.mu.RUnlock()
  423. size := tx.Size()
  424. db := tx.DB()
  425. atomic.StoreInt64(&b.size, size)
  426. atomic.StoreInt64(&b.sizeInUse, size-(int64(db.Stats().FreePageN)*int64(db.Info().PageSize)))
  427. return tx
  428. }
  429. func (b *backend) unsafeBegin(write bool) *bolt.Tx {
  430. tx, err := b.db.Begin(write)
  431. if err != nil {
  432. if b.lg != nil {
  433. b.lg.Fatal("failed to begin tx", zap.Error(err))
  434. } else {
  435. plog.Fatalf("cannot begin tx (%s)", err)
  436. }
  437. }
  438. return tx
  439. }
  440. // NewTmpBackend creates a backend implementation for testing.
  441. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  442. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  443. if err != nil {
  444. panic(err)
  445. }
  446. tmpPath := filepath.Join(dir, "database")
  447. bcfg := DefaultBackendConfig()
  448. bcfg.Path, bcfg.BatchInterval, bcfg.BatchLimit = tmpPath, batchInterval, batchLimit
  449. return newBackend(bcfg), tmpPath
  450. }
  451. func NewDefaultTmpBackend() (*backend, string) {
  452. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  453. }
  454. type snapshot struct {
  455. *bolt.Tx
  456. stopc chan struct{}
  457. donec chan struct{}
  458. }
  459. func (s *snapshot) Close() error {
  460. close(s.stopc)
  461. <-s.donec
  462. return s.Tx.Rollback()
  463. }