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 25acd1534a
commit aa98aeb4b1
7 changed files with 72 additions and 57 deletions

View File

@ -5,7 +5,6 @@ import (
"crypto/sha512" "crypto/sha512"
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -30,7 +29,6 @@ import (
"github.com/hashicorp/consul/logger" "github.com/hashicorp/consul/logger"
"github.com/hashicorp/consul/types" "github.com/hashicorp/consul/types"
"github.com/hashicorp/consul/watch" "github.com/hashicorp/consul/watch"
"github.com/hashicorp/go-sockaddr/template"
"github.com/hashicorp/go-uuid" "github.com/hashicorp/go-uuid"
"github.com/hashicorp/raft" "github.com/hashicorp/raft"
"github.com/hashicorp/serf/coordinate" "github.com/hashicorp/serf/coordinate"
@ -229,34 +227,6 @@ func New(c *Config) (*Agent, error) {
tokens: new(token.Store), 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. // Set up the initial state of the token store based on the config.
a.tokens.UpdateUserToken(a.config.ACLToken) a.tokens.UpdateUserToken(a.config.ACLToken)
a.tokens.UpdateAgentToken(a.config.ACLAgentToken) a.tokens.UpdateAgentToken(a.config.ACLAgentToken)
@ -799,25 +769,6 @@ func (a *Agent) consulConfig() (*consul.Config, error) {
return base, nil 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. // makeRandomID will generate a random UUID for a node.
func (a *Agent) makeRandomID() (string, error) { func (a *Agent) makeRandomID() (string, error) {
id, err := uuid.GenerateUUID() 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.SerfLan, _ = net.ResolveTCPAddr("tcp", "127.0.0.42:1233")
cfg.AdvertiseAddrs.SerfWan, _ = net.ResolveTCPAddr("tcp", "127.0.0.43:1234") cfg.AdvertiseAddrs.SerfWan, _ = net.ResolveTCPAddr("tcp", "127.0.0.43:1234")
cfg.AdvertiseAddrs.RPC, _ = net.ResolveTCPAddr("tcp", "127.0.0.44:1235") cfg.AdvertiseAddrs.RPC, _ = net.ResolveTCPAddr("tcp", "127.0.0.44:1235")
cfg.SetupTaggedAndAdvertiseAddrs()
a := NewTestAgent(t.Name(), cfg) a := NewTestAgent(t.Name(), cfg)
defer a.Shutdown() defer a.Shutdown()

View File

@ -16,10 +16,12 @@ import (
"github.com/hashicorp/consul/agent/consul" "github.com/hashicorp/consul/agent/consul"
"github.com/hashicorp/consul/agent/consul/structs" "github.com/hashicorp/consul/agent/consul/structs"
"github.com/hashicorp/consul/ipaddr"
"github.com/hashicorp/consul/lib" "github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/tlsutil" "github.com/hashicorp/consul/tlsutil"
"github.com/hashicorp/consul/types" "github.com/hashicorp/consul/types"
"github.com/hashicorp/consul/watch" "github.com/hashicorp/consul/watch"
"github.com/hashicorp/go-sockaddr/template"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
) )
@ -2203,18 +2205,61 @@ func (c *Config) ResolveTmplAddrs() error {
c.SerfWanBindAddr = ipStr c.SerfWanBindAddr = ipStr
} }
// Parse all tagged addresses return nil
for k, v := range c.TaggedAddresses { }
ipStr, err := parseSingleIPTemplate(v)
if err != nil { // Additional post processing of the configs to set tagged and advertise addresses
return fmt.Errorf("%s address resolution failed: %v", k, err) 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 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 // Implement the sort interface for dirEnts
func (d dirEnts) Len() int { func (d dirEnts) Len() int {
return len(d) return len(d)

View File

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

View File

@ -334,6 +334,7 @@ func TestConfig() *Config {
ccfg.CoordinateUpdatePeriod = 100 * time.Millisecond ccfg.CoordinateUpdatePeriod = 100 * time.Millisecond
ccfg.ServerHealthInterval = 10 * time.Millisecond ccfg.ServerHealthInterval = 10 * time.Millisecond
cfg.SetupTaggedAndAdvertiseAddrs()
return cfg 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)) cmd.UI.Error(fmt.Sprintf("Failed to parse config: %v", err))
return nil 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 return cfg
} }

View File

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