backend.go 9.4 KB

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