kvstore.go 10 KB

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