Skip to content

Commit

Permalink
etcdctl/ctlv3: add 'transfer-leadership'
Browse files Browse the repository at this point in the history
Signed-off-by: Gyu-Ho Lee <gyuhox@gmail.com>
  • Loading branch information
gyuho committed Jun 21, 2017
1 parent 1056e08 commit 9a7a9f4
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 0 deletions.
90 changes: 90 additions & 0 deletions e2e/ctl_v3_transfer_leadership_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright 2017 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package e2e

import (
"context"
"fmt"
"os"
"testing"
"time"

"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/pkg/testutil"
"github.com/coreos/etcd/pkg/types"
)

func TestCtlV3TransferLeadership(t *testing.T) {
defer testutil.AfterTest(t)

epc := setupEtcdctlTest(t, &configNoTLS, true)
defer func() {
if errC := epc.Close(); errC != nil {
t.Fatalf("error closing etcd processes (%v)", errC)
}
}()

var leadIdx int
var transferee uint64
for i, ep := range epc.grpcEndpoints() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{ep},
DialTimeout: 3 * time.Second,
})
if err != nil {
t.Fatal(err)
}
resp, err := cli.Status(context.Background(), ep)
if err != nil {
t.Fatal(err)
}
cli.Close()

if resp.Header.GetMemberId() == resp.Leader {
leadIdx = i
} else {
transferee = resp.Header.GetMemberId()
}
}

os.Setenv("ETCDCTL_API", "3")
defer os.Unsetenv("ETCDCTL_API")
cx := ctlCtx{
t: t,
cfg: configNoTLS,
dialTimeout: 7 * time.Second,
epc: epc,
}

tests := []struct {
prefixes []string
expect string
}{
{ // request to non-leader
cx.prefixArgs([]string{cx.epc.grpcEndpoints()[(leadIdx+1)%3]}),
"etcdserver: not a leader",
},
{ // request to leader
cx.prefixArgs([]string{cx.epc.grpcEndpoints()[leadIdx]}),
fmt.Sprintf("leader transferred to %s", types.ID(transferee)),
},
}
for i, tc := range tests {
cmdArgs := append(tc.prefixes, "transfer-leadership", types.ID(transferee).String())
if err := spawnWithExpect(cmdArgs, tc.expect); err != nil {
t.Fatalf("#%d: %v", i, err)
}
}
}
29 changes: 29 additions & 0 deletions etcdctl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,35 @@ Prints a line of JSON encoding the database hash, revision, total keys, and size
+----------+----------+------------+------------+
```

### TRANSFER-LEADERSHIP \<hexadecimal-transferee-id\>

TRANSFER-LEADERSHIP manually transfers a leadership to another node in the cluster.

#### Example

```bash
# to get leader endpoint
leader_ep=$(./etcdctl \
--endpoints localhost:12379,localhost:22379,localhost:32379 \
endpoint status | grep -m 1 "true" | awk -F', ' '{print $1}')
echo leader_ep: ${leader_ep}

# to choose transferee
transferee_id=$(./etcdctl \
--endpoints localhost:12379,localhost:22379,localhost:32379 \
endpoint status | grep -m 1 "false" | awk -F', ' '{print $2}')
echo ${transferee_id}
# c89feb932daef420

# request to follower should fail
./etcdctl --endpoints ${transferee_ep} transfer-leadership ${transferee_id}
# Error: etcdserver: not a leader

# request to leader with follower node ID
./etcdctl --endpoints ${leader_ep} transfer-leadership ${transferee_id}
# leader transferred to c89feb932daef420
```

## Concurrency commands

### LOCK \<lockname\> [command arg1 arg2 ...]
Expand Down
55 changes: 55 additions & 0 deletions etcdctl/ctlv3/command/transfer_leadership_command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2017 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package command

import (
"fmt"
"strconv"

"github.com/coreos/etcd/pkg/types"
"github.com/spf13/cobra"
)

// NewTransferLeadershipCommand returns the cobra command for "transfer-leadership".
func NewTransferLeadershipCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "transfer-leadership <transferee>",
Short: "Transfers leadership.",
Run: transferLeadershipCommandFunc,
}
return cmd
}

// transferLeadershipCommandFunc executes the "compaction" command.
func transferLeadershipCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("transfer-leadership command needs 1 argument"))
}

transferee, err := strconv.ParseUint(args[0], 16, 64)
if err != nil {
ExitWithError(ExitError, err)
}

c := mustClientFromCmd(cmd)
ctx, cancel := commandCtx(cmd)
cerr := c.TransferLeadership(ctx, transferee)
cancel()
if cerr != nil {
ExitWithError(ExitError, cerr)
return
}
fmt.Printf("leader transferred to %s\n", types.ID(transferee))
}
1 change: 1 addition & 0 deletions etcdctl/ctlv3/ctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ func init() {
command.NewUserCommand(),
command.NewRoleCommand(),
command.NewCheckCommand(),
command.NewTransferLeadershipCommand(),
)
}

Expand Down

0 comments on commit 9a7a9f4

Please sign in to comment.