github.hscsec.cn/hashicorp/consul@v1.4.5/command/join/join.go (about)

     1  package join
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  
     7  	"github.com/hashicorp/consul/command/flags"
     8  	"github.com/mitchellh/cli"
     9  )
    10  
    11  func New(ui cli.Ui) *cmd {
    12  	c := &cmd{UI: ui}
    13  	c.init()
    14  	return c
    15  }
    16  
    17  type cmd struct {
    18  	UI    cli.Ui
    19  	flags *flag.FlagSet
    20  	http  *flags.HTTPFlags
    21  	help  string
    22  	wan   bool
    23  }
    24  
    25  func (c *cmd) init() {
    26  	c.flags = flag.NewFlagSet("", flag.ContinueOnError)
    27  	c.flags.BoolVar(&c.wan, "wan", false,
    28  		"Joins a server to another server in the WAN pool.")
    29  
    30  	c.http = &flags.HTTPFlags{}
    31  	flags.Merge(c.flags, c.http.ClientFlags())
    32  	c.help = flags.Usage(help, c.flags)
    33  }
    34  
    35  func (c *cmd) Run(args []string) int {
    36  	if err := c.flags.Parse(args); err != nil {
    37  		return 1
    38  	}
    39  
    40  	addrs := c.flags.Args()
    41  	if len(addrs) == 0 {
    42  		c.UI.Error("At least one address to join must be specified.")
    43  		c.UI.Error("")
    44  		c.UI.Error(c.Help())
    45  		return 1
    46  	}
    47  
    48  	client, err := c.http.APIClient()
    49  	if err != nil {
    50  		c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
    51  		return 1
    52  	}
    53  
    54  	joins := 0
    55  	for _, addr := range addrs {
    56  		err := client.Agent().Join(addr, c.wan)
    57  		if err != nil {
    58  			c.UI.Error(fmt.Sprintf("Error joining address '%s': %s", addr, err))
    59  		} else {
    60  			joins++
    61  		}
    62  	}
    63  
    64  	if joins == 0 {
    65  		c.UI.Error("Failed to join any nodes.")
    66  		return 1
    67  	}
    68  
    69  	c.UI.Output(fmt.Sprintf("Successfully joined cluster by contacting %d nodes.", joins))
    70  	return 0
    71  }
    72  
    73  func (c *cmd) Synopsis() string {
    74  	return synopsis
    75  }
    76  
    77  func (c *cmd) Help() string {
    78  	return c.help
    79  }
    80  
    81  const synopsis = "Tell Consul agent to join cluster"
    82  const help = `
    83  Usage: consul join [options] address ...
    84  
    85    Tells a running Consul agent (with "consul agent") to join the cluster
    86    by specifying at least one existing member.
    87  `