github.com/itscaro/cli@v0.0.0-20190705081621-c9db0fe93829/cli/command/swarm/init.go (about)

     1  package swarm
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"strings"
     8  
     9  	"github.com/docker/cli/cli"
    10  	"github.com/docker/cli/cli/command"
    11  	"github.com/docker/docker/api/types/swarm"
    12  	"github.com/pkg/errors"
    13  	"github.com/spf13/cobra"
    14  	"github.com/spf13/pflag"
    15  )
    16  
    17  type initOptions struct {
    18  	swarmOptions
    19  	listenAddr NodeAddrOption
    20  	// Not a NodeAddrOption because it has no default port.
    21  	advertiseAddr             string
    22  	dataPathAddr              string
    23  	dataPathPort              uint32
    24  	forceNewCluster           bool
    25  	availability              string
    26  	defaultAddrPools          []net.IPNet
    27  	DefaultAddrPoolMaskLength uint32
    28  }
    29  
    30  func newInitCommand(dockerCli command.Cli) *cobra.Command {
    31  	opts := initOptions{
    32  		listenAddr: NewListenAddrOption(),
    33  	}
    34  
    35  	cmd := &cobra.Command{
    36  		Use:   "init [OPTIONS]",
    37  		Short: "Initialize a swarm",
    38  		Args:  cli.NoArgs,
    39  		RunE: func(cmd *cobra.Command, args []string) error {
    40  			return runInit(dockerCli, cmd.Flags(), opts)
    41  		},
    42  	}
    43  
    44  	flags := cmd.Flags()
    45  	flags.Var(&opts.listenAddr, flagListenAddr, "Listen address (format: <ip|interface>[:port])")
    46  	flags.StringVar(&opts.advertiseAddr, flagAdvertiseAddr, "", "Advertised address (format: <ip|interface>[:port])")
    47  	flags.StringVar(&opts.dataPathAddr, flagDataPathAddr, "", "Address or interface to use for data path traffic (format: <ip|interface>)")
    48  	flags.SetAnnotation(flagDataPathAddr, "version", []string{"1.31"})
    49  	flags.Uint32Var(&opts.dataPathPort, flagDataPathPort, 0, "Port number to use for data path traffic (1024 - 49151). If no value is set or is set to 0, the default port (4789) is used.")
    50  	flags.SetAnnotation(flagDataPathPort, "version", []string{"1.40"})
    51  	flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state")
    52  	flags.BoolVar(&opts.autolock, flagAutolock, false, "Enable manager autolocking (requiring an unlock key to start a stopped manager)")
    53  	flags.StringVar(&opts.availability, flagAvailability, "active", `Availability of the node ("active"|"pause"|"drain")`)
    54  	flags.IPNetSliceVar(&opts.defaultAddrPools, flagDefaultAddrPool, []net.IPNet{}, "default address pool in CIDR format")
    55  	flags.SetAnnotation(flagDefaultAddrPool, "version", []string{"1.39"})
    56  	flags.Uint32Var(&opts.DefaultAddrPoolMaskLength, flagDefaultAddrPoolMaskLength, 24, "default address pool subnet mask length")
    57  	flags.SetAnnotation(flagDefaultAddrPoolMaskLength, "version", []string{"1.39"})
    58  	addSwarmFlags(flags, &opts.swarmOptions)
    59  	return cmd
    60  }
    61  
    62  func runInit(dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) error {
    63  	var defaultAddrPool []string
    64  
    65  	client := dockerCli.Client()
    66  	ctx := context.Background()
    67  
    68  	for _, p := range opts.defaultAddrPools {
    69  		defaultAddrPool = append(defaultAddrPool, p.String())
    70  	}
    71  	req := swarm.InitRequest{
    72  		ListenAddr:       opts.listenAddr.String(),
    73  		AdvertiseAddr:    opts.advertiseAddr,
    74  		DataPathAddr:     opts.dataPathAddr,
    75  		DataPathPort:     opts.dataPathPort,
    76  		DefaultAddrPool:  defaultAddrPool,
    77  		ForceNewCluster:  opts.forceNewCluster,
    78  		Spec:             opts.swarmOptions.ToSpec(flags),
    79  		AutoLockManagers: opts.swarmOptions.autolock,
    80  		SubnetSize:       opts.DefaultAddrPoolMaskLength,
    81  	}
    82  	if flags.Changed(flagAvailability) {
    83  		availability := swarm.NodeAvailability(strings.ToLower(opts.availability))
    84  		switch availability {
    85  		case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain:
    86  			req.Availability = availability
    87  		default:
    88  			return errors.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability)
    89  		}
    90  	}
    91  
    92  	nodeID, err := client.SwarmInit(ctx, req)
    93  	if err != nil {
    94  		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") {
    95  			return errors.New(err.Error() + " - specify one with --advertise-addr")
    96  		}
    97  		return err
    98  	}
    99  
   100  	fmt.Fprintf(dockerCli.Out(), "Swarm initialized: current node (%s) is now a manager.\n\n", nodeID)
   101  
   102  	if err := printJoinCommand(ctx, dockerCli, nodeID, true, false); err != nil {
   103  		return err
   104  	}
   105  
   106  	fmt.Fprint(dockerCli.Out(), "To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.\n\n")
   107  
   108  	if req.AutoLockManagers {
   109  		unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
   110  		if err != nil {
   111  			return errors.Wrap(err, "could not fetch unlock key")
   112  		}
   113  		printUnlockCommand(dockerCli.Out(), unlockKeyResp.UnlockKey)
   114  	}
   115  
   116  	return nil
   117  }