init.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package swarm
  2. import (
  3. "fmt"
  4. "golang.org/x/net/context"
  5. "github.com/docker/docker/api/client"
  6. "github.com/docker/docker/cli"
  7. "github.com/docker/engine-api/types/swarm"
  8. "github.com/spf13/cobra"
  9. "github.com/spf13/pflag"
  10. )
  11. const (
  12. generatedSecretEntropyBytes = 16
  13. generatedSecretBase = 36
  14. // floor(log(2^128-1, 36)) + 1
  15. maxGeneratedSecretLength = 25
  16. )
  17. type initOptions struct {
  18. swarmOptions
  19. listenAddr NodeAddrOption
  20. forceNewCluster bool
  21. }
  22. func newInitCommand(dockerCli *client.DockerCli) *cobra.Command {
  23. opts := initOptions{
  24. listenAddr: NewListenAddrOption(),
  25. swarmOptions: swarmOptions{
  26. autoAccept: NewAutoAcceptOption(),
  27. },
  28. }
  29. cmd := &cobra.Command{
  30. Use: "init",
  31. Short: "Initialize a Swarm",
  32. Args: cli.NoArgs,
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. return runInit(dockerCli, cmd.Flags(), opts)
  35. },
  36. }
  37. flags := cmd.Flags()
  38. flags.Var(&opts.listenAddr, "listen-addr", "Listen address")
  39. flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state.")
  40. addSwarmFlags(flags, &opts.swarmOptions)
  41. return cmd
  42. }
  43. func runInit(dockerCli *client.DockerCli, flags *pflag.FlagSet, opts initOptions) error {
  44. client := dockerCli.Client()
  45. ctx := context.Background()
  46. // If no secret was specified, we create a random one
  47. if !flags.Changed("secret") {
  48. opts.secret = generateRandomSecret()
  49. fmt.Fprintf(dockerCli.Out(), "No --secret provided. Generated random secret:\n\t%s\n\n", opts.secret)
  50. }
  51. req := swarm.InitRequest{
  52. ListenAddr: opts.listenAddr.String(),
  53. ForceNewCluster: opts.forceNewCluster,
  54. Spec: opts.swarmOptions.ToSpec(),
  55. }
  56. nodeID, err := client.SwarmInit(ctx, req)
  57. if err != nil {
  58. return err
  59. }
  60. fmt.Fprintf(dockerCli.Out(), "Swarm initialized: current node (%s) is now a manager.\n\n", nodeID)
  61. // Fetch CAHash and Address from the API
  62. info, err := client.Info(ctx)
  63. if err != nil {
  64. return err
  65. }
  66. node, _, err := client.NodeInspectWithRaw(ctx, nodeID)
  67. if err != nil {
  68. return err
  69. }
  70. if node.ManagerStatus != nil && info.Swarm.CACertHash != "" {
  71. var secretArgs string
  72. if opts.secret != "" {
  73. secretArgs = "--secret " + opts.secret
  74. }
  75. fmt.Fprintf(dockerCli.Out(), "To add a worker to this swarm, run the following command:\n\tdocker swarm join %s \\\n\t--ca-hash %s \\\n\t%s\n", secretArgs, info.Swarm.CACertHash, node.ManagerStatus.Addr)
  76. }
  77. return nil
  78. }