remove_command.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package server
  2. import (
  3. "encoding/binary"
  4. "path"
  5. "github.com/coreos/etcd/store"
  6. "github.com/coreos/go-raft"
  7. )
  8. func init() {
  9. raft.RegisterCommand(&RemoveCommand{})
  10. }
  11. // The RemoveCommand removes a server from the cluster.
  12. type RemoveCommand struct {
  13. Name string `json:"name"`
  14. }
  15. // The name of the remove command in the log
  16. func (c *RemoveCommand) CommandName() string {
  17. return "etcd:remove"
  18. }
  19. // Remove a server from the cluster
  20. func (c *RemoveCommand) Apply(server *raft.Server) (interface{}, error) {
  21. s, _ := server.StateMachine().(*store.Store)
  22. ps, _ := server.Context().(*PeerServer)
  23. // Remove node from the shared registry.
  24. err := ps.registry.Unregister(c.Name, server.CommitIndex(), server.Term())
  25. // Delete from stats
  26. delete(ps.followersStats.Followers, c.Name)
  27. if err != nil {
  28. return []byte{0}, err
  29. }
  30. // Remove peer in raft
  31. err = server.RemovePeer(c.Name)
  32. if err != nil {
  33. return []byte{0}, err
  34. }
  35. if c.Name == server.Name() {
  36. // the removed node is this node
  37. // if the node is not replaying the previous logs
  38. // and the node has sent out a join request in this
  39. // start. It is sure that this node received a new remove
  40. // command and need to be removed
  41. if server.CommitIndex() > ps.joinIndex && ps.joinIndex != 0 {
  42. debugf("server [%s] is removed", server.Name())
  43. os.Exit(0)
  44. } else {
  45. // else ignore remove
  46. debugf("ignore previous remove command.")
  47. }
  48. }
  49. b := make([]byte, 8)
  50. binary.PutUvarint(b, server.CommitIndex())
  51. return b, err
  52. }