init.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. package swarm
  2. import (
  3. "bufio"
  4. "crypto/rand"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/big"
  9. "strings"
  10. "golang.org/x/crypto/ssh/terminal"
  11. "golang.org/x/net/context"
  12. "github.com/docker/docker/api/types/swarm"
  13. "github.com/docker/docker/cli"
  14. "github.com/docker/docker/cli/command"
  15. "github.com/spf13/cobra"
  16. "github.com/spf13/pflag"
  17. )
  18. type initOptions struct {
  19. swarmOptions
  20. listenAddr NodeAddrOption
  21. // Not a NodeAddrOption because it has no default port.
  22. advertiseAddr string
  23. forceNewCluster bool
  24. lockKey bool
  25. }
  26. func newInitCommand(dockerCli *command.DockerCli) *cobra.Command {
  27. opts := initOptions{
  28. listenAddr: NewListenAddrOption(),
  29. }
  30. cmd := &cobra.Command{
  31. Use: "init [OPTIONS]",
  32. Short: "Initialize a swarm",
  33. Args: cli.NoArgs,
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. return runInit(dockerCli, cmd.Flags(), opts)
  36. },
  37. }
  38. flags := cmd.Flags()
  39. flags.Var(&opts.listenAddr, flagListenAddr, "Listen address (format: <ip|interface>[:port])")
  40. flags.StringVar(&opts.advertiseAddr, flagAdvertiseAddr, "", "Advertised address (format: <ip|interface>[:port])")
  41. flags.BoolVar(&opts.lockKey, flagLockKey, false, "Encrypt swarm with optionally provided key from stdin")
  42. flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state")
  43. addSwarmFlags(flags, &opts.swarmOptions)
  44. return cmd
  45. }
  46. func runInit(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts initOptions) error {
  47. client := dockerCli.Client()
  48. ctx := context.Background()
  49. var lockKey string
  50. if opts.lockKey {
  51. var err error
  52. lockKey, err = readKey(dockerCli.In(), "Please enter key for encrypting swarm(leave empty to generate): ")
  53. if err != nil {
  54. return err
  55. }
  56. if len(lockKey) == 0 {
  57. randBytes := make([]byte, 16)
  58. if _, err := rand.Read(randBytes[:]); err != nil {
  59. panic(fmt.Errorf("failed to general random lock key: %v", err))
  60. }
  61. var n big.Int
  62. n.SetBytes(randBytes[:])
  63. lockKey = n.Text(36)
  64. }
  65. }
  66. req := swarm.InitRequest{
  67. ListenAddr: opts.listenAddr.String(),
  68. AdvertiseAddr: opts.advertiseAddr,
  69. ForceNewCluster: opts.forceNewCluster,
  70. Spec: opts.swarmOptions.ToSpec(flags),
  71. LockKey: lockKey,
  72. }
  73. nodeID, err := client.SwarmInit(ctx, req)
  74. if err != nil {
  75. if strings.Contains(err.Error(), "could not choose an IP address to advertise") || strings.Contains(err.Error(), "could not find the system's IP address") {
  76. return errors.New(err.Error() + " - specify one with --advertise-addr")
  77. }
  78. return err
  79. }
  80. fmt.Fprintf(dockerCli.Out(), "Swarm initialized: current node (%s) is now a manager.\n\n", nodeID)
  81. if len(lockKey) > 0 {
  82. fmt.Fprintf(dockerCli.Out(), "Swarm is encrypted. When a node is restarted it needs to be unlocked by running command:\n\n echo '%s' | docker swarm unlock\n\n", lockKey)
  83. }
  84. if err := printJoinCommand(ctx, dockerCli, nodeID, true, false); err != nil {
  85. return err
  86. }
  87. fmt.Fprint(dockerCli.Out(), "To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.\n\n")
  88. return nil
  89. }
  90. func readKey(in *command.InStream, prompt string) (string, error) {
  91. if in.IsTerminal() {
  92. fmt.Print(prompt)
  93. dt, err := terminal.ReadPassword(int(in.FD()))
  94. fmt.Println()
  95. return string(dt), err
  96. } else {
  97. key, err := bufio.NewReader(in).ReadString('\n')
  98. if err == io.EOF {
  99. err = nil
  100. }
  101. return strings.TrimSpace(key), err
  102. }
  103. }