init.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package swarm
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/types/swarm"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/pkg/errors"
  10. "github.com/spf13/cobra"
  11. "github.com/spf13/pflag"
  12. )
  13. type initOptions struct {
  14. swarmOptions
  15. listenAddr NodeAddrOption
  16. // Not a NodeAddrOption because it has no default port.
  17. advertiseAddr string
  18. forceNewCluster bool
  19. }
  20. func newInitCommand(dockerCli *command.DockerCli) *cobra.Command {
  21. opts := initOptions{
  22. listenAddr: NewListenAddrOption(),
  23. }
  24. cmd := &cobra.Command{
  25. Use: "init [OPTIONS]",
  26. Short: "Initialize a swarm",
  27. Args: cli.NoArgs,
  28. RunE: func(cmd *cobra.Command, args []string) error {
  29. return runInit(dockerCli, cmd.Flags(), opts)
  30. },
  31. }
  32. flags := cmd.Flags()
  33. flags.Var(&opts.listenAddr, flagListenAddr, "Listen address (format: <ip|interface>[:port])")
  34. flags.StringVar(&opts.advertiseAddr, flagAdvertiseAddr, "", "Advertised address (format: <ip|interface>[:port])")
  35. flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state")
  36. addSwarmFlags(flags, &opts.swarmOptions)
  37. return cmd
  38. }
  39. func runInit(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts initOptions) error {
  40. client := dockerCli.Client()
  41. ctx := context.Background()
  42. req := swarm.InitRequest{
  43. ListenAddr: opts.listenAddr.String(),
  44. AdvertiseAddr: opts.advertiseAddr,
  45. ForceNewCluster: opts.forceNewCluster,
  46. Spec: opts.swarmOptions.ToSpec(flags),
  47. AutoLockManagers: opts.swarmOptions.autolock,
  48. }
  49. nodeID, err := client.SwarmInit(ctx, req)
  50. if err != nil {
  51. 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") {
  52. return errors.New(err.Error() + " - specify one with --advertise-addr")
  53. }
  54. return err
  55. }
  56. fmt.Fprintf(dockerCli.Out(), "Swarm initialized: current node (%s) is now a manager.\n\n", nodeID)
  57. if err := printJoinCommand(ctx, dockerCli, nodeID, true, false); err != nil {
  58. return err
  59. }
  60. fmt.Fprint(dockerCli.Out(), "To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.\n\n")
  61. if req.AutoLockManagers {
  62. unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
  63. if err != nil {
  64. return errors.Wrap(err, "could not fetch unlock key")
  65. }
  66. printUnlockCommand(ctx, dockerCli, unlockKeyResp.UnlockKey)
  67. }
  68. return nil
  69. }