remove_command.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package server
  2. import (
  3. "encoding/binary"
  4. "os"
  5. "github.com/coreos/etcd/log"
  6. "github.com/coreos/etcd/third_party/github.com/coreos/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(context raft.Context) (interface{}, error) {
  21. ps, _ := context.Server().Context().(*PeerServer)
  22. // If this is a proxy then remove it and exit.
  23. if ps.registry.ProxyExists(c.Name) {
  24. return []byte{0}, ps.registry.UnregisterProxy(c.Name)
  25. }
  26. // Remove node from the shared registry.
  27. err := ps.registry.UnregisterPeer(c.Name)
  28. // Delete from stats
  29. delete(ps.followersStats.Followers, c.Name)
  30. if err != nil {
  31. log.Debugf("Error while unregistering: %s (%v)", c.Name, err)
  32. return []byte{0}, err
  33. }
  34. // Remove peer in raft
  35. err = context.Server().RemovePeer(c.Name)
  36. if err != nil {
  37. log.Debugf("Unable to remove peer: %s (%v)", c.Name, err)
  38. return []byte{0}, err
  39. }
  40. if c.Name == context.Server().Name() {
  41. // the removed node is this node
  42. // if the node is not replaying the previous logs
  43. // and the node has sent out a join request in this
  44. // start. It is sure that this node received a new remove
  45. // command and need to be removed
  46. if context.CommitIndex() > ps.joinIndex && ps.joinIndex != 0 {
  47. log.Debugf("server [%s] is removed", context.Server().Name())
  48. os.Exit(0)
  49. } else {
  50. // else ignore remove
  51. log.Debugf("ignore previous remove command.")
  52. }
  53. }
  54. b := make([]byte, 8)
  55. binary.PutUvarint(b, context.CommitIndex())
  56. return b, err
  57. }