config: improve the interface of Load

This commit reduces the interface to Load() a bit, in preparation for
unexporting NewBuilder and having everything call Load.

The three arguments are reduced to a single argument by moving the other
two into the options struct.

The three return values are reduced to two by moving the RuntimeConfig
and Warnings into a LoadResult struct.
This commit is contained in:
Daniel Nephin 2020-12-21 13:25:32 -05:00
parent 27df0d9a78
commit 97a577502d
18 changed files with 257 additions and 224 deletions

View File

@ -43,16 +43,17 @@ func NewTestACLAgent(t *testing.T, name string, hcl string, resolveAuthz authzRe
dataDir := testutil.TempDir(t, "acl-agent")
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)
opts := config.BuilderOpts{
HCL: []string{TestConfigHCL(NodeID()), hcl, dataDir},
opts := config.LoadOpts{
HCL: []string{TestConfigHCL(NodeID()), hcl, dataDir},
DefaultConfig: source,
}
cfg, warnings, err := config.Load(opts, source)
if cfg != nil {
cfg.Telemetry.Disable = true
result, err := config.Load(opts)
if result.RuntimeConfig != nil {
result.RuntimeConfig.Telemetry.Disable = true
}
return cfg, warnings, err
return result, err
}
bd, err := NewBaseDeps(loader, logBuffer)
require.NoError(t, err)

View File

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

View File

@ -29,11 +29,13 @@ import (
)
type configLoader struct {
opts config.BuilderOpts
opts config.LoadOpts
}
func (c *configLoader) Load(source config.Source) (*config.RuntimeConfig, []string, error) {
return config.Load(c.opts, source)
func (c *configLoader) Load(source config.Source) (config.LoadResult, error) {
opts := c.opts
opts.DefaultConfig = source
return config.Load(opts)
}
func (c *configLoader) addConfigHCL(cfg string) {
@ -131,8 +133,8 @@ func TestNew(t *testing.T) {
for name, tcase := range cases {
t.Run(name, func(t *testing.T) {
cfg := Config{
Loader: func(source config.Source) (cfg *config.RuntimeConfig, warnings []string, err error) {
return nil, nil, nil
Loader: func(source config.Source) (result config.LoadResult, err error) {
return config.LoadResult{}, nil
},
DirectRPC: newMockDirectRPC(t),
Tokens: newMockTokenStore(t),
@ -168,15 +170,18 @@ func TestReadConfig(t *testing.T) {
},
logger: testutil.Logger(t),
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()
if err != nil {
return nil, nil, err
return r, err
}
return &config.RuntimeConfig{
r.RuntimeConfig = &config.RuntimeConfig{
DevMode: true,
NodeName: *cfg.NodeName,
}, nil, nil
}
return r, nil
},
},
}
@ -194,8 +199,8 @@ func setupRuntimeConfig(t *testing.T) *configLoader {
dataDir := testutil.TempDir(t, "auto-config")
opts := config.BuilderOpts{
Config: config.Config{
opts := config.LoadOpts{
FlagValues: config.Config{
DataDir: &dataDir,
Datacenter: stringPointer("dc1"),
NodeName: stringPointer("autoconf"),
@ -225,7 +230,7 @@ func TestInitialConfiguration_disabled(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, cfg)
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) {
@ -286,7 +291,7 @@ func TestInitialConfiguration_restored(t *testing.T) {
indexedRoots, cert, extraCACerts := mcfg.setupInitialTLS(t, "autoconf", "dc1", "secret")
// 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{
Config: &pbconfig.Config{
PrimaryDatacenter: "primary",
@ -394,7 +399,7 @@ func TestInitialConfiguration_success(t *testing.T) {
require.Equal(t, "primary", cfg.PrimaryDatacenter)
// 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)
}
@ -511,7 +516,7 @@ func TestInitialConfiguration_retries(t *testing.T) {
require.Equal(t, "primary", cfg.PrimaryDatacenter)
// 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)
}

View File

@ -287,7 +287,7 @@ func TestAutoEncrypt_InitialConfiguration(t *testing.T) {
tls = true
}
`)
loader.opts.Config.NodeName = &nodeName
loader.opts.FlagValues.NodeName = &nodeName
mcfg.Config.Loader = loader.Load
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
// 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
// auto encrypt/auto config certs as they are renewed.

View File

@ -13,7 +13,7 @@ func TestBuildAndValidate_HTTPMaxConnsPerClientExceedsRLimit(t *testing.T) {
# This value is more than max on Windows as well
http_max_conns_per_client = 16777217
}`
b, err := NewBuilder(BuilderOpts{})
b, err := NewBuilder(LoadOpts{})
assert.NoError(t, err)
testsrc := FileSource{
Name: "test",

View File

@ -41,29 +41,70 @@ import (
"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.
type LoadOpts struct {
// FlagValues contains the command line arguments that can also be set
// in a config file.
FlagValues Config
// ConfigFiles is a slice of paths to config files and directories that will
// be loaded.
ConfigFiles []string
// ConfigFormat forces all config files to be interpreted as this format
// independent of their extension. Value may be `hcl` or `json`.
ConfigFormat string
// DevMode indicates whether the agent should be started in development
// mode. This cannot be configured in a config file.
DevMode *bool
// 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)
}
// Load will build the configuration including the config source injected
// after all other defaults but before any user supplied configuration and the overrides
// source injected as the final source in the configuration parsing chain.
func Load(opts BuilderOpts, extraHead Source, overrides ...Source) (*RuntimeConfig, []string, error) {
//
// The caller is responsible for handling any warnings in LoadResult.Warnings.
func Load(opts LoadOpts) (LoadResult, error) {
r := LoadResult{}
b, err := NewBuilder(opts)
if err != nil {
return nil, nil, err
return r, err
}
if extraHead != nil {
b.Head = append(b.Head, extraHead)
}
if len(overrides) != 0 {
b.Tail = append(b.Tail, overrides...)
}
cfg, err := b.BuildAndValidate()
if err != nil {
return nil, nil, err
return r, err
}
return LoadResult{RuntimeConfig: &cfg, Warnings: b.Warnings}, nil
}
return &cfg, 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 a valid runtime configuration from multiple
@ -92,7 +133,7 @@ func Load(opts BuilderOpts, extraHead Source, overrides ...Source) (*RuntimeConf
// since not all pre-conditions have to be satisfied when performing
// syntactical tests.
type Builder struct {
opts BuilderOpts
opts LoadOpts
// Head, Sources, and Tail are used to manage the order of the
// config sources, as described in the comments above.
@ -109,8 +150,8 @@ type Builder struct {
err error
}
// NewBuilder returns a new configuration Builder from the BuilderOpts.
func NewBuilder(opts BuilderOpts) (*Builder, error) {
// NewBuilder returns a new configuration Builder from the LoadOpts.
func NewBuilder(opts LoadOpts) (*Builder, error) {
configFormat := opts.ConfigFormat
if configFormat != "" && configFormat != "json" && configFormat != "hcl" {
return nil, fmt.Errorf("config: -config-format must be either 'hcl' or 'json'")
@ -130,8 +171,12 @@ func NewBuilder(opts BuilderOpts) (*Builder, error) {
// we need to merge all slice values defined in flags before we
// merge the config files since the flag values for slices are
// 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})
if opts.DefaultConfig != nil {
b.Head = append(b.Head, opts.DefaultConfig)
}
for _, path := range opts.ConfigFiles {
sources, err := b.sourcesFromPath(path, opts.ConfigFormat)
if err != nil {
@ -151,6 +196,9 @@ func NewBuilder(opts BuilderOpts) (*Builder, error) {
if boolVal(opts.DevMode) {
b.Tail = append(b.Tail, DevConsulSource())
}
if len(opts.Overrides) != 0 {
b.Tail = append(b.Tail, opts.Overrides...)
}
return b, nil
}

View File

@ -17,25 +17,28 @@ func TestLoad(t *testing.T) {
// Basically just testing that injection of the extra
// source works.
devMode := true
builderOpts := BuilderOpts{
builderOpts := LoadOpts{
// putting this in dev mode so that the config validates
// without having to specify a data directory
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{
Name: "test",
Format: "hcl",
Data: `node_name = "hobbiton"`,
},
FileSource{
Name: "overrides",
Format: "json",
Data: `{"check_reap_interval": "1ms"}`,
})
result, err := Load(builderOpts)
require.NoError(t, err)
require.Empty(t, warnings)
require.Empty(t, result.Warnings)
cfg := result.RuntimeConfig
require.NotNil(t, cfg)
require.Equal(t, "hobbiton", cfg.NodeName)
require.Equal(t, 1*time.Millisecond, cfg.CheckReapInterval)
@ -65,7 +68,7 @@ func TestShouldParseFile(t *testing.T) {
func TestNewBuilder_PopulatesSourcesFromConfigFiles(t *testing.T) {
paths := setupConfigFiles(t)
b, err := NewBuilder(BuilderOpts{ConfigFiles: paths})
b, err := NewBuilder(LoadOpts{ConfigFiles: paths})
require.NoError(t, err)
expected := []Source{
@ -81,7 +84,7 @@ func TestNewBuilder_PopulatesSourcesFromConfigFiles(t *testing.T) {
func TestNewBuilder_PopulatesSourcesFromConfigFiles_WithConfigFormat(t *testing.T) {
paths := setupConfigFiles(t)
b, err := NewBuilder(BuilderOpts{ConfigFiles: paths, ConfigFormat: "hcl"})
b, err := NewBuilder(LoadOpts{ConfigFiles: paths, ConfigFormat: "hcl"})
require.NoError(t, err)
expected := []Source{
@ -132,8 +135,8 @@ func TestBuilder_BuildAndValidate_NodeName(t *testing.T) {
}
fn := func(t *testing.T, tc testCase) {
b, err := NewBuilder(BuilderOpts{
Config: Config{
b, err := NewBuilder(LoadOpts{
FlagValues: Config{
NodeName: pString(tc.nodeName),
DataDir: pString("dir"),
},

View File

@ -271,7 +271,7 @@ func strPtr(v string) *string {
}
func DefaultRuntimeConfig(hcl string) *RuntimeConfig {
b, err := NewBuilder(BuilderOpts{HCL: []string{hcl}})
b, err := NewBuilder(LoadOpts{HCL: []string{hcl}})
if err != nil {
panic(err)
}

View File

@ -3,43 +3,11 @@ package config
import (
"flag"
"fmt"
"net"
"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.
func AddFlags(fs *flag.FlagSet, f *BuilderOpts) {
func AddFlags(fs *flag.FlagSet, f *LoadOpts) {
add := func(p interface{}, name, help string) {
switch x := p.(type) {
case **bool:
@ -60,70 +28,70 @@ func AddFlags(fs *flag.FlagSet, f *BuilderOpts) {
}
// command line flags ordered by flag name
add(&f.Config.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.Config.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.Config.Bootstrap, "bootstrap", "Sets server to bootstrap mode.")
add(&f.Config.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.Config.CheckOutputMaxSize, "check_output_max_size", "Sets the maximum output size for checks on this agent")
add(&f.FlagValues.AdvertiseAddrLAN, "advertise", "Sets the advertise address to use.")
add(&f.FlagValues.AdvertiseAddrWAN, "advertise-wan", "Sets address to advertise on WAN instead of -advertise address.")
add(&f.FlagValues.BindAddr, "bind", "Sets the bind address for cluster communication.")
add(&f.FlagValues.Ports.Server, "server-port", "Sets the server port to listen on.")
add(&f.FlagValues.Bootstrap, "bootstrap", "Sets server to bootstrap mode.")
add(&f.FlagValues.BootstrapExpect, "bootstrap-expect", "Sets server to expect bootstrap mode.")
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.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-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'")
add(&f.Config.DataDir, "data-dir", "Path to a data directory to store agent state.")
add(&f.Config.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.DataDir, "data-dir", "Path to a data directory to store agent state.")
add(&f.FlagValues.Datacenter, "datacenter", "Datacenter of the agent.")
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.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.Config.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.Config.DNSDomain, "domain", "Domain to use for DNS interface.")
add(&f.Config.DNSAltDomain, "alt-domain", "Alternate domain to use for DNS interface.")
add(&f.Config.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.Config.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.Config.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.Config.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.Config.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.Config.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.Config.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.Config.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.Config.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.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.Config.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.Config.PidFile, "pid-file", "Path to file to store agent PID.")
add(&f.Config.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.Config.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.Config.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.Config.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.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.Config.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.Config.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.Config.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.Config.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.Config.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.Config.EnableSyslog, "syslog", "Enables logging to syslog.")
add(&f.Config.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.Config.UIConfig.Dir, "ui-dir", "Path to directory containing the web UI resources.")
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.FlagValues.DisableKeyringFile, "disable-keyring-file", "Disables the backing up of the keyring to a file.")
add(&f.FlagValues.Ports.DNS, "dns-port", "DNS port to use.")
add(&f.FlagValues.DNSDomain, "domain", "Domain to use for DNS interface.")
add(&f.FlagValues.DNSAltDomain, "alt-domain", "Alternate domain to use for DNS interface.")
add(&f.FlagValues.EnableScriptChecks, "enable-script-checks", "Enables health check scripts.")
add(&f.FlagValues.EnableLocalScriptChecks, "enable-local-script-checks", "Enables health check scripts from configuration file.")
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.FlagValues.EncryptKey, "encrypt", "Provides the gossip encryption key.")
add(&f.FlagValues.Ports.GRPC, "grpc-port", "Sets the gRPC API port to listen on (currently needed for Envoy xDS only).")
add(&f.FlagValues.Ports.HTTP, "http-port", "Sets the HTTP API port to listen on.")
add(&f.FlagValues.Ports.HTTPS, "https-port", "Sets the HTTPS API port to listen on.")
add(&f.FlagValues.StartJoinAddrsLAN, "join", "Address of an agent to join 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.FlagValues.LogLevel, "log-level", "Log level of the agent.")
add(&f.FlagValues.LogJSON, "log-json", "Output logs in JSON format.")
add(&f.FlagValues.LogFile, "log-file", "Path to the file the logs get written to")
add(&f.FlagValues.LogRotateBytes, "log-rotate-bytes", "Maximum number of bytes that should be written to a log file")
add(&f.FlagValues.LogRotateDuration, "log-rotate-duration", "Time after which log rotation needs to be performed")
add(&f.FlagValues.LogRotateMaxFiles, "log-rotate-max-files", "Maximum number of log file archives to keep")
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.FlagValues.NodeName, "node", "Name of this node. Must be unique in the cluster.")
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.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.FlagValues.ReadReplica, "non-voting-server", "(Enterprise-only) DEPRECATED: -read-replica should be used instead")
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.FlagValues.PidFile, "pid-file", "Path to file to store agent PID.")
add(&f.FlagValues.RPCProtocol, "protocol", "Sets the protocol version. Defaults to latest.")
add(&f.FlagValues.RaftProtocol, "raft-protocol", "Sets the Raft protocol version. Defaults to latest.")
add(&f.FlagValues.DNSRecursors, "recursor", "Address of an upstream DNS server. 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.FlagValues.RejoinAfterLeave, "rejoin", "Ignores a previous leave and attempts to rejoin the cluster.")
add(&f.FlagValues.RetryJoinIntervalLAN, "retry-interval", "Time to wait between join attempts.")
add(&f.FlagValues.RetryJoinIntervalWAN, "retry-interval-wan", "Time to wait between join -wan attempts.")
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.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.FlagValues.RetryJoinMaxAttemptsLAN, "retry-max", "Maximum number of join 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.FlagValues.SerfAllowedCIDRsLAN, "serf-lan-allowed-cidrs", "Networks (eg: 192.168.1.0/24) allowed for Serf LAN. 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.FlagValues.SerfBindAddrLAN, "serf-lan-bind", "Address to bind Serf LAN listeners to.")
add(&f.FlagValues.Ports.SerfLAN, "serf-lan-port", "Sets the Serf LAN port to listen on.")
add(&f.FlagValues.SegmentName, "segment", "(Enterprise-only) Sets the network segment to join.")
add(&f.FlagValues.SerfBindAddrWAN, "serf-wan-bind", "Address to bind Serf WAN listeners to.")
add(&f.FlagValues.Ports.SerfWAN, "serf-wan-port", "Sets the Serf WAN port to listen on.")
add(&f.FlagValues.ServerMode, "server", "Switches agent to server mode.")
add(&f.FlagValues.EnableSyslog, "syslog", "Enables logging to syslog.")
add(&f.FlagValues.UIConfig.Enabled, "ui", "Enables the built-in static web UI server.")
add(&f.FlagValues.UIConfig.ContentPath, "ui-content-path", "Sets the external UI path to a string. Defaults to: /ui/ ")
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.")
}

View File

@ -15,78 +15,78 @@ import (
func TestAddFlags_WithParse(t *testing.T) {
tests := []struct {
args []string
expected BuilderOpts
expected LoadOpts
extra []string
}{
{},
{
args: []string{`-bind`, `a`},
expected: BuilderOpts{Config: Config{BindAddr: pString("a")}},
expected: LoadOpts{FlagValues: Config{BindAddr: pString("a")}},
},
{
args: []string{`-bootstrap`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(true)}},
expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(true)}},
},
{
args: []string{`-bootstrap=true`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(true)}},
expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(true)}},
},
{
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`},
expected: BuilderOpts{ConfigFiles: []string{"a", "b", "c", "d"}},
expected: LoadOpts{ConfigFiles: []string{"a", "b", "c", "d"}},
},
{
args: []string{`-datacenter`, `a`},
expected: BuilderOpts{Config: Config{Datacenter: pString("a")}},
expected: LoadOpts{FlagValues: Config{Datacenter: pString("a")}},
},
{
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`},
expected: BuilderOpts{Config: Config{Ports: Ports{GRPC: pInt(1)}}},
expected: LoadOpts{FlagValues: Config{Ports: Ports{GRPC: pInt(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`},
expected: BuilderOpts{Config: Config{Ports: Ports{HTTPS: pInt(1)}}},
expected: LoadOpts{FlagValues: Config{Ports: Ports{HTTPS: pInt(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`},
expected: BuilderOpts{Config: Config{Ports: Ports{SerfWAN: pInt(1)}}},
expected: LoadOpts{FlagValues: Config{Ports: Ports{SerfWAN: pInt(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`},
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`},
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`},
expected: BuilderOpts{Config: Config{Bootstrap: pBool(true)}},
expected: LoadOpts{FlagValues: Config{Bootstrap: pBool(true)}},
extra: []string{"true"},
},
{
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",
}}},
},
@ -94,7 +94,7 @@ func TestAddFlags_WithParse(t *testing.T) {
for _, tt := range tests {
t.Run(strings.Join(tt.args, " "), func(t *testing.T) {
flags := BuilderOpts{}
flags := LoadOpts{}
fs := flag.NewFlagSet("", flag.ContinueOnError)
AddFlags(fs, &flags)
@ -106,8 +106,8 @@ func TestAddFlags_WithParse(t *testing.T) {
if tt.extra == nil && fs.Args() != nil {
tt.extra = []string{}
}
if len(tt.expected.Config.NodeMeta) == 0 {
tt.expected.Config.NodeMeta = map[string]string{}
if len(tt.expected.FlagValues.NodeMeta) == 0 {
tt.expected.FlagValues.NodeMeta = map[string]string{}
}
require.Equal(t, tt.extra, fs.Args())
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) {
flags := BuilderOpts{}
flags := LoadOpts{}
fs := flag.NewFlagSet("", flag.ContinueOnError)
AddFlags(fs, &flags)
err := fs.Parse(tt.args)
@ -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
// and compare it with the generated configuration. Since the expected
// runtime config has been validated we do not need to validate it again.
x, err := NewBuilder(BuilderOpts{})
x, err := NewBuilder(LoadOpts{})
if err != nil {
t.Fatal(err)
}
@ -4998,7 +4997,7 @@ func assertDeepEqual(t *testing.T, x, y interface{}, opts ...cmp.Option) {
}
func TestNewBuilder_InvalidConfigFormat(t *testing.T) {
_, err := NewBuilder(BuilderOpts{ConfigFormat: "yaml"})
_, err := NewBuilder(LoadOpts{ConfigFormat: "yaml"})
require.Error(t, err)
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
ACLDisabledTTL: 957 * time.Second,
AEInterval: 10003 * time.Second,
@ -7205,7 +7204,7 @@ func TestFullConfig(t *testing.T) {
},
}
entFullRuntimeConfig(&want)
entFullRuntimeConfig(&expected)
warns := []string{
`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): * ignore the Check field
// 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)
}
@ -7228,7 +7227,7 @@ func TestFullConfig(t *testing.T) {
t.Run(format, func(t *testing.T) {
// parse the flags since this is the only way we can set the
// DevMode flag
var flags BuilderOpts
var flags LoadOpts
fs := flag.NewFlagSet("", flag.ContinueOnError)
AddFlags(fs, &flags)
if err := fs.Parse(flagSrc); err != nil {
@ -7250,7 +7249,7 @@ func TestFullConfig(t *testing.T) {
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
// for all fields but the validation will fail since certain

View File

@ -11,6 +11,7 @@ import (
"github.com/hashicorp/consul/agent/consul/fsm"
"github.com/armon/go-metrics/prometheus"
"github.com/hashicorp/consul/agent/consul/usagemetrics"
"github.com/hashicorp/consul/agent/local"
@ -52,15 +53,16 @@ type MetricsHandler interface {
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) {
d := BaseDeps{}
cfg, warnings, err := configLoader(nil)
result, err := configLoader(nil)
if err != nil {
return d, err
}
cfg := result.RuntimeConfig
logConf := cfg.Logging
logConf.Name = logging.Agent
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))
for _, w := range warnings {
for _, w := range result.Warnings {
d.Logger.Warn(w)
}

View File

@ -16,12 +16,13 @@ import (
"time"
metrics "github.com/armon/go-metrics"
"github.com/hashicorp/consul/sdk/testutil"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-hclog"
uuid "github.com/hashicorp/go-uuid"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/sdk/testutil"
"github.com/hashicorp/consul/acl"
"github.com/hashicorp/consul/agent/config"
"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
testHCLConfig := TestConfigHCL(NodeID())
loader := func(source config.Source) (*config.RuntimeConfig, []string, error) {
opts := config.BuilderOpts{
HCL: []string{testHCLConfig, portsConfig, a.HCL, hclDataDir},
loader := func(source config.Source) (config.LoadResult, error) {
opts := config.LoadOpts{
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{
config.FileSource{
Name: "test-overrides",
Format: "hcl",
Data: a.Overrides},
config.DefaultConsulSource(),
config.DevConsulSource(),
result, err := config.Load(opts)
if result.RuntimeConfig != nil {
result.RuntimeConfig.Telemetry.Disable = true
}
cfg, warnings, err := config.Load(opts, source, overrides...)
if cfg != nil {
cfg.Telemetry.Disable = true
}
return cfg, warnings, err
return result, err
}
bd, err := NewBaseDeps(loader, logOutput)
require.NoError(t, err)
@ -435,7 +437,7 @@ func TestConfig(logger hclog.Logger, sources ...config.Source) *config.RuntimeCo
`,
}
b, err := config.NewBuilder(config.BuilderOpts{})
b, err := config.NewBuilder(config.LoadOpts{})
if err != nil {
panic("NewBuilder failed: " + err.Error())
}

View File

@ -11,15 +11,16 @@ import (
"syscall"
"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/config"
"github.com/hashicorp/consul/command/flags"
"github.com/hashicorp/consul/lib"
"github.com/hashicorp/consul/logging"
"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 {
@ -56,13 +57,13 @@ type cmd struct {
versionPrerelease string
versionHuman string
shutdownCh <-chan struct{}
flagArgs config.BuilderOpts
configLoadOpts config.LoadOpts
logger hclog.InterceptLogger
}
func (c *cmd) init() {
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)
}
@ -161,8 +162,9 @@ func (c *cmd) run(args []string) int {
}
logGate := &logging.GatedWriter{Writer: &cli.UiWriter{Ui: c.UI}}
loader := func(source config.Source) (cfg *config.RuntimeConfig, warnings []string, err error) {
return config.Load(c.flagArgs, source)
loader := func(source config.Source) (config.LoadResult, error) {
c.configLoadOpts.DefaultConfig = source
return config.Load(c.configLoadOpts)
}
bd, err := agent.NewBaseDeps(loader, logGate)
if err != nil {

View File

@ -4,11 +4,12 @@ import (
"reflect"
"time"
"github.com/mitchellh/cli"
"github.com/mitchellh/mapstructure"
"github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/api"
"github.com/mitchellh/cli"
"github.com/mitchellh/mapstructure"
)
// ServicesFromFiles returns the list of agent service registration structs
@ -18,7 +19,7 @@ func ServicesFromFiles(ui cli.Ui, files []string) ([]*api.AgentServiceRegistrati
// configuration. devMode doesn't set any services by default so this
// is okay since we only look at services.
devMode := true
b, err := config.NewBuilder(config.BuilderOpts{
b, err := config.NewBuilder(config.LoadOpts{
ConfigFiles: files,
DevMode: &devMode,
})

View File

@ -4,10 +4,11 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/api"
"github.com/stretchr/testify/require"
)
// This test ensures that dev mode doesn't register services by default.
@ -18,7 +19,7 @@ func TestDevModeHasNoServices(t *testing.T) {
require := require.New(t)
devMode := true
b, err := config.NewBuilder(config.BuilderOpts{
b, err := config.NewBuilder(config.LoadOpts{
DevMode: &devMode,
})
require.NoError(err)

View File

@ -4,9 +4,10 @@ import (
"flag"
"fmt"
"github.com/mitchellh/cli"
"github.com/hashicorp/consul/agent/config"
"github.com/hashicorp/consul/command/flags"
"github.com/mitchellh/cli"
)
func New(ui cli.Ui) *cmd {
@ -51,7 +52,7 @@ func (c *cmd) Run(args []string) int {
return 1
}
b, err := config.NewBuilder(config.BuilderOpts{ConfigFiles: configFiles, ConfigFormat: c.configFormat})
b, err := config.NewBuilder(config.LoadOpts{ConfigFiles: configFiles, ConfigFormat: c.configFormat})
if err != nil {
c.UI.Error(fmt.Sprintf("Config validation failed: %v", err.Error()))
return 1