forked from docker/cli
-
Notifications
You must be signed in to change notification settings - Fork 8
/
unlock.go
75 lines (65 loc) · 1.59 KB
/
unlock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package swarm
import (
"bufio"
"context"
"fmt"
"io"
"strings"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/streams"
"github.com/docker/docker/api/types/swarm"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/term"
)
func newUnlockCommand(dockerCli command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "unlock",
Short: "Unlock swarm",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runUnlock(dockerCli)
},
}
return cmd
}
func runUnlock(dockerCli command.Cli) error {
client := dockerCli.Client()
ctx := context.Background()
// First see if the node is actually part of a swarm, and if it is actually locked first.
// If it's in any other state than locked, don't ask for the key.
info, err := client.Info(ctx)
if err != nil {
return err
}
switch info.Swarm.LocalNodeState {
case swarm.LocalNodeStateInactive:
return errors.New("Error: This node is not part of a swarm")
case swarm.LocalNodeStateLocked:
break
default:
return errors.New("Error: swarm is not locked")
}
key, err := readKey(dockerCli.In(), "Please enter unlock key: ")
if err != nil {
return err
}
req := swarm.UnlockRequest{
UnlockKey: key,
}
return client.SwarmUnlock(ctx, req)
}
func readKey(in *streams.In, prompt string) (string, error) {
if in.IsTerminal() {
fmt.Print(prompt)
dt, err := term.ReadPassword(int(in.FD()))
fmt.Println()
return string(dt), err
}
key, err := bufio.NewReader(in).ReadString('\n')
if err == io.EOF {
err = nil
}
return strings.TrimSpace(key), err
}