remove_command.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/goraft/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. index, err := applyRemove(c, context)
  22. if err != nil {
  23. return nil, err
  24. }
  25. b := make([]byte, 8)
  26. binary.PutUvarint(b, index)
  27. return b, nil
  28. }
  29. // applyRemove removes the given machine from the cluster.
  30. func applyRemove(c *RemoveCommand, context raft.Context) (uint64, error) {
  31. ps, _ := context.Server().Context().(*PeerServer)
  32. commitIndex := context.CommitIndex()
  33. // Remove node from the shared registry.
  34. err := ps.registry.Unregister(c.Name)
  35. // Delete from stats
  36. delete(ps.followersStats.Followers, c.Name)
  37. if err != nil {
  38. log.Debugf("Error while unregistering: %s (%v)", c.Name, err)
  39. return 0, err
  40. }
  41. // Remove peer in raft
  42. if err := context.Server().RemovePeer(c.Name); err != nil {
  43. log.Debugf("Unable to remove peer: %s (%v)", c.Name, err)
  44. return 0, err
  45. }
  46. if c.Name == context.Server().Name() {
  47. // the removed node is this node
  48. // if the node is not replaying the previous logs
  49. // and the node has sent out a join request in this
  50. // start. It is sure that this node received a new remove
  51. // command and need to be removed
  52. if context.CommitIndex() > ps.joinIndex && ps.joinIndex != 0 {
  53. log.Debugf("server [%s] is removed", context.Server().Name())
  54. os.Exit(0)
  55. } else {
  56. // else ignore remove
  57. log.Debugf("ignore previous remove command.")
  58. }
  59. }
  60. return commitIndex, nil
  61. }