github.com/sl1pm4t/consul@v1.4.5-0.20190325224627-74c31c540f9c/command/catalog/list/dc/catalog_list_datacenters.go (about)

     1  package dc
     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  }
    23  
    24  func (c *cmd) init() {
    25  	c.flags = flag.NewFlagSet("", flag.ContinueOnError)
    26  	c.http = &flags.HTTPFlags{}
    27  	flags.Merge(c.flags, c.http.ClientFlags())
    28  	flags.Merge(c.flags, c.http.ServerFlags())
    29  	c.help = flags.Usage(help, c.flags)
    30  }
    31  
    32  func (c *cmd) Run(args []string) int {
    33  	if err := c.flags.Parse(args); err != nil {
    34  		return 1
    35  	}
    36  
    37  	if l := len(c.flags.Args()); l > 0 {
    38  		c.UI.Error(fmt.Sprintf("Too many arguments (expected 0, got %d)", l))
    39  		return 1
    40  	}
    41  
    42  	// Create and test the HTTP client
    43  	client, err := c.http.APIClient()
    44  	if err != nil {
    45  		c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
    46  		return 1
    47  	}
    48  
    49  	dcs, err := client.Catalog().Datacenters()
    50  	if err != nil {
    51  		c.UI.Error(fmt.Sprintf("Error listing datacenters: %s", err))
    52  		return 1
    53  	}
    54  
    55  	for _, dc := range dcs {
    56  		c.UI.Info(dc)
    57  	}
    58  
    59  	return 0
    60  }
    61  
    62  func (c *cmd) Synopsis() string {
    63  	return synopsis
    64  }
    65  
    66  func (c *cmd) Help() string {
    67  	return c.help
    68  }
    69  
    70  const synopsis = "Lists all known datacenters"
    71  const help = `
    72  Usage: consul catalog datacenters [options]
    73  
    74    Retrieves the list of all known datacenters. This datacenters are sorted in
    75    ascending order based on the estimated median round trip time from the servers
    76    in this datacenter to the servers in the other datacenters.
    77  
    78    To retrieve the list of datacenters:
    79  
    80        $ consul catalog datacenters
    81  
    82    For a full list of options and examples, please see the Consul documentation.
    83  `