kvstore.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright 2015 The etcd Authors
  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 main
  15. import (
  16. "bytes"
  17. "encoding/gob"
  18. "encoding/json"
  19. "log"
  20. "sync"
  21. "github.com/coreos/etcd/snap"
  22. )
  23. // a key-value store backed by raft
  24. type kvstore struct {
  25. proposeC chan<- string // channel for proposing updates
  26. mu sync.RWMutex
  27. kvStore map[string]string // current committed key-value pairs
  28. snapshotter *snap.Snapshotter
  29. }
  30. type kv struct {
  31. Key string
  32. Val string
  33. }
  34. func newKVStore(snapshotter *snap.Snapshotter, proposeC chan<- string, commitC <-chan *string, errorC <-chan error) *kvstore {
  35. s := &kvstore{proposeC: proposeC, kvStore: make(map[string]string), snapshotter: snapshotter}
  36. // replay log into key-value map
  37. s.readCommits(commitC, errorC)
  38. // read commits from raft into kvStore map until error
  39. go s.readCommits(commitC, errorC)
  40. return s
  41. }
  42. func (s *kvstore) Lookup(key string) (string, bool) {
  43. s.mu.RLock()
  44. v, ok := s.kvStore[key]
  45. s.mu.RUnlock()
  46. return v, ok
  47. }
  48. func (s *kvstore) Propose(k string, v string) {
  49. var buf bytes.Buffer
  50. if err := gob.NewEncoder(&buf).Encode(kv{k, v}); err != nil {
  51. log.Fatal(err)
  52. }
  53. s.proposeC <- buf.String()
  54. }
  55. func (s *kvstore) readCommits(commitC <-chan *string, errorC <-chan error) {
  56. for data := range commitC {
  57. if data == nil {
  58. // done replaying log; new data incoming
  59. // OR signaled to load snapshot
  60. snapshot, err := s.snapshotter.Load()
  61. if err == snap.ErrNoSnapshot {
  62. return
  63. }
  64. if err != nil && err != snap.ErrNoSnapshot {
  65. log.Panic(err)
  66. }
  67. log.Printf("loading snapshot at term %d and index %d", snapshot.Metadata.Term, snapshot.Metadata.Index)
  68. if err := s.recoverFromSnapshot(snapshot.Data); err != nil {
  69. log.Panic(err)
  70. }
  71. continue
  72. }
  73. var dataKv kv
  74. dec := gob.NewDecoder(bytes.NewBufferString(*data))
  75. if err := dec.Decode(&dataKv); err != nil {
  76. log.Fatalf("raftexample: could not decode message (%v)", err)
  77. }
  78. s.mu.Lock()
  79. s.kvStore[dataKv.Key] = dataKv.Val
  80. s.mu.Unlock()
  81. }
  82. if err, ok := <-errorC; ok {
  83. log.Fatal(err)
  84. }
  85. }
  86. func (s *kvstore) getSnapshot() ([]byte, error) {
  87. s.mu.Lock()
  88. defer s.mu.Unlock()
  89. return json.Marshal(s.kvStore)
  90. }
  91. func (s *kvstore) recoverFromSnapshot(snapshot []byte) error {
  92. var store map[string]string
  93. if err := json.Unmarshal(snapshot, &store); err != nil {
  94. return err
  95. }
  96. s.mu.Lock()
  97. s.kvStore = store
  98. s.mu.Unlock()
  99. return nil
  100. }