Skip to content

Commit

Permalink
Enhance config.Namespace
Browse files Browse the repository at this point in the history
when unpacking into config.Namespace, namespaces can be disabled
via `enabled: false` now. For settings allowing exactly one configuration, this
can be used by users to enabled/disable namespace without having to comment
them out in the configuration file.

example usage:

```
type Config struct {
    Output common.ConfigNamespace
}
```

user can have at most one enabled:

```
output.namespace1:
  enabled: false

output.namespace2:
  enabled: true
```
  • Loading branch information
urso committed Jun 19, 2017
1 parent 76a9b87 commit 6167cc8
Showing 1 changed file with 34 additions and 14 deletions.
48 changes: 34 additions & 14 deletions libbeat/common/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ type Config ucfg.Config

// ConfigNamespace storing at most one configuration section by name and sub-section.
type ConfigNamespace struct {
C map[string]*Config `config:",inline"`
name string
config *Config
}

type flagOverwrite struct {
Expand Down Expand Up @@ -327,33 +328,52 @@ func (f *flagOverwrite) Get() interface{} {
return f.value
}

// Validate checks at most one sub-namespace being set.
func (ns *ConfigNamespace) Validate() error {
if len(ns.C) > 1 {
return errors.New("more then one namespace configured")
// Unpack unpacks a configuration with at most one sub object. An sub object is
// ignored if it is disabled by setting `enabled: false`. If the configuration
// passed contains multiple active sub objects, Unpack will return an error.
func (ns *ConfigNamespace) Unpack(cfg *Config) error {
fields := cfg.GetFields()
if len(fields) == 0 {
return nil
}

for _, name := range fields {
sub, err := cfg.Child(name, -1)
if err != nil {
// element is no configuration object -> continue so a namespace
// Config unpacked as a namespace can have other configuration
// values as well
continue
}

if !sub.Enabled() {
continue
}

if ns.name != "" {
return errors.New("more then one namespace configured")
}

ns.name = name
ns.config = sub
}

return nil
}

// Name returns the configuration sections it's name if a section has been set.
func (ns *ConfigNamespace) Name() string {
for name := range ns.C {
return name
}
return ""
return ns.name
}

// Config return the sub-configuration section if a section has been set.
func (ns *ConfigNamespace) Config() *Config {
for _, cfg := range ns.C {
return cfg
}
return nil
return ns.config
}

// IsSet returns true if a sub-configuration section has been set.
func (ns *ConfigNamespace) IsSet() bool {
return len(ns.C) != 0
return ns.config != nil
}

func configDebugString(c *Config, filterPrivate bool) string {
Expand Down

0 comments on commit 6167cc8

Please sign in to comment.