kvstore.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // Copyright 2015 CoreOS, Inc.
  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 storage
  15. import (
  16. "errors"
  17. "log"
  18. "math"
  19. "math/rand"
  20. "sync"
  21. "time"
  22. "github.com/coreos/etcd/storage/backend"
  23. "github.com/coreos/etcd/storage/storagepb"
  24. )
  25. var (
  26. batchLimit = 10000
  27. batchInterval = 100 * time.Millisecond
  28. keyBucketName = []byte("key")
  29. metaBucketName = []byte("meta")
  30. // markedRevBytesLen is the byte length of marked revision.
  31. // The first `revBytesLen` bytes represents a normal revision. The last
  32. // one byte is the mark.
  33. markedRevBytesLen = revBytesLen + 1
  34. markBytePosition = markedRevBytesLen - 1
  35. markTombstone byte = 't'
  36. scheduledCompactKeyName = []byte("scheduledCompactRev")
  37. finishedCompactKeyName = []byte("finishedCompactRev")
  38. ErrTxnIDMismatch = errors.New("storage: txn id mismatch")
  39. ErrCompacted = errors.New("storage: required revision has been compacted")
  40. ErrFutureRev = errors.New("storage: required revision is a future revision")
  41. ErrCanceled = errors.New("storage: watcher is canceled")
  42. )
  43. type store struct {
  44. mu sync.Mutex // guards the following
  45. b backend.Backend
  46. kvindex index
  47. currentRev revision
  48. // the main revision of the last compaction
  49. compactMainRev int64
  50. tx backend.BatchTx
  51. txnID int64 // tracks the current txnID to verify txn operations
  52. wg sync.WaitGroup
  53. stopc chan struct{}
  54. }
  55. func newStore(path string) *store {
  56. s := &store{
  57. b: backend.New(path, batchInterval, batchLimit),
  58. kvindex: newTreeIndex(),
  59. currentRev: revision{},
  60. compactMainRev: -1,
  61. stopc: make(chan struct{}),
  62. }
  63. tx := s.b.BatchTx()
  64. tx.Lock()
  65. tx.UnsafeCreateBucket(keyBucketName)
  66. tx.UnsafeCreateBucket(metaBucketName)
  67. tx.Unlock()
  68. s.b.ForceCommit()
  69. return s
  70. }
  71. func (s *store) Rev() int64 {
  72. s.mu.Lock()
  73. defer s.mu.Unlock()
  74. return s.currentRev.main
  75. }
  76. func (s *store) Put(key, value []byte) int64 {
  77. id := s.TxnBegin()
  78. s.put(key, value)
  79. s.txnEnd(id)
  80. putCounter.Inc()
  81. return int64(s.currentRev.main)
  82. }
  83. func (s *store) Range(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  84. id := s.TxnBegin()
  85. kvs, rev, err = s.rangeKeys(key, end, limit, rangeRev)
  86. s.txnEnd(id)
  87. rangeCounter.Inc()
  88. return kvs, rev, err
  89. }
  90. func (s *store) DeleteRange(key, end []byte) (n, rev int64) {
  91. id := s.TxnBegin()
  92. n = s.deleteRange(key, end)
  93. s.txnEnd(id)
  94. deleteCounter.Inc()
  95. return n, int64(s.currentRev.main)
  96. }
  97. func (s *store) TxnBegin() int64 {
  98. s.mu.Lock()
  99. s.currentRev.sub = 0
  100. s.tx = s.b.BatchTx()
  101. s.tx.Lock()
  102. s.txnID = rand.Int63()
  103. return s.txnID
  104. }
  105. func (s *store) TxnEnd(txnID int64) error {
  106. err := s.txnEnd(txnID)
  107. if err != nil {
  108. return err
  109. }
  110. txnCounter.Inc()
  111. return nil
  112. }
  113. // txnEnd is used for unlocking an internal txn. It does
  114. // not increase the txnCounter.
  115. func (s *store) txnEnd(txnID int64) error {
  116. if txnID != s.txnID {
  117. return ErrTxnIDMismatch
  118. }
  119. s.tx.Unlock()
  120. if s.currentRev.sub != 0 {
  121. s.currentRev.main += 1
  122. }
  123. s.currentRev.sub = 0
  124. dbTotalSize.Set(float64(s.b.Size()))
  125. s.mu.Unlock()
  126. return nil
  127. }
  128. func (s *store) TxnRange(txnID int64, key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  129. if txnID != s.txnID {
  130. return nil, 0, ErrTxnIDMismatch
  131. }
  132. return s.rangeKeys(key, end, limit, rangeRev)
  133. }
  134. func (s *store) TxnPut(txnID int64, key, value []byte) (rev int64, err error) {
  135. if txnID != s.txnID {
  136. return 0, ErrTxnIDMismatch
  137. }
  138. s.put(key, value)
  139. return int64(s.currentRev.main + 1), nil
  140. }
  141. func (s *store) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) {
  142. if txnID != s.txnID {
  143. return 0, 0, ErrTxnIDMismatch
  144. }
  145. n = s.deleteRange(key, end)
  146. if n != 0 || s.currentRev.sub != 0 {
  147. rev = int64(s.currentRev.main + 1)
  148. } else {
  149. rev = int64(s.currentRev.main)
  150. }
  151. return n, rev, nil
  152. }
  153. func (s *store) Compact(rev int64) error {
  154. s.mu.Lock()
  155. defer s.mu.Unlock()
  156. if rev <= s.compactMainRev {
  157. return ErrCompacted
  158. }
  159. if rev > s.currentRev.main {
  160. return ErrFutureRev
  161. }
  162. start := time.Now()
  163. s.compactMainRev = rev
  164. rbytes := newRevBytes()
  165. revToBytes(revision{main: rev}, rbytes)
  166. tx := s.b.BatchTx()
  167. tx.Lock()
  168. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  169. tx.Unlock()
  170. // ensure that desired compaction is persisted
  171. s.b.ForceCommit()
  172. keep := s.kvindex.Compact(rev)
  173. s.wg.Add(1)
  174. go s.scheduleCompaction(rev, keep)
  175. indexCompactionPauseDurations.Observe(float64(time.Now().Sub(start) / time.Millisecond))
  176. return nil
  177. }
  178. func (s *store) Hash() (uint32, error) {
  179. s.b.ForceCommit()
  180. return s.b.Hash()
  181. }
  182. func (s *store) Snapshot() Snapshot {
  183. s.b.ForceCommit()
  184. return s.b.Snapshot()
  185. }
  186. func (s *store) Commit() { s.b.ForceCommit() }
  187. func (s *store) Restore() error {
  188. s.mu.Lock()
  189. defer s.mu.Unlock()
  190. min, max := newRevBytes(), newRevBytes()
  191. revToBytes(revision{}, min)
  192. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  193. // restore index
  194. tx := s.b.BatchTx()
  195. tx.Lock()
  196. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  197. if len(finishedCompactBytes) != 0 {
  198. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  199. log.Printf("storage: restore compact to %d", s.compactMainRev)
  200. }
  201. // TODO: limit N to reduce max memory usage
  202. keys, vals := tx.UnsafeRange(keyBucketName, min, max, 0)
  203. for i, key := range keys {
  204. var kv storagepb.KeyValue
  205. if err := kv.Unmarshal(vals[i]); err != nil {
  206. log.Fatalf("storage: cannot unmarshal event: %v", err)
  207. }
  208. rev := bytesToRev(key[:revBytesLen])
  209. // restore index
  210. switch {
  211. case isTombstone(key):
  212. s.kvindex.Tombstone(kv.Key, rev)
  213. default:
  214. s.kvindex.Restore(kv.Key, revision{kv.CreateRevision, 0}, rev, kv.Version)
  215. }
  216. // update revision
  217. s.currentRev = rev
  218. }
  219. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  220. if len(scheduledCompactBytes) != 0 {
  221. scheduledCompact := bytesToRev(scheduledCompactBytes[0]).main
  222. if scheduledCompact > s.compactMainRev {
  223. log.Printf("storage: resume scheduled compaction at %d", scheduledCompact)
  224. go s.Compact(scheduledCompact)
  225. }
  226. }
  227. tx.Unlock()
  228. return nil
  229. }
  230. func (s *store) Close() error {
  231. close(s.stopc)
  232. s.wg.Wait()
  233. return s.b.Close()
  234. }
  235. func (a *store) Equal(b *store) bool {
  236. if a.currentRev != b.currentRev {
  237. return false
  238. }
  239. if a.compactMainRev != b.compactMainRev {
  240. return false
  241. }
  242. return a.kvindex.Equal(b.kvindex)
  243. }
  244. // range is a keyword in Go, add Keys suffix.
  245. func (s *store) rangeKeys(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  246. curRev := int64(s.currentRev.main)
  247. if s.currentRev.sub > 0 {
  248. curRev += 1
  249. }
  250. if rangeRev > curRev {
  251. return nil, s.currentRev.main, ErrFutureRev
  252. }
  253. if rangeRev <= 0 {
  254. rev = curRev
  255. } else {
  256. rev = rangeRev
  257. }
  258. if rev <= s.compactMainRev {
  259. return nil, 0, ErrCompacted
  260. }
  261. _, revpairs := s.kvindex.Range(key, end, int64(rev))
  262. if len(revpairs) == 0 {
  263. return nil, rev, nil
  264. }
  265. for _, revpair := range revpairs {
  266. start, end := revBytesRange(revpair)
  267. _, vs := s.tx.UnsafeRange(keyBucketName, start, end, 0)
  268. if len(vs) != 1 {
  269. log.Fatalf("storage: range cannot find rev (%d,%d)", revpair.main, revpair.sub)
  270. }
  271. var kv storagepb.KeyValue
  272. if err := kv.Unmarshal(vs[0]); err != nil {
  273. log.Fatalf("storage: cannot unmarshal event: %v", err)
  274. }
  275. kvs = append(kvs, kv)
  276. if limit > 0 && len(kvs) >= int(limit) {
  277. break
  278. }
  279. }
  280. return kvs, rev, nil
  281. }
  282. func (s *store) put(key, value []byte) {
  283. rev := s.currentRev.main + 1
  284. c := rev
  285. // if the key exists before, use its previous created
  286. _, created, ver, err := s.kvindex.Get(key, rev)
  287. if err == nil {
  288. c = created.main
  289. }
  290. ibytes := newRevBytes()
  291. revToBytes(revision{main: rev, sub: s.currentRev.sub}, ibytes)
  292. ver = ver + 1
  293. kv := storagepb.KeyValue{
  294. Key: key,
  295. Value: value,
  296. CreateRevision: c,
  297. ModRevision: rev,
  298. Version: ver,
  299. }
  300. d, err := kv.Marshal()
  301. if err != nil {
  302. log.Fatalf("storage: cannot marshal event: %v", err)
  303. }
  304. s.tx.UnsafePut(keyBucketName, ibytes, d)
  305. s.kvindex.Put(key, revision{main: rev, sub: s.currentRev.sub})
  306. s.currentRev.sub += 1
  307. }
  308. func (s *store) deleteRange(key, end []byte) int64 {
  309. rrev := s.currentRev.main
  310. if s.currentRev.sub > 0 {
  311. rrev += 1
  312. }
  313. keys, _ := s.kvindex.Range(key, end, rrev)
  314. if len(keys) == 0 {
  315. return 0
  316. }
  317. for _, key := range keys {
  318. s.delete(key)
  319. }
  320. return int64(len(keys))
  321. }
  322. func (s *store) delete(key []byte) {
  323. mainrev := s.currentRev.main + 1
  324. ibytes := newRevBytes()
  325. revToBytes(revision{main: mainrev, sub: s.currentRev.sub}, ibytes)
  326. ibytes = appendMarkTombstone(ibytes)
  327. kv := storagepb.KeyValue{
  328. Key: key,
  329. }
  330. d, err := kv.Marshal()
  331. if err != nil {
  332. log.Fatalf("storage: cannot marshal event: %v", err)
  333. }
  334. s.tx.UnsafePut(keyBucketName, ibytes, d)
  335. err = s.kvindex.Tombstone(key, revision{main: mainrev, sub: s.currentRev.sub})
  336. if err != nil {
  337. log.Fatalf("storage: cannot tombstone an existing key (%s): %v", string(key), err)
  338. }
  339. s.currentRev.sub += 1
  340. }
  341. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  342. func appendMarkTombstone(b []byte) []byte {
  343. if len(b) != revBytesLen {
  344. log.Panicf("cannot append mark to non normal revision bytes")
  345. }
  346. return append(b, markTombstone)
  347. }
  348. // isTombstone checks whether the revision bytes is a tombstone.
  349. func isTombstone(b []byte) bool {
  350. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  351. }
  352. // revBytesRange returns the range of revision bytes at
  353. // the given revision.
  354. func revBytesRange(rev revision) (start, end []byte) {
  355. start = newRevBytes()
  356. revToBytes(rev, start)
  357. end = newRevBytes()
  358. endRev := revision{main: rev.main, sub: rev.sub + 1}
  359. revToBytes(endRev, end)
  360. return start, end
  361. }