github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/cli/command/swarm/unlock_key.go (about) 1 package swarm 2 3 import ( 4 "fmt" 5 6 "github.com/docker/docker/api/types/swarm" 7 "github.com/docker/docker/cli" 8 "github.com/docker/docker/cli/command" 9 "github.com/pkg/errors" 10 "github.com/spf13/cobra" 11 "golang.org/x/net/context" 12 ) 13 14 type unlockKeyOptions struct { 15 rotate bool 16 quiet bool 17 } 18 19 func newUnlockKeyCommand(dockerCli command.Cli) *cobra.Command { 20 opts := unlockKeyOptions{} 21 22 cmd := &cobra.Command{ 23 Use: "unlock-key [OPTIONS]", 24 Short: "Manage the unlock key", 25 Args: cli.NoArgs, 26 RunE: func(cmd *cobra.Command, args []string) error { 27 return runUnlockKey(dockerCli, opts) 28 }, 29 } 30 31 flags := cmd.Flags() 32 flags.BoolVar(&opts.rotate, flagRotate, false, "Rotate unlock key") 33 flags.BoolVarP(&opts.quiet, flagQuiet, "q", false, "Only display token") 34 35 return cmd 36 } 37 38 func runUnlockKey(dockerCli command.Cli, opts unlockKeyOptions) error { 39 client := dockerCli.Client() 40 ctx := context.Background() 41 42 if opts.rotate { 43 flags := swarm.UpdateFlags{RotateManagerUnlockKey: true} 44 45 sw, err := client.SwarmInspect(ctx) 46 if err != nil { 47 return err 48 } 49 50 if !sw.Spec.EncryptionConfig.AutoLockManagers { 51 return errors.New("cannot rotate because autolock is not turned on") 52 } 53 54 if err := client.SwarmUpdate(ctx, sw.Version, sw.Spec, flags); err != nil { 55 return err 56 } 57 58 if !opts.quiet { 59 fmt.Fprintf(dockerCli.Out(), "Successfully rotated manager unlock key.\n\n") 60 } 61 } 62 63 unlockKeyResp, err := client.SwarmGetUnlockKey(ctx) 64 if err != nil { 65 return errors.Wrap(err, "could not fetch unlock key") 66 } 67 68 if unlockKeyResp.UnlockKey == "" { 69 return errors.New("no unlock key is set") 70 } 71 72 if opts.quiet { 73 fmt.Fprintln(dockerCli.Out(), unlockKeyResp.UnlockKey) 74 return nil 75 } 76 77 printUnlockCommand(ctx, dockerCli, unlockKeyResp.UnlockKey) 78 return nil 79 } 80 81 func printUnlockCommand(ctx context.Context, dockerCli command.Cli, unlockKey string) { 82 if len(unlockKey) > 0 { 83 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) 84 } 85 return 86 }