init.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. }
  26. cmd := &cobra.Command{
  27. Use: "init [OPTIONS]",
  28. Short: "Initialize a swarm",
  29. Args: cli.NoArgs,
  30. RunE: func(cmd *cobra.Command, args []string) error {
  31. return runInit(dockerCli, cmd.Flags(), opts)
  32. },
  33. }
  34. flags := cmd.Flags()
  35. flags.Var(&opts.listenAddr, "listen-addr", "Listen address")
  36. flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state.")
  37. addSwarmFlags(flags, &opts.swarmOptions)
  38. return cmd
  39. }
  40. func runInit(dockerCli *client.DockerCli, flags *pflag.FlagSet, opts initOptions) error {
  41. client := dockerCli.Client()
  42. ctx := context.Background()
  43. req := swarm.InitRequest{
  44. ListenAddr: opts.listenAddr.String(),
  45. ForceNewCluster: opts.forceNewCluster,
  46. Spec: opts.swarmOptions.ToSpec(),
  47. }
  48. nodeID, err := client.SwarmInit(ctx, req)
  49. if err != nil {
  50. return err
  51. }
  52. fmt.Fprintf(dockerCli.Out(), "Swarm initialized: current node (%s) is now a manager.\n\n", nodeID)
  53. return printJoinCommand(ctx, dockerCli, nodeID, true, true)
  54. }