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