kvstore.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. "io"
  18. "log"
  19. "math"
  20. "math/rand"
  21. "sync"
  22. "time"
  23. "github.com/coreos/etcd/storage/backend"
  24. "github.com/coreos/etcd/storage/storagepb"
  25. )
  26. var (
  27. batchLimit = 10000
  28. batchInterval = 100 * time.Millisecond
  29. keyBucketName = []byte("key")
  30. metaBucketName = []byte("meta")
  31. scheduledCompactKeyName = []byte("scheduledCompactRev")
  32. finishedCompactKeyName = []byte("finishedCompactRev")
  33. ErrTxnIDMismatch = errors.New("storage: txn id mismatch")
  34. ErrCompacted = errors.New("storage: required revision has been compacted")
  35. ErrFutureRev = errors.New("storage: required revision is a future revision")
  36. ErrCanceled = errors.New("storage: watcher is canceled")
  37. )
  38. type store struct {
  39. mu sync.RWMutex
  40. b backend.Backend
  41. kvindex index
  42. currentRev revision
  43. // the main revision of the last compaction
  44. compactMainRev int64
  45. tmu sync.Mutex // protect the txnID field
  46. txnID int64 // tracks the current txnID to verify txn operations
  47. wg sync.WaitGroup
  48. stopc chan struct{}
  49. }
  50. func New(path string) KV {
  51. return newStore(path)
  52. }
  53. func newStore(path string) *store {
  54. s := &store{
  55. b: backend.New(path, batchInterval, batchLimit),
  56. kvindex: newTreeIndex(),
  57. currentRev: revision{},
  58. compactMainRev: -1,
  59. stopc: make(chan struct{}),
  60. }
  61. tx := s.b.BatchTx()
  62. tx.Lock()
  63. tx.UnsafeCreateBucket(keyBucketName)
  64. tx.UnsafeCreateBucket(metaBucketName)
  65. tx.Unlock()
  66. s.b.ForceCommit()
  67. return s
  68. }
  69. func (s *store) Rev() int64 {
  70. s.mu.RLock()
  71. defer s.mu.RUnlock()
  72. return s.currentRev.main
  73. }
  74. func (s *store) Put(key, value []byte) int64 {
  75. id := s.TxnBegin()
  76. s.put(key, value)
  77. s.txnEnd(id)
  78. putCounter.Inc()
  79. return int64(s.currentRev.main)
  80. }
  81. func (s *store) Range(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  82. id := s.TxnBegin()
  83. kvs, rev, err = s.rangeKeys(key, end, limit, rangeRev)
  84. s.txnEnd(id)
  85. rangeCounter.Inc()
  86. return kvs, rev, err
  87. }
  88. func (s *store) DeleteRange(key, end []byte) (n, rev int64) {
  89. id := s.TxnBegin()
  90. n = s.deleteRange(key, end)
  91. s.txnEnd(id)
  92. deleteCounter.Inc()
  93. return n, int64(s.currentRev.main)
  94. }
  95. func (s *store) TxnBegin() int64 {
  96. s.mu.Lock()
  97. s.currentRev.sub = 0
  98. s.tmu.Lock()
  99. defer s.tmu.Unlock()
  100. s.txnID = rand.Int63()
  101. return s.txnID
  102. }
  103. func (s *store) TxnEnd(txnID int64) error {
  104. err := s.txnEnd(txnID)
  105. if err != nil {
  106. return err
  107. }
  108. txnCounter.Inc()
  109. return nil
  110. }
  111. // txnEnd is used for unlocking an internal txn. It does
  112. // not increase the txnCounter.
  113. func (s *store) txnEnd(txnID int64) error {
  114. s.tmu.Lock()
  115. defer s.tmu.Unlock()
  116. if txnID != s.txnID {
  117. return ErrTxnIDMismatch
  118. }
  119. if s.currentRev.sub != 0 {
  120. s.currentRev.main += 1
  121. }
  122. s.currentRev.sub = 0
  123. s.mu.Unlock()
  124. return nil
  125. }
  126. func (s *store) TxnRange(txnID int64, key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  127. s.tmu.Lock()
  128. defer s.tmu.Unlock()
  129. if txnID != s.txnID {
  130. return nil, 0, ErrTxnIDMismatch
  131. }
  132. return s.rangeKeys(key, end, limit, rangeRev)
  133. }
  134. func (s *store) TxnPut(txnID int64, key, value []byte) (rev int64, err error) {
  135. s.tmu.Lock()
  136. defer s.tmu.Unlock()
  137. if txnID != s.txnID {
  138. return 0, ErrTxnIDMismatch
  139. }
  140. s.put(key, value)
  141. return int64(s.currentRev.main + 1), nil
  142. }
  143. func (s *store) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) {
  144. s.tmu.Lock()
  145. defer s.tmu.Unlock()
  146. if txnID != s.txnID {
  147. return 0, 0, ErrTxnIDMismatch
  148. }
  149. n = s.deleteRange(key, end)
  150. if n != 0 || s.currentRev.sub != 0 {
  151. rev = int64(s.currentRev.main + 1)
  152. } else {
  153. rev = int64(s.currentRev.main)
  154. }
  155. return n, rev, nil
  156. }
  157. // RangeEvents gets the events from key to end in [startRev, endRev).
  158. // If `end` is nil, the request only observes the events on key.
  159. // If `end` is not nil, it observes the events on key range [key, range_end).
  160. // Limit limits the number of events returned.
  161. // If startRev <=0, rangeEvents returns events from the beginning of uncompacted history.
  162. // If endRev <=0, it indicates there is no end revision.
  163. //
  164. // If the required start rev is compacted, ErrCompacted will be returned.
  165. // If the required start rev has not happened, ErrFutureRev will be returned.
  166. //
  167. // RangeEvents returns events that satisfy the requirement (0 <= n <= limit).
  168. // If events in the revision range have not all happened, it returns immeidately
  169. // what is available.
  170. // It also returns nextRev which indicates the start revision used for the following
  171. // RangeEvents call. The nextRev could be smaller than the given endRev if the store
  172. // has not progressed so far or it hits the event limit.
  173. //
  174. // TODO: return byte slices instead of events to avoid meaningless encode and decode.
  175. func (s *store) RangeEvents(key, end []byte, limit, startRev, endRev int64) (evs []storagepb.Event, nextRev int64, err error) {
  176. s.mu.Lock()
  177. defer s.mu.Unlock()
  178. if startRev > 0 && startRev <= s.compactMainRev {
  179. return nil, 0, ErrCompacted
  180. }
  181. if startRev > s.currentRev.main {
  182. return nil, 0, ErrFutureRev
  183. }
  184. revs := s.kvindex.RangeEvents(key, end, startRev)
  185. if len(revs) == 0 {
  186. return nil, s.currentRev.main + 1, nil
  187. }
  188. tx := s.b.BatchTx()
  189. tx.Lock()
  190. defer tx.Unlock()
  191. // fetch events from the backend using revisions
  192. for _, rev := range revs {
  193. if endRev > 0 && rev.main >= endRev {
  194. return evs, rev.main, nil
  195. }
  196. revbytes := newRevBytes()
  197. revToBytes(rev, revbytes)
  198. _, vs := tx.UnsafeRange(keyBucketName, revbytes, nil, 0)
  199. if len(vs) != 1 {
  200. log.Fatalf("storage: range cannot find rev (%d,%d)", rev.main, rev.sub)
  201. }
  202. e := storagepb.Event{}
  203. if err := e.Unmarshal(vs[0]); err != nil {
  204. log.Fatalf("storage: cannot unmarshal event: %v", err)
  205. }
  206. evs = append(evs, e)
  207. if limit > 0 && len(evs) >= int(limit) {
  208. return evs, rev.main + 1, nil
  209. }
  210. }
  211. return evs, s.currentRev.main + 1, nil
  212. }
  213. func (s *store) Compact(rev int64) error {
  214. s.mu.Lock()
  215. defer s.mu.Unlock()
  216. if rev <= s.compactMainRev {
  217. return ErrCompacted
  218. }
  219. if rev > s.currentRev.main {
  220. return ErrFutureRev
  221. }
  222. start := time.Now()
  223. s.compactMainRev = rev
  224. rbytes := newRevBytes()
  225. revToBytes(revision{main: rev}, rbytes)
  226. tx := s.b.BatchTx()
  227. tx.Lock()
  228. tx.UnsafePut(metaBucketName, scheduledCompactKeyName, rbytes)
  229. tx.Unlock()
  230. // ensure that desired compaction is persisted
  231. s.b.ForceCommit()
  232. keep := s.kvindex.Compact(rev)
  233. s.wg.Add(1)
  234. go s.scheduleCompaction(rev, keep)
  235. indexCompactionPauseDurations.Observe(float64(time.Now().Sub(start) / time.Millisecond))
  236. return nil
  237. }
  238. func (s *store) Hash() (uint32, error) {
  239. s.b.ForceCommit()
  240. return s.b.Hash()
  241. }
  242. func (s *store) Snapshot(w io.Writer) (int64, error) {
  243. s.b.ForceCommit()
  244. return s.b.Snapshot(w)
  245. }
  246. func (s *store) Restore() error {
  247. s.mu.Lock()
  248. defer s.mu.Unlock()
  249. min, max := newRevBytes(), newRevBytes()
  250. revToBytes(revision{}, min)
  251. revToBytes(revision{main: math.MaxInt64, sub: math.MaxInt64}, max)
  252. // restore index
  253. tx := s.b.BatchTx()
  254. tx.Lock()
  255. _, finishedCompactBytes := tx.UnsafeRange(metaBucketName, finishedCompactKeyName, nil, 0)
  256. if len(finishedCompactBytes) != 0 {
  257. s.compactMainRev = bytesToRev(finishedCompactBytes[0]).main
  258. log.Printf("storage: restore compact to %d", s.compactMainRev)
  259. }
  260. // TODO: limit N to reduce max memory usage
  261. keys, vals := tx.UnsafeRange(keyBucketName, min, max, 0)
  262. for i, key := range keys {
  263. e := &storagepb.Event{}
  264. if err := e.Unmarshal(vals[i]); err != nil {
  265. log.Fatalf("storage: cannot unmarshal event: %v", err)
  266. }
  267. rev := bytesToRev(key)
  268. // restore index
  269. switch e.Type {
  270. case storagepb.PUT:
  271. s.kvindex.Restore(e.Kv.Key, revision{e.Kv.CreateRevision, 0}, rev, e.Kv.Version)
  272. case storagepb.DELETE:
  273. s.kvindex.Tombstone(e.Kv.Key, rev)
  274. default:
  275. log.Panicf("storage: unexpected event type %s", e.Type)
  276. }
  277. // update revision
  278. s.currentRev = rev
  279. }
  280. _, scheduledCompactBytes := tx.UnsafeRange(metaBucketName, scheduledCompactKeyName, nil, 0)
  281. if len(scheduledCompactBytes) != 0 {
  282. scheduledCompact := bytesToRev(scheduledCompactBytes[0]).main
  283. if scheduledCompact > s.compactMainRev {
  284. log.Printf("storage: resume scheduled compaction at %d", scheduledCompact)
  285. go s.Compact(scheduledCompact)
  286. }
  287. }
  288. tx.Unlock()
  289. return nil
  290. }
  291. func (s *store) Close() error {
  292. close(s.stopc)
  293. s.wg.Wait()
  294. return s.b.Close()
  295. }
  296. func (a *store) Equal(b *store) bool {
  297. if a.currentRev != b.currentRev {
  298. return false
  299. }
  300. if a.compactMainRev != b.compactMainRev {
  301. return false
  302. }
  303. return a.kvindex.Equal(b.kvindex)
  304. }
  305. // range is a keyword in Go, add Keys suffix.
  306. func (s *store) rangeKeys(key, end []byte, limit, rangeRev int64) (kvs []storagepb.KeyValue, rev int64, err error) {
  307. curRev := int64(s.currentRev.main)
  308. if s.currentRev.sub > 0 {
  309. curRev += 1
  310. }
  311. if rangeRev > curRev {
  312. return nil, s.currentRev.main, ErrFutureRev
  313. }
  314. if rangeRev <= 0 {
  315. rev = curRev
  316. } else {
  317. rev = rangeRev
  318. }
  319. if rev <= s.compactMainRev {
  320. return nil, 0, ErrCompacted
  321. }
  322. _, revpairs := s.kvindex.Range(key, end, int64(rev))
  323. if len(revpairs) == 0 {
  324. return nil, rev, nil
  325. }
  326. tx := s.b.BatchTx()
  327. tx.Lock()
  328. defer tx.Unlock()
  329. for _, revpair := range revpairs {
  330. revbytes := newRevBytes()
  331. revToBytes(revpair, revbytes)
  332. _, vs := tx.UnsafeRange(keyBucketName, revbytes, nil, 0)
  333. if len(vs) != 1 {
  334. log.Fatalf("storage: range cannot find rev (%d,%d)", revpair.main, revpair.sub)
  335. }
  336. e := &storagepb.Event{}
  337. if err := e.Unmarshal(vs[0]); err != nil {
  338. log.Fatalf("storage: cannot unmarshal event: %v", err)
  339. }
  340. kvs = append(kvs, *e.Kv)
  341. if limit > 0 && len(kvs) >= int(limit) {
  342. break
  343. }
  344. }
  345. return kvs, rev, nil
  346. }
  347. func (s *store) put(key, value []byte) {
  348. rev := s.currentRev.main + 1
  349. c := rev
  350. // if the key exists before, use its previous created
  351. _, created, ver, err := s.kvindex.Get(key, rev)
  352. if err == nil {
  353. c = created.main
  354. }
  355. ibytes := newRevBytes()
  356. revToBytes(revision{main: rev, sub: s.currentRev.sub}, ibytes)
  357. ver = ver + 1
  358. event := storagepb.Event{
  359. Type: storagepb.PUT,
  360. Kv: &storagepb.KeyValue{
  361. Key: key,
  362. Value: value,
  363. CreateRevision: c,
  364. ModRevision: rev,
  365. Version: ver,
  366. },
  367. }
  368. d, err := event.Marshal()
  369. if err != nil {
  370. log.Fatalf("storage: cannot marshal event: %v", err)
  371. }
  372. tx := s.b.BatchTx()
  373. tx.Lock()
  374. defer tx.Unlock()
  375. tx.UnsafePut(keyBucketName, ibytes, d)
  376. s.kvindex.Put(key, revision{main: rev, sub: s.currentRev.sub})
  377. s.currentRev.sub += 1
  378. }
  379. func (s *store) deleteRange(key, end []byte) int64 {
  380. rrev := s.currentRev.main
  381. if s.currentRev.sub > 0 {
  382. rrev += 1
  383. }
  384. keys, _ := s.kvindex.Range(key, end, rrev)
  385. if len(keys) == 0 {
  386. return 0
  387. }
  388. for _, key := range keys {
  389. s.delete(key)
  390. }
  391. return int64(len(keys))
  392. }
  393. func (s *store) delete(key []byte) {
  394. mainrev := s.currentRev.main + 1
  395. tx := s.b.BatchTx()
  396. tx.Lock()
  397. defer tx.Unlock()
  398. ibytes := newRevBytes()
  399. revToBytes(revision{main: mainrev, sub: s.currentRev.sub}, ibytes)
  400. event := storagepb.Event{
  401. Type: storagepb.DELETE,
  402. Kv: &storagepb.KeyValue{
  403. Key: key,
  404. },
  405. }
  406. d, err := event.Marshal()
  407. if err != nil {
  408. log.Fatalf("storage: cannot marshal event: %v", err)
  409. }
  410. tx.UnsafePut(keyBucketName, ibytes, d)
  411. err = s.kvindex.Tombstone(key, revision{main: mainrev, sub: s.currentRev.sub})
  412. if err != nil {
  413. log.Fatalf("storage: cannot tombstone an existing key (%s): %v", string(key), err)
  414. }
  415. s.currentRev.sub += 1
  416. }