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