Merge pull request #9448 from hashicorp/dnephin/config-load-interface

config: reduce interface to a single Load function
This commit is contained in:
Daniel Nephin 2021-01-27 17:54:05 -05:00 committed by GitHub
commit 603c692190
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 389 additions and 392 deletions

View File

@ -43,16 +43,17 @@ func NewTestACLAgent(t *testing.T, name string, hcl string, resolveAuthz authzRe
dataDir := testutil.TempDir(t, "acl-agent") dataDir := testutil.TempDir(t, "acl-agent")
logBuffer := testutil.NewLogBuffer(t) logBuffer := testutil.NewLogBuffer(t)
loader := func(source config.Source) (*config.RuntimeConfig, []string, error) { loader := func(source config.Source) (config.LoadResult, error) {
dataDir := fmt.Sprintf(`data_dir = "%s"`, dataDir) dataDir := fmt.Sprintf(`data_dir = "%s"`, dataDir)
opts := config.BuilderOpts{ opts := config.LoadOpts{
HCL: []string{TestConfigHCL(NodeID()), hcl, dataDir}, HCL: []string{TestConfigHCL(NodeID()), hcl, dataDir},
DefaultConfig: source,
} }
cfg, warnings, err := config.Load(opts, source) result, err := config.Load(opts)
if cfg != nil { if result.RuntimeConfig != nil {
cfg.Telemetry.Disable = true result.RuntimeConfig.Telemetry.Disable = true
} }
return cfg, warnings, err return result, err
} }
bd, err := NewBaseDeps(loader, logBuffer) bd, err := NewBaseDeps(loader, logBuffer)
require.NoError(t, err) require.NoError(t, err)

View File

@ -103,17 +103,17 @@ func New(config Config) (*AutoConfig, error) {
func (ac *AutoConfig) ReadConfig() (*config.RuntimeConfig, error) { func (ac *AutoConfig) ReadConfig() (*config.RuntimeConfig, error) {
ac.Lock() ac.Lock()
defer ac.Unlock() defer ac.Unlock()
cfg, warnings, err := ac.acConfig.Loader(ac.autoConfigSource) result, err := ac.acConfig.Loader(ac.autoConfigSource)
if err != nil { if err != nil {
return cfg, err return result.RuntimeConfig, err
} }
for _, w := range warnings { for _, w := range result.Warnings {
ac.logger.Warn(w) ac.logger.Warn(w)
} }
ac.config = cfg ac.config = result.RuntimeConfig
return cfg, nil return ac.config, nil
} }
// InitialConfiguration will perform a one-time RPC request to the configured servers // InitialConfiguration will perform a one-time RPC request to the configured servers

View File

@ -29,11 +29,13 @@ import (
) )
type configLoader struct { type configLoader struct {
opts config.BuilderOpts opts config.LoadOpts
} }
func (c *configLoader) Load(source config.Source) (*config.RuntimeConfig, []string, error) { func (c *configLoader) Load(source config.Source) (config.LoadResult, error) {
return config.Load(c.opts, source) opts := c.opts
opts.DefaultConfig = source
return config.Load(opts)
} }
func (c *configLoader) addConfigHCL(cfg string) { func (c *configLoader) addConfigHCL(cfg string) {
@ -131,8 +133,8 @@ func TestNew(t *testing.T) {
for name, tcase := range cases { for name, tcase := range cases {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
cfg := Config{ cfg := Config{
Loader: func(source config.Source) (cfg *config.RuntimeConfig, warnings []string, err error) { Loader: func(source config.Source) (result config.LoadResult, err error) {
return nil, nil, nil return config.LoadResult{}, nil
}, },
DirectRPC: newMockDirectRPC(t), DirectRPC: newMockDirectRPC(t),
Tokens: newMockTokenStore(t), Tokens: newMockTokenStore(t),
@ -168,15 +170,18 @@ func TestReadConfig(t *testing.T) {
}, },
logger: testutil.Logger(t), logger: testutil.Logger(t),
acConfig: Config{ acConfig: Config{
Loader: func(source config.Source) (*config.RuntimeConfig, []string, error) { Loader: func(source config.Source) (config.LoadResult, error) {
r := config.LoadResult{}
cfg, _, err := source.Parse() cfg, _, err := source.Parse()
if err != nil { if err != nil {
return nil, nil, err return r, err
} }
return &config.RuntimeConfig{
r.RuntimeConfig = &config.RuntimeConfig{
DevMode: true, DevMode: true,
NodeName: *cfg.NodeName, NodeName: *cfg.NodeName,
}, nil, nil }
return r, nil
}, },
}, },
} }
@ -194,8 +199,8 @@ func setupRuntimeConfig(t *testing.T) *configLoader {
dataDir := testutil.TempDir(t, "auto-config") dataDir := testutil.TempDir(t, "auto-config")
opts := config.BuilderOpts{ opts := config.LoadOpts{
Config: config.Config{ FlagValues: config.Config{
DataDir: &dataDir, DataDir: &dataDir,
Datacenter: stringPointer("dc1"), Datacenter: stringPointer("dc1"),
NodeName: stringPointer("autoconf"), NodeName: stringPointer("autoconf"),
@ -225,7 +230,7 @@ func TestInitialConfiguration_disabled(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, cfg) require.NotNil(t, cfg)
require.Equal(t, "primary", cfg.PrimaryDatacenter) require.Equal(t, "primary", cfg.PrimaryDatacenter)
require.NoFileExists(t, filepath.Join(*loader.opts.Config.DataDir, autoConfigFileName)) require.NoFileExists(t, filepath.Join(*loader.opts.FlagValues.DataDir, autoConfigFileName))
} }
func TestInitialConfiguration_cancelled(t *testing.T) { func TestInitialConfiguration_cancelled(t *testing.T) {
@ -286,7 +291,7 @@ func TestInitialConfiguration_restored(t *testing.T) {
indexedRoots, cert, extraCACerts := mcfg.setupInitialTLS(t, "autoconf", "dc1", "secret") indexedRoots, cert, extraCACerts := mcfg.setupInitialTLS(t, "autoconf", "dc1", "secret")
// persist an auto config response to the data dir where it is expected // persist an auto config response to the data dir where it is expected
persistedFile := filepath.Join(*loader.opts.Config.DataDir, autoConfigFileName) persistedFile := filepath.Join(*loader.opts.FlagValues.DataDir, autoConfigFileName)
response := &pbautoconf.AutoConfigResponse{ response := &pbautoconf.AutoConfigResponse{
Config: &pbconfig.Config{ Config: &pbconfig.Config{
PrimaryDatacenter: "primary", PrimaryDatacenter: "primary",
@ -394,7 +399,7 @@ func TestInitialConfiguration_success(t *testing.T) {
require.Equal(t, "primary", cfg.PrimaryDatacenter) require.Equal(t, "primary", cfg.PrimaryDatacenter)
// the file was written to. // the file was written to.
persistedFile := filepath.Join(*loader.opts.Config.DataDir, autoConfigFileName) persistedFile := filepath.Join(*loader.opts.FlagValues.DataDir, autoConfigFileName)
require.FileExists(t, persistedFile) require.FileExists(t, persistedFile)
} }
@ -511,7 +516,7 @@ func TestInitialConfiguration_retries(t *testing.T) {
require.Equal(t, "primary", cfg.PrimaryDatacenter) require.Equal(t, "primary", cfg.PrimaryDatacenter)
// the file was written to. // the file was written to.
persistedFile := filepath.Join(*loader.opts.Config.DataDir, autoConfigFileName) persistedFile := filepath.Join(*loader.opts.FlagValues.DataDir, autoConfigFileName)
require.FileExists(t, persistedFile) require.FileExists(t, persistedFile)
} }

View File

@ -287,7 +287,7 @@ func TestAutoEncrypt_InitialConfiguration(t *testing.T) {
tls = true tls = true
} }
`) `)
loader.opts.Config.NodeName = &nodeName loader.opts.FlagValues.NodeName = &nodeName
mcfg.Config.Loader = loader.Load mcfg.Config.Loader = loader.Load
indexedRoots, cert, extraCerts := mcfg.setupInitialTLS(t, nodeName, datacenter, token) indexedRoots, cert, extraCerts := mcfg.setupInitialTLS(t, nodeName, datacenter, token)

View File

@ -82,7 +82,7 @@ type Config struct {
// Loader merges source with the existing FileSources and returns the complete // Loader merges source with the existing FileSources and returns the complete
// RuntimeConfig. // RuntimeConfig.
Loader func(source config.Source) (cfg *config.RuntimeConfig, warnings []string, err error) Loader func(source config.Source) (config.LoadResult, error)
// TLSConfigurator is the shared TLS Configurator. AutoConfig will update the // TLSConfigurator is the shared TLS Configurator. AutoConfig will update the
// auto encrypt/auto config certs as they are renewed. // auto encrypt/auto config certs as they are renewed.

View File

@ -1,42 +0,0 @@
package config
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestBuildAndValidate_HTTPMaxConnsPerClientExceedsRLimit(t *testing.T) {
hcl := `
limits{
# We put a very high value to be sure to fail
# This value is more than max on Windows as well
http_max_conns_per_client = 16777217
}`
b, err := NewBuilder(BuilderOpts{})
assert.NoError(t, err)
testsrc := FileSource{
Name: "test",
Format: "hcl",
Data: `
ae_interval = "1m"
data_dir="/tmp/00000000001979"
bind_addr = "127.0.0.1"
advertise_addr = "127.0.0.1"
datacenter = "dc1"
bootstrap = true
server = true
node_id = "00000000001979"
node_name = "Node-00000000001979"
`,
}
b.Head = append(b.Head, testsrc)
b.Tail = append(b.Tail, DefaultConsulSource(), DevConsulSource())
b.Tail = append(b.Head, FileSource{Name: "hcl", Format: "hcl", Data: hcl})
_, validationError := b.BuildAndValidate()
if validationError == nil {
assert.Fail(t, "Config should not be valid")
}
assert.Contains(t, validationError.Error(), "but limits.http_max_conns_per_client: 16777217 needs at least 16777237")
}

View File

@ -41,58 +41,87 @@ import (
"github.com/hashicorp/consul/types" "github.com/hashicorp/consul/types"
) )
// Load will build the configuration including the extraHead source injected // LoadOpts used by Load to construct and validate a RuntimeConfig.
// after all other defaults but before any user supplied configuration and the overrides type LoadOpts struct {
// source injected as the final source in the configuration parsing chain. // FlagValues contains the command line arguments that can also be set
func Load(opts BuilderOpts, extraHead Source, overrides ...Source) (*RuntimeConfig, []string, error) { // in a config file.
b, err := NewBuilder(opts) FlagValues Config
if err != nil {
return nil, nil, err
}
if extraHead != nil { // ConfigFiles is a slice of paths to config files and directories that will
b.Head = append(b.Head, extraHead) // be loaded.
} ConfigFiles []string
if len(overrides) != 0 { // ConfigFormat forces all config files to be interpreted as this format
b.Tail = append(b.Tail, overrides...) // independent of their extension. Value may be `hcl` or `json`.
} ConfigFormat string
cfg, err := b.BuildAndValidate() // DevMode indicates whether the agent should be started in development
if err != nil { // mode. This cannot be configured in a config file.
return nil, nil, err DevMode *bool
}
return &cfg, b.Warnings, nil // HCL is a slice of config data in hcl format. Each one will be loaded as
// if it were the source of a config file. Values from HCL will override
// values from ConfigFiles and FlagValues.
HCL []string
// DefaultConfig is an optional source that is applied after other defaults
// but before ConfigFiles and all other user specified config.
DefaultConfig Source
// Overrides are optional config sources that are applied as the very last
// config source so they can override any previous values.
Overrides []Source
// hostname is a shim for testing, allowing tests to specify a replacement
// for os.Hostname.
hostname func() (string, error)
// getPrivateIPv4 and getPublicIPv6 are shims for testing, allowing tests to
// specify a replacement for ipaddr.GetPrivateIPv4 and ipaddr.GetPublicIPv6.
getPrivateIPv4 func() ([]*net.IPAddr, error)
getPublicIPv6 func() ([]*net.IPAddr, error)
} }
// Builder constructs a valid runtime configuration from multiple // Load will build the configuration including the config source injected
// configuration sources. // after all other defaults but before any user supplied configuration and the overrides
// source injected as the final source in the configuration parsing chain.
// //
// To build the runtime configuration first call Build() which merges // The caller is responsible for handling any warnings in LoadResult.Warnings.
// the sources in a pre-defined order, converts the data types and func Load(opts LoadOpts) (LoadResult, error) {
// structures into their final form and performs the syntactic r := LoadResult{}
// validation. b, err := newBuilder(opts)
if err != nil {
return r, err
}
cfg, err := b.BuildAndValidate()
if err != nil {
return r, err
}
return LoadResult{RuntimeConfig: &cfg, Warnings: b.Warnings}, nil
}
// LoadResult is the result returned from Load. The caller is responsible for
// handling any warnings.
type LoadResult struct {
RuntimeConfig *RuntimeConfig
Warnings []string
}
// builder constructs and validates a runtime configuration from multiple
// configuration sources.
// //
// The sources are merged in the following order: // The sources are merged in the following order:
// //
// * default configuration // * default configuration
// * config files in alphabetical order // * config files in alphabetical order
// * command line arguments // * command line arguments
// * overrides
// //
// The config sources are merged sequentially and later values // The config sources are merged sequentially and later values overwrite
// overwrite previously set values. Slice values are merged by // previously set values. Slice values are merged by concatenating the two slices.
// concatenating the two slices. Map values are merged by over- // Map values are merged by over-laying the later maps on top of earlier ones.
// laying the later maps on top of earlier ones. type builder struct {
// opts LoadOpts
// Then call Validate() to perform the semantic validation to ensure
// that the configuration is ready to be used.
//
// Splitting the construction into two phases greatly simplifies testing
// since not all pre-conditions have to be satisfied when performing
// syntactical tests.
type Builder struct {
opts BuilderOpts
// Head, Sources, and Tail are used to manage the order of the // Head, Sources, and Tail are used to manage the order of the
// config sources, as described in the comments above. // config sources, as described in the comments above.
@ -109,14 +138,14 @@ type Builder struct {
err error err error
} }
// NewBuilder returns a new configuration Builder from the BuilderOpts. // newBuilder returns a new configuration Builder from the LoadOpts.
func NewBuilder(opts BuilderOpts) (*Builder, error) { func newBuilder(opts LoadOpts) (*builder, error) {
configFormat := opts.ConfigFormat configFormat := opts.ConfigFormat
if configFormat != "" && configFormat != "json" && configFormat != "hcl" { if configFormat != "" && configFormat != "json" && configFormat != "hcl" {
return nil, fmt.Errorf("config: -config-format must be either 'hcl' or 'json'") return nil, fmt.Errorf("config: -config-format must be either 'hcl' or 'json'")
} }
b := &Builder{ b := &builder{
opts: opts, opts: opts,
Head: []Source{DefaultSource(), DefaultEnterpriseSource()}, Head: []Source{DefaultSource(), DefaultEnterpriseSource()},
} }
@ -130,8 +159,12 @@ func NewBuilder(opts BuilderOpts) (*Builder, error) {
// we need to merge all slice values defined in flags before we // we need to merge all slice values defined in flags before we
// merge the config files since the flag values for slices are // merge the config files since the flag values for slices are
// otherwise appended instead of prepended. // otherwise appended instead of prepended.
slices, values := splitSlicesAndValues(opts.Config) slices, values := splitSlicesAndValues(opts.FlagValues)
b.Head = append(b.Head, LiteralSource{Name: "flags.slices", Config: slices}) b.Head = append(b.Head, LiteralSource{Name: "flags.slices", Config: slices})
if opts.DefaultConfig != nil {
b.Head = append(b.Head, opts.DefaultConfig)
}
for _, path := range opts.ConfigFiles { for _, path := range opts.ConfigFiles {
sources, err := b.sourcesFromPath(path, opts.ConfigFormat) sources, err := b.sourcesFromPath(path, opts.ConfigFormat)
if err != nil { if err != nil {
@ -151,13 +184,16 @@ func NewBuilder(opts BuilderOpts) (*Builder, error) {
if boolVal(opts.DevMode) { if boolVal(opts.DevMode) {
b.Tail = append(b.Tail, DevConsulSource()) b.Tail = append(b.Tail, DevConsulSource())
} }
if len(opts.Overrides) != 0 {
b.Tail = append(b.Tail, opts.Overrides...)
}
return b, nil return b, nil
} }
// sourcesFromPath reads a single config file or all files in a directory (but // sourcesFromPath reads a single config file or all files in a directory (but
// not its sub-directories) and returns Sources created from the // not its sub-directories) and returns Sources created from the
// files. // files.
func (b *Builder) sourcesFromPath(path string, format string) ([]Source, error) { func (b *builder) sourcesFromPath(path string, format string) ([]Source, error) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("config: Open failed on %s. %s", path, err) return nil, fmt.Errorf("config: Open failed on %s. %s", path, err)
@ -258,7 +294,7 @@ func (a byName) Len() int { return len(a) }
func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name() < a[j].Name() } func (a byName) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
func (b *Builder) BuildAndValidate() (RuntimeConfig, error) { func (b *builder) BuildAndValidate() (RuntimeConfig, error) {
rt, err := b.Build() rt, err := b.Build()
if err != nil { if err != nil {
return RuntimeConfig{}, err return RuntimeConfig{}, err
@ -275,7 +311,7 @@ func (b *Builder) BuildAndValidate() (RuntimeConfig, error) {
// precedence over the other sources. If the error is nil then // precedence over the other sources. If the error is nil then
// warnings can still contain deprecation or format warnings that should // warnings can still contain deprecation or format warnings that should
// be presented to the user. // be presented to the user.
func (b *Builder) Build() (rt RuntimeConfig, err error) { func (b *builder) Build() (rt RuntimeConfig, err error) {
srcs := make([]Source, 0, len(b.Head)+len(b.Sources)+len(b.Tail)) srcs := make([]Source, 0, len(b.Head)+len(b.Sources)+len(b.Tail))
srcs = append(srcs, b.Head...) srcs = append(srcs, b.Head...)
srcs = append(srcs, b.Sources...) srcs = append(srcs, b.Sources...)
@ -1133,7 +1169,7 @@ func validateBasicName(field, value string, allowEmpty bool) error {
} }
// Validate performs semantic validation of the runtime configuration. // Validate performs semantic validation of the runtime configuration.
func (b *Builder) Validate(rt RuntimeConfig) error { func (b *builder) Validate(rt RuntimeConfig) error {
// validContentPath defines a regexp for a valid content path name. // validContentPath defines a regexp for a valid content path name.
var validContentPath = regexp.MustCompile(`^[A-Za-z0-9/_-]+$`) var validContentPath = regexp.MustCompile(`^[A-Za-z0-9/_-]+$`)
@ -1501,11 +1537,11 @@ func splitSlicesAndValues(c Config) (slices, values Config) {
return rs.Elem().Interface().(Config), rv.Elem().Interface().(Config) return rs.Elem().Interface().(Config), rv.Elem().Interface().(Config)
} }
func (b *Builder) warn(msg string, args ...interface{}) { func (b *builder) warn(msg string, args ...interface{}) {
b.Warnings = append(b.Warnings, fmt.Sprintf(msg, args...)) b.Warnings = append(b.Warnings, fmt.Sprintf(msg, args...))
} }
func (b *Builder) checkVal(v *CheckDefinition) *structs.CheckDefinition { func (b *builder) checkVal(v *CheckDefinition) *structs.CheckDefinition {
if v == nil { if v == nil {
return nil return nil
} }
@ -1543,7 +1579,7 @@ func (b *Builder) checkVal(v *CheckDefinition) *structs.CheckDefinition {
} }
} }
func (b *Builder) svcTaggedAddresses(v map[string]ServiceAddress) map[string]structs.ServiceAddress { func (b *builder) svcTaggedAddresses(v map[string]ServiceAddress) map[string]structs.ServiceAddress {
if len(v) <= 0 { if len(v) <= 0 {
return nil return nil
} }
@ -1563,7 +1599,7 @@ func (b *Builder) svcTaggedAddresses(v map[string]ServiceAddress) map[string]str
return svcAddrs return svcAddrs
} }
func (b *Builder) serviceVal(v *ServiceDefinition) *structs.ServiceDefinition { func (b *builder) serviceVal(v *ServiceDefinition) *structs.ServiceDefinition {
if v == nil { if v == nil {
return nil return nil
} }
@ -1616,7 +1652,7 @@ func (b *Builder) serviceVal(v *ServiceDefinition) *structs.ServiceDefinition {
} }
} }
func (b *Builder) serviceKindVal(v *string) structs.ServiceKind { func (b *builder) serviceKindVal(v *string) structs.ServiceKind {
if v == nil { if v == nil {
return structs.ServiceKindTypical return structs.ServiceKindTypical
} }
@ -1634,7 +1670,7 @@ func (b *Builder) serviceKindVal(v *string) structs.ServiceKind {
} }
} }
func (b *Builder) serviceProxyVal(v *ServiceProxy) *structs.ConnectProxyConfig { func (b *builder) serviceProxyVal(v *ServiceProxy) *structs.ConnectProxyConfig {
if v == nil { if v == nil {
return nil return nil
} }
@ -1651,7 +1687,7 @@ func (b *Builder) serviceProxyVal(v *ServiceProxy) *structs.ConnectProxyConfig {
} }
} }
func (b *Builder) upstreamsVal(v []Upstream) structs.Upstreams { func (b *builder) upstreamsVal(v []Upstream) structs.Upstreams {
ups := make(structs.Upstreams, len(v)) ups := make(structs.Upstreams, len(v))
for i, u := range v { for i, u := range v {
ups[i] = structs.Upstream{ ups[i] = structs.Upstream{
@ -1671,7 +1707,7 @@ func (b *Builder) upstreamsVal(v []Upstream) structs.Upstreams {
return ups return ups
} }
func (b *Builder) meshGatewayConfVal(mgConf *MeshGatewayConfig) structs.MeshGatewayConfig { func (b *builder) meshGatewayConfVal(mgConf *MeshGatewayConfig) structs.MeshGatewayConfig {
cfg := structs.MeshGatewayConfig{Mode: structs.MeshGatewayModeDefault} cfg := structs.MeshGatewayConfig{Mode: structs.MeshGatewayModeDefault}
if mgConf == nil || mgConf.Mode == nil { if mgConf == nil || mgConf.Mode == nil {
// return defaults // return defaults
@ -1688,7 +1724,7 @@ func (b *Builder) meshGatewayConfVal(mgConf *MeshGatewayConfig) structs.MeshGate
return cfg return cfg
} }
func (b *Builder) exposeConfVal(v *ExposeConfig) structs.ExposeConfig { func (b *builder) exposeConfVal(v *ExposeConfig) structs.ExposeConfig {
var out structs.ExposeConfig var out structs.ExposeConfig
if v == nil { if v == nil {
return out return out
@ -1699,7 +1735,7 @@ func (b *Builder) exposeConfVal(v *ExposeConfig) structs.ExposeConfig {
return out return out
} }
func (b *Builder) pathsVal(v []ExposePath) []structs.ExposePath { func (b *builder) pathsVal(v []ExposePath) []structs.ExposePath {
paths := make([]structs.ExposePath, len(v)) paths := make([]structs.ExposePath, len(v))
for i, p := range v { for i, p := range v {
paths[i] = structs.ExposePath{ paths[i] = structs.ExposePath{
@ -1712,7 +1748,7 @@ func (b *Builder) pathsVal(v []ExposePath) []structs.ExposePath {
return paths return paths
} }
func (b *Builder) serviceConnectVal(v *ServiceConnect) *structs.ServiceConnect { func (b *builder) serviceConnectVal(v *ServiceConnect) *structs.ServiceConnect {
if v == nil { if v == nil {
return nil return nil
} }
@ -1738,7 +1774,7 @@ func (b *Builder) serviceConnectVal(v *ServiceConnect) *structs.ServiceConnect {
} }
} }
func (b *Builder) uiConfigVal(v RawUIConfig) UIConfig { func (b *builder) uiConfigVal(v RawUIConfig) UIConfig {
return UIConfig{ return UIConfig{
Enabled: boolVal(v.Enabled), Enabled: boolVal(v.Enabled),
Dir: stringVal(v.Dir), Dir: stringVal(v.Dir),
@ -1751,7 +1787,7 @@ func (b *Builder) uiConfigVal(v RawUIConfig) UIConfig {
} }
} }
func (b *Builder) uiMetricsProxyVal(v RawUIMetricsProxy) UIMetricsProxy { func (b *builder) uiMetricsProxyVal(v RawUIMetricsProxy) UIMetricsProxy {
var hdrs []UIMetricsProxyAddHeader var hdrs []UIMetricsProxyAddHeader
for _, hdr := range v.AddHeaders { for _, hdr := range v.AddHeaders {
@ -1782,7 +1818,7 @@ func boolVal(v *bool) bool {
return *v return *v
} }
func (b *Builder) durationValWithDefault(name string, v *string, defaultVal time.Duration) (d time.Duration) { func (b *builder) durationValWithDefault(name string, v *string, defaultVal time.Duration) (d time.Duration) {
if v == nil { if v == nil {
return defaultVal return defaultVal
} }
@ -1793,7 +1829,7 @@ func (b *Builder) durationValWithDefault(name string, v *string, defaultVal time
return d return d
} }
func (b *Builder) durationVal(name string, v *string) (d time.Duration) { func (b *builder) durationVal(name string, v *string) (d time.Duration) {
return b.durationValWithDefault(name, v, 0) return b.durationValWithDefault(name, v, 0)
} }
@ -1825,7 +1861,7 @@ func uint64Val(v *uint64) uint64 {
return *v return *v
} }
func (b *Builder) portVal(name string, v *int) int { func (b *builder) portVal(name string, v *int) int {
if v == nil || *v <= 0 { if v == nil || *v <= 0 {
return -1 return -1
} }
@ -1860,7 +1896,7 @@ func float64Val(v *float64) float64 {
return float64ValWithDefault(v, 0) return float64ValWithDefault(v, 0)
} }
func (b *Builder) cidrsVal(name string, v []string) (nets []*net.IPNet) { func (b *builder) cidrsVal(name string, v []string) (nets []*net.IPNet) {
if v == nil { if v == nil {
return return
} }
@ -1876,7 +1912,7 @@ func (b *Builder) cidrsVal(name string, v []string) (nets []*net.IPNet) {
return return
} }
func (b *Builder) tlsCipherSuites(name string, v *string) []uint16 { func (b *builder) tlsCipherSuites(name string, v *string) []uint16 {
if v == nil { if v == nil {
return nil return nil
} }
@ -1889,7 +1925,7 @@ func (b *Builder) tlsCipherSuites(name string, v *string) []uint16 {
return a return a
} }
func (b *Builder) nodeName(v *string) string { func (b *builder) nodeName(v *string) string {
nodeName := stringVal(v) nodeName := stringVal(v)
if nodeName == "" { if nodeName == "" {
fn := b.opts.hostname fn := b.opts.hostname
@ -1908,7 +1944,7 @@ func (b *Builder) nodeName(v *string) string {
// expandAddrs expands the go-sockaddr template in s and returns the // expandAddrs expands the go-sockaddr template in s and returns the
// result as a list of *net.IPAddr and *net.UnixAddr. // result as a list of *net.IPAddr and *net.UnixAddr.
func (b *Builder) expandAddrs(name string, s *string) []net.Addr { func (b *builder) expandAddrs(name string, s *string) []net.Addr {
if s == nil || *s == "" { if s == nil || *s == "" {
return nil return nil
} }
@ -1947,7 +1983,7 @@ func (b *Builder) expandAddrs(name string, s *string) []net.Addr {
// error set. In contrast to expandAddrs, expandOptionalAddrs does not validate // error set. In contrast to expandAddrs, expandOptionalAddrs does not validate
// if the result contains valid addresses and returns a list of strings. // if the result contains valid addresses and returns a list of strings.
// However, if the expansion of the go-sockaddr template fails an error is set. // However, if the expansion of the go-sockaddr template fails an error is set.
func (b *Builder) expandOptionalAddrs(name string, s *string) []string { func (b *builder) expandOptionalAddrs(name string, s *string) []string {
if s == nil || *s == "" { if s == nil || *s == "" {
return nil return nil
} }
@ -1967,7 +2003,7 @@ func (b *Builder) expandOptionalAddrs(name string, s *string) []string {
} }
} }
func (b *Builder) expandAllOptionalAddrs(name string, addrs []string) []string { func (b *builder) expandAllOptionalAddrs(name string, addrs []string) []string {
out := make([]string, 0, len(addrs)) out := make([]string, 0, len(addrs))
for _, a := range addrs { for _, a := range addrs {
expanded := b.expandOptionalAddrs(name, &a) expanded := b.expandOptionalAddrs(name, &a)
@ -1981,7 +2017,7 @@ func (b *Builder) expandAllOptionalAddrs(name string, addrs []string) []string {
// expandIPs expands the go-sockaddr template in s and returns a list of // expandIPs expands the go-sockaddr template in s and returns a list of
// *net.IPAddr. If one of the expanded addresses is a unix socket // *net.IPAddr. If one of the expanded addresses is a unix socket
// address an error is set and nil is returned. // address an error is set and nil is returned.
func (b *Builder) expandIPs(name string, s *string) []*net.IPAddr { func (b *builder) expandIPs(name string, s *string) []*net.IPAddr {
if s == nil || *s == "" { if s == nil || *s == "" {
return nil return nil
} }
@ -2007,7 +2043,7 @@ func (b *Builder) expandIPs(name string, s *string) []*net.IPAddr {
// first address which is either a *net.IPAddr or a *net.UnixAddr. If // first address which is either a *net.IPAddr or a *net.UnixAddr. If
// the template expands to multiple addresses an error is set and nil // the template expands to multiple addresses an error is set and nil
// is returned. // is returned.
func (b *Builder) expandFirstAddr(name string, s *string) net.Addr { func (b *builder) expandFirstAddr(name string, s *string) net.Addr {
if s == nil || *s == "" { if s == nil || *s == "" {
return nil return nil
} }
@ -2030,7 +2066,7 @@ func (b *Builder) expandFirstAddr(name string, s *string) net.Addr {
// expandFirstIP expands the go-sockaddr template in s and returns the // expandFirstIP expands the go-sockaddr template in s and returns the
// first address if it is not a unix socket address. If the template // first address if it is not a unix socket address. If the template
// expands to multiple addresses an error is set and nil is returned. // expands to multiple addresses an error is set and nil is returned.
func (b *Builder) expandFirstIP(name string, s *string) *net.IPAddr { func (b *builder) expandFirstIP(name string, s *string) *net.IPAddr {
if s == nil || *s == "" { if s == nil || *s == "" {
return nil return nil
} }
@ -2058,7 +2094,7 @@ func makeIPAddr(pri *net.IPAddr, sec *net.IPAddr) *net.IPAddr {
return sec return sec
} }
func (b *Builder) makeTCPAddr(pri *net.IPAddr, sec net.Addr, port int) *net.TCPAddr { func (b *builder) makeTCPAddr(pri *net.IPAddr, sec net.Addr, port int) *net.TCPAddr {
if pri == nil && reflect.ValueOf(sec).IsNil() || port <= 0 { if pri == nil && reflect.ValueOf(sec).IsNil() || port <= 0 {
return nil return nil
} }
@ -2079,7 +2115,7 @@ func (b *Builder) makeTCPAddr(pri *net.IPAddr, sec net.Addr, port int) *net.TCPA
// makeAddr creates an *net.TCPAddr or a *net.UnixAddr from either the // makeAddr creates an *net.TCPAddr or a *net.UnixAddr from either the
// primary or secondary address and the given port. If the port is <= 0 // primary or secondary address and the given port. If the port is <= 0
// then the address is considered to be disabled and nil is returned. // then the address is considered to be disabled and nil is returned.
func (b *Builder) makeAddr(pri, sec net.Addr, port int) net.Addr { func (b *builder) makeAddr(pri, sec net.Addr, port int) net.Addr {
if reflect.ValueOf(pri).IsNil() && reflect.ValueOf(sec).IsNil() || port <= 0 { if reflect.ValueOf(pri).IsNil() && reflect.ValueOf(sec).IsNil() || port <= 0 {
return nil return nil
} }
@ -2101,7 +2137,7 @@ func (b *Builder) makeAddr(pri, sec net.Addr, port int) net.Addr {
// from either the primary or secondary addresses and the given port. // from either the primary or secondary addresses and the given port.
// If the port is <= 0 then the address is considered to be disabled // If the port is <= 0 then the address is considered to be disabled
// and nil is returned. // and nil is returned.
func (b *Builder) makeAddrs(pri []net.Addr, sec []*net.IPAddr, port int) []net.Addr { func (b *builder) makeAddrs(pri []net.Addr, sec []*net.IPAddr, port int) []net.Addr {
if len(pri) == 0 && len(sec) == 0 || port <= 0 { if len(pri) == 0 && len(sec) == 0 || port <= 0 {
return nil return nil
} }
@ -2119,7 +2155,7 @@ func (b *Builder) makeAddrs(pri []net.Addr, sec []*net.IPAddr, port int) []net.A
return x return x
} }
func (b *Builder) autoConfigVal(raw AutoConfigRaw) AutoConfig { func (b *builder) autoConfigVal(raw AutoConfigRaw) AutoConfig {
var val AutoConfig var val AutoConfig
val.Enabled = boolValWithDefault(raw.Enabled, false) val.Enabled = boolValWithDefault(raw.Enabled, false)
@ -2152,7 +2188,7 @@ func (b *Builder) autoConfigVal(raw AutoConfigRaw) AutoConfig {
return val return val
} }
func (b *Builder) autoConfigAuthorizerVal(raw AutoConfigAuthorizationRaw) AutoConfigAuthorizer { func (b *builder) autoConfigAuthorizerVal(raw AutoConfigAuthorizationRaw) AutoConfigAuthorizer {
// Our config file syntax wraps the static authorizer configuration in a "static" stanza. However // Our config file syntax wraps the static authorizer configuration in a "static" stanza. However
// internally we do not support multiple configured authorization types so the RuntimeConfig just // internally we do not support multiple configured authorization types so the RuntimeConfig just
// inlines the static one. While we can and probably should extend the authorization types in the // inlines the static one. While we can and probably should extend the authorization types in the
@ -2187,7 +2223,7 @@ func (b *Builder) autoConfigAuthorizerVal(raw AutoConfigAuthorizationRaw) AutoCo
return val return val
} }
func (b *Builder) validateAutoConfig(rt RuntimeConfig) error { func (b *builder) validateAutoConfig(rt RuntimeConfig) error {
autoconf := rt.AutoConfig autoconf := rt.AutoConfig
if err := validateAutoConfigAuthorizer(rt); err != nil { if err := validateAutoConfigAuthorizer(rt); err != nil {

View File

@ -62,10 +62,10 @@ func (e enterpriseConfigKeyError) Error() string {
return fmt.Sprintf("%q is a Consul Enterprise configuration and will have no effect", e.key) return fmt.Sprintf("%q is a Consul Enterprise configuration and will have no effect", e.key)
} }
func (*Builder) BuildEnterpriseRuntimeConfig(_ *RuntimeConfig, _ *Config) error { func (*builder) BuildEnterpriseRuntimeConfig(_ *RuntimeConfig, _ *Config) error {
return nil return nil
} }
func (*Builder) validateEnterpriseConfig(_ RuntimeConfig) error { func (*builder) validateEnterpriseConfig(_ RuntimeConfig) error {
return nil return nil
} }

View File

@ -10,6 +10,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -17,25 +18,28 @@ func TestLoad(t *testing.T) {
// Basically just testing that injection of the extra // Basically just testing that injection of the extra
// source works. // source works.
devMode := true devMode := true
builderOpts := BuilderOpts{ builderOpts := LoadOpts{
// putting this in dev mode so that the config validates // putting this in dev mode so that the config validates
// without having to specify a data directory // without having to specify a data directory
DevMode: &devMode, DevMode: &devMode,
DefaultConfig: FileSource{
Name: "test",
Format: "hcl",
Data: `node_name = "hobbiton"`,
},
Overrides: []Source{
FileSource{
Name: "overrides",
Format: "json",
Data: `{"check_reap_interval": "1ms"}`,
},
},
} }
cfg, warnings, err := Load(builderOpts, FileSource{ result, err := Load(builderOpts)
Name: "test",
Format: "hcl",
Data: `node_name = "hobbiton"`,
},
FileSource{
Name: "overrides",
Format: "json",
Data: `{"check_reap_interval": "1ms"}`,
})
require.NoError(t, err) require.NoError(t, err)
require.Empty(t, warnings) require.Empty(t, result.Warnings)
cfg := result.RuntimeConfig
require.NotNil(t, cfg) require.NotNil(t, cfg)
require.Equal(t, "hobbiton", cfg.NodeName) require.Equal(t, "hobbiton", cfg.NodeName)
require.Equal(t, 1*time.Millisecond, cfg.CheckReapInterval) require.Equal(t, 1*time.Millisecond, cfg.CheckReapInterval)
@ -65,7 +69,7 @@ func TestShouldParseFile(t *testing.T) {
func TestNewBuilder_PopulatesSourcesFromConfigFiles(t *testing.T) { func TestNewBuilder_PopulatesSourcesFromConfigFiles(t *testing.T) {
paths := setupConfigFiles(t) paths := setupConfigFiles(t)
b, err := NewBuilder(BuilderOpts{ConfigFiles: paths}) b, err := newBuilder(LoadOpts{ConfigFiles: paths})
require.NoError(t, err) require.NoError(t, err)
expected := []Source{ expected := []Source{
@ -81,7 +85,7 @@ func TestNewBuilder_PopulatesSourcesFromConfigFiles(t *testing.T) {
func TestNewBuilder_PopulatesSourcesFromConfigFiles_WithConfigFormat(t *testing.T) { func TestNewBuilder_PopulatesSourcesFromConfigFiles_WithConfigFormat(t *testing.T) {
paths := setupConfigFiles(t) paths := setupConfigFiles(t)
b, err := NewBuilder(BuilderOpts{ConfigFiles: paths, ConfigFormat: "hcl"}) b, err := newBuilder(LoadOpts{ConfigFiles: paths, ConfigFormat: "hcl"})
require.NoError(t, err) require.NoError(t, err)
expected := []Source{ expected := []Source{
@ -132,8 +136,8 @@ func TestBuilder_BuildAndValidate_NodeName(t *testing.T) {
} }
fn := func(t *testing.T, tc testCase) { fn := func(t *testing.T, tc testCase) {
b, err := NewBuilder(BuilderOpts{ b, err := newBuilder(LoadOpts{
Config: Config{ FlagValues: Config{
NodeName: pString(tc.nodeName), NodeName: pString(tc.nodeName),
DataDir: pString("dir"), DataDir: pString("dir"),
}, },
@ -171,7 +175,7 @@ func TestBuilder_BuildAndValidate_NodeName(t *testing.T) {
} }
} }
func patchBuilderShims(b *Builder) { func patchBuilderShims(b *builder) {
b.opts.hostname = func() (string, error) { b.opts.hostname = func() (string, error) {
return "thehostname", nil return "thehostname", nil
} }
@ -182,3 +186,35 @@ func patchBuilderShims(b *Builder) {
return []*net.IPAddr{ipAddr("dead:beef::1")}, nil return []*net.IPAddr{ipAddr("dead:beef::1")}, nil
} }
} }
func TestLoad_HTTPMaxConnsPerClientExceedsRLimit(t *testing.T) {
hcl := `
limits{
# We put a very high value to be sure to fail
# This value is more than max on Windows as well
http_max_conns_per_client = 16777217
}`
opts := LoadOpts{
DefaultConfig: FileSource{
Name: "test",
Format: "hcl",
Data: `
ae_interval = "1m"
data_dir="/tmp/00000000001979"
bind_addr = "127.0.0.1"
advertise_addr = "127.0.0.1"
datacenter = "dc1"
bootstrap = true
server = true
node_id = "00000000001979"
node_name = "Node-00000000001979"
`,
},
HCL: []string{hcl},
}
_, err := Load(opts)
require.Error(t, err)
assert.Contains(t, err.Error(), "but limits.http_max_conns_per_client: 16777217 needs at least 16777237")
}

View File

@ -269,15 +269,3 @@ func DevConsulSource() Source {
func strPtr(v string) *string { func strPtr(v string) *string {
return &v return &v
} }
func DefaultRuntimeConfig(hcl string) *RuntimeConfig {
b, err := NewBuilder(BuilderOpts{HCL: []string{hcl}})
if err != nil {
panic(err)
}
rt, err := b.BuildAndValidate()
if err != nil {
panic(err)
}
return &rt
}

View File

@ -3,43 +3,11 @@ package config
import ( import (
"flag" "flag"
"fmt" "fmt"
"net"
"time" "time"
) )
// BuilderOpts used by Builder to construct and validate a RuntimeConfig.
type BuilderOpts struct {
// Config contains the command line arguments that can also be set
// in a config file.
Config Config
// ConfigFiles contains the list of config files and directories
// that should be read.
ConfigFiles []string
// ConfigFormat forces all config files to be interpreted as this
// format independent of their extension.
ConfigFormat string
// DevMode indicates whether the agent should be started in development
// mode. This cannot be configured in a config file.
DevMode *bool
// HCL contains an arbitrary config in hcl format.
HCL []string
// hostname is a shim for testing, allowing tests to specify a replacement
// for os.Hostname.
hostname func() (string, error)
// getPrivateIPv4 and getPublicIPv6 are shims for testing, allowing tests to
// specify a replacement for ipaddr.GetPrivateIPv4 and ipaddr.GetPublicIPv6.
getPrivateIPv4 func() ([]*net.IPAddr, error)
getPublicIPv6 func() ([]*net.IPAddr, error)
}
// AddFlags adds the command line flags for the agent. // AddFlags adds the command line flags for the agent.
func AddFlags(fs *flag.FlagSet, f *BuilderOpts) { func AddFlags(fs *flag.FlagSet, f *LoadOpts) {
add := func(p interface{}, name, help string) { add := func(p interface{}, name, help string) {
switch x := p.(type) { switch x := p.(type) {
case **bool: case **bool:
@ -60,70 +28,70 @@ func AddFlags(fs *flag.FlagSet, f *BuilderOpts) {
} }
// command line flags ordered by flag name // command line flags ordered by flag name
add(&f.Config.AdvertiseAddrLAN, "advertise", "Sets the advertise address to use.") add(&f.FlagValues.AdvertiseAddrLAN, "advertise", "Sets the advertise address to use.")
add(&f.Config.AdvertiseAddrWAN, "advertise-wan", "Sets address to advertise on WAN instead of -advertise address.") add(&f.FlagValues.AdvertiseAddrWAN, "advertise-wan", "Sets address to advertise on WAN instead of -advertise address.")
add(&f.Config.BindAddr, "bind", "Sets the bind address for cluster communication.") add(&f.FlagValues.BindAddr, "bind", "Sets the bind address for cluster communication.")
add(&f.Config.Ports.Server, "server-port", "Sets the server port to listen on.") add(&f.FlagValues.Ports.Server, "server-port", "Sets the server port to listen on.")
add(&f.Config.Bootstrap, "bootstrap", "Sets server to bootstrap mode.") add(&f.FlagValues.Bootstrap, "bootstrap", "Sets server to bootstrap mode.")
add(&f.Config.BootstrapExpect, "bootstrap-expect", "Sets server to expect bootstrap mode.") add(&f.FlagValues.BootstrapExpect, "bootstrap-expect", "Sets server to expect bootstrap mode.")
add(&f.Config.ClientAddr, "client", "Sets the address to bind for client access. This includes RPC, DNS, HTTP, HTTPS and gRPC (if configured).") add(&f.FlagValues.ClientAddr, "client", "Sets the address to bind for client access. This includes RPC, DNS, HTTP, HTTPS and gRPC (if configured).")
add(&f.Config.CheckOutputMaxSize, "check_output_max_size", "Sets the maximum output size for checks on this agent") add(&f.FlagValues.CheckOutputMaxSize, "check_output_max_size", "Sets the maximum output size for checks on this agent")
add(&f.ConfigFiles, "config-dir", "Path to a directory to read configuration files from. This will read every file ending in '.json' as configuration in this directory in alphabetical order. Can be specified multiple times.") add(&f.ConfigFiles, "config-dir", "Path to a directory to read configuration files from. This will read every file ending in '.json' as configuration in this directory in alphabetical order. Can be specified multiple times.")
add(&f.ConfigFiles, "config-file", "Path to a file in JSON or HCL format with a matching file extension. Can be specified multiple times.") add(&f.ConfigFiles, "config-file", "Path to a file in JSON or HCL format with a matching file extension. Can be specified multiple times.")
fs.StringVar(&f.ConfigFormat, "config-format", "", "Config files are in this format irrespective of their extension. Must be 'hcl' or 'json'") fs.StringVar(&f.ConfigFormat, "config-format", "", "Config files are in this format irrespective of their extension. Must be 'hcl' or 'json'")
add(&f.Config.DataDir, "data-dir", "Path to a data directory to store agent state.") add(&f.FlagValues.DataDir, "data-dir", "Path to a data directory to store agent state.")
add(&f.Config.Datacenter, "datacenter", "Datacenter of the agent.") add(&f.FlagValues.Datacenter, "datacenter", "Datacenter of the agent.")
add(&f.Config.DefaultQueryTime, "default-query-time", "the amount of time a blocking query will wait before Consul will force a response. This value can be overridden by the 'wait' query parameter.") add(&f.FlagValues.DefaultQueryTime, "default-query-time", "the amount of time a blocking query will wait before Consul will force a response. This value can be overridden by the 'wait' query parameter.")
add(&f.DevMode, "dev", "Starts the agent in development mode.") add(&f.DevMode, "dev", "Starts the agent in development mode.")
add(&f.Config.DisableHostNodeID, "disable-host-node-id", "Setting this to true will prevent Consul from using information from the host to generate a node ID, and will cause Consul to generate a random node ID instead.") add(&f.FlagValues.DisableHostNodeID, "disable-host-node-id", "Setting this to true will prevent Consul from using information from the host to generate a node ID, and will cause Consul to generate a random node ID instead.")
add(&f.Config.DisableKeyringFile, "disable-keyring-file", "Disables the backing up of the keyring to a file.") add(&f.FlagValues.DisableKeyringFile, "disable-keyring-file", "Disables the backing up of the keyring to a file.")
add(&f.Config.Ports.DNS, "dns-port", "DNS port to use.") add(&f.FlagValues.Ports.DNS, "dns-port", "DNS port to use.")
add(&f.Config.DNSDomain, "domain", "Domain to use for DNS interface.") add(&f.FlagValues.DNSDomain, "domain", "Domain to use for DNS interface.")
add(&f.Config.DNSAltDomain, "alt-domain", "Alternate domain to use for DNS interface.") add(&f.FlagValues.DNSAltDomain, "alt-domain", "Alternate domain to use for DNS interface.")
add(&f.Config.EnableScriptChecks, "enable-script-checks", "Enables health check scripts.") add(&f.FlagValues.EnableScriptChecks, "enable-script-checks", "Enables health check scripts.")
add(&f.Config.EnableLocalScriptChecks, "enable-local-script-checks", "Enables health check scripts from configuration file.") add(&f.FlagValues.EnableLocalScriptChecks, "enable-local-script-checks", "Enables health check scripts from configuration file.")
add(&f.Config.HTTPConfig.AllowWriteHTTPFrom, "allow-write-http-from", "Only allow write endpoint calls from given network. CIDR format, can be specified multiple times.") add(&f.FlagValues.HTTPConfig.AllowWriteHTTPFrom, "allow-write-http-from", "Only allow write endpoint calls from given network. CIDR format, can be specified multiple times.")
add(&f.Config.EncryptKey, "encrypt", "Provides the gossip encryption key.") add(&f.FlagValues.EncryptKey, "encrypt", "Provides the gossip encryption key.")
add(&f.Config.Ports.GRPC, "grpc-port", "Sets the gRPC API port to listen on (currently needed for Envoy xDS only).") add(&f.FlagValues.Ports.GRPC, "grpc-port", "Sets the gRPC API port to listen on (currently needed for Envoy xDS only).")
add(&f.Config.Ports.HTTP, "http-port", "Sets the HTTP API port to listen on.") add(&f.FlagValues.Ports.HTTP, "http-port", "Sets the HTTP API port to listen on.")
add(&f.Config.Ports.HTTPS, "https-port", "Sets the HTTPS API port to listen on.") add(&f.FlagValues.Ports.HTTPS, "https-port", "Sets the HTTPS API port to listen on.")
add(&f.Config.StartJoinAddrsLAN, "join", "Address of an agent to join at start time. Can be specified multiple times.") add(&f.FlagValues.StartJoinAddrsLAN, "join", "Address of an agent to join at start time. Can be specified multiple times.")
add(&f.Config.StartJoinAddrsWAN, "join-wan", "Address of an agent to join -wan at start time. Can be specified multiple times.") add(&f.FlagValues.StartJoinAddrsWAN, "join-wan", "Address of an agent to join -wan at start time. Can be specified multiple times.")
add(&f.Config.LogLevel, "log-level", "Log level of the agent.") add(&f.FlagValues.LogLevel, "log-level", "Log level of the agent.")
add(&f.Config.LogJSON, "log-json", "Output logs in JSON format.") add(&f.FlagValues.LogJSON, "log-json", "Output logs in JSON format.")
add(&f.Config.LogFile, "log-file", "Path to the file the logs get written to") add(&f.FlagValues.LogFile, "log-file", "Path to the file the logs get written to")
add(&f.Config.LogRotateBytes, "log-rotate-bytes", "Maximum number of bytes that should be written to a log file") add(&f.FlagValues.LogRotateBytes, "log-rotate-bytes", "Maximum number of bytes that should be written to a log file")
add(&f.Config.LogRotateDuration, "log-rotate-duration", "Time after which log rotation needs to be performed") add(&f.FlagValues.LogRotateDuration, "log-rotate-duration", "Time after which log rotation needs to be performed")
add(&f.Config.LogRotateMaxFiles, "log-rotate-max-files", "Maximum number of log file archives to keep") add(&f.FlagValues.LogRotateMaxFiles, "log-rotate-max-files", "Maximum number of log file archives to keep")
add(&f.Config.MaxQueryTime, "max-query-time", "the maximum amount of time a blocking query can wait before Consul will force a response. Consul applies jitter to the wait time. The jittered time will be capped to MaxQueryTime.") add(&f.FlagValues.MaxQueryTime, "max-query-time", "the maximum amount of time a blocking query can wait before Consul will force a response. Consul applies jitter to the wait time. The jittered time will be capped to MaxQueryTime.")
add(&f.Config.NodeName, "node", "Name of this node. Must be unique in the cluster.") add(&f.FlagValues.NodeName, "node", "Name of this node. Must be unique in the cluster.")
add(&f.Config.NodeID, "node-id", "A unique ID for this node across space and time. Defaults to a randomly-generated ID that persists in the data-dir.") add(&f.FlagValues.NodeID, "node-id", "A unique ID for this node across space and time. Defaults to a randomly-generated ID that persists in the data-dir.")
add(&f.Config.NodeMeta, "node-meta", "An arbitrary metadata key/value pair for this node, of the format `key:value`. Can be specified multiple times.") add(&f.FlagValues.NodeMeta, "node-meta", "An arbitrary metadata key/value pair for this node, of the format `key:value`. Can be specified multiple times.")
add(&f.Config.ReadReplica, "non-voting-server", "(Enterprise-only) DEPRECATED: -read-replica should be used instead") add(&f.FlagValues.ReadReplica, "non-voting-server", "(Enterprise-only) DEPRECATED: -read-replica should be used instead")
add(&f.Config.ReadReplica, "read-replica", "(Enterprise-only) This flag is used to make the server not participate in the Raft quorum, and have it only receive the data replication stream. This can be used to add read scalability to a cluster in cases where a high volume of reads to servers are needed.") add(&f.FlagValues.ReadReplica, "read-replica", "(Enterprise-only) This flag is used to make the server not participate in the Raft quorum, and have it only receive the data replication stream. This can be used to add read scalability to a cluster in cases where a high volume of reads to servers are needed.")
add(&f.Config.PidFile, "pid-file", "Path to file to store agent PID.") add(&f.FlagValues.PidFile, "pid-file", "Path to file to store agent PID.")
add(&f.Config.RPCProtocol, "protocol", "Sets the protocol version. Defaults to latest.") add(&f.FlagValues.RPCProtocol, "protocol", "Sets the protocol version. Defaults to latest.")
add(&f.Config.RaftProtocol, "raft-protocol", "Sets the Raft protocol version. Defaults to latest.") add(&f.FlagValues.RaftProtocol, "raft-protocol", "Sets the Raft protocol version. Defaults to latest.")
add(&f.Config.DNSRecursors, "recursor", "Address of an upstream DNS server. Can be specified multiple times.") add(&f.FlagValues.DNSRecursors, "recursor", "Address of an upstream DNS server. Can be specified multiple times.")
add(&f.Config.PrimaryGateways, "primary-gateway", "Address of a mesh gateway in the primary datacenter to use to bootstrap WAN federation at start time with retries enabled. Can be specified multiple times.") add(&f.FlagValues.PrimaryGateways, "primary-gateway", "Address of a mesh gateway in the primary datacenter to use to bootstrap WAN federation at start time with retries enabled. Can be specified multiple times.")
add(&f.Config.RejoinAfterLeave, "rejoin", "Ignores a previous leave and attempts to rejoin the cluster.") add(&f.FlagValues.RejoinAfterLeave, "rejoin", "Ignores a previous leave and attempts to rejoin the cluster.")
add(&f.Config.RetryJoinIntervalLAN, "retry-interval", "Time to wait between join attempts.") add(&f.FlagValues.RetryJoinIntervalLAN, "retry-interval", "Time to wait between join attempts.")
add(&f.Config.RetryJoinIntervalWAN, "retry-interval-wan", "Time to wait between join -wan attempts.") add(&f.FlagValues.RetryJoinIntervalWAN, "retry-interval-wan", "Time to wait between join -wan attempts.")
add(&f.Config.RetryJoinLAN, "retry-join", "Address of an agent to join at start time with retries enabled. Can be specified multiple times.") add(&f.FlagValues.RetryJoinLAN, "retry-join", "Address of an agent to join at start time with retries enabled. Can be specified multiple times.")
add(&f.Config.RetryJoinWAN, "retry-join-wan", "Address of an agent to join -wan at start time with retries enabled. Can be specified multiple times.") add(&f.FlagValues.RetryJoinWAN, "retry-join-wan", "Address of an agent to join -wan at start time with retries enabled. Can be specified multiple times.")
add(&f.Config.RetryJoinMaxAttemptsLAN, "retry-max", "Maximum number of join attempts. Defaults to 0, which will retry indefinitely.") add(&f.FlagValues.RetryJoinMaxAttemptsLAN, "retry-max", "Maximum number of join attempts. Defaults to 0, which will retry indefinitely.")
add(&f.Config.RetryJoinMaxAttemptsWAN, "retry-max-wan", "Maximum number of join -wan attempts. Defaults to 0, which will retry indefinitely.") add(&f.FlagValues.RetryJoinMaxAttemptsWAN, "retry-max-wan", "Maximum number of join -wan attempts. Defaults to 0, which will retry indefinitely.")
add(&f.Config.SerfAllowedCIDRsLAN, "serf-lan-allowed-cidrs", "Networks (eg: 192.168.1.0/24) allowed for Serf LAN. Can be specified multiple times.") add(&f.FlagValues.SerfAllowedCIDRsLAN, "serf-lan-allowed-cidrs", "Networks (eg: 192.168.1.0/24) allowed for Serf LAN. Can be specified multiple times.")
add(&f.Config.SerfAllowedCIDRsWAN, "serf-wan-allowed-cidrs", "Networks (eg: 192.168.1.0/24) allowed for Serf WAN (other datacenters). Can be specified multiple times.") add(&f.FlagValues.SerfAllowedCIDRsWAN, "serf-wan-allowed-cidrs", "Networks (eg: 192.168.1.0/24) allowed for Serf WAN (other datacenters). Can be specified multiple times.")
add(&f.Config.SerfBindAddrLAN, "serf-lan-bind", "Address to bind Serf LAN listeners to.") add(&f.FlagValues.SerfBindAddrLAN, "serf-lan-bind", "Address to bind Serf LAN listeners to.")
add(&f.Config.Ports.SerfLAN, "serf-lan-port", "Sets the Serf LAN port to listen on.") add(&f.FlagValues.Ports.SerfLAN, "serf-lan-port", "Sets the Serf LAN port to listen on.")
add(&f.Config.SegmentName, "segment", "(Enterprise-only) Sets the network segment to join.") add(&f.FlagValues.SegmentName, "segment", "(Enterprise-only) Sets the network segment to join.")
add(&f.Config.SerfBindAddrWAN, "serf-wan-bind", "Address to bind Serf WAN listeners to.") add(&f.FlagValues.SerfBindAddrWAN, "serf-wan-bind", "Address to bind Serf WAN listeners to.")
add(&f.Config.Ports.SerfWAN, "serf-wan-port", "Sets the Serf WAN port to listen on.") add(&f.FlagValues.Ports.SerfWAN, "serf-wan-port", "Sets the Serf WAN port to listen on.")
add(&f.Config.ServerMode, "server", "Switches agent to server mode.") add(&f.FlagValues.ServerMode, "server", "Switches agent to server mode.")
add(&f.Config.EnableSyslog, "syslog", "Enables logging to syslog.") add(&f.FlagValues.EnableSyslog, "syslog", "Enables logging to syslog.")
add(&f.Config.UIConfig.Enabled, "ui", "Enables the built-in static web UI server.") add(&f.FlagValues.UIConfig.Enabled, "ui", "Enables the built-in static web UI server.")
add(&f.Config.UIConfig.ContentPath, "ui-content-path", "Sets the external UI path to a string. Defaults to: /ui/ ") add(&f.FlagValues.UIConfig.ContentPath, "ui-content-path", "Sets the external UI path to a string. Defaults to: /ui/ ")
add(&f.Config.UIConfig.Dir, "ui-dir", "Path to directory containing the web UI resources.") add(&f.FlagValues.UIConfig.Dir, "ui-dir", "Path to directory containing the web UI resources.")
add(&f.HCL, "hcl", "hcl config fragment. Can be specified multiple times.") add(&f.HCL, "hcl", "hcl config fragment. Can be specified multiple times.")
} }

View File

@ -15,78 +15,78 @@ import (
func TestAddFlags_WithParse(t *testing.T) { func TestAddFlags_WithParse(t *testing.T) {
tests := []struct { tests := []struct {
args []string args []string
expected BuilderOpts expected LoadOpts
extra []string extra []string
}{ }{
{}, {},
{ {
args: []string{`-bind`, `a`}, args: []string{`-bind`, `a`},
expected: BuilderOpts{Config: Config{BindAddr: pString("a")}}, expected: LoadOpts{FlagValues: Config{BindAddr: pString("a")}},
}, },
{ {
args: []string{`-bootstrap`}, args: []string{`-bootstrap`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(true)}}, expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(true)}},
}, },
{ {
args: []string{`-bootstrap=true`}, args: []string{`-bootstrap=true`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(true)}}, expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(true)}},
}, },
{ {
args: []string{`-bootstrap=false`}, args: []string{`-bootstrap=false`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(false)}}, expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(false)}},
}, },
{ {
args: []string{`-config-file`, `a`, `-config-dir`, `b`, `-config-file`, `c`, `-config-dir`, `d`}, args: []string{`-config-file`, `a`, `-config-dir`, `b`, `-config-file`, `c`, `-config-dir`, `d`},
expected: BuilderOpts{ConfigFiles: []string{"a", "b", "c", "d"}}, expected: LoadOpts{ConfigFiles: []string{"a", "b", "c", "d"}},
}, },
{ {
args: []string{`-datacenter`, `a`}, args: []string{`-datacenter`, `a`},
expected: BuilderOpts{Config: Config{Datacenter: pString("a")}}, expected: LoadOpts{FlagValues: Config{Datacenter: pString("a")}},
}, },
{ {
args: []string{`-dns-port`, `1`}, args: []string{`-dns-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{DNS: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{DNS: pInt(1)}}},
}, },
{ {
args: []string{`-grpc-port`, `1`}, args: []string{`-grpc-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{GRPC: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{GRPC: pInt(1)}}},
}, },
{ {
args: []string{`-http-port`, `1`}, args: []string{`-http-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{HTTP: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{HTTP: pInt(1)}}},
}, },
{ {
args: []string{`-https-port`, `1`}, args: []string{`-https-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{HTTPS: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{HTTPS: pInt(1)}}},
}, },
{ {
args: []string{`-serf-lan-port`, `1`}, args: []string{`-serf-lan-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{SerfLAN: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{SerfLAN: pInt(1)}}},
}, },
{ {
args: []string{`-serf-wan-port`, `1`}, args: []string{`-serf-wan-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{SerfWAN: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{SerfWAN: pInt(1)}}},
}, },
{ {
args: []string{`-server-port`, `1`}, args: []string{`-server-port`, `1`},
expected: BuilderOpts{Config: Config{Ports: Ports{Server: pInt(1)}}}, expected: LoadOpts{FlagValues: Config{Ports: Ports{Server: pInt(1)}}},
}, },
{ {
args: []string{`-join`, `a`, `-join`, `b`}, args: []string{`-join`, `a`, `-join`, `b`},
expected: BuilderOpts{Config: Config{StartJoinAddrsLAN: []string{"a", "b"}}}, expected: LoadOpts{FlagValues: Config{StartJoinAddrsLAN: []string{"a", "b"}}},
}, },
{ {
args: []string{`-node-meta`, `a:b`, `-node-meta`, `c:d`}, args: []string{`-node-meta`, `a:b`, `-node-meta`, `c:d`},
expected: BuilderOpts{Config: Config{NodeMeta: map[string]string{"a": "b", "c": "d"}}}, expected: LoadOpts{FlagValues: Config{NodeMeta: map[string]string{"a": "b", "c": "d"}}},
}, },
{ {
args: []string{`-bootstrap`, `true`}, args: []string{`-bootstrap`, `true`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(true)}}, expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(true)}},
extra: []string{"true"}, extra: []string{"true"},
}, },
{ {
args: []string{`-primary-gateway`, `foo.local`, `-primary-gateway`, `bar.local`}, args: []string{`-primary-gateway`, `foo.local`, `-primary-gateway`, `bar.local`},
expected: BuilderOpts{Config: Config{PrimaryGateways: []string{ expected: LoadOpts{FlagValues: Config{PrimaryGateways: []string{
"foo.local", "bar.local", "foo.local", "bar.local",
}}}, }}},
}, },
@ -94,7 +94,7 @@ func TestAddFlags_WithParse(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(strings.Join(tt.args, " "), func(t *testing.T) { t.Run(strings.Join(tt.args, " "), func(t *testing.T) {
flags := BuilderOpts{} flags := LoadOpts{}
fs := flag.NewFlagSet("", flag.ContinueOnError) fs := flag.NewFlagSet("", flag.ContinueOnError)
AddFlags(fs, &flags) AddFlags(fs, &flags)
@ -106,8 +106,8 @@ func TestAddFlags_WithParse(t *testing.T) {
if tt.extra == nil && fs.Args() != nil { if tt.extra == nil && fs.Args() != nil {
tt.extra = []string{} tt.extra = []string{}
} }
if len(tt.expected.Config.NodeMeta) == 0 { if len(tt.expected.FlagValues.NodeMeta) == 0 {
tt.expected.Config.NodeMeta = map[string]string{} tt.expected.FlagValues.NodeMeta = map[string]string{}
} }
require.Equal(t, tt.extra, fs.Args()) require.Equal(t, tt.extra, fs.Args())
require.Equal(t, tt.expected, flags) require.Equal(t, tt.expected, flags)

View File

@ -4898,8 +4898,7 @@ func testConfig(t *testing.T, tests []configTest, dataDir string) {
} }
t.Run(strings.Join(desc, ":"), func(t *testing.T) { t.Run(strings.Join(desc, ":"), func(t *testing.T) {
flags := BuilderOpts{} flags := LoadOpts{}
fs := flag.NewFlagSet("", flag.ContinueOnError) fs := flag.NewFlagSet("", flag.ContinueOnError)
AddFlags(fs, &flags) AddFlags(fs, &flags)
err := fs.Parse(tt.args) err := fs.Parse(tt.args)
@ -4913,7 +4912,7 @@ func testConfig(t *testing.T, tests []configTest, dataDir string) {
} }
// Then create a builder with the flags. // Then create a builder with the flags.
b, err := NewBuilder(flags) b, err := newBuilder(flags)
require.NoError(t, err) require.NoError(t, err)
patchBuilderShims(b) patchBuilderShims(b)
@ -4964,7 +4963,7 @@ func testConfig(t *testing.T, tests []configTest, dataDir string) {
// build a default configuration, then patch the fields we expect to change // build a default configuration, then patch the fields we expect to change
// and compare it with the generated configuration. Since the expected // and compare it with the generated configuration. Since the expected
// runtime config has been validated we do not need to validate it again. // runtime config has been validated we do not need to validate it again.
x, err := NewBuilder(BuilderOpts{}) x, err := newBuilder(LoadOpts{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -4997,8 +4996,8 @@ func assertDeepEqual(t *testing.T, x, y interface{}, opts ...cmp.Option) {
} }
} }
func TestNewBuilder_InvalidConfigFormat(t *testing.T) { func TestLoad_InvalidConfigFormat(t *testing.T) {
_, err := NewBuilder(BuilderOpts{ConfigFormat: "yaml"}) _, err := Load(LoadOpts{ConfigFormat: "yaml"})
require.Error(t, err) require.Error(t, err)
require.Contains(t, err.Error(), "-config-format must be either 'hcl' or 'json'") require.Contains(t, err.Error(), "-config-format must be either 'hcl' or 'json'")
} }
@ -6496,7 +6495,7 @@ func TestFullConfig(t *testing.T) {
}, },
} }
want := RuntimeConfig{ expected := RuntimeConfig{
// non-user configurable values // non-user configurable values
ACLDisabledTTL: 957 * time.Second, ACLDisabledTTL: 957 * time.Second,
AEInterval: 10003 * time.Second, AEInterval: 10003 * time.Second,
@ -7205,7 +7204,7 @@ func TestFullConfig(t *testing.T) {
}, },
} }
entFullRuntimeConfig(&want) entFullRuntimeConfig(&expected)
warns := []string{ warns := []string{
`The 'acl_datacenter' field is deprecated. Use the 'primary_datacenter' field instead.`, `The 'acl_datacenter' field is deprecated. Use the 'primary_datacenter' field instead.`,
@ -7220,7 +7219,7 @@ func TestFullConfig(t *testing.T) {
// todo(fs): * move first check into the Check field // todo(fs): * move first check into the Check field
// todo(fs): * ignore the Check field // todo(fs): * ignore the Check field
// todo(fs): both feel like a hack // todo(fs): both feel like a hack
if err := nonZero("RuntimeConfig", nil, want); err != nil { if err := nonZero("RuntimeConfig", nil, expected); err != nil {
t.Log(err) t.Log(err)
} }
@ -7228,7 +7227,7 @@ func TestFullConfig(t *testing.T) {
t.Run(format, func(t *testing.T) { t.Run(format, func(t *testing.T) {
// parse the flags since this is the only way we can set the // parse the flags since this is the only way we can set the
// DevMode flag // DevMode flag
var flags BuilderOpts var flags LoadOpts
fs := flag.NewFlagSet("", flag.ContinueOnError) fs := flag.NewFlagSet("", flag.ContinueOnError)
AddFlags(fs, &flags) AddFlags(fs, &flags)
if err := fs.Parse(flagSrc); err != nil { if err := fs.Parse(flagSrc); err != nil {
@ -7236,7 +7235,7 @@ func TestFullConfig(t *testing.T) {
} }
require.Len(t, fs.Args(), 0) require.Len(t, fs.Args(), 0)
b, err := NewBuilder(flags) b, err := newBuilder(flags)
if err != nil { if err != nil {
t.Fatalf("NewBuilder: %s", err) t.Fatalf("NewBuilder: %s", err)
} }
@ -7250,7 +7249,7 @@ func TestFullConfig(t *testing.T) {
t.Fatalf("Build: %s", err) t.Fatalf("Build: %s", err)
} }
require.Equal(t, want, rt) require.Equal(t, expected, rt)
// at this point we have confirmed that the parsing worked // at this point we have confirmed that the parsing worked
// for all fields but the validation will fail since certain // for all fields but the validation will fail since certain

View File

@ -6,7 +6,7 @@ import (
"github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/agent/structs"
) )
func (b *Builder) validateSegments(rt RuntimeConfig) error { func (b *builder) validateSegments(rt RuntimeConfig) error {
if rt.SegmentName != "" { if rt.SegmentName != "" {
return structs.ErrSegmentsNotSupported return structs.ErrSegmentsNotSupported
} }

View File

@ -10,6 +10,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/hashicorp/serf/coordinate"
"github.com/miekg/dns"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/agent/config" "github.com/hashicorp/consul/agent/config"
agentdns "github.com/hashicorp/consul/agent/dns" agentdns "github.com/hashicorp/consul/agent/dns"
"github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/agent/structs"
@ -17,9 +21,6 @@ import (
"github.com/hashicorp/consul/lib" "github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/sdk/testutil/retry" "github.com/hashicorp/consul/sdk/testutil/retry"
"github.com/hashicorp/consul/testrpc" "github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/serf/coordinate"
"github.com/miekg/dns"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -6664,7 +6665,7 @@ func TestDNS_trimUDPResponse_NoTrim(t *testing.T) {
}, },
} }
cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) cfg := loadRuntimeConfig(t, `data_dir = "a" bind_addr = "127.0.0.1"`)
if trimmed := trimUDPResponse(req, resp, cfg.DNSUDPAnswerLimit); trimmed { if trimmed := trimUDPResponse(req, resp, cfg.DNSUDPAnswerLimit); trimmed {
t.Fatalf("Bad %#v", *resp) t.Fatalf("Bad %#v", *resp)
} }
@ -6698,7 +6699,7 @@ func TestDNS_trimUDPResponse_NoTrim(t *testing.T) {
func TestDNS_trimUDPResponse_TrimLimit(t *testing.T) { func TestDNS_trimUDPResponse_TrimLimit(t *testing.T) {
t.Parallel() t.Parallel()
cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) cfg := loadRuntimeConfig(t, `data_dir = "a" bind_addr = "127.0.0.1"`)
req, resp, expected := &dns.Msg{}, &dns.Msg{}, &dns.Msg{} req, resp, expected := &dns.Msg{}, &dns.Msg{}, &dns.Msg{}
for i := 0; i < cfg.DNSUDPAnswerLimit+1; i++ { for i := 0; i < cfg.DNSUDPAnswerLimit+1; i++ {
@ -6736,9 +6737,17 @@ func TestDNS_trimUDPResponse_TrimLimit(t *testing.T) {
} }
} }
func loadRuntimeConfig(t *testing.T, hcl string) *config.RuntimeConfig {
t.Helper()
result, err := config.Load(config.LoadOpts{HCL: []string{hcl}})
require.NoError(t, err)
require.Len(t, result.Warnings, 0)
return result.RuntimeConfig
}
func TestDNS_trimUDPResponse_TrimSize(t *testing.T) { func TestDNS_trimUDPResponse_TrimSize(t *testing.T) {
t.Parallel() t.Parallel()
cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) cfg := loadRuntimeConfig(t, `data_dir = "a" bind_addr = "127.0.0.1"`)
req, resp := &dns.Msg{}, &dns.Msg{} req, resp := &dns.Msg{}, &dns.Msg{}
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
@ -6791,7 +6800,7 @@ func TestDNS_trimUDPResponse_TrimSize(t *testing.T) {
func TestDNS_trimUDPResponse_TrimSizeEDNS(t *testing.T) { func TestDNS_trimUDPResponse_TrimSizeEDNS(t *testing.T) {
t.Parallel() t.Parallel()
cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) cfg := loadRuntimeConfig(t, `data_dir = "a" bind_addr = "127.0.0.1"`)
req, resp := &dns.Msg{}, &dns.Msg{} req, resp := &dns.Msg{}, &dns.Msg{}
@ -7094,7 +7103,7 @@ func TestDNS_syncExtra(t *testing.T) {
func TestDNS_Compression_trimUDPResponse(t *testing.T) { func TestDNS_Compression_trimUDPResponse(t *testing.T) {
t.Parallel() t.Parallel()
cfg := config.DefaultRuntimeConfig(`data_dir = "a" bind_addr = "127.0.0.1"`) cfg := loadRuntimeConfig(t, `data_dir = "a" bind_addr = "127.0.0.1"`)
req, m := dns.Msg{}, dns.Msg{} req, m := dns.Msg{}, dns.Msg{}
trimUDPResponse(&req, &m, cfg.DNSUDPAnswerLimit) trimUDPResponse(&req, &m, cfg.DNSUDPAnswerLimit)

View File

@ -1773,7 +1773,7 @@ func TestAgent_ServiceTokens(t *testing.T) {
tokens := new(token.Store) tokens := new(token.Store)
tokens.UpdateUserToken("default", token.TokenSourceConfig) tokens.UpdateUserToken("default", token.TokenSourceConfig)
cfg := config.DefaultRuntimeConfig(`bind_addr = "127.0.0.1" data_dir = "dummy"`) cfg := loadRuntimeConfig(t, `bind_addr = "127.0.0.1" data_dir = "dummy"`)
l := local.NewState(agent.LocalConfig(cfg), nil, tokens) l := local.NewState(agent.LocalConfig(cfg), nil, tokens)
l.TriggerSyncChanges = func() {} l.TriggerSyncChanges = func() {}
@ -1797,12 +1797,20 @@ func TestAgent_ServiceTokens(t *testing.T) {
} }
} }
func loadRuntimeConfig(t *testing.T, hcl string) *config.RuntimeConfig {
t.Helper()
result, err := config.Load(config.LoadOpts{HCL: []string{hcl}})
require.NoError(t, err)
require.Len(t, result.Warnings, 0)
return result.RuntimeConfig
}
func TestAgent_CheckTokens(t *testing.T) { func TestAgent_CheckTokens(t *testing.T) {
t.Parallel() t.Parallel()
tokens := new(token.Store) tokens := new(token.Store)
tokens.UpdateUserToken("default", token.TokenSourceConfig) tokens.UpdateUserToken("default", token.TokenSourceConfig)
cfg := config.DefaultRuntimeConfig(`bind_addr = "127.0.0.1" data_dir = "dummy"`) cfg := loadRuntimeConfig(t, `bind_addr = "127.0.0.1" data_dir = "dummy"`)
l := local.NewState(agent.LocalConfig(cfg), nil, tokens) l := local.NewState(agent.LocalConfig(cfg), nil, tokens)
l.TriggerSyncChanges = func() {} l.TriggerSyncChanges = func() {}
@ -1827,7 +1835,7 @@ func TestAgent_CheckTokens(t *testing.T) {
func TestAgent_CheckCriticalTime(t *testing.T) { func TestAgent_CheckCriticalTime(t *testing.T) {
t.Parallel() t.Parallel()
cfg := config.DefaultRuntimeConfig(`bind_addr = "127.0.0.1" data_dir = "dummy"`) cfg := loadRuntimeConfig(t, `bind_addr = "127.0.0.1" data_dir = "dummy"`)
l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store)) l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store))
l.TriggerSyncChanges = func() {} l.TriggerSyncChanges = func() {}
@ -1891,7 +1899,7 @@ func TestAgent_CheckCriticalTime(t *testing.T) {
func TestAgent_AddCheckFailure(t *testing.T) { func TestAgent_AddCheckFailure(t *testing.T) {
t.Parallel() t.Parallel()
cfg := config.DefaultRuntimeConfig(`bind_addr = "127.0.0.1" data_dir = "dummy"`) cfg := loadRuntimeConfig(t, `bind_addr = "127.0.0.1" data_dir = "dummy"`)
l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store)) l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store))
l.TriggerSyncChanges = func() {} l.TriggerSyncChanges = func() {}
@ -1914,7 +1922,7 @@ func TestAgent_AliasCheck(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
cfg := config.DefaultRuntimeConfig(`bind_addr = "127.0.0.1" data_dir = "dummy"`) cfg := loadRuntimeConfig(t, `bind_addr = "127.0.0.1" data_dir = "dummy"`)
l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store)) l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store))
l.TriggerSyncChanges = func() {} l.TriggerSyncChanges = func() {}
@ -1965,7 +1973,7 @@ func TestAgent_AliasCheck_ServiceNotification(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
cfg := config.DefaultRuntimeConfig(`bind_addr = "127.0.0.1" data_dir = "dummy"`) cfg := loadRuntimeConfig(t, `bind_addr = "127.0.0.1" data_dir = "dummy"`)
l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store)) l := local.NewState(agent.LocalConfig(cfg), nil, new(token.Store))
l.TriggerSyncChanges = func() {} l.TriggerSyncChanges = func() {}

View File

@ -11,6 +11,7 @@ import (
"github.com/hashicorp/consul/agent/consul/fsm" "github.com/hashicorp/consul/agent/consul/fsm"
"github.com/armon/go-metrics/prometheus" "github.com/armon/go-metrics/prometheus"
"github.com/hashicorp/consul/agent/consul/usagemetrics" "github.com/hashicorp/consul/agent/consul/usagemetrics"
"github.com/hashicorp/consul/agent/local" "github.com/hashicorp/consul/agent/local"
@ -52,15 +53,16 @@ type MetricsHandler interface {
DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error)
} }
type ConfigLoader func(source config.Source) (cfg *config.RuntimeConfig, warnings []string, err error) type ConfigLoader func(source config.Source) (config.LoadResult, error)
func NewBaseDeps(configLoader ConfigLoader, logOut io.Writer) (BaseDeps, error) { func NewBaseDeps(configLoader ConfigLoader, logOut io.Writer) (BaseDeps, error) {
d := BaseDeps{} d := BaseDeps{}
cfg, warnings, err := configLoader(nil) result, err := configLoader(nil)
if err != nil { if err != nil {
return d, err return d, err
} }
cfg := result.RuntimeConfig
logConf := cfg.Logging logConf := cfg.Logging
logConf.Name = logging.Agent logConf.Name = logging.Agent
d.Logger, err = logging.Setup(logConf, logOut) d.Logger, err = logging.Setup(logConf, logOut)
@ -69,7 +71,7 @@ func NewBaseDeps(configLoader ConfigLoader, logOut io.Writer) (BaseDeps, error)
} }
grpclog.SetLoggerV2(logging.NewGRPCLogger(cfg.Logging.LogLevel, d.Logger)) grpclog.SetLoggerV2(logging.NewGRPCLogger(cfg.Logging.LogLevel, d.Logger))
for _, w := range warnings { for _, w := range result.Warnings {
d.Logger.Warn(w) d.Logger.Warn(w)
} }

View File

@ -16,12 +16,13 @@ import (
"time" "time"
metrics "github.com/armon/go-metrics" metrics "github.com/armon/go-metrics"
"github.com/hashicorp/consul/sdk/testutil"
"github.com/hashicorp/errwrap" "github.com/hashicorp/errwrap"
"github.com/hashicorp/go-hclog" "github.com/hashicorp/go-hclog"
uuid "github.com/hashicorp/go-uuid" uuid "github.com/hashicorp/go-uuid"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/hashicorp/consul/sdk/testutil"
"github.com/hashicorp/consul/acl" "github.com/hashicorp/consul/acl"
"github.com/hashicorp/consul/agent/config" "github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/agent/connect" "github.com/hashicorp/consul/agent/connect"
@ -168,23 +169,24 @@ func (a *TestAgent) Start(t *testing.T) (err error) {
// Create NodeID outside the closure, so that it does not change // Create NodeID outside the closure, so that it does not change
testHCLConfig := TestConfigHCL(NodeID()) testHCLConfig := TestConfigHCL(NodeID())
loader := func(source config.Source) (*config.RuntimeConfig, []string, error) { loader := func(source config.Source) (config.LoadResult, error) {
opts := config.BuilderOpts{ opts := config.LoadOpts{
HCL: []string{testHCLConfig, portsConfig, a.HCL, hclDataDir}, DefaultConfig: source,
HCL: []string{testHCLConfig, portsConfig, a.HCL, hclDataDir},
Overrides: []config.Source{
config.FileSource{
Name: "test-overrides",
Format: "hcl",
Data: a.Overrides},
config.DefaultConsulSource(),
config.DevConsulSource(),
},
} }
overrides := []config.Source{ result, err := config.Load(opts)
config.FileSource{ if result.RuntimeConfig != nil {
Name: "test-overrides", result.RuntimeConfig.Telemetry.Disable = true
Format: "hcl",
Data: a.Overrides},
config.DefaultConsulSource(),
config.DevConsulSource(),
} }
cfg, warnings, err := config.Load(opts, source, overrides...) return result, err
if cfg != nil {
cfg.Telemetry.Disable = true
}
return cfg, warnings, err
} }
bd, err := NewBaseDeps(loader, logOutput) bd, err := NewBaseDeps(loader, logOutput)
require.NoError(t, err) require.NoError(t, err)
@ -408,8 +410,7 @@ func NodeID() string {
return id return id
} }
// TestConfig returns a unique default configuration for testing an // TestConfig returns a unique default configuration for testing an agent.
// agent.
func TestConfig(logger hclog.Logger, sources ...config.Source) *config.RuntimeConfig { func TestConfig(logger hclog.Logger, sources ...config.Source) *config.RuntimeConfig {
nodeID := NodeID() nodeID := NodeID()
testsrc := config.FileSource{ testsrc := config.FileSource{
@ -435,29 +436,25 @@ func TestConfig(logger hclog.Logger, sources ...config.Source) *config.RuntimeCo
`, `,
} }
b, err := config.NewBuilder(config.BuilderOpts{}) opts := config.LoadOpts{
if err != nil { DefaultConfig: testsrc,
panic("NewBuilder failed: " + err.Error()) Overrides: sources,
} }
b.Head = append(b.Head, testsrc) r, err := config.Load(opts)
b.Tail = append(b.Tail, config.DefaultConsulSource(), config.DevConsulSource())
b.Tail = append(b.Tail, sources...)
cfg, err := b.BuildAndValidate()
if err != nil { if err != nil {
panic("Error building config: " + err.Error()) panic("config.Load failed: " + err.Error())
} }
for _, w := range r.Warnings {
for _, w := range b.Warnings {
logger.Warn(w) logger.Warn(w)
} }
cfg := r.RuntimeConfig
// Effectively disables the delay after root rotation before requesting CSRs // Effectively disables the delay after root rotation before requesting CSRs
// to make test deterministic. 0 results in default jitter being applied but a // to make test deterministic. 0 results in default jitter being applied but a
// tiny delay is effectively thre same. // tiny delay is effectively thre same.
cfg.ConnectTestCALeafRootChangeSpread = 1 * time.Nanosecond cfg.ConnectTestCALeafRootChangeSpread = 1 * time.Nanosecond
return &cfg return cfg
} }
// TestACLConfig returns a default configuration for testing an agent // TestACLConfig returns a default configuration for testing an agent

View File

@ -11,15 +11,16 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/hashicorp/go-checkpoint"
"github.com/hashicorp/go-hclog"
"github.com/mitchellh/cli"
"github.com/hashicorp/consul/agent" "github.com/hashicorp/consul/agent"
"github.com/hashicorp/consul/agent/config" "github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/command/flags" "github.com/hashicorp/consul/command/flags"
"github.com/hashicorp/consul/lib" "github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/logging" "github.com/hashicorp/consul/logging"
"github.com/hashicorp/consul/service_os" "github.com/hashicorp/consul/service_os"
"github.com/hashicorp/go-checkpoint"
"github.com/hashicorp/go-hclog"
"github.com/mitchellh/cli"
) )
func New(ui cli.Ui, revision, version, versionPre, versionHuman string, shutdownCh <-chan struct{}) *cmd { func New(ui cli.Ui, revision, version, versionPre, versionHuman string, shutdownCh <-chan struct{}) *cmd {
@ -56,13 +57,13 @@ type cmd struct {
versionPrerelease string versionPrerelease string
versionHuman string versionHuman string
shutdownCh <-chan struct{} shutdownCh <-chan struct{}
flagArgs config.BuilderOpts configLoadOpts config.LoadOpts
logger hclog.InterceptLogger logger hclog.InterceptLogger
} }
func (c *cmd) init() { func (c *cmd) init() {
c.flags = flag.NewFlagSet("", flag.ContinueOnError) c.flags = flag.NewFlagSet("", flag.ContinueOnError)
config.AddFlags(c.flags, &c.flagArgs) config.AddFlags(c.flags, &c.configLoadOpts)
c.help = flags.Usage(help, c.flags) c.help = flags.Usage(help, c.flags)
} }
@ -161,8 +162,9 @@ func (c *cmd) run(args []string) int {
} }
logGate := &logging.GatedWriter{Writer: &cli.UiWriter{Ui: c.UI}} logGate := &logging.GatedWriter{Writer: &cli.UiWriter{Ui: c.UI}}
loader := func(source config.Source) (cfg *config.RuntimeConfig, warnings []string, err error) { loader := func(source config.Source) (config.LoadResult, error) {
return config.Load(c.flagArgs, source) c.configLoadOpts.DefaultConfig = source
return config.Load(c.configLoadOpts)
} }
bd, err := agent.NewBaseDeps(loader, logGate) bd, err := agent.NewBaseDeps(loader, logGate)
if err != nil { if err != nil {

View File

@ -4,11 +4,12 @@ import (
"reflect" "reflect"
"time" "time"
"github.com/mitchellh/cli"
"github.com/mitchellh/mapstructure"
"github.com/hashicorp/consul/agent/config" "github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/mitchellh/cli"
"github.com/mitchellh/mapstructure"
) )
// ServicesFromFiles returns the list of agent service registration structs // ServicesFromFiles returns the list of agent service registration structs
@ -18,26 +19,22 @@ func ServicesFromFiles(ui cli.Ui, files []string) ([]*api.AgentServiceRegistrati
// configuration. devMode doesn't set any services by default so this // configuration. devMode doesn't set any services by default so this
// is okay since we only look at services. // is okay since we only look at services.
devMode := true devMode := true
b, err := config.NewBuilder(config.BuilderOpts{ r, err := config.Load(config.LoadOpts{
ConfigFiles: files, ConfigFiles: files,
DevMode: &devMode, DevMode: &devMode,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
} }
for _, w := range r.Warnings {
cfg, err := b.BuildAndValidate()
if err != nil {
return nil, err
}
for _, w := range b.Warnings {
ui.Warn(w) ui.Warn(w)
} }
// The services are now in "structs.ServiceDefinition" form and we need // The services are now in "structs.ServiceDefinition" form and we need
// them in "api.AgentServiceRegistration" form so do the conversion. // them in "api.AgentServiceRegistration" form so do the conversion.
result := make([]*api.AgentServiceRegistration, 0, len(cfg.Services)) services := r.RuntimeConfig.Services
for _, svc := range cfg.Services { result := make([]*api.AgentServiceRegistration, 0, len(services))
for _, svc := range services {
apiSvc, err := serviceToAgentService(svc) apiSvc, err := serviceToAgentService(svc)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -4,28 +4,22 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/agent/config" "github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/agent/structs" "github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/stretchr/testify/require"
) )
// This test ensures that dev mode doesn't register services by default. // This test ensures that dev mode doesn't register services by default.
// We depend on this behavior for ServiesFromFiles so we want to fail // We depend on this behavior for ServiesFromFiles so we want to fail
// tests if that ever changes. // tests if that ever changes.
func TestDevModeHasNoServices(t *testing.T) { func TestDevModeHasNoServices(t *testing.T) {
t.Parallel()
require := require.New(t)
devMode := true devMode := true
b, err := config.NewBuilder(config.BuilderOpts{ result, err := config.Load(config.LoadOpts{DevMode: &devMode})
DevMode: &devMode, require.NoError(t, err)
}) require.Len(t, result.Warnings, 0)
require.NoError(err) require.Len(t, result.RuntimeConfig.Services, 0)
cfg, err := b.BuildAndValidate()
require.NoError(err)
require.Empty(cfg.Services)
} }
func TestStructsToAgentService(t *testing.T) { func TestStructsToAgentService(t *testing.T) {

View File

@ -4,9 +4,10 @@ import (
"flag" "flag"
"fmt" "fmt"
"github.com/mitchellh/cli"
"github.com/hashicorp/consul/agent/config" "github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/command/flags" "github.com/hashicorp/consul/command/flags"
"github.com/mitchellh/cli"
) )
func New(ui cli.Ui) *cmd { func New(ui cli.Ui) *cmd {
@ -51,17 +52,13 @@ func (c *cmd) Run(args []string) int {
return 1 return 1
} }
b, err := config.NewBuilder(config.BuilderOpts{ConfigFiles: configFiles, ConfigFormat: c.configFormat}) result, err := config.Load(config.LoadOpts{ConfigFiles: configFiles, ConfigFormat: c.configFormat})
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error())) c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
return 1 return 1
} }
if _, err := b.BuildAndValidate(); err != nil {
c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
return 1
}
if !c.quiet { if !c.quiet {
for _, w := range b.Warnings { for _, w := range result.Warnings {
c.UI.Warn(w) c.UI.Warn(w)
} }
c.UI.Output("Configuration is valid!") c.UI.Output("Configuration is valid!")