forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
report.go
115 lines (95 loc) · 2.57 KB
/
report.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package report
import (
"errors"
"fmt"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
)
type config struct {
// allow for maximum one reporter being configured
Reporter common.ConfigNamespace `config:",inline"`
}
type Reporter interface {
Stop()
}
type ReporterFactory func(beat.Info, *common.Config) (Reporter, error)
var (
defaultConfig = config{}
reportFactories = map[string]ReporterFactory{}
)
func RegisterReporterFactory(name string, f ReporterFactory) {
if reportFactories[name] != nil {
panic(fmt.Sprintf("Reporter '%v' already registered", name))
}
reportFactories[name] = f
}
func New(
beat beat.Info,
cfg *common.Config,
outputs common.ConfigNamespace,
) (Reporter, error) {
name, cfg, err := getReporterConfig(cfg, outputs)
if err != nil {
return nil, err
}
f := reportFactories[name]
if f == nil {
return nil, fmt.Errorf("unknown reporter type '%v'", name)
}
return f(beat, cfg)
}
func getReporterConfig(
cfg *common.Config,
outputs common.ConfigNamespace,
) (string, *common.Config, error) {
cfg = collectSubObject(cfg)
config := defaultConfig
if err := cfg.Unpack(&config); err != nil {
return "", nil, err
}
// load reporter from `monitoring` section and optionally
// merge with output settings
if config.Reporter.IsSet() {
name := config.Reporter.Name()
rc := config.Reporter.Config()
// merge reporter config with output config if both are present
if outCfg := outputs.Config(); outputs.Name() == name && outCfg != nil {
// require monitoring to not configure any hosts if output is configured:
hosts := struct {
Hosts []string `config:"hosts"`
}{}
rc.Unpack(&hosts)
if len(hosts.Hosts) > 0 {
pathMonHosts := rc.PathOf("hosts")
pathOutHost := outCfg.PathOf("hosts")
err := fmt.Errorf("'%v' and '%v' are configured", pathMonHosts, pathOutHost)
return "", nil, err
}
merged, err := common.MergeConfigs(outCfg, rc)
if err != nil {
return "", nil, err
}
rc = merged
}
return name, rc, nil
}
// find output also available for reporting telemetry.
if outputs.IsSet() {
name := outputs.Name()
if reportFactories[name] != nil {
return name, outputs.Config(), nil
}
}
return "", nil, errors.New("No monitoring reporter configured")
}
func collectSubObject(cfg *common.Config) *common.Config {
out := common.NewConfig()
for _, field := range cfg.GetFields() {
if obj, err := cfg.Child(field, -1); err == nil {
// on error field is no object, but primitive value -> ignore
out.SetChild(field, -1, obj)
continue
}
}
return out
}