2016-10-27 21:50:49 -04:00
package swarm
import (
"fmt"
2017-04-17 18:07:56 -04:00
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
2016-10-28 19:35:49 -04:00
"github.com/docker/docker/api/types/swarm"
2016-10-27 21:50:49 -04:00
"github.com/pkg/errors"
2016-12-25 16:23:35 -05:00
"github.com/spf13/cobra"
2016-10-27 21:50:49 -04:00
"golang.org/x/net/context"
)
2016-11-21 05:22:22 -05:00
type unlockKeyOptions struct {
rotate bool
quiet bool
}
2016-12-25 16:23:35 -05:00
func newUnlockKeyCommand ( dockerCli command . Cli ) * cobra . Command {
2016-11-21 05:22:22 -05:00
opts := unlockKeyOptions { }
2016-10-27 21:50:49 -04:00
cmd := & cobra . Command {
Use : "unlock-key [OPTIONS]" ,
Short : "Manage the unlock key" ,
Args : cli . NoArgs ,
RunE : func ( cmd * cobra . Command , args [ ] string ) error {
2016-11-21 05:22:22 -05:00
return runUnlockKey ( dockerCli , opts )
2016-10-27 21:50:49 -04:00
} ,
}
flags := cmd . Flags ( )
2016-11-21 05:22:22 -05:00
flags . BoolVar ( & opts . rotate , flagRotate , false , "Rotate unlock key" )
flags . BoolVarP ( & opts . quiet , flagQuiet , "q" , false , "Only display token" )
2016-10-27 21:50:49 -04:00
return cmd
}
2016-12-25 16:23:35 -05:00
func runUnlockKey ( dockerCli command . Cli , opts unlockKeyOptions ) error {
2016-11-21 05:22:22 -05:00
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
2016-10-27 21:50:49 -04:00
}
2016-11-21 05:22:22 -05:00
printUnlockCommand ( ctx , dockerCli , unlockKeyResp . UnlockKey )
return nil
}
2016-12-25 16:23:35 -05:00
func printUnlockCommand ( ctx context . Context , dockerCli command . Cli , unlockKey string ) {
2016-11-21 05:22:22 -05:00
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 )
}
2016-10-27 21:50:49 -04:00
return
}