join_command.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package server
  2. import (
  3. "encoding/binary"
  4. etcdErr "github.com/coreos/etcd/error"
  5. "github.com/coreos/etcd/log"
  6. "github.com/coreos/go-raft"
  7. )
  8. func init() {
  9. raft.RegisterCommand(&JoinCommand{})
  10. }
  11. // The JoinCommand adds a node to the cluster.
  12. type JoinCommand struct {
  13. MinVersion int `json:"minVersion"`
  14. MaxVersion int `json:"maxVersion"`
  15. Name string `json:"name"`
  16. RaftURL string `json:"raftURL"`
  17. EtcdURL string `json:"etcdURL"`
  18. }
  19. func NewJoinCommand(minVersion int, maxVersion int, name, raftUrl, etcdUrl string) *JoinCommand {
  20. return &JoinCommand{
  21. MinVersion: minVersion,
  22. MaxVersion: maxVersion,
  23. Name: name,
  24. RaftURL: raftUrl,
  25. EtcdURL: etcdUrl,
  26. }
  27. }
  28. // The name of the join command in the log
  29. func (c *JoinCommand) CommandName() string {
  30. return "etcd:join"
  31. }
  32. // Join a server to the cluster
  33. func (c *JoinCommand) Apply(server raft.Server) (interface{}, error) {
  34. ps, _ := server.Context().(*PeerServer)
  35. b := make([]byte, 8)
  36. binary.PutUvarint(b, server.CommitIndex())
  37. // Make sure we're not getting a cached value from the registry.
  38. ps.registry.Invalidate(c.Name)
  39. // Check if the join command is from a previous peer, who lost all its previous log.
  40. if _, ok := ps.registry.ClientURL(c.Name); ok {
  41. return b, nil
  42. }
  43. // Check peer number in the cluster
  44. if ps.registry.Count() == ps.MaxClusterSize {
  45. log.Debug("Reject join request from ", c.Name)
  46. return []byte{0}, etcdErr.NewError(etcdErr.EcodeNoMorePeer, "", server.CommitIndex())
  47. }
  48. // Add to shared peer registry.
  49. ps.registry.Register(c.Name, c.RaftURL, c.EtcdURL)
  50. // Add peer in raft
  51. err := server.AddPeer(c.Name, "")
  52. // Add peer stats
  53. if c.Name != ps.RaftServer().Name() {
  54. ps.followersStats.Followers[c.Name] = &raftFollowerStats{}
  55. ps.followersStats.Followers[c.Name].Latency.Minimum = 1 << 63
  56. }
  57. return b, err
  58. }
  59. func (c *JoinCommand) NodeName() string {
  60. return c.Name
  61. }