github.com/kunnos/engine@v1.13.1/cli/command/swarm/join.go (about)

     1  package swarm
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/docker/docker/api/types/swarm"
     7  	"github.com/docker/docker/cli"
     8  	"github.com/docker/docker/cli/command"
     9  	"github.com/spf13/cobra"
    10  	"golang.org/x/net/context"
    11  )
    12  
    13  type joinOptions struct {
    14  	remote     string
    15  	listenAddr NodeAddrOption
    16  	// Not a NodeAddrOption because it has no default port.
    17  	advertiseAddr string
    18  	token         string
    19  }
    20  
    21  func newJoinCommand(dockerCli *command.DockerCli) *cobra.Command {
    22  	opts := joinOptions{
    23  		listenAddr: NewListenAddrOption(),
    24  	}
    25  
    26  	cmd := &cobra.Command{
    27  		Use:   "join [OPTIONS] HOST:PORT",
    28  		Short: "Join a swarm as a node and/or manager",
    29  		Args:  cli.ExactArgs(1),
    30  		RunE: func(cmd *cobra.Command, args []string) error {
    31  			opts.remote = args[0]
    32  			return runJoin(dockerCli, opts)
    33  		},
    34  	}
    35  
    36  	flags := cmd.Flags()
    37  	flags.Var(&opts.listenAddr, flagListenAddr, "Listen address (format: <ip|interface>[:port])")
    38  	flags.StringVar(&opts.advertiseAddr, flagAdvertiseAddr, "", "Advertised address (format: <ip|interface>[:port])")
    39  	flags.StringVar(&opts.token, flagToken, "", "Token for entry into the swarm")
    40  	return cmd
    41  }
    42  
    43  func runJoin(dockerCli *command.DockerCli, opts joinOptions) error {
    44  	client := dockerCli.Client()
    45  	ctx := context.Background()
    46  
    47  	req := swarm.JoinRequest{
    48  		JoinToken:     opts.token,
    49  		ListenAddr:    opts.listenAddr.String(),
    50  		AdvertiseAddr: opts.advertiseAddr,
    51  		RemoteAddrs:   []string{opts.remote},
    52  	}
    53  	err := client.SwarmJoin(ctx, req)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	info, err := client.Info(ctx)
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	if info.Swarm.ControlAvailable {
    64  		fmt.Fprintln(dockerCli.Out(), "This node joined a swarm as a manager.")
    65  	} else {
    66  		fmt.Fprintln(dockerCli.Out(), "This node joined a swarm as a worker.")
    67  	}
    68  	return nil
    69  }