v2_raft.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Copyright 2014 CoreOS Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcd
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "time"
  18. "github.com/coreos/etcd/raft"
  19. )
  20. type v2Proposal struct {
  21. data []byte
  22. ret chan interface{}
  23. }
  24. type wait struct {
  25. index int64
  26. term int64
  27. }
  28. type v2Raft struct {
  29. *raft.Node
  30. result map[wait]chan interface{}
  31. term int64
  32. }
  33. func (r *v2Raft) Propose(p v2Proposal) {
  34. if !r.Node.IsLeader() {
  35. p.ret <- fmt.Errorf("not leader")
  36. return
  37. }
  38. r.Node.Propose(p.data)
  39. r.result[wait{r.Index(), r.Term()}] = p.ret
  40. return
  41. }
  42. func (r *v2Raft) Sync() {
  43. if !r.Node.IsLeader() {
  44. return
  45. }
  46. sync := &cmd{Type: "sync", Time: time.Now()}
  47. data, err := json.Marshal(sync)
  48. if err != nil {
  49. panic(err)
  50. }
  51. r.Node.Propose(data)
  52. }
  53. func (r *v2Raft) StopProposalWaiters() {
  54. for k, ch := range r.result {
  55. ch <- raftStopErr
  56. delete(r.result, k)
  57. }
  58. }