forked from prometheus/mysqld_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysqld_exporter.go
416 lines (389 loc) · 13.3 KB
/
mysqld_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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package main
import (
"database/sql"
"flag"
"fmt"
"net/http"
"os"
"path"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
"gopkg.in/ini.v1"
"github.com/prometheus/mysqld_exporter/collector"
)
var (
listenAddress = flag.String(
"web.listen-address", ":9104",
"Address to listen on for web interface and telemetry.",
)
metricPath = flag.String(
"web.telemetry-path", "/metrics",
"Path under which to expose metrics.",
)
configMycnf = flag.String(
"config.my-cnf", path.Join(os.Getenv("HOME"), ".my.cnf"),
"Path to .my.cnf file to read MySQL credentials from.",
)
slowLogFilter = flag.Bool(
"log_slow_filter", false,
"Add a log_slow_filter to avoid exessive MySQL slow logging. NOTE: Not supported by Oracle MySQL.",
)
collectProcesslist = flag.Bool(
"collect.info_schema.processlist", false,
"Collect current thread state counts from the information_schema.processlist",
)
collectTableSchema = flag.Bool(
"collect.info_schema.tables", true,
"Collect metrics from information_schema.tables",
)
collectInnodbTablespaces = flag.Bool(
"collect.info_schema.innodb_tablespaces", true,
"Collect metrics from information_schema.innodb_sys_tablepaces",
)
innodbMetrics = flag.Bool(
"collect.info_schema.innodb_metrics", false,
"Collect metrics from information_schema.innodb_metrics",
)
collectGlobalStatus = flag.Bool(
"collect.global_status", true,
"Collect from SHOW GLOBAL STATUS",
)
collectGlobalVariables = flag.Bool(
"collect.global_variables", true,
"Collect from SHOW GLOBAL VARIABLES",
)
collectSlaveStatus = flag.Bool(
"collect.slave_status", true,
"Collect from SHOW SLAVE STATUS",
)
collectAutoIncrementColumns = flag.Bool(
"collect.auto_increment.columns", false,
"Collect auto_increment columns and max values from information_schema",
)
collectBinlogSize = flag.Bool(
"collect.binlog_size", false,
"Collect the current size of all registered binlog files",
)
collectPerfTableIOWaits = flag.Bool(
"collect.perf_schema.tableiowaits", false,
"Collect metrics from performance_schema.table_io_waits_summary_by_table",
)
collectPerfIndexIOWaits = flag.Bool(
"collect.perf_schema.indexiowaits", false,
"Collect metrics from performance_schema.table_io_waits_summary_by_index_usage",
)
collectPerfTableLockWaits = flag.Bool(
"collect.perf_schema.tablelocks", false,
"Collect metrics from performance_schema.table_lock_waits_summary_by_table",
)
collectPerfEventsStatements = flag.Bool(
"collect.perf_schema.eventsstatements", false,
"Collect metrics from performance_schema.events_statements_summary_by_digest",
)
collectPerfEventsWaits = flag.Bool(
"collect.perf_schema.eventswaits", false,
"Collect metrics from performance_schema.events_waits_summary_global_by_event_name",
)
collectPerfFileEvents = flag.Bool(
"collect.perf_schema.file_events", false,
"Collect metrics from performance_schema.file_summary_by_event_name",
)
collectUserStat = flag.Bool("collect.info_schema.userstats", false,
"If running with userstat=1, set to true to collect user statistics",
)
collectTableStat = flag.Bool("collect.info_schema.tablestats", false,
"If running with userstat=1, set to true to collect table statistics",
)
collectQueryResponseTime = flag.Bool("collect.info_schema.query_response_time", false,
"Collect query response time distribution if query_response_time_stats is ON.")
collectEngineTokudbStatus = flag.Bool("collect.engine_tokudb_status", false,
"Collect from SHOW ENGINE TOKUDB STATUS")
)
// Metric name parts.
const (
// Namespace for all metrics.
namespace = "mysql"
// Subsystem(s).
exporter = "exporter"
)
// SQL Queries.
const (
sessionSettingsQuery = `SET SESSION log_slow_filter = 'tmp_table_on_disk,filesort_on_disk'`
upQuery = `SELECT 1`
)
// landingPage contains the HTML served at '/'.
// TODO: Make this nicer and more informative.
var landingPage = []byte(`<html>
<head><title>MySQLd exporter</title></head>
<body>
<h1>MySQLd exporter</h1>
<p><a href='` + *metricPath + `'>Metrics</a></p>
</body>
</html>
`)
// Exporter collects MySQL metrics. It implements prometheus.Collector.
type Exporter struct {
dsn string
duration, error prometheus.Gauge
totalScrapes prometheus.Counter
scrapeErrors *prometheus.CounterVec
mysqldUp prometheus.Gauge
}
// NewExporter returns a new MySQL exporter for the provided DSN.
func NewExporter(dsn string) *Exporter {
return &Exporter{
dsn: dsn,
duration: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: exporter,
Name: "last_scrape_duration_seconds",
Help: "Duration of the last scrape of metrics from MySQL.",
}),
totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Subsystem: exporter,
Name: "scrapes_total",
Help: "Total number of times MySQL was scraped for metrics.",
}),
scrapeErrors: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Subsystem: exporter,
Name: "scrape_errors_total",
Help: "Total number of times an error occured scraping a MySQL.",
}, []string{"collector"}),
error: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: exporter,
Name: "last_scrape_error",
Help: "Whether the last scrape of metrics from MySQL resulted in an error (1 for error, 0 for success).",
}),
mysqldUp: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "up",
Help: "Whether the MySQL server is up.",
}),
}
}
// Describe implements prometheus.Collector.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
// We cannot know in advance what metrics the exporter will generate
// from MySQL. So we use the poor man's describe method: Run a collect
// and send the descriptors of all the collected metrics. The problem
// here is that we need to connect to the MySQL DB. If it is currently
// unavailable, the descriptors will be incomplete. Since this is a
// stand-alone exporter and not used as a library within other code
// implementing additional metrics, the worst that can happen is that we
// don't detect inconsistent metrics created by this exporter
// itself. Also, a change in the monitored MySQL instance may change the
// exported metrics during the runtime of the exporter.
metricCh := make(chan prometheus.Metric)
doneCh := make(chan struct{})
go func() {
for m := range metricCh {
ch <- m.Desc()
}
close(doneCh)
}()
e.Collect(metricCh)
close(metricCh)
<-doneCh
}
// Collect implements prometheus.Collector.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
e.scrape(ch)
ch <- e.duration
ch <- e.totalScrapes
ch <- e.error
e.scrapeErrors.Collect(ch)
ch <- e.mysqldUp
}
func (e *Exporter) scrape(ch chan<- prometheus.Metric) {
e.totalScrapes.Inc()
var err error
defer func(begun time.Time) {
e.duration.Set(time.Since(begun).Seconds())
if err == nil {
e.error.Set(0)
} else {
e.error.Set(1)
}
}(time.Now())
db, err := sql.Open("mysql", e.dsn)
if err != nil {
log.Errorln("Error opening connection to database:", err)
return
}
defer db.Close()
isUpRows, err := db.Query(upQuery)
if err != nil {
log.Errorln("Error pinging mysqld:", err)
e.mysqldUp.Set(0)
return
}
isUpRows.Close()
e.mysqldUp.Set(1)
if *slowLogFilter {
sessionSettingsRows, err := db.Query(sessionSettingsQuery)
if err != nil {
log.Errorln("Error setting log_slow_filter:", err)
return
}
sessionSettingsRows.Close()
}
if *collectGlobalStatus {
if err = collector.ScrapeGlobalStatus(db, ch); err != nil {
log.Errorln("Error scraping for collect.global_status:", err)
e.scrapeErrors.WithLabelValues("collect.global_status").Inc()
}
}
if *collectGlobalVariables {
if err = collector.ScrapeGlobalVariables(db, ch); err != nil {
log.Errorln("Error scraping for collect.global_variables:", err)
e.scrapeErrors.WithLabelValues("collect.global_variables").Inc()
}
}
if *collectSlaveStatus {
if err = collector.ScrapeSlaveStatus(db, ch); err != nil {
log.Errorln("Error scraping for collect.slave_status:", err)
e.scrapeErrors.WithLabelValues("collect.slave_status").Inc()
}
}
if *collectProcesslist {
if err = collector.ScrapeProcesslist(db, ch); err != nil {
log.Errorln("Error scraping for collect.info_schema.processlist:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.processlist").Inc()
}
}
if *collectTableSchema {
if err = collector.ScrapeTableSchema(db, ch); err != nil {
log.Errorln("Error scraping collect.info_schema.tables:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.tables").Inc()
}
}
if *collectInnodbTablespaces {
if err = collector.ScrapeInfoSchemaInnodbTablespaces(db, ch); err != nil {
log.Errorln("Error scraping for collect.info_schema.innodb_sys_tablespaces:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.innodb_sys_tablespaces").Inc()
}
}
if *innodbMetrics {
if err = collector.ScrapeInnodbMetrics(db, ch); err != nil {
log.Errorln("Error scraping for collect.info_schema.innodb_metrics:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.innodb_metrics").Inc()
}
}
if *collectAutoIncrementColumns {
if err = collector.ScrapeAutoIncrementColumns(db, ch); err != nil {
log.Errorln("Error scraping for collect.auto_increment.columns:", err)
e.scrapeErrors.WithLabelValues("collect.auto_increment.columns").Inc()
}
}
if *collectBinlogSize {
if err = collector.ScrapeBinlogSize(db, ch); err != nil {
log.Errorln("Error scraping for collect.binlog_size:", err)
e.scrapeErrors.WithLabelValues("collect.binlog_size").Inc()
}
}
if *collectPerfTableIOWaits {
if err = collector.ScrapePerfTableIOWaits(db, ch); err != nil {
log.Errorln("Error scraping for collect.perf_schema.tableiowaits:", err)
e.scrapeErrors.WithLabelValues("collect.perf_schema.tableiowaits").Inc()
}
}
if *collectPerfIndexIOWaits {
if err = collector.ScrapePerfIndexIOWaits(db, ch); err != nil {
log.Errorln("Error scraping for collect.perf_schema.indexiowaits:", err)
e.scrapeErrors.WithLabelValues("collect.perf_schema.indexiowaits").Inc()
}
}
if *collectPerfTableLockWaits {
if err = collector.ScrapePerfTableLockWaits(db, ch); err != nil {
log.Errorln("Error scraping for collect.perf_schema.tablelocks:", err)
e.scrapeErrors.WithLabelValues("collect.perf_schema.tablelocks").Inc()
}
}
if *collectPerfEventsStatements {
if err = collector.ScrapePerfEventsStatements(db, ch); err != nil {
log.Errorln("Error scraping for collect.perf_schema.eventsstatements:", err)
e.scrapeErrors.WithLabelValues("collect.perf_schema.eventsstatements").Inc()
}
}
if *collectPerfEventsWaits {
if err = collector.ScrapePerfEventsWaits(db, ch); err != nil {
log.Errorln("Error scraping for collect.perf_schema.eventswaits:", err)
e.scrapeErrors.WithLabelValues("collect.perf_schema.eventswaits").Inc()
}
}
if *collectPerfFileEvents {
if err = collector.ScrapePerfFileEvents(db, ch); err != nil {
log.Errorln("Error scraping for collect.perf_schema.file_events:", err)
e.scrapeErrors.WithLabelValues("collect.perf_schema.file_events").Inc()
}
}
if *collectUserStat {
if err = collector.ScrapeUserStat(db, ch); err != nil {
log.Errorln("Error scraping for collect.info_schema.userstats:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.userstats").Inc()
}
}
if *collectTableStat {
if err = collector.ScrapeTableStat(db, ch); err != nil {
log.Errorln("Error scraping table stat:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.tablestats").Inc()
}
}
if *collectQueryResponseTime {
if err = collector.ScrapeQueryResponseTime(db, ch); err != nil {
log.Errorln("Error scraping query response time:", err)
e.scrapeErrors.WithLabelValues("collect.info_schema.query_response_time").Inc()
}
}
if *collectEngineTokudbStatus {
if err = collector.ScrapeEngineTokudbStatus(db, ch); err != nil {
log.Errorln("Error scraping TokuDB engine status:", err)
e.scrapeErrors.WithLabelValues("collect.engine_tokudb_status").Inc()
}
}
}
func parseMycnf(config interface{}) (string, error) {
var dsn string
cfg, err := ini.Load(config)
if err != nil {
return dsn, fmt.Errorf("failed reading ini file: %s", err)
}
user := cfg.Section("client").Key("user").String()
password := cfg.Section("client").Key("password").String()
if (user == "") || (password == "") {
return dsn, fmt.Errorf("no user or password specified under [client] in %s", config)
}
host := cfg.Section("client").Key("host").MustString("localhost")
port := cfg.Section("client").Key("port").MustUint(3306)
socket := cfg.Section("client").Key("socket").String()
if socket != "" {
dsn = fmt.Sprintf("%s:%s@unix(%s)/", user, password, socket)
} else {
dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/", user, password, host, port)
}
log.Debugln(dsn)
return dsn, nil
}
func main() {
flag.Parse()
dsn := os.Getenv("DATA_SOURCE_NAME")
if len(dsn) == 0 {
var err error
if dsn, err = parseMycnf(*configMycnf); err != nil {
log.Fatal(err)
}
}
exporter := NewExporter(dsn)
prometheus.MustRegister(exporter)
http.Handle(*metricPath, prometheus.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(landingPage)
})
log.Infof("Starting Server: %s", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}