node.go 1.9 KB

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