kvstore.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. le lease.Lessor
  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. // NewStore returns a new store. It is useful to create a store inside
  56. // storage pkg. It should only be used for testing externally.
  57. func NewStore(b backend.Backend, le lease.Lessor) *store {
  58. s := &store{
  59. b: b,
  60. kvindex: newTreeIndex(),
  61. le: le,
  62. currentRev: revision{main: 1},
  63. compactMainRev: -1,
  64. stopc: make(chan struct{}),
  65. }
  66. if s.le != nil {
  67. s.le.SetRangeDeleter(s)
  68. }
  69. tx := s.b.BatchTx()
  70. tx.Lock()
  71. tx.UnsafeCreateBucket(keyBucketName)
  72. tx.UnsafeCreateBucket(metaBucketName)
  73. tx.Unlock()
  74. s.b.ForceCommit()
  75. if err := s.restore(); err != nil {
  76. // TODO: return the error instead of panic here?
  77. panic("failed to recover store from backend")
  78. }
  79. return s
  80. }
  81. func (s *store) Rev() int64 {
  82. s.mu.Lock()
  83. defer s.mu.Unlock()
  84. return s.currentRev.main
  85. }
  86. func (s *store) Put(key, value []byte, lease lease.LeaseID) int64 {
  87. id := s.TxnBegin()
  88. s.put(key, value, lease)
  89. s.txnEnd(id)
  90. putCounter.Inc()
  91. return int64(s.currentRev.main)
  92. }
  93. func (s *store) Range(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  94. id := s.TxnBegin()
  95. kvs, rev, err = s.rangeKeys(key, end, limit, rangeRev)
  96. s.txnEnd(id)
  97. rangeCounter.Inc()
  98. return kvs, rev, err
  99. }
  100. func (s *store) DeleteRange(key, end []byte) (n, rev int64) {
  101. id := s.TxnBegin()
  102. n = s.deleteRange(key, end)
  103. s.txnEnd(id)
  104. deleteCounter.Inc()
  105. return n, int64(s.currentRev.main)
  106. }
  107. func (s *store) TxnBegin() int64 {
  108. s.mu.Lock()
  109. s.currentRev.sub = 0
  110. s.tx = s.b.BatchTx()
  111. s.tx.Lock()
  112. s.txnID = rand.Int63()
  113. return s.txnID
  114. }
  115. func (s *store) TxnEnd(txnID int64) error {
  116. err := s.txnEnd(txnID)
  117. if err != nil {
  118. return err
  119. }
  120. txnCounter.Inc()
  121. return nil
  122. }
  123. // txnEnd is used for unlocking an internal txn. It does
  124. // not increase the txnCounter.
  125. func (s *store) txnEnd(txnID int64) error {
  126. if txnID != s.txnID {
  127. return ErrTxnIDMismatch
  128. }
  129. s.tx.Unlock()
  130. if s.currentRev.sub != 0 {
  131. s.currentRev.main += 1
  132. }
  133. s.currentRev.sub = 0
  134. dbTotalSize.Set(float64(s.b.Size()))
  135. s.mu.Unlock()
  136. return nil
  137. }
  138. func (s *store) TxnRange(txnID int64, key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  139. if txnID != s.txnID {
  140. return nil, 0, ErrTxnIDMismatch
  141. }
  142. return s.rangeKeys(key, end, limit, rangeRev)
  143. }
  144. func (s *store) TxnPut(txnID int64, key, value []byte, lease lease.LeaseID) (rev int64, err error) {
  145. if txnID != s.txnID {
  146. return 0, ErrTxnIDMismatch
  147. }
  148. s.put(key, value, lease)
  149. return int64(s.currentRev.main + 1), nil
  150. }
  151. func (s *store) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) {
  152. if txnID != s.txnID {
  153. return 0, 0, ErrTxnIDMismatch
  154. }
  155. n = s.deleteRange(key, end)
  156. if n != 0 || s.currentRev.sub != 0 {
  157. rev = int64(s.currentRev.main + 1)
  158. } else {
  159. rev = int64(s.currentRev.main)
  160. }
  161. return n, rev, nil
  162. }
  163. func (s *store) Compact(rev int64) error {
  164. s.mu.Lock()
  165. defer s.mu.Unlock()
  166. if rev <= s.compactMainRev {
  167. return ErrCompacted
  168. }
  169. if rev > s.currentRev.main {
  170. return ErrFutureRev
  171. }
  172. start := time.Now()
  173. s.compactMainRev = rev
  174. rbytes := newRevBytes()
  175. revToBytes(revision{main: rev}, rbytes)
  176. tx := s.b.BatchTx()
  177. tx.Lock()
  178. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  179. tx.Unlock()
  180. // ensure that desired compaction is persisted
  181. s.b.ForceCommit()
  182. keep := s.kvindex.Compact(rev)
  183. s.wg.Add(1)
  184. go s.scheduleCompaction(rev, keep)
  185. indexCompactionPauseDurations.Observe(float64(time.Now().Sub(start) / time.Millisecond))
  186. return nil
  187. }
  188. func (s *store) Hash() (uint32, error) {
  189. s.b.ForceCommit()
  190. return s.b.Hash()
  191. }
  192. func (s *store) Commit() { s.b.ForceCommit() }
  193. func (s *store) Restore(b backend.Backend) error {
  194. s.mu.Lock()
  195. defer s.mu.Unlock()
  196. close(s.stopc)
  197. // TODO: restore without waiting for compaction routine to finish.
  198. // We need a way to notify that the store is finished using the old
  199. // backend though.
  200. s.wg.Wait()
  201. s.b = b
  202. s.kvindex = newTreeIndex()
  203. s.currentRev = revision{main: 1}
  204. s.compactMainRev = -1
  205. s.tx = b.BatchTx()
  206. s.txnID = -1
  207. s.stopc = make(chan struct{})
  208. return s.restore()
  209. }
  210. func (s *store) restore() error {
  211. min, max := newRevBytes(), newRevBytes()
  212. revToBytes(revision{main: 1}, min)
  213. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  214. // restore index
  215. tx := s.b.BatchTx()
  216. tx.Lock()
  217. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  218. if len(finishedCompactBytes) != 0 {
  219. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  220. log.Printf("storage: restore compact to %d", s.compactMainRev)
  221. }
  222. // TODO: limit N to reduce max memory usage
  223. keys, vals := tx.UnsafeRange(keyBucketName, min, max, 0)
  224. for i, key := range keys {
  225. var kv storagepb.KeyValue
  226. if err := kv.Unmarshal(vals[i]); err != nil {
  227. log.Fatalf("storage: cannot unmarshal event: %v", err)
  228. }
  229. rev := bytesToRev(key[:revBytesLen])
  230. // restore index
  231. switch {
  232. case isTombstone(key):
  233. // TODO: De-attach keys from lease if necessary
  234. s.kvindex.Tombstone(kv.Key, rev)
  235. default:
  236. s.kvindex.Restore(kv.Key, revision{kv.CreateRevision, 0}, rev, kv.Version)
  237. if lease.LeaseID(kv.Lease) != lease.NoLease {
  238. if s.le == nil {
  239. panic("no lessor to attach lease")
  240. }
  241. err := s.le.Attach(lease.LeaseID(kv.Lease), []lease.LeaseItem{{Key: string(kv.Key)}})
  242. // We are walking through the kv history here. It is possible that we attached a key to
  243. // the lease and the lease was revoked later.
  244. // Thus attaching an old version of key to a none existing lease is possible here, and
  245. // we should just ignore the error.
  246. if err != nil && err != lease.ErrLeaseNotFound {
  247. panic("unexpected Attach error")
  248. }
  249. }
  250. }
  251. // update revision
  252. s.currentRev = rev
  253. }
  254. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  255. if len(scheduledCompactBytes) != 0 {
  256. scheduledCompact := bytesToRev(scheduledCompactBytes[0]).main
  257. if scheduledCompact > s.compactMainRev {
  258. log.Printf("storage: resume scheduled compaction at %d", scheduledCompact)
  259. go s.Compact(scheduledCompact)
  260. }
  261. }
  262. tx.Unlock()
  263. return nil
  264. }
  265. func (s *store) Close() error {
  266. close(s.stopc)
  267. s.wg.Wait()
  268. return nil
  269. }
  270. func (a *store) Equal(b *store) bool {
  271. if a.currentRev != b.currentRev {
  272. return false
  273. }
  274. if a.compactMainRev != b.compactMainRev {
  275. return false
  276. }
  277. return a.kvindex.Equal(b.kvindex)
  278. }
  279. // range is a keyword in Go, add Keys suffix.
  280. func (s *store) rangeKeys(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  281. curRev := int64(s.currentRev.main)
  282. if s.currentRev.sub > 0 {
  283. curRev += 1
  284. }
  285. if rangeRev > curRev {
  286. return nil, s.currentRev.main, ErrFutureRev
  287. }
  288. if rangeRev <= 0 {
  289. rev = curRev
  290. } else {
  291. rev = rangeRev
  292. }
  293. if rev <= s.compactMainRev {
  294. return nil, 0, ErrCompacted
  295. }
  296. _, revpairs := s.kvindex.Range(key, end, int64(rev))
  297. if len(revpairs) == 0 {
  298. return nil, rev, nil
  299. }
  300. for _, revpair := range revpairs {
  301. start, end := revBytesRange(revpair)
  302. _, vs := s.tx.UnsafeRange(keyBucketName, start, end, 0)
  303. if len(vs) != 1 {
  304. log.Fatalf("storage: range cannot find rev (%d,%d)", revpair.main, revpair.sub)
  305. }
  306. var kv storagepb.KeyValue
  307. if err := kv.Unmarshal(vs[0]); err != nil {
  308. log.Fatalf("storage: cannot unmarshal event: %v", err)
  309. }
  310. kvs = append(kvs, kv)
  311. if limit > 0 && len(kvs) >= int(limit) {
  312. break
  313. }
  314. }
  315. return kvs, rev, nil
  316. }
  317. func (s *store) put(key, value []byte, leaseID lease.LeaseID) {
  318. rev := s.currentRev.main + 1
  319. c := rev
  320. // if the key exists before, use its previous created
  321. _, created, ver, err := s.kvindex.Get(key, rev)
  322. if err == nil {
  323. c = created.main
  324. }
  325. ibytes := newRevBytes()
  326. revToBytes(revision{main: rev, sub: s.currentRev.sub}, ibytes)
  327. ver = ver + 1
  328. kv := storagepb.KeyValue{
  329. Key: key,
  330. Value: value,
  331. CreateRevision: c,
  332. ModRevision: rev,
  333. Version: ver,
  334. Lease: int64(leaseID),
  335. }
  336. d, err := kv.Marshal()
  337. if err != nil {
  338. log.Fatalf("storage: cannot marshal event: %v", err)
  339. }
  340. s.tx.UnsafePut(keyBucketName, ibytes, d)
  341. s.kvindex.Put(key, revision{main: rev, sub: s.currentRev.sub})
  342. s.currentRev.sub += 1
  343. if leaseID != lease.NoLease {
  344. if s.le == nil {
  345. panic("no lessor to attach lease")
  346. }
  347. // TODO: validate the existence of lease before call Attach.
  348. // We need to ensure put always successful since we do not want
  349. // to handle abortion for txn request. We need to ensure all requests
  350. // inside the txn can execute without error before executing them.
  351. err = s.le.Attach(leaseID, []lease.LeaseItem{{Key: string(key)}})
  352. if err != nil {
  353. panic("unexpected error from lease Attach")
  354. }
  355. }
  356. }
  357. func (s *store) deleteRange(key, end []byte) int64 {
  358. rrev := s.currentRev.main
  359. if s.currentRev.sub > 0 {
  360. rrev += 1
  361. }
  362. keys, _ := s.kvindex.Range(key, end, rrev)
  363. if len(keys) == 0 {
  364. return 0
  365. }
  366. for _, key := range keys {
  367. s.delete(key)
  368. }
  369. return int64(len(keys))
  370. }
  371. func (s *store) delete(key []byte) {
  372. mainrev := s.currentRev.main + 1
  373. ibytes := newRevBytes()
  374. revToBytes(revision{main: mainrev, sub: s.currentRev.sub}, ibytes)
  375. ibytes = appendMarkTombstone(ibytes)
  376. kv := storagepb.KeyValue{
  377. Key: key,
  378. }
  379. d, err := kv.Marshal()
  380. if err != nil {
  381. log.Fatalf("storage: cannot marshal event: %v", err)
  382. }
  383. s.tx.UnsafePut(keyBucketName, ibytes, d)
  384. err = s.kvindex.Tombstone(key, revision{main: mainrev, sub: s.currentRev.sub})
  385. if err != nil {
  386. log.Fatalf("storage: cannot tombstone an existing key (%s): %v", string(key), err)
  387. }
  388. s.currentRev.sub += 1
  389. // TODO: De-attach keys from lease if necessary
  390. }
  391. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  392. func appendMarkTombstone(b []byte) []byte {
  393. if len(b) != revBytesLen {
  394. log.Panicf("cannot append mark to non normal revision bytes")
  395. }
  396. return append(b, markTombstone)
  397. }
  398. // isTombstone checks whether the revision bytes is a tombstone.
  399. func isTombstone(b []byte) bool {
  400. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  401. }
  402. // revBytesRange returns the range of revision bytes at
  403. // the given revision.
  404. func revBytesRange(rev revision) (start, end []byte) {
  405. start = newRevBytes()
  406. revToBytes(rev, start)
  407. end = newRevBytes()
  408. endRev := revision{main: rev.main, sub: rev.sub + 1}
  409. revToBytes(endRev, end)
  410. return start, end
  411. }