DockerCLI/cli/command/swarm/init.go

122 lines
4.7 KiB
Go
Raw Normal View History

package swarm
import (
"context"
"fmt"
"net"
"strings"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/docker/api/types/swarm"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type initOptions struct {
swarmOptions
listenAddr NodeAddrOption
// Not a NodeAddrOption because it has no default port.
advertiseAddr string
dataPathAddr string
dataPathPort uint32
forceNewCluster bool
availability string
defaultAddrPools []net.IPNet
DefaultAddrPoolMaskLength uint32
}
func newInitCommand(dockerCli command.Cli) *cobra.Command {
opts := initOptions{
listenAddr: NewListenAddrOption(),
}
cmd := &cobra.Command{
Use: "init [OPTIONS]",
Short: "Initialize a swarm",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runInit(cmd.Context(), dockerCli, cmd.Flags(), opts)
},
Annotations: map[string]string{
"version": "1.24",
"swarm": "", // swarm init does not require swarm to be active, and is always available on API 1.24 and up
},
ValidArgsFunction: completion.NoComplete,
}
flags := cmd.Flags()
flags.Var(&opts.listenAddr, flagListenAddr, `Listen address (format: "<ip|interface>[:port]")`)
flags.StringVar(&opts.advertiseAddr, flagAdvertiseAddr, "", `Advertised address (format: "<ip|interface>[:port]")`)
flags.StringVar(&opts.dataPathAddr, flagDataPathAddr, "", `Address or interface to use for data path traffic (format: "<ip|interface>")`)
flags.SetAnnotation(flagDataPathAddr, "version", []string{"1.31"})
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.")
flags.SetAnnotation(flagDataPathPort, "version", []string{"1.40"})
flags.BoolVar(&opts.forceNewCluster, "force-new-cluster", false, "Force create a new cluster from current state")
flags.BoolVar(&opts.autolock, flagAutolock, false, "Enable manager autolocking (requiring an unlock key to start a stopped manager)")
flags.StringVar(&opts.availability, flagAvailability, "active", `Availability of the node ("active", "pause", "drain")`)
flags.Var(newIPNetSliceValue([]net.IPNet{}, &opts.defaultAddrPools), flagDefaultAddrPool, "default address pool in CIDR format")
flags.SetAnnotation(flagDefaultAddrPool, "version", []string{"1.39"})
flags.Uint32Var(&opts.DefaultAddrPoolMaskLength, flagDefaultAddrPoolMaskLength, 24, "default address pool subnet mask length")
flags.SetAnnotation(flagDefaultAddrPoolMaskLength, "version", []string{"1.39"})
addSwarmFlags(flags, &opts.swarmOptions)
return cmd
}
func runInit(ctx context.Context, dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) error {
client := dockerCli.Client()
linting: Consider pre-allocating sliceVar (prealloc) While updating, also addressed some redundant fmt.Sprintf() opts/throttledevice.go:86:2: Consider pre-allocating `out` (prealloc) var out []string ^ opts/ulimit.go:37:2: Consider pre-allocating `out` (prealloc) var out []string ^ opts/ulimit.go:47:2: Consider pre-allocating `ulimits` (prealloc) var ulimits []*units.Ulimit ^ opts/weightdevice.go:68:2: Consider pre-allocating `out` (prealloc) var out []string ^ cli/context/store/metadatastore.go:96:2: Consider pre-allocating `res` (prealloc) var res []Metadata ^ cli/context/store/store.go:127:2: Consider pre-allocating `names` (prealloc) var names []string ^ cli/compose/loader/loader.go:223:2: Consider pre-allocating `keys` (prealloc) var keys []string ^ cli/compose/loader/loader.go:397:2: Consider pre-allocating `services` (prealloc) var services []types.ServiceConfig ^ cli/command/stack/loader/loader.go:63:2: Consider pre-allocating `msgs` (prealloc) var msgs []string ^ cli/command/stack/loader/loader.go:118:2: Consider pre-allocating `configFiles` (prealloc) var configFiles []composetypes.ConfigFile ^ cli/command/formatter/container.go:245:2: Consider pre-allocating `joinLabels` (prealloc) var joinLabels []string ^ cli/command/formatter/container.go:265:2: Consider pre-allocating `mounts` (prealloc) var mounts []string ^ cli/command/formatter/container.go:316:2: Consider pre-allocating `result` (prealloc) var result []string ^ cli/command/formatter/displayutils.go:43:2: Consider pre-allocating `display` (prealloc) var ( ^ cli/command/formatter/volume.go:103:2: Consider pre-allocating `joinLabels` (prealloc) var joinLabels []string ^ cli-plugins/manager/manager_test.go:49:2: Consider pre-allocating `dirs` (prealloc) var dirs []string ^ cli/command/swarm/init.go:69:2: Consider pre-allocating `defaultAddrPool` (prealloc) var defaultAddrPool []string ^ cli/command/manifest/push.go:195:2: Consider pre-allocating `blobReqs` (prealloc) var blobReqs []manifestBlob ^ cli/command/secret/formatter.go:111:2: Consider pre-allocating `joinLabels` (prealloc) var joinLabels []string ^ cli/command/network/formatter.go:104:2: Consider pre-allocating `joinLabels` (prealloc) var joinLabels []string ^ cli/command/context/list.go:52:2: Consider pre-allocating `contexts` (prealloc) var contexts []*formatter.ClientContext ^ cli/command/config/formatter.go:104:2: Consider pre-allocating `joinLabels` (prealloc) var joinLabels []string ^ cli/command/trust/common_test.go:23:2: Consider pre-allocating `targetNames` (prealloc) var targetNames []string ^ cli/command/service/generic_resource_opts.go:55:2: Consider pre-allocating `generic` (prealloc) var generic []swarm.GenericResource ^ cli/command/service/generic_resource_opts.go:98:2: Consider pre-allocating `l` (prealloc) var l []swarm.GenericResource ^ cli/command/service/opts.go:378:2: Consider pre-allocating `netAttach` (prealloc) var netAttach []swarm.NetworkAttachmentConfig ^ cli/command/service/update.go:731:2: Consider pre-allocating `limits` (prealloc) var limits []*units.Ulimit ^ cli/command/service/update.go:1315:2: Consider pre-allocating `newNetworks` (prealloc) var newNetworks []swarm.NetworkAttachmentConfig ^ cli/command/service/update.go:1514:2: Consider pre-allocating `out` (prealloc) var out []string ^ cli/compose/convert/service.go:713:2: Consider pre-allocating `ulimits` (prealloc) var ulimits []*units.Ulimit ^ cli/compose/convert/volume.go:13:2: Consider pre-allocating `mounts` (prealloc) var mounts []mount.Mount ^ cli/command/stack/swarm/list.go:39:2: Consider pre-allocating `stacks` (prealloc) var stacks []*formatter.Stack ^ Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-09-03 14:07:29 -04:00
defaultAddrPool := make([]string, 0, len(opts.defaultAddrPools))
for _, p := range opts.defaultAddrPools {
defaultAddrPool = append(defaultAddrPool, p.String())
}
req := swarm.InitRequest{
ListenAddr: opts.listenAddr.String(),
AdvertiseAddr: opts.advertiseAddr,
DataPathAddr: opts.dataPathAddr,
DataPathPort: opts.dataPathPort,
DefaultAddrPool: defaultAddrPool,
ForceNewCluster: opts.forceNewCluster,
Spec: opts.swarmOptions.ToSpec(flags),
AutoLockManagers: opts.swarmOptions.autolock,
SubnetSize: opts.DefaultAddrPoolMaskLength,
}
if flags.Changed(flagAvailability) {
availability := swarm.NodeAvailability(strings.ToLower(opts.availability))
switch availability {
case swarm.NodeAvailabilityActive, swarm.NodeAvailabilityPause, swarm.NodeAvailabilityDrain:
req.Availability = availability
default:
return errors.Errorf("invalid availability %q, only active, pause and drain are supported", opts.availability)
}
}
nodeID, err := client.SwarmInit(ctx, req)
if err != nil {
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") {
return errors.New(err.Error() + " - specify one with --advertise-addr")
}
return err
}
fmt.Fprintf(dockerCli.Out(), "Swarm initialized: current node (%s) is now a manager.\n\n", nodeID)
if err := printJoinCommand(ctx, dockerCli, nodeID, true, false); err != nil {
return err
}
fmt.Fprint(dockerCli.Out(), "To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.\n\n")
if req.AutoLockManagers {
unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
if err != nil {
return errors.Wrap(err, "could not fetch unlock key")
}
printUnlockCommand(dockerCli.Out(), unlockKeyResp.UnlockKey)
}
return nil
}