func runInit(dockerCli command.Cli, flags *pflag.FlagSet, opts initOptions) error { client := dockerCli.Client() ctx := context.Background() req := swarm.InitRequest{ ListenAddr: opts.listenAddr.String(), AdvertiseAddr: opts.advertiseAddr, ForceNewCluster: opts.forceNewCluster, Spec: opts.swarmOptions.ToSpec(flags), AutoLockManagers: opts.swarmOptions.autolock, } 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 fmt.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, false, true); 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(ctx, dockerCli, unlockKeyResp.UnlockKey) } return nil }
// Init initializes a new swarm cluster. func (d *SwarmDaemon) Init(req swarm.InitRequest) error { if req.ListenAddr == "" { req.ListenAddr = d.listenAddr } status, out, err := d.SockRequest("POST", "/swarm/init", req) if status != http.StatusOK { return fmt.Errorf("initializing swarm: invalid statuscode %v, %q", status, out) } if err != nil { return fmt.Errorf("initializing swarm: %v", err) } info, err := d.info() if err != nil { return err } d.Info = info return nil }