backend.go 14 KB

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