node.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 proposal struct {
  10. id int64
  11. data []byte
  12. }
  13. type Node struct {
  14. ctx context.Context
  15. propc chan proposal
  16. recvc chan Message
  17. statec chan stateResp
  18. }
  19. func Start(ctx context.Context, name string, election, heartbeat int) *Node {
  20. n := &Node{
  21. ctx: ctx,
  22. propc: make(chan proposal),
  23. recvc: make(chan Message),
  24. statec: make(chan stateResp),
  25. }
  26. r := &raft{
  27. name: name,
  28. election: election,
  29. heartbeat: heartbeat,
  30. }
  31. go n.run(r)
  32. return n
  33. }
  34. func (n *Node) run(r *raft) {
  35. propc := n.propc
  36. for {
  37. if r.hasLeader() {
  38. propc = n.propc
  39. } else {
  40. // We cannot accept proposals because we don't know who
  41. // to send them to, so we'll apply back-pressure and
  42. // block senders.
  43. propc = nil
  44. }
  45. select {
  46. case p := <-propc:
  47. r.propose(p.id, p.data)
  48. case m := <-n.recvc:
  49. r.step(m)
  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. // Propose proposes data be appended to the log.
  58. func (n *Node) Propose(id int64, data []byte) error {
  59. select {
  60. case n.propc <- proposal{id, data}:
  61. return nil
  62. case <-n.ctx.Done():
  63. return n.ctx.Err()
  64. }
  65. }
  66. // Step advances the state machine using m.
  67. func (n *Node) Step(m Message) error {
  68. select {
  69. case n.recvc <- m:
  70. return nil
  71. case <-n.ctx.Done():
  72. return n.ctx.Err()
  73. }
  74. }
  75. // ReadMessages returns the current point-in-time state.
  76. func (n *Node) ReadState() (State, []Entry, []Message, error) {
  77. select {
  78. case sr := <-n.statec:
  79. return sr.state, sr.ents, sr.msgs, nil
  80. case <-n.ctx.Done():
  81. return State{}, nil, nil, n.ctx.Err()
  82. }
  83. }