demote_command.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package server
  2. import (
  3. "fmt"
  4. "github.com/coreos/etcd/log"
  5. "github.com/coreos/etcd/third_party/github.com/goraft/raft"
  6. )
  7. func init() {
  8. raft.RegisterCommand(&DemoteCommand{})
  9. }
  10. // DemoteCommand represents a command to change a peer to a proxy.
  11. type DemoteCommand struct {
  12. Name string `json:"name"`
  13. }
  14. // CommandName returns the name of the command.
  15. func (c *DemoteCommand) CommandName() string {
  16. return "etcd:demote"
  17. }
  18. // Apply executes the command.
  19. func (c *DemoteCommand) Apply(context raft.Context) (interface{}, error) {
  20. ps, _ := context.Server().Context().(*PeerServer)
  21. // Ignore this command if there is no peer.
  22. if !ps.registry.PeerExists(c.Name) {
  23. return nil, fmt.Errorf("peer does not exist: %s", c.Name)
  24. }
  25. // Save URLs.
  26. clientURL, _ := ps.registry.ClientURL(c.Name)
  27. peerURL, _ := ps.registry.PeerURL(c.Name)
  28. // Remove node from the shared registry.
  29. err := ps.registry.UnregisterPeer(c.Name)
  30. if err != nil {
  31. log.Debugf("Demote peer %s: Error while unregistering (%v)", c.Name, err)
  32. return nil, err
  33. }
  34. // Delete from stats
  35. delete(ps.followersStats.Followers, c.Name)
  36. // Remove peer in raft
  37. err = context.Server().RemovePeer(c.Name)
  38. if err != nil {
  39. log.Debugf("Demote peer %s: (%v)", c.Name, err)
  40. return nil, err
  41. }
  42. // Register node as a proxy.
  43. ps.registry.RegisterProxy(c.Name, peerURL, clientURL)
  44. // Update mode if this change applies to this server.
  45. if c.Name == ps.Config.Name {
  46. log.Infof("Demote peer %s: Set mode to proxy with %s", c.Name, ps.server.Leader())
  47. ps.proxyPeerURL, _ = ps.registry.PeerURL(ps.server.Leader())
  48. go ps.setMode(ProxyMode)
  49. }
  50. return nil, nil
  51. }
  52. // NodeName returns the name of the affected node.
  53. func (c *DemoteCommand) NodeName() string {
  54. return c.Name
  55. }