node.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. // TODO(bmizerany): move to raft.go or log.go by removing the
  44. // idea "unstable" in those files. Callers of ReadState can
  45. // determine what is committed by comparing State.Commit to
  46. // each Entry.Index. This will also avoid this horrible copy
  47. // and alloc.
  48. ents := append(r.raftLog.nextEnts(), r.raftLog.unstableEnts()...)
  49. select {
  50. case p := <-propc:
  51. r.propose(p)
  52. case m := <-n.recvc:
  53. r.Step(m) // raft never returns an error
  54. case <-n.tickc:
  55. // r.tick()
  56. case n.statec <- stateResp{r.State, ents, r.msgs}:
  57. r.raftLog.resetNextEnts()
  58. r.raftLog.resetUnstable()
  59. r.msgs = nil
  60. case <-n.ctx.Done():
  61. return
  62. }
  63. }
  64. }
  65. func (n *Node) Tick() error {
  66. select {
  67. case n.tickc <- struct{}{}:
  68. return nil
  69. case <-n.ctx.Done():
  70. return n.ctx.Err()
  71. }
  72. }
  73. // Propose proposes data be appended to the log.
  74. func (n *Node) Propose(data []byte) error {
  75. select {
  76. case n.propc <- data:
  77. return nil
  78. case <-n.ctx.Done():
  79. return n.ctx.Err()
  80. }
  81. }
  82. // Step advances the state machine using m.
  83. func (n *Node) Step(m Message) error {
  84. select {
  85. case n.recvc <- m:
  86. return nil
  87. case <-n.ctx.Done():
  88. return n.ctx.Err()
  89. }
  90. }
  91. // ReadState returns the current point-in-time state.
  92. func (n *Node) ReadState() (State, []Entry, []Message, error) {
  93. select {
  94. case sr := <-n.statec:
  95. return sr.state, sr.ents, sr.msgs, nil
  96. case <-n.ctx.Done():
  97. return State{}, nil, nil, n.ctx.Err()
  98. }
  99. }