backend.go 10 KB

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