unlock_key.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package swarm
  2. import (
  3. "fmt"
  4. "github.com/docker/docker/api/types/swarm"
  5. "github.com/docker/docker/cli"
  6. "github.com/docker/docker/cli/command"
  7. "github.com/pkg/errors"
  8. "github.com/spf13/cobra"
  9. "golang.org/x/net/context"
  10. )
  11. type unlockKeyOptions struct {
  12. rotate bool
  13. quiet bool
  14. }
  15. func newUnlockKeyCommand(dockerCli command.Cli) *cobra.Command {
  16. opts := unlockKeyOptions{}
  17. cmd := &cobra.Command{
  18. Use: "unlock-key [OPTIONS]",
  19. Short: "Manage the unlock key",
  20. Args: cli.NoArgs,
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. return runUnlockKey(dockerCli, opts)
  23. },
  24. }
  25. flags := cmd.Flags()
  26. flags.BoolVar(&opts.rotate, flagRotate, false, "Rotate unlock key")
  27. flags.BoolVarP(&opts.quiet, flagQuiet, "q", false, "Only display token")
  28. return cmd
  29. }
  30. func runUnlockKey(dockerCli command.Cli, opts unlockKeyOptions) error {
  31. client := dockerCli.Client()
  32. ctx := context.Background()
  33. if opts.rotate {
  34. flags := swarm.UpdateFlags{RotateManagerUnlockKey: true}
  35. sw, err := client.SwarmInspect(ctx)
  36. if err != nil {
  37. return err
  38. }
  39. if !sw.Spec.EncryptionConfig.AutoLockManagers {
  40. return errors.New("cannot rotate because autolock is not turned on")
  41. }
  42. if err := client.SwarmUpdate(ctx, sw.Version, sw.Spec, flags); err != nil {
  43. return err
  44. }
  45. if !opts.quiet {
  46. fmt.Fprintf(dockerCli.Out(), "Successfully rotated manager unlock key.\n\n")
  47. }
  48. }
  49. unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
  50. if err != nil {
  51. return errors.Wrap(err, "could not fetch unlock key")
  52. }
  53. if unlockKeyResp.UnlockKey == "" {
  54. return errors.New("no unlock key is set")
  55. }
  56. if opts.quiet {
  57. fmt.Fprintln(dockerCli.Out(), unlockKeyResp.UnlockKey)
  58. return nil
  59. }
  60. printUnlockCommand(ctx, dockerCli, unlockKeyResp.UnlockKey)
  61. return nil
  62. }
  63. func printUnlockCommand(ctx context.Context, dockerCli command.Cli, unlockKey string) {
  64. if len(unlockKey) > 0 {
  65. fmt.Fprintf(dockerCli.Out(), "To unlock a swarm manager after it restarts, run the `docker swarm unlock`\ncommand and provide the following key:\n\n %s\n\nPlease remember to store this key in a password manager, since without it you\nwill not be able to restart the manager.\n", unlockKey)
  66. }
  67. return
  68. }