1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00
moby--moby/cli/command/swarm/unlock_key.go
Vincent Demeester f151c297eb
Add some unit tests to the node and swarm cli code
Start work on adding unit tests to our cli code in order to have to
write less costly integration test.

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2017-01-09 18:30:15 +01:00

86 lines
2.1 KiB
Go

package swarm
import (
"fmt"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/cli"
"github.com/docker/docker/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/net/context"
)
type unlockKeyOptions struct {
rotate bool
quiet bool
}
func newUnlockKeyCommand(dockerCli command.Cli) *cobra.Command {
opts := unlockKeyOptions{}
cmd := &cobra.Command{
Use: "unlock-key [OPTIONS]",
Short: "Manage the unlock key",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runUnlockKey(dockerCli, opts)
},
}
flags := cmd.Flags()
flags.BoolVar(&opts.rotate, flagRotate, false, "Rotate unlock key")
flags.BoolVarP(&opts.quiet, flagQuiet, "q", false, "Only display token")
return cmd
}
func runUnlockKey(dockerCli command.Cli, opts unlockKeyOptions) error {
client := dockerCli.Client()
ctx := context.Background()
if opts.rotate {
flags := swarm.UpdateFlags{RotateManagerUnlockKey: true}
sw, err := client.SwarmInspect(ctx)
if err != nil {
return err
}
if !sw.Spec.EncryptionConfig.AutoLockManagers {
return errors.New("cannot rotate because autolock is not turned on")
}
if err := client.SwarmUpdate(ctx, sw.Version, sw.Spec, flags); err != nil {
return err
}
if !opts.quiet {
fmt.Fprintf(dockerCli.Out(), "Successfully rotated manager unlock key.\n\n")
}
}
unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
if err != nil {
return errors.Wrap(err, "could not fetch unlock key")
}
if unlockKeyResp.UnlockKey == "" {
return errors.New("no unlock key is set")
}
if opts.quiet {
fmt.Fprintln(dockerCli.Out(), unlockKeyResp.UnlockKey)
return nil
}
printUnlockCommand(ctx, dockerCli, unlockKeyResp.UnlockKey)
return nil
}
func printUnlockCommand(ctx context.Context, dockerCli command.Cli, unlockKey string) {
if len(unlockKey) > 0 {
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)
}
return
}