kvstore.go 12 KB

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