backend.go 13 KB

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