remove_command.go 1.5 KB

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