remove_command.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package server
  2. import (
  3. "encoding/binary"
  4. "github.com/coreos/etcd/log"
  5. "github.com/coreos/etcd/third_party/github.com/goraft/raft"
  6. )
  7. func init() {
  8. raft.RegisterCommand(&RemoveCommand{})
  9. }
  10. // The RemoveCommand removes a server from the cluster.
  11. type RemoveCommand struct {
  12. Name string `json:"name"`
  13. }
  14. // The name of the remove command in the log
  15. func (c *RemoveCommand) CommandName() string {
  16. return "etcd:remove"
  17. }
  18. // Remove a server from the cluster
  19. func (c *RemoveCommand) Apply(context raft.Context) (interface{}, error) {
  20. index, err := applyRemove(c, context)
  21. if err != nil {
  22. return nil, err
  23. }
  24. b := make([]byte, 8)
  25. binary.PutUvarint(b, index)
  26. return b, nil
  27. }
  28. // applyRemove removes the given machine from the cluster.
  29. func applyRemove(c *RemoveCommand, context raft.Context) (uint64, error) {
  30. ps, _ := context.Server().Context().(*PeerServer)
  31. commitIndex := context.CommitIndex()
  32. // Remove node from the shared registry.
  33. err := ps.registry.Unregister(c.Name)
  34. // Delete from stats
  35. delete(ps.followersStats.Followers, c.Name)
  36. if err != nil {
  37. log.Debugf("Error while unregistering: %s (%v)", c.Name, err)
  38. return 0, err
  39. }
  40. // Remove peer in raft
  41. if err := context.Server().RemovePeer(c.Name); err != nil {
  42. log.Debugf("Unable to remove peer: %s (%v)", c.Name, err)
  43. return 0, err
  44. }
  45. if c.Name == context.Server().Name() {
  46. // the removed node is this node
  47. // if the node is not replaying the previous logs
  48. // and the node has sent out a join request in this
  49. // start. It is sure that this node received a new remove
  50. // command and need to be removed
  51. if context.CommitIndex() > ps.joinIndex && ps.joinIndex != 0 {
  52. log.Debugf("server [%s] is removed", context.Server().Name())
  53. ps.asyncRemove()
  54. } else {
  55. // else ignore remove
  56. log.Debugf("ignore previous remove command.")
  57. ps.removedInLog = true
  58. }
  59. }
  60. return commitIndex, nil
  61. }