unlock.go 1.6 KB

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