backend.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. snapshotDurations.Observe(time.Since(start).Seconds())
  149. return
  150. }
  151. }
  152. }()
  153. b.batchTx.Commit()
  154. b.mu.RLock()
  155. defer b.mu.RUnlock()
  156. tx, err := b.db.Begin(false)
  157. if err != nil {
  158. plog.Fatalf("cannot begin tx (%s)", err)
  159. }
  160. return &snapshot{tx, stopc, donec}
  161. }
  162. type IgnoreKey struct {
  163. Bucket string
  164. Key string
  165. }
  166. func (b *backend) Hash(ignores map[IgnoreKey]struct{}) (uint32, error) {
  167. h := crc32.New(crc32.MakeTable(crc32.Castagnoli))
  168. b.mu.RLock()
  169. defer b.mu.RUnlock()
  170. err := b.db.View(func(tx *bolt.Tx) error {
  171. c := tx.Cursor()
  172. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  173. b := tx.Bucket(next)
  174. if b == nil {
  175. return fmt.Errorf("cannot get hash of bucket %s", string(next))
  176. }
  177. h.Write(next)
  178. b.ForEach(func(k, v []byte) error {
  179. bk := IgnoreKey{Bucket: string(next), Key: string(k)}
  180. if _, ok := ignores[bk]; !ok {
  181. h.Write(k)
  182. h.Write(v)
  183. }
  184. return nil
  185. })
  186. }
  187. return nil
  188. })
  189. if err != nil {
  190. return 0, err
  191. }
  192. return h.Sum32(), nil
  193. }
  194. func (b *backend) Size() int64 {
  195. return atomic.LoadInt64(&b.size)
  196. }
  197. func (b *backend) run() {
  198. defer close(b.donec)
  199. t := time.NewTimer(b.batchInterval)
  200. defer t.Stop()
  201. for {
  202. select {
  203. case <-t.C:
  204. case <-b.stopc:
  205. b.batchTx.CommitAndStop()
  206. return
  207. }
  208. b.batchTx.Commit()
  209. t.Reset(b.batchInterval)
  210. }
  211. }
  212. func (b *backend) Close() error {
  213. close(b.stopc)
  214. <-b.donec
  215. return b.db.Close()
  216. }
  217. // Commits returns total number of commits since start
  218. func (b *backend) Commits() int64 {
  219. return atomic.LoadInt64(&b.commits)
  220. }
  221. func (b *backend) Defrag() error {
  222. err := b.defrag()
  223. if err != nil {
  224. return err
  225. }
  226. // commit to update metadata like db.size
  227. b.batchTx.Commit()
  228. return nil
  229. }
  230. func (b *backend) defrag() error {
  231. // TODO: make this non-blocking?
  232. // lock batchTx to ensure nobody is using previous tx, and then
  233. // close previous ongoing tx.
  234. b.batchTx.Lock()
  235. defer b.batchTx.Unlock()
  236. // lock database after lock tx to avoid deadlock.
  237. b.mu.Lock()
  238. defer b.mu.Unlock()
  239. // block concurrent read requests while resetting tx
  240. b.readTx.mu.Lock()
  241. defer b.readTx.mu.Unlock()
  242. b.batchTx.unsafeCommit(true)
  243. b.batchTx.tx = nil
  244. tmpdb, err := bolt.Open(b.db.Path()+".tmp", 0600, boltOpenOptions)
  245. if err != nil {
  246. return err
  247. }
  248. err = defragdb(b.db, tmpdb, defragLimit)
  249. if err != nil {
  250. tmpdb.Close()
  251. os.RemoveAll(tmpdb.Path())
  252. return err
  253. }
  254. dbp := b.db.Path()
  255. tdbp := tmpdb.Path()
  256. err = b.db.Close()
  257. if err != nil {
  258. plog.Fatalf("cannot close database (%s)", err)
  259. }
  260. err = tmpdb.Close()
  261. if err != nil {
  262. plog.Fatalf("cannot close database (%s)", err)
  263. }
  264. err = os.Rename(tdbp, dbp)
  265. if err != nil {
  266. plog.Fatalf("cannot rename database (%s)", err)
  267. }
  268. b.db, err = bolt.Open(dbp, 0600, boltOpenOptions)
  269. if err != nil {
  270. plog.Panicf("cannot open database at %s (%v)", dbp, err)
  271. }
  272. b.batchTx.tx, err = b.db.Begin(true)
  273. if err != nil {
  274. plog.Fatalf("cannot begin tx (%s)", err)
  275. }
  276. b.readTx.buf.reset()
  277. b.readTx.tx = b.unsafeBegin(false)
  278. atomic.StoreInt64(&b.size, b.readTx.tx.Size())
  279. return nil
  280. }
  281. func defragdb(odb, tmpdb *bolt.DB, limit int) error {
  282. // open a tx on tmpdb for writes
  283. tmptx, err := tmpdb.Begin(true)
  284. if err != nil {
  285. return err
  286. }
  287. // open a tx on old db for read
  288. tx, err := odb.Begin(false)
  289. if err != nil {
  290. return err
  291. }
  292. defer tx.Rollback()
  293. c := tx.Cursor()
  294. count := 0
  295. for next, _ := c.First(); next != nil; next, _ = c.Next() {
  296. b := tx.Bucket(next)
  297. if b == nil {
  298. return fmt.Errorf("backend: cannot defrag bucket %s", string(next))
  299. }
  300. tmpb, berr := tmptx.CreateBucketIfNotExists(next)
  301. tmpb.FillPercent = 0.9 // for seq write in for each
  302. if berr != nil {
  303. return berr
  304. }
  305. b.ForEach(func(k, v []byte) error {
  306. count++
  307. if count > limit {
  308. err = tmptx.Commit()
  309. if err != nil {
  310. return err
  311. }
  312. tmptx, err = tmpdb.Begin(true)
  313. if err != nil {
  314. return err
  315. }
  316. tmpb = tmptx.Bucket(next)
  317. tmpb.FillPercent = 0.9 // for seq write in for each
  318. count = 0
  319. }
  320. return tmpb.Put(k, v)
  321. })
  322. }
  323. return tmptx.Commit()
  324. }
  325. func (b *backend) begin(write bool) *bolt.Tx {
  326. b.mu.RLock()
  327. tx := b.unsafeBegin(write)
  328. b.mu.RUnlock()
  329. atomic.StoreInt64(&b.size, tx.Size())
  330. return tx
  331. }
  332. func (b *backend) unsafeBegin(write bool) *bolt.Tx {
  333. tx, err := b.db.Begin(write)
  334. if err != nil {
  335. plog.Fatalf("cannot begin tx (%s)", err)
  336. }
  337. return tx
  338. }
  339. // NewTmpBackend creates a backend implementation for testing.
  340. func NewTmpBackend(batchInterval time.Duration, batchLimit int) (*backend, string) {
  341. dir, err := ioutil.TempDir(os.TempDir(), "etcd_backend_test")
  342. if err != nil {
  343. plog.Fatal(err)
  344. }
  345. tmpPath := filepath.Join(dir, "database")
  346. bcfg := DefaultBackendConfig()
  347. bcfg.Path, bcfg.BatchInterval, bcfg.BatchLimit = tmpPath, batchInterval, batchLimit
  348. return newBackend(bcfg), tmpPath
  349. }
  350. func NewDefaultTmpBackend() (*backend, string) {
  351. return NewTmpBackend(defaultBatchInterval, defaultBatchLimit)
  352. }
  353. type snapshot struct {
  354. *bolt.Tx
  355. stopc chan struct{}
  356. donec chan struct{}
  357. }
  358. func (s *snapshot) Close() error {
  359. close(s.stopc)
  360. <-s.donec
  361. return s.Tx.Rollback()
  362. }