-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
collector.go
272 lines (239 loc) · 7.38 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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package collector
import (
"regexp"
"sync"
"github.com/pkg/errors"
dto "github.com/prometheus/client_model/go"
"github.com/elastic/beats/v7/libbeat/common"
p "github.com/elastic/beats/v7/metricbeat/helper/prometheus"
"github.com/elastic/beats/v7/metricbeat/mb"
"github.com/elastic/beats/v7/metricbeat/mb/parse"
)
const (
defaultScheme = "http"
defaultPath = "/metrics"
)
var (
// HostParser parses a Prometheus endpoint URL
HostParser = parse.URLHostParserBuilder{
DefaultScheme: defaultScheme,
DefaultPath: defaultPath,
PathConfigKey: "metrics_path",
}.Build()
upMetricName = "up"
upMetricType = dto.MetricType_GAUGE
upMetricInstanceLabel = "instance"
upMetricJobLabel = "job"
upMetricJobValue = "prometheus"
)
func init() {
mb.Registry.MustAddMetricSet("prometheus", "collector",
MetricSetBuilder("prometheus", DefaultPromEventsGeneratorFactory),
mb.WithHostParser(HostParser),
mb.DefaultMetricSet(),
)
}
// PromEventsGenerator converts a Prometheus metric family into a PromEvent list
type PromEventsGenerator interface {
// Start must be called before using the generator
Start()
// converts a Prometheus metric family into a list of PromEvents
GeneratePromEvents(mf *dto.MetricFamily) []PromEvent
// Stop must be called when the generator won't be used anymore
Stop()
}
// PromEventsGeneratorFactory creates a PromEventsGenerator when instanciating a metricset
type PromEventsGeneratorFactory func(ms mb.BaseMetricSet) (PromEventsGenerator, error)
// MetricSet for fetching prometheus data
type MetricSet struct {
mb.BaseMetricSet
prometheus p.Prometheus
includeMetrics []*regexp.Regexp
excludeMetrics []*regexp.Regexp
namespace string
promEventsGen PromEventsGenerator
once sync.Once
host string
}
// MetricSetBuilder returns a builder function for a new Prometheus metricset using
// the given namespace and event generator
func MetricSetBuilder(namespace string, genFactory PromEventsGeneratorFactory) func(base mb.BaseMetricSet) (mb.MetricSet, error) {
return func(base mb.BaseMetricSet) (mb.MetricSet, error) {
config := defaultConfig
if err := base.Module().UnpackConfig(&config); err != nil {
return nil, err
}
prometheus, err := p.NewPrometheusClient(base)
if err != nil {
return nil, err
}
promEventsGen, err := genFactory(base)
if err != nil {
return nil, err
}
ms := &MetricSet{
BaseMetricSet: base,
prometheus: prometheus,
namespace: namespace,
promEventsGen: promEventsGen,
}
// store host here to use it as a pointer when building `up` metric
ms.host = ms.Host()
ms.excludeMetrics, err = compilePatternList(config.MetricsFilters.ExcludeMetrics)
if err != nil {
return nil, errors.Wrapf(err, "unable to compile exclude patterns")
}
ms.includeMetrics, err = compilePatternList(config.MetricsFilters.IncludeMetrics)
if err != nil {
return nil, errors.Wrapf(err, "unable to compile include patterns")
}
return ms, nil
}
}
// Fetch fetches data and reports it
func (m *MetricSet) Fetch(reporter mb.ReporterV2) error {
m.once.Do(m.promEventsGen.Start)
families, err := m.prometheus.GetFamilies()
eventList := map[string]common.MapStr{}
if err != nil {
// send up event only
families = append(families, m.upMetricFamily(0.0))
// set the error to report it after sending the up event
err = errors.Wrap(err, "unable to decode response from prometheus endpoint")
} else {
// add up event to the list
families = append(families, m.upMetricFamily(1.0))
}
for _, family := range families {
if m.skipFamily(family) {
continue
}
promEvents := m.promEventsGen.GeneratePromEvents(family)
for _, promEvent := range promEvents {
labelsHash := promEvent.LabelsHash()
if _, ok := eventList[labelsHash]; !ok {
eventList[labelsHash] = common.MapStr{}
// Add default instance label if not already there
if exists, _ := promEvent.Labels.HasKey(upMetricInstanceLabel); !exists {
promEvent.Labels.Put(upMetricInstanceLabel, m.Host())
}
// Add default job label if not already there
if exists, _ := promEvent.Labels.HasKey("job"); !exists {
promEvent.Labels.Put("job", m.Module().Name())
}
// Add labels
if len(promEvent.Labels) > 0 {
eventList[labelsHash]["labels"] = promEvent.Labels
}
}
// Accumulate metrics in the event
eventList[labelsHash].DeepUpdate(promEvent.Data)
}
}
// Report events
for _, e := range eventList {
isOpen := reporter.Event(mb.Event{
RootFields: common.MapStr{m.namespace: e},
})
if !isOpen {
break
}
}
return err
}
// Close stops the metricset
func (m *MetricSet) Close() error {
m.promEventsGen.Stop()
return nil
}
func (m *MetricSet) upMetricFamily(value float64) *dto.MetricFamily {
gauge := dto.Gauge{
Value: &value,
}
label1 := dto.LabelPair{
Name: &upMetricInstanceLabel,
Value: &m.host,
}
label2 := dto.LabelPair{
Name: &upMetricJobLabel,
Value: &upMetricJobValue,
}
metric := dto.Metric{
Gauge: &gauge,
Label: []*dto.LabelPair{&label1, &label2},
}
return &dto.MetricFamily{
Name: &upMetricName,
Type: &upMetricType,
Metric: []*dto.Metric{&metric},
}
}
func (m *MetricSet) skipFamily(family *dto.MetricFamily) bool {
if family == nil {
return false
}
return m.skipFamilyName(*family.Name)
}
func (m *MetricSet) skipFamilyName(family string) bool {
// example:
// include_metrics:
// - node_*
// exclude_metrics:
// - node_disk_*
//
// This would mean that we want to keep only the metrics that start with node_ prefix but
// are not related to disk so we exclude node_disk_* metrics from them.
// if include_metrics are defined, check if this metric should be included
if len(m.includeMetrics) > 0 {
if !matchMetricFamily(family, m.includeMetrics) {
return true
}
}
// now exclude the metric if it matches any of the given patterns
if len(m.excludeMetrics) > 0 {
if matchMetricFamily(family, m.excludeMetrics) {
return true
}
}
return false
}
func compilePatternList(patterns *[]string) ([]*regexp.Regexp, error) {
var compiledPatterns []*regexp.Regexp
compiledPatterns = []*regexp.Regexp{}
if patterns != nil {
for _, pattern := range *patterns {
r, err := regexp.Compile(pattern)
if err != nil {
return nil, errors.Wrapf(err, "compiling pattern '%s'", pattern)
}
compiledPatterns = append(compiledPatterns, r)
}
return compiledPatterns, nil
}
return []*regexp.Regexp{}, nil
}
func matchMetricFamily(family string, matchMetrics []*regexp.Regexp) bool {
for _, checkMetric := range matchMetrics {
matched := checkMetric.MatchString(family)
if matched {
return true
}
}
return false
}