backend.go 14 KB

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