Moved handling advertise address to readConfig and out of the agent's constructor, plus unit test fixes

This commit is contained in:
Preetha Appan 2017-07-27 22:06:31 -05:00
parent 398c1e450c
commit 28016190e0
7 changed files with 72 additions and 57 deletions

View File

@ -5,7 +5,6 @@ import (
"crypto/sha512"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -30,7 +29,6 @@ import (
"github.com/hashicorp/consul/logger"
"github.com/hashicorp/consul/types"
"github.com/hashicorp/consul/watch"
"github.com/hashicorp/go-sockaddr/template"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/raft"
"github.com/hashicorp/serf/coordinate"
@ -229,34 +227,6 @@ func New(c *Config) (*Agent, error) {
tokens: new(token.Store),
}
// Try to get an advertise address
switch {
case a.config.BindAddr != "" && !ipaddr.IsAny(a.config.BindAddr):
a.config.AdvertiseAddr = a.config.BindAddr
default:
ip, err := consul.GetPrivateIP()
if ipaddr.IsAnyV6(a.config.BindAddr) {
ip, err = consul.GetPublicIPv6()
}
if err != nil {
return nil, fmt.Errorf("Failed to get advertise address: %v", err)
}
a.config.AdvertiseAddr = ip.String()
}
// Try to get an advertise address for the wan
if a.config.AdvertiseAddrWan == "" {
a.config.AdvertiseAddrWan = a.config.AdvertiseAddr
}
// Create the default set of tagged addresses.
a.config.TaggedAddresses = map[string]string{
"lan": a.config.AdvertiseAddr,
"wan": a.config.AdvertiseAddrWan,
}
// Set up the initial state of the token store based on the config.
a.tokens.UpdateUserToken(a.config.ACLToken)
a.tokens.UpdateAgentToken(a.config.ACLAgentToken)
@ -799,25 +769,6 @@ func (a *Agent) consulConfig() (*consul.Config, error) {
return base, nil
}
// parseSingleIPTemplate is used as a helper function to parse out a single IP
// address from a config parameter.
func parseSingleIPTemplate(ipTmpl string) (string, error) {
out, err := template.Parse(ipTmpl)
if err != nil {
return "", fmt.Errorf("Unable to parse address template %q: %v", ipTmpl, err)
}
ips := strings.Split(out, " ")
switch len(ips) {
case 0:
return "", errors.New("No addresses found, please configure one.")
case 1:
return ips[0], nil
default:
return "", fmt.Errorf("Multiple addresses found (%q), please configure one.", out)
}
}
// makeRandomID will generate a random UUID for a node.
func (a *Agent) makeRandomID() (string, error) {
id, err := uuid.GenerateUUID()

View File

@ -117,6 +117,7 @@ func TestAgent_CheckAdvertiseAddrsSettings(t *testing.T) {
cfg.AdvertiseAddrs.SerfLan, _ = net.ResolveTCPAddr("tcp", "127.0.0.42:1233")
cfg.AdvertiseAddrs.SerfWan, _ = net.ResolveTCPAddr("tcp", "127.0.0.43:1234")
cfg.AdvertiseAddrs.RPC, _ = net.ResolveTCPAddr("tcp", "127.0.0.44:1235")
cfg.SetupTaggedAndAdvertiseAddrs()
a := NewTestAgent(t.Name(), cfg)
defer a.Shutdown()

View File

@ -16,10 +16,12 @@ import (
"github.com/hashicorp/consul/agent/consul"
"github.com/hashicorp/consul/agent/consul/structs"
"github.com/hashicorp/consul/ipaddr"
"github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/tlsutil"
"github.com/hashicorp/consul/types"
"github.com/hashicorp/consul/watch"
"github.com/hashicorp/go-sockaddr/template"
"github.com/mitchellh/mapstructure"
)
@ -2203,18 +2205,61 @@ func (c *Config) ResolveTmplAddrs() error {
c.SerfWanBindAddr = ipStr
}
// Parse all tagged addresses
for k, v := range c.TaggedAddresses {
ipStr, err := parseSingleIPTemplate(v)
if err != nil {
return fmt.Errorf("%s address resolution failed: %v", k, err)
return nil
}
// Additional post processing of the configs to set tagged and advertise addresses
func (cfg *Config) SetupTaggedAndAdvertiseAddrs() error {
if cfg.AdvertiseAddr == "" {
switch {
case cfg.BindAddr != "" && !ipaddr.IsAny(cfg.BindAddr):
cfg.AdvertiseAddr = cfg.BindAddr
default:
ip, err := consul.GetPrivateIP()
if ipaddr.IsAnyV6(cfg.BindAddr) {
ip, err = consul.GetPublicIPv6()
}
if err != nil {
return fmt.Errorf("Failed to get advertise address: %v", err)
}
cfg.AdvertiseAddr = ip.String()
}
c.TaggedAddresses[k] = ipStr
}
// Try to get an advertise address for the wan
if cfg.AdvertiseAddrWan == "" {
cfg.AdvertiseAddrWan = cfg.AdvertiseAddr
}
// Create the default set of tagged addresses.
cfg.TaggedAddresses = map[string]string{
"lan": cfg.AdvertiseAddr,
"wan": cfg.AdvertiseAddrWan,
}
return nil
}
// parseSingleIPTemplate is used as a helper function to parse out a single IP
// address from a config parameter.
func parseSingleIPTemplate(ipTmpl string) (string, error) {
out, err := template.Parse(ipTmpl)
if err != nil {
return "", fmt.Errorf("Unable to parse address template %q: %v", ipTmpl, err)
}
ips := strings.Split(out, " ")
switch len(ips) {
case 0:
return "", errors.New("No addresses found, please configure one.")
case 1:
return ips[0], nil
default:
return "", fmt.Errorf("Multiple addresses found (%q), please configure one.", out)
}
}
// Implement the sort interface for dirEnts
func (d dirEnts) Len() int {
return len(d)

View File

@ -14,7 +14,9 @@ import (
func TestAgentAntiEntropy_Services(t *testing.T) {
t.Parallel()
a := &TestAgent{Name: t.Name(), NoInitialSync: true}
cfg := TestConfig()
a := &TestAgent{Name: t.Name(), NoInitialSync: true, Config: cfg}
a.Start()
defer a.Shutdown()
@ -670,8 +672,10 @@ func TestAgentAntiEntropy_Services_ACLDeny(t *testing.T) {
func TestAgentAntiEntropy_Checks(t *testing.T) {
t.Parallel()
a := &TestAgent{Name: t.Name(), NoInitialSync: true}
cfg := TestConfig()
a := &TestAgent{Name: t.Name(), NoInitialSync: true, Config: cfg}
a.Start()
defer a.Shutdown()
// Register info

View File

@ -334,6 +334,7 @@ func TestConfig() *Config {
ccfg.CoordinateUpdatePeriod = 100 * time.Millisecond
ccfg.ServerHealthInterval = 10 * time.Millisecond
cfg.SetupTaggedAndAdvertiseAddrs()
return cfg
}

View File

@ -466,6 +466,13 @@ func (cmd *AgentCommand) readConfig() *agent.Config {
cmd.UI.Error(fmt.Sprintf("Failed to parse config: %v", err))
return nil
}
// More post processing of the config
if err := cfg.SetupTaggedAndAdvertiseAddrs(); err != nil {
cmd.UI.Error(fmt.Sprintf("Failed to set up tagged and advertise addresses: %v", err))
return nil
}
// Try to get an advertise address if not set
return cfg
}

View File

@ -176,6 +176,7 @@ func TestReadCliConfig(t *testing.T) {
args: []string{
"-data-dir", tmpDir,
"-node", `"a"`,
"-bind", "1.2.3.4",
"-advertise-wan", "1.2.3.4",
"-serf-wan-bind", "4.3.2.1",
"-serf-lan-bind", "4.3.2.2",
@ -207,6 +208,7 @@ func TestReadCliConfig(t *testing.T) {
"-data-dir", tmpDir,
"-node-meta", "somekey:somevalue",
"-node-meta", "otherkey:othervalue",
"-bind", "1.2.3.4",
},
ShutdownCh: shutdownCh,
BaseCommand: baseCommand(cli.NewMockUi()),
@ -229,6 +231,7 @@ func TestReadCliConfig(t *testing.T) {
"-node", `"server1"`,
"-server",
"-data-dir", tmpDir,
"-bind", "1.2.3.4",
},
ShutdownCh: shutdownCh,
BaseCommand: baseCommand(ui),
@ -256,6 +259,7 @@ func TestReadCliConfig(t *testing.T) {
args: []string{
"-data-dir", tmpDir,
"-node", `"client"`,
"-bind", "1.2.3.4",
},
ShutdownCh: shutdownCh,
BaseCommand: baseCommand(ui),
@ -301,6 +305,7 @@ func TestAgent_HostBasedIDs(t *testing.T) {
cmd := &AgentCommand{
args: []string{
"-data-dir", tmpDir,
"-bind", "127.0.0.1",
},
BaseCommand: baseCommand(cli.NewMockUi()),
}
@ -317,6 +322,7 @@ func TestAgent_HostBasedIDs(t *testing.T) {
args: []string{
"-data-dir", tmpDir,
"-disable-host-node-id=false",
"-bind", "127.0.0.1",
},
BaseCommand: baseCommand(cli.NewMockUi()),
}