kvstore.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/etcd/lease"
  24. "github.com/coreos/etcd/pkg/schedule"
  25. "github.com/coreos/etcd/storage/backend"
  26. "github.com/coreos/etcd/storage/storagepb"
  27. )
  28. var (
  29. keyBucketName = []byte("key")
  30. metaBucketName = []byte("meta")
  31. // markedRevBytesLen is the byte length of marked revision.
  32. // The first `revBytesLen` bytes represents a normal revision. The last
  33. // one byte is the mark.
  34. markedRevBytesLen = revBytesLen + 1
  35. markBytePosition = markedRevBytesLen - 1
  36. markTombstone byte = 't'
  37. scheduledCompactKeyName = []byte("scheduledCompactRev")
  38. finishedCompactKeyName = []byte("finishedCompactRev")
  39. ErrTxnIDMismatch = errors.New("storage: txn id mismatch")
  40. ErrCompacted = errors.New("storage: required revision has been compacted")
  41. ErrFutureRev = errors.New("storage: required revision is a future revision")
  42. ErrCanceled = errors.New("storage: watcher is canceled")
  43. )
  44. type store struct {
  45. mu sync.Mutex // guards the following
  46. b backend.Backend
  47. kvindex index
  48. le lease.Lessor
  49. currentRev revision
  50. // the main revision of the last compaction
  51. compactMainRev int64
  52. tx backend.BatchTx
  53. txnID int64 // tracks the current txnID to verify txn operations
  54. changes []storagepb.KeyValue
  55. fifoSched schedule.Scheduler
  56. stopc chan struct{}
  57. }
  58. // NewStore returns a new store. It is useful to create a store inside
  59. // storage pkg. It should only be used for testing externally.
  60. func NewStore(b backend.Backend, le lease.Lessor) *store {
  61. s := &store{
  62. b: b,
  63. kvindex: newTreeIndex(),
  64. le: le,
  65. currentRev: revision{main: 1},
  66. compactMainRev: -1,
  67. fifoSched: schedule.NewFIFOScheduler(),
  68. stopc: make(chan struct{}),
  69. }
  70. if s.le != nil {
  71. s.le.SetRangeDeleter(s)
  72. }
  73. tx := s.b.BatchTx()
  74. tx.Lock()
  75. tx.UnsafeCreateBucket(keyBucketName)
  76. tx.UnsafeCreateBucket(metaBucketName)
  77. tx.Unlock()
  78. s.b.ForceCommit()
  79. if err := s.restore(); err != nil {
  80. // TODO: return the error instead of panic here?
  81. panic("failed to recover store from backend")
  82. }
  83. return s
  84. }
  85. func (s *store) Rev() int64 {
  86. s.mu.Lock()
  87. defer s.mu.Unlock()
  88. return s.currentRev.main
  89. }
  90. func (s *store) FirstRev() int64 {
  91. s.mu.Lock()
  92. defer s.mu.Unlock()
  93. return s.compactMainRev
  94. }
  95. func (s *store) Put(key, value []byte, lease lease.LeaseID) int64 {
  96. id := s.TxnBegin()
  97. s.put(key, value, lease)
  98. s.txnEnd(id)
  99. putCounter.Inc()
  100. return int64(s.currentRev.main)
  101. }
  102. func (s *store) Range(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  103. id := s.TxnBegin()
  104. kvs, rev, err = s.rangeKeys(key, end, limit, rangeRev)
  105. s.txnEnd(id)
  106. rangeCounter.Inc()
  107. return kvs, rev, err
  108. }
  109. func (s *store) DeleteRange(key, end []byte) (n, rev int64) {
  110. id := s.TxnBegin()
  111. n = s.deleteRange(key, end)
  112. s.txnEnd(id)
  113. deleteCounter.Inc()
  114. return n, int64(s.currentRev.main)
  115. }
  116. func (s *store) TxnBegin() int64 {
  117. s.mu.Lock()
  118. s.currentRev.sub = 0
  119. s.tx = s.b.BatchTx()
  120. s.tx.Lock()
  121. s.txnID = rand.Int63()
  122. return s.txnID
  123. }
  124. func (s *store) TxnEnd(txnID int64) error {
  125. err := s.txnEnd(txnID)
  126. if err != nil {
  127. return err
  128. }
  129. txnCounter.Inc()
  130. return nil
  131. }
  132. // txnEnd is used for unlocking an internal txn. It does
  133. // not increase the txnCounter.
  134. func (s *store) txnEnd(txnID int64) error {
  135. if txnID != s.txnID {
  136. return ErrTxnIDMismatch
  137. }
  138. s.tx.Unlock()
  139. if s.currentRev.sub != 0 {
  140. s.currentRev.main += 1
  141. }
  142. s.currentRev.sub = 0
  143. dbTotalSize.Set(float64(s.b.Size()))
  144. s.mu.Unlock()
  145. return nil
  146. }
  147. func (s *store) TxnRange(txnID int64, key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  148. if txnID != s.txnID {
  149. return nil, 0, ErrTxnIDMismatch
  150. }
  151. return s.rangeKeys(key, end, limit, rangeRev)
  152. }
  153. func (s *store) TxnPut(txnID int64, key, value []byte, lease lease.LeaseID) (rev int64, err error) {
  154. if txnID != s.txnID {
  155. return 0, ErrTxnIDMismatch
  156. }
  157. s.put(key, value, lease)
  158. return int64(s.currentRev.main + 1), nil
  159. }
  160. func (s *store) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) {
  161. if txnID != s.txnID {
  162. return 0, 0, ErrTxnIDMismatch
  163. }
  164. n = s.deleteRange(key, end)
  165. if n != 0 || s.currentRev.sub != 0 {
  166. rev = int64(s.currentRev.main + 1)
  167. } else {
  168. rev = int64(s.currentRev.main)
  169. }
  170. return n, rev, nil
  171. }
  172. func (s *store) Compact(rev int64) error {
  173. s.mu.Lock()
  174. defer s.mu.Unlock()
  175. if rev <= s.compactMainRev {
  176. return ErrCompacted
  177. }
  178. if rev > s.currentRev.main {
  179. return ErrFutureRev
  180. }
  181. start := time.Now()
  182. s.compactMainRev = rev
  183. rbytes := newRevBytes()
  184. revToBytes(revision{main: rev}, rbytes)
  185. tx := s.b.BatchTx()
  186. tx.Lock()
  187. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  188. tx.Unlock()
  189. // ensure that desired compaction is persisted
  190. s.b.ForceCommit()
  191. keep := s.kvindex.Compact(rev)
  192. var j = func(ctx context.Context) {
  193. select {
  194. case <-ctx.Done():
  195. return
  196. default:
  197. }
  198. s.scheduleCompaction(rev, keep)
  199. }
  200. s.fifoSched.Schedule(j)
  201. indexCompactionPauseDurations.Observe(float64(time.Now().Sub(start) / time.Millisecond))
  202. return nil
  203. }
  204. func (s *store) Hash() (uint32, error) {
  205. s.b.ForceCommit()
  206. return s.b.Hash()
  207. }
  208. func (s *store) Commit() { s.b.ForceCommit() }
  209. func (s *store) Restore(b backend.Backend) error {
  210. s.mu.Lock()
  211. defer s.mu.Unlock()
  212. close(s.stopc)
  213. s.fifoSched.Stop()
  214. s.b = b
  215. s.kvindex = newTreeIndex()
  216. s.currentRev = revision{main: 1}
  217. s.compactMainRev = -1
  218. s.tx = b.BatchTx()
  219. s.txnID = -1
  220. s.fifoSched = schedule.NewFIFOScheduler()
  221. s.stopc = make(chan struct{})
  222. return s.restore()
  223. }
  224. func (s *store) restore() error {
  225. min, max := newRevBytes(), newRevBytes()
  226. revToBytes(revision{main: 1}, min)
  227. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  228. // restore index
  229. tx := s.b.BatchTx()
  230. tx.Lock()
  231. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  232. if len(finishedCompactBytes) != 0 {
  233. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  234. log.Printf("storage: restore compact to %d", s.compactMainRev)
  235. }
  236. // TODO: limit N to reduce max memory usage
  237. keys, vals := tx.UnsafeRange(keyBucketName, min, max, 0)
  238. for i, key := range keys {
  239. var kv storagepb.KeyValue
  240. if err := kv.Unmarshal(vals[i]); err != nil {
  241. log.Fatalf("storage: cannot unmarshal event: %v", err)
  242. }
  243. rev := bytesToRev(key[:revBytesLen])
  244. // restore index
  245. switch {
  246. case isTombstone(key):
  247. s.kvindex.Tombstone(kv.Key, rev)
  248. if lease.LeaseID(kv.Lease) != lease.NoLease {
  249. err := s.le.Detach(lease.LeaseID(kv.Lease), []lease.LeaseItem{{Key: string(kv.Key)}})
  250. if err != nil && err != lease.ErrLeaseNotFound {
  251. log.Fatalf("storage: unexpected Detach error %v", err)
  252. }
  253. }
  254. default:
  255. s.kvindex.Restore(kv.Key, revision{kv.CreateRevision, 0}, rev, kv.Version)
  256. if lease.LeaseID(kv.Lease) != lease.NoLease {
  257. if s.le == nil {
  258. panic("no lessor to attach lease")
  259. }
  260. err := s.le.Attach(lease.LeaseID(kv.Lease), []lease.LeaseItem{{Key: string(kv.Key)}})
  261. // We are walking through the kv history here. It is possible that we attached a key to
  262. // the lease and the lease was revoked later.
  263. // Thus attaching an old version of key to a none existing lease is possible here, and
  264. // we should just ignore the error.
  265. if err != nil && err != lease.ErrLeaseNotFound {
  266. panic("unexpected Attach error")
  267. }
  268. }
  269. }
  270. // update revision
  271. s.currentRev = rev
  272. }
  273. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  274. if len(scheduledCompactBytes) != 0 {
  275. scheduledCompact := bytesToRev(scheduledCompactBytes[0]).main
  276. if scheduledCompact > s.compactMainRev {
  277. log.Printf("storage: resume scheduled compaction at %d", scheduledCompact)
  278. go s.Compact(scheduledCompact)
  279. }
  280. }
  281. tx.Unlock()
  282. return nil
  283. }
  284. func (s *store) Close() error {
  285. close(s.stopc)
  286. s.fifoSched.Stop()
  287. return nil
  288. }
  289. func (a *store) Equal(b *store) bool {
  290. if a.currentRev != b.currentRev {
  291. return false
  292. }
  293. if a.compactMainRev != b.compactMainRev {
  294. return false
  295. }
  296. return a.kvindex.Equal(b.kvindex)
  297. }
  298. // range is a keyword in Go, add Keys suffix.
  299. func (s *store) rangeKeys(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, curRev int64, err error) {
  300. curRev = int64(s.currentRev.main)
  301. if s.currentRev.sub > 0 {
  302. curRev += 1
  303. }
  304. if rangeRev > curRev {
  305. return nil, s.currentRev.main, ErrFutureRev
  306. }
  307. var rev int64
  308. if rangeRev <= 0 {
  309. rev = curRev
  310. } else {
  311. rev = rangeRev
  312. }
  313. if rev <= s.compactMainRev {
  314. return nil, 0, ErrCompacted
  315. }
  316. _, revpairs := s.kvindex.Range(key, end, int64(rev))
  317. if len(revpairs) == 0 {
  318. return nil, curRev, nil
  319. }
  320. for _, revpair := range revpairs {
  321. start, end := revBytesRange(revpair)
  322. _, vs := s.tx.UnsafeRange(keyBucketName, start, end, 0)
  323. if len(vs) != 1 {
  324. log.Fatalf("storage: range cannot find rev (%d,%d)", revpair.main, revpair.sub)
  325. }
  326. var kv storagepb.KeyValue
  327. if err := kv.Unmarshal(vs[0]); err != nil {
  328. log.Fatalf("storage: cannot unmarshal event: %v", err)
  329. }
  330. kvs = append(kvs, kv)
  331. if limit > 0 && len(kvs) >= int(limit) {
  332. break
  333. }
  334. }
  335. return kvs, curRev, nil
  336. }
  337. func (s *store) put(key, value []byte, leaseID lease.LeaseID) {
  338. rev := s.currentRev.main + 1
  339. c := rev
  340. oldLease := lease.NoLease
  341. // if the key exists before, use its previous created and
  342. // get its previous leaseID
  343. grev, created, ver, err := s.kvindex.Get(key, rev)
  344. if err == nil {
  345. c = created.main
  346. ibytes := newRevBytes()
  347. revToBytes(grev, ibytes)
  348. _, vs := s.tx.UnsafeRange(keyBucketName, ibytes, nil, 0)
  349. var kv storagepb.KeyValue
  350. if err = kv.Unmarshal(vs[0]); err != nil {
  351. log.Fatalf("storage: cannot unmarshal value: %v", err)
  352. }
  353. oldLease = lease.LeaseID(kv.Lease)
  354. }
  355. ibytes := newRevBytes()
  356. revToBytes(revision{main: rev, sub: s.currentRev.sub}, ibytes)
  357. ver = ver + 1
  358. kv := storagepb.KeyValue{
  359. Key: key,
  360. Value: value,
  361. CreateRevision: c,
  362. ModRevision: rev,
  363. Version: ver,
  364. Lease: int64(leaseID),
  365. }
  366. d, err := kv.Marshal()
  367. if err != nil {
  368. log.Fatalf("storage: cannot marshal event: %v", err)
  369. }
  370. s.tx.UnsafeSeqPut(keyBucketName, ibytes, d)
  371. s.kvindex.Put(key, revision{main: rev, sub: s.currentRev.sub})
  372. s.changes = append(s.changes, kv)
  373. s.currentRev.sub += 1
  374. if oldLease != lease.NoLease {
  375. if s.le == nil {
  376. panic("no lessor to detach lease")
  377. }
  378. err = s.le.Detach(oldLease, []lease.LeaseItem{{Key: string(key)}})
  379. if err != nil {
  380. panic("unexpected error from lease detach")
  381. }
  382. }
  383. if leaseID != lease.NoLease {
  384. if s.le == nil {
  385. panic("no lessor to attach lease")
  386. }
  387. err = s.le.Attach(leaseID, []lease.LeaseItem{{Key: string(key)}})
  388. if err != nil {
  389. panic("unexpected error from lease Attach")
  390. }
  391. }
  392. }
  393. func (s *store) deleteRange(key, end []byte) int64 {
  394. rrev := s.currentRev.main
  395. if s.currentRev.sub > 0 {
  396. rrev += 1
  397. }
  398. keys, revs := s.kvindex.Range(key, end, rrev)
  399. if len(keys) == 0 {
  400. return 0
  401. }
  402. for i, key := range keys {
  403. s.delete(key, revs[i])
  404. }
  405. return int64(len(keys))
  406. }
  407. func (s *store) delete(key []byte, rev revision) {
  408. mainrev := s.currentRev.main + 1
  409. ibytes := newRevBytes()
  410. revToBytes(revision{main: mainrev, sub: s.currentRev.sub}, ibytes)
  411. ibytes = appendMarkTombstone(ibytes)
  412. kv := storagepb.KeyValue{
  413. Key: key,
  414. }
  415. d, err := kv.Marshal()
  416. if err != nil {
  417. log.Fatalf("storage: cannot marshal event: %v", err)
  418. }
  419. s.tx.UnsafeSeqPut(keyBucketName, ibytes, d)
  420. err = s.kvindex.Tombstone(key, revision{main: mainrev, sub: s.currentRev.sub})
  421. if err != nil {
  422. log.Fatalf("storage: cannot tombstone an existing key (%s): %v", string(key), err)
  423. }
  424. s.changes = append(s.changes, kv)
  425. s.currentRev.sub += 1
  426. ibytes = newRevBytes()
  427. revToBytes(rev, ibytes)
  428. _, vs := s.tx.UnsafeRange(keyBucketName, ibytes, nil, 0)
  429. kv.Reset()
  430. if err = kv.Unmarshal(vs[0]); err != nil {
  431. log.Fatalf("storage: cannot unmarshal value: %v", err)
  432. }
  433. if lease.LeaseID(kv.Lease) != lease.NoLease {
  434. err = s.le.Detach(lease.LeaseID(kv.Lease), []lease.LeaseItem{{Key: string(kv.Key)}})
  435. if err != nil {
  436. log.Fatalf("storage: cannot detach %v", err)
  437. }
  438. }
  439. }
  440. func (s *store) getChanges() []storagepb.KeyValue {
  441. changes := s.changes
  442. s.changes = make([]storagepb.KeyValue, 0, 128)
  443. return changes
  444. }
  445. // appendMarkTombstone appends tombstone mark to normal revision bytes.
  446. func appendMarkTombstone(b []byte) []byte {
  447. if len(b) != revBytesLen {
  448. log.Panicf("cannot append mark to non normal revision bytes")
  449. }
  450. return append(b, markTombstone)
  451. }
  452. // isTombstone checks whether the revision bytes is a tombstone.
  453. func isTombstone(b []byte) bool {
  454. return len(b) == markedRevBytesLen && b[markBytePosition] == markTombstone
  455. }
  456. // revBytesRange returns the range of revision bytes at
  457. // the given revision.
  458. func revBytesRange(rev revision) (start, end []byte) {
  459. start = newRevBytes()
  460. revToBytes(rev, start)
  461. end = newRevBytes()
  462. endRev := revision{main: rev.main, sub: rev.sub + 1}
  463. revToBytes(endRev, end)
  464. return start, end
  465. }