kvstore.go 10 KB

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