move_leader_command.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2017 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package command
  15. import (
  16. "fmt"
  17. "strconv"
  18. "time"
  19. "github.com/coreos/etcd/clientv3"
  20. "github.com/spf13/cobra"
  21. )
  22. // NewMoveLeaderCommand returns the cobra command for "move-leader".
  23. func NewMoveLeaderCommand() *cobra.Command {
  24. cmd := &cobra.Command{
  25. Use: "move-leader <transferee-member-id>",
  26. Short: "Transfers leadership to another etcd cluster member.",
  27. Run: transferLeadershipCommandFunc,
  28. }
  29. return cmd
  30. }
  31. // transferLeadershipCommandFunc executes the "compaction" command.
  32. func transferLeadershipCommandFunc(cmd *cobra.Command, args []string) {
  33. if len(args) != 1 {
  34. ExitWithError(ExitBadArgs, fmt.Errorf("move-leader command needs 1 argument"))
  35. }
  36. target, err := strconv.ParseUint(args[0], 16, 64)
  37. if err != nil {
  38. ExitWithError(ExitBadArgs, err)
  39. }
  40. c := mustClientFromCmd(cmd)
  41. eps := c.Endpoints()
  42. c.Close()
  43. ctx, cancel := commandCtx(cmd)
  44. // find current leader
  45. var leaderCli *clientv3.Client
  46. var leaderID uint64
  47. for _, ep := range eps {
  48. cli, err := clientv3.New(clientv3.Config{
  49. Endpoints: []string{ep},
  50. DialTimeout: 3 * time.Second,
  51. })
  52. if err != nil {
  53. ExitWithError(ExitError, err)
  54. }
  55. resp, err := cli.Status(ctx, ep)
  56. if err != nil {
  57. ExitWithError(ExitError, err)
  58. }
  59. if resp.Header.GetMemberId() == resp.Leader {
  60. leaderCli = cli
  61. leaderID = resp.Leader
  62. break
  63. }
  64. cli.Close()
  65. }
  66. if leaderCli == nil {
  67. ExitWithError(ExitBadArgs, fmt.Errorf("no leader endpoint given at %v", eps))
  68. }
  69. var resp *clientv3.MoveLeaderResponse
  70. resp, err = leaderCli.MoveLeader(ctx, target)
  71. cancel()
  72. if err != nil {
  73. ExitWithError(ExitError, err)
  74. }
  75. display.MoveLeader(leaderID, target, *resp)
  76. }