remove_command.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // +build ignore
  2. package server
  3. import (
  4. "encoding/binary"
  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. ps.asyncRemove()
  55. } else {
  56. // else ignore remove
  57. log.Debugf("ignore previous remove command.")
  58. ps.removedInLog = true
  59. }
  60. }
  61. return commitIndex, nil
  62. }