unlock_key.go 2.0 KB

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