2016-06-13 22:56:23 -04:00
|
|
|
package swarm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"golang.org/x/net/context"
|
|
|
|
|
|
|
|
"github.com/docker/docker/api/client"
|
|
|
|
"github.com/docker/docker/cli"
|
|
|
|
"github.com/docker/engine-api/types/swarm"
|
|
|
|
"github.com/spf13/cobra"
|
2016-06-15 17:30:54 -04:00
|
|
|
"github.com/spf13/pflag"
|
2016-06-13 22:56:23 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type initOptions struct {
|
|
|
|
listenAddr NodeAddrOption
|
|
|
|
autoAccept AutoAcceptOption
|
|
|
|
forceNewCluster bool
|
|
|
|
secret string
|
|
|
|
}
|
|
|
|
|
|
|
|
func newInitCommand(dockerCli *client.DockerCli) *cobra.Command {
|
2016-06-15 17:30:54 -04:00
|
|
|
var flags *pflag.FlagSet
|
2016-06-13 22:56:23 -04:00
|
|
|
opts := initOptions{
|
2016-06-17 15:42:16 -04:00
|
|
|
listenAddr: NewListenAddrOption(),
|
2016-06-13 22:56:23 -04:00
|
|
|
autoAccept: NewAutoAcceptOption(),
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "init",
|
2016-06-17 11:26:47 -04:00
|
|
|
Short: "Initialize a Swarm",
|
2016-06-13 22:56:23 -04:00
|
|
|
Args: cli.NoArgs,
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2016-06-15 17:30:54 -04:00
|
|
|
return runInit(dockerCli, flags, opts)
|
2016-06-13 22:56:23 -04:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2016-06-17 16:02:04 -04:00
|
|
|
flags = cmd.Flags()
|
2016-06-17 15:42:16 -04:00
|
|
|
flags.Var(&opts.listenAddr, flagListenAddr, "Listen address")
|
|
|
|
flags.Var(&opts.autoAccept, flagAutoAccept, "Auto acceptance policy (worker, manager, or none)")
|
|
|
|
flags.StringVar(&opts.secret, flagSecret, "", "Set secret value needed to accept nodes into cluster")
|
2016-06-13 22:56:23 -04:00
|
|
|
flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state.")
|
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
2016-06-15 17:30:54 -04:00
|
|
|
func runInit(dockerCli *client.DockerCli, flags *pflag.FlagSet, opts initOptions) error {
|
2016-06-13 22:56:23 -04:00
|
|
|
client := dockerCli.Client()
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
req := swarm.InitRequest{
|
|
|
|
ListenAddr: opts.listenAddr.String(),
|
|
|
|
ForceNewCluster: opts.forceNewCluster,
|
|
|
|
}
|
|
|
|
|
2016-06-15 17:30:54 -04:00
|
|
|
if flags.Changed("secret") {
|
|
|
|
req.Spec.AcceptancePolicy.Policies = opts.autoAccept.Policies(&opts.secret)
|
|
|
|
} else {
|
|
|
|
req.Spec.AcceptancePolicy.Policies = opts.autoAccept.Policies(nil)
|
|
|
|
}
|
2016-06-13 22:56:23 -04:00
|
|
|
nodeID, err := client.SwarmInit(ctx, req)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fmt.Printf("Swarm initialized: current node (%s) is now a manager.\n", nodeID)
|
|
|
|
return nil
|
|
|
|
}
|