-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
exporter.go
248 lines (218 loc) · 6.56 KB
/
exporter.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
package sql_exporter
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"github.com/burningalchemist/sql_exporter/config"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
)
var (
SvcRegistry = prometheus.NewRegistry()
svcMetricLabels = []string{"job", "target", "collector", "query"}
scrapeErrorsMetric *prometheus.CounterVec
)
// Exporter is a prometheus.Gatherer that gathers SQL metrics from targets and merges them with the default registry.
type Exporter interface {
prometheus.Gatherer
// WithContext returns a (single use) copy of the Exporter, which will use the provided context for Gather() calls.
WithContext(context.Context) Exporter
// Config returns the Exporter's underlying Config object.
Config() *config.Config
// UpdateTarget updates the targets field
UpdateTarget([]Target)
// SetJobFilters sets the jobFilters field
SetJobFilters([]string)
// DropErrorMetrics resets the scrape_errors_total metric
DropErrorMetrics()
}
type exporter struct {
config *config.Config
targets []Target
jobFilters []string
ctx context.Context
}
// NewExporter returns a new Exporter with the provided config.
func NewExporter(configFile string) (Exporter, error) {
c, err := config.Load(configFile)
if err != nil {
return nil, err
}
// Override the DSN if requested (and in single target mode).
if config.DsnOverride != "" {
if len(c.Jobs) > 0 {
return nil, errors.New("the config.data-source-name flag only applies in single target mode")
}
c.Target.DSN = config.Secret(config.DsnOverride)
}
var targets []Target
if c.Target != nil {
target, err := NewTarget("", c.Target.Name, "", string(c.Target.DSN), c.Target.Collectors(), nil, c.Globals, c.Target.EnablePing)
if err != nil {
return nil, err
}
targets = []Target{target}
} else {
if len(c.Jobs) > (config.MaxInt32 / 3) {
return nil, errors.New("'jobs' list is too large")
}
targets = make([]Target, 0, len(c.Jobs)*3)
for _, jc := range c.Jobs {
job, err := NewJob(jc, c.Globals)
if err != nil {
return nil, err
}
targets = append(targets, job.Targets()...)
}
}
scrapeErrorsMetric = registerScrapeErrorMetric()
return &exporter{
config: c,
targets: targets,
jobFilters: []string{},
ctx: context.Background(),
}, nil
}
func (e *exporter) WithContext(ctx context.Context) Exporter {
return &exporter{
config: e.config,
targets: e.targets,
jobFilters: e.jobFilters,
ctx: ctx,
}
}
// Gather implements prometheus.Gatherer.
func (e *exporter) Gather() ([]*dto.MetricFamily, error) {
var (
metricChan = make(chan Metric, capMetricChan)
errs prometheus.MultiError
)
// Filter out jobs that are not in the jobFilters list
e.filterTargets(e.jobFilters)
if len(e.targets) == 0 {
return nil, errors.New("no targets found")
}
var wg sync.WaitGroup
wg.Add(len(e.targets))
for _, t := range e.targets {
go func(target Target) {
defer wg.Done()
target.Collect(e.ctx, metricChan)
}(t)
}
// Wait for all collectors to complete, then close the channel.
go func() {
wg.Wait()
close(metricChan)
}()
// Drain metricChan in case of premature return.
defer func() {
for range metricChan {
}
}()
// Gather.
dtoMetricFamilies := make(map[string]*dto.MetricFamily, 10)
for metric := range metricChan {
dtoMetric := &dto.Metric{}
if err := metric.Write(dtoMetric); err != nil {
errs = append(errs, err)
if err.Context() != "" {
ctxLabels := parseContextLog(err.Context())
values := make([]string, len(svcMetricLabels))
for i, label := range svcMetricLabels {
values[i] = ctxLabels[label]
}
scrapeErrorsMetric.WithLabelValues(values...).Inc()
}
continue
}
metricDesc := metric.Desc()
dtoMetricFamily, ok := dtoMetricFamilies[metricDesc.Name()]
if !ok {
dtoMetricFamily = &dto.MetricFamily{}
dtoMetricFamily.Name = proto.String(metricDesc.Name())
dtoMetricFamily.Help = proto.String(metricDesc.Help())
switch {
case dtoMetric.Gauge != nil:
dtoMetricFamily.Type = dto.MetricType_GAUGE.Enum()
case dtoMetric.Counter != nil:
dtoMetricFamily.Type = dto.MetricType_COUNTER.Enum()
default:
errs = append(errs, fmt.Errorf("don't know how to handle metric %v", dtoMetric))
continue
}
dtoMetricFamilies[metricDesc.Name()] = dtoMetricFamily
}
dtoMetricFamily.Metric = append(dtoMetricFamily.Metric, dtoMetric)
}
// No need to sort metric families, prometheus.Gatherers will do that for us when merging.
result := make([]*dto.MetricFamily, 0, len(dtoMetricFamilies))
for _, mf := range dtoMetricFamilies {
result = append(result, mf)
}
return result, errs
}
func (e *exporter) filterTargets(jf []string) {
if len(jf) > 0 {
var filteredTargets []Target
for _, target := range e.targets {
for _, jobFilter := range jf {
if jobFilter == target.JobGroup() {
filteredTargets = append(filteredTargets, target)
break
}
}
}
if len(filteredTargets) == 0 {
slog.Error("No targets found for job filters. Nothing to scrape.")
}
e.targets = filteredTargets
}
}
// Config implements Exporter.
func (e *exporter) Config() *config.Config {
return e.config
}
// UpdateTarget implements Exporter.
func (e *exporter) UpdateTarget(target []Target) {
e.targets = target
}
// SetJobFilters implements Exporter.
func (e *exporter) SetJobFilters(filters []string) {
e.jobFilters = filters
}
// DropErrorMetrics implements Exporter.
func (e *exporter) DropErrorMetrics() {
scrapeErrorsMetric.Reset()
slog.Debug("Dropped scrape_errors_total metric")
}
// registerScrapeErrorMetric registers the metrics for the exporter itself.
func registerScrapeErrorMetric() *prometheus.CounterVec {
scrapeErrors := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "scrape_errors_total",
Help: "Total number of scrape errors per job, target, collector and query",
}, svcMetricLabels)
SvcRegistry.MustRegister(scrapeErrors)
return scrapeErrors
}
// split comma separated list of key=value pairs and return a map of key value pairs
func parseContextLog(list string) map[string]string {
m := make(map[string]string)
for _, item := range strings.Split(list, ",") {
parts := strings.SplitN(item, "=", 2)
m[parts[0]] = parts[1]
}
return m
}
// Leading comma appears when previous parameter is undefined, which is a side-effect of running in single target mode.
// Let's trim to avoid confusions.
func TrimMissingCtx(logContext string) string {
if strings.HasPrefix(logContext, ",") {
logContext = strings.TrimLeft(logContext, ", ")
}
return logContext
}