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 15package command 16 17import ( 18 "fmt" 19 "strconv" 20 21 "github.com/spf13/cobra" 22 "go.etcd.io/etcd/client/v3" 23) 24 25// NewMoveLeaderCommand returns the cobra command for "move-leader". 26func NewMoveLeaderCommand() *cobra.Command { 27 cmd := &cobra.Command{ 28 Use: "move-leader <transferee-member-id>", 29 Short: "Transfers leadership to another etcd cluster member.", 30 Run: transferLeadershipCommandFunc, 31 } 32 return cmd 33} 34 35// transferLeadershipCommandFunc executes the "compaction" command. 36func transferLeadershipCommandFunc(cmd *cobra.Command, args []string) { 37 if len(args) != 1 { 38 ExitWithError(ExitBadArgs, fmt.Errorf("move-leader command needs 1 argument")) 39 } 40 target, err := strconv.ParseUint(args[0], 16, 64) 41 if err != nil { 42 ExitWithError(ExitBadArgs, err) 43 } 44 45 c := mustClientFromCmd(cmd) 46 eps := c.Endpoints() 47 c.Close() 48 49 ctx, cancel := commandCtx(cmd) 50 51 // find current leader 52 var leaderCli *clientv3.Client 53 var leaderID uint64 54 for _, ep := range eps { 55 cfg := clientConfigFromCmd(cmd) 56 cfg.endpoints = []string{ep} 57 cli := cfg.mustClient() 58 resp, serr := cli.Status(ctx, ep) 59 if serr != nil { 60 ExitWithError(ExitError, serr) 61 } 62 63 if resp.Header.GetMemberId() == resp.Leader { 64 leaderCli = cli 65 leaderID = resp.Leader 66 break 67 } 68 cli.Close() 69 } 70 if leaderCli == nil { 71 ExitWithError(ExitBadArgs, fmt.Errorf("no leader endpoint given at %v", eps)) 72 } 73 74 var resp *clientv3.MoveLeaderResponse 75 resp, err = leaderCli.MoveLeader(ctx, target) 76 cancel() 77 if err != nil { 78 ExitWithError(ExitError, err) 79 } 80 81 display.MoveLeader(leaderID, target, *resp) 82} 83