forked from premendrasingh/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collector.go
90 lines (72 loc) · 1.96 KB
/
collector.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
package collector
import (
"fmt"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/cfgwarn"
"github.com/elastic/beats/metricbeat/helper"
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/metricbeat/mb/parse"
)
const (
defaultScheme = "http"
defaultPath = "/metrics"
)
var (
hostParser = parse.URLHostParserBuilder{
DefaultScheme: defaultScheme,
DefaultPath: defaultPath,
PathConfigKey: "metrics_path",
}.Build()
)
func init() {
if err := mb.Registry.AddMetricSet("prometheus", "collector", New, hostParser); err != nil {
panic(err)
}
}
type MetricSet struct {
mb.BaseMetricSet
prometheus *helper.Prometheus
namespace string
}
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
cfgwarn.Beta("The prometheus collector metricset is beta")
config := struct {
Namespace string `config:"namespace" validate:"required"`
}{}
err := base.Module().UnpackConfig(&config)
if err != nil {
return nil, err
}
return &MetricSet{
BaseMetricSet: base,
prometheus: helper.NewPrometheusClient(base),
namespace: config.Namespace,
}, nil
}
func (m *MetricSet) Fetch() ([]common.MapStr, error) {
families, err := m.prometheus.GetFamilies()
if err != nil {
return nil, fmt.Errorf("Unable to decode response from prometheus endpoint")
}
eventList := map[string]common.MapStr{}
for _, family := range families {
promEvents := GetPromEventsFromMetricFamily(family)
for _, promEvent := range promEvents {
if _, ok := eventList[promEvent.labelHash]; !ok {
eventList[promEvent.labelHash] = common.MapStr{}
// Add labels
if len(promEvent.labels) > 0 {
eventList[promEvent.labelHash]["label"] = promEvent.labels
}
}
eventList[promEvent.labelHash][promEvent.key] = promEvent.value
}
}
// Converts hash list to slice
events := []common.MapStr{}
for _, e := range eventList {
e[mb.NamespaceKey] = m.namespace
events = append(events, e)
}
return events, err
}