node.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Package raft implements raft.
  2. package raft
  3. import "code.google.com/p/go.net/context"
  4. type stateResp struct {
  5. state State
  6. ents []Entry
  7. msgs []Message
  8. }
  9. type Node struct {
  10. ctx context.Context
  11. propc chan []byte
  12. recvc chan Message
  13. statec chan stateResp
  14. tickc chan struct{}
  15. }
  16. func Start(ctx context.Context, name string, election, heartbeat int) *Node {
  17. n := &Node{
  18. ctx: ctx,
  19. propc: make(chan []byte),
  20. recvc: make(chan Message),
  21. statec: make(chan stateResp),
  22. tickc: make(chan struct{}),
  23. }
  24. r := &raft{
  25. name: name,
  26. election: election,
  27. heartbeat: heartbeat,
  28. }
  29. go n.run(r)
  30. return n
  31. }
  32. func (n *Node) run(r *raft) {
  33. propc := n.propc
  34. for {
  35. if r.hasLeader() {
  36. propc = n.propc
  37. } else {
  38. // We cannot accept proposals because we don't know who
  39. // to send them to, so we'll apply back-pressure and
  40. // block senders.
  41. propc = nil
  42. }
  43. select {
  44. case p := <-propc:
  45. r.propose(p)
  46. case m := <-n.recvc:
  47. r.Step(m) // raft never returns an error
  48. case <-n.tickc:
  49. // r.tick()
  50. // case n.statec <- stateResp{r.State, r.ents, r.msgs}:
  51. // r.resetState()
  52. case <-n.ctx.Done():
  53. return
  54. }
  55. }
  56. }
  57. func (n *Node) Tick() error {
  58. select {
  59. case n.tickc <- struct{}{}:
  60. return nil
  61. case <-n.ctx.Done():
  62. return n.ctx.Err()
  63. }
  64. }
  65. // Propose proposes data be appended to the log.
  66. func (n *Node) Propose(data []byte) error {
  67. select {
  68. case n.propc <- data:
  69. return nil
  70. case <-n.ctx.Done():
  71. return n.ctx.Err()
  72. }
  73. }
  74. // Step advances the state machine using m.
  75. func (n *Node) Step(m Message) error {
  76. select {
  77. case n.recvc <- m:
  78. return nil
  79. case <-n.ctx.Done():
  80. return n.ctx.Err()
  81. }
  82. }
  83. // ReadState returns the current point-in-time state.
  84. func (n *Node) ReadState() (State, []Entry, []Message, error) {
  85. select {
  86. case sr := <-n.statec:
  87. return sr.state, sr.ents, sr.msgs, nil
  88. case <-n.ctx.Done():
  89. return State{}, nil, nil, n.ctx.Err()
  90. }
  91. }