forked from NoahAmethyst/sql_zh_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexporter.go
106 lines (95 loc) · 2.25 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
package main
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/robfig/cron/v3"
"sql_zh_exporter/util/log"
)
// Exporter collects SQL metrics. It implements prometheus.Collector.
type Exporter struct {
jobs []*Job
cronScheduler *cron.Cron
}
// NewExporter returns a new SQL Exporter for the provided config.
func NewExporter(configFile string) (*Exporter, error) {
// read config
cfg, err := Read(configFile)
if err != nil {
return nil, err
}
exp := &Exporter{
jobs: make([]*Job, 0, len(cfg.Jobs)),
cronScheduler: cron.New(),
}
// dispatch all jobs
for _, job := range cfg.Jobs {
if job == nil {
continue
}
if err := job.Init(cfg.Queries); err != nil {
log.Warn().Fields(
map[string]interface{}{
"message": "Skipping job. Failed to initialize",
"error": err,
"job": job.Name,
}).Send()
continue
}
exp.jobs = append(exp.jobs, job)
if job.CronSchedule.schedule != nil {
exp.cronScheduler.Schedule(job.CronSchedule.schedule, job)
log.Info().Fields(map[string]interface{}{
"message": "Scheduled CRON job",
"job": job.Name,
"cron_schedule": job.CronSchedule.definition,
}).Send()
} else {
go job.ExecutePeriodically()
log.Info().Fields(map[string]interface{}{
"message": "Started periodically execution of job",
"job": job.Name,
"interval": job.Interval.String(),
}).Send()
}
}
exp.cronScheduler.Start()
return exp, nil
}
// Describe implements prometheus.Collector
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, job := range e.jobs {
if job == nil {
continue
}
for _, query := range job.Queries {
if query == nil {
continue
}
if query.desc == nil {
log.Error().Fields(map[string]interface{}{
"error": "Query has no descripto",
"query": query.Name,
}).Send()
continue
}
ch <- query.desc
}
}
}
// Collect implements prometheus.Collector
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
for _, job := range e.jobs {
if job == nil {
continue
}
for _, query := range job.Queries {
if query == nil {
continue
}
for _, metrics := range query.metrics {
for _, metric := range metrics {
ch <- metric
}
}
}
}
}