remove_command.go 1.4 KB

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