-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmysql.go
116 lines (94 loc) · 2.12 KB
/
mysql.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
package prometheus
import (
"context"
"strconv"
"time"
"unicode"
"github.com/prometheus/client_golang/prometheus"
)
type MySQL struct {
Prefix string
Interval uint32
VariableNames []string
status map[string]prometheus.Gauge
}
func (m *MySQL) Metrics(p *Prometheus) []prometheus.Collector {
if m.Prefix == "" {
m.Prefix = "gorm_status_"
}
if m.Interval == 0 {
m.Interval = p.RefreshInterval
}
if m.status == nil {
m.status = map[string]prometheus.Gauge{}
}
go func() {
for range time.Tick(time.Duration(m.Interval) * time.Second) {
m.collect(p)
}
}()
m.collect(p)
collectors := make([]prometheus.Collector, 0, len(m.status))
for _, v := range m.status {
collectors = append(collectors, v)
}
return collectors
}
func (m *MySQL) collect(p *Prometheus) {
rows, err := p.DB.Raw("SHOW STATUS").Rows()
if err != nil {
p.DB.Logger.Error(context.Background(), "gorm:prometheus query error: %v", err)
return
}
var variableName, variableValue string
for rows.Next() {
err = rows.Scan(&variableName, &variableValue)
if err != nil {
p.DB.Logger.Error(context.Background(), "gorm:prometheus scan got error: %v", err)
continue
}
var found = len(m.VariableNames) == 0
for _, name := range m.VariableNames {
if name == variableName {
found = true
break
}
}
if found {
// check if variableValue is string
if variableValue == "" {
continue
}
isFloat64 := true
for _, r := range variableValue {
if !unicode.IsNumber(r) {
isFloat64 = false
break
}
if r == ':' {
isFloat64 = false
break
}
}
if !isFloat64 {
continue
}
value, err := strconv.ParseFloat(variableValue, 64)
if err != nil {
p.DB.Logger.Error(context.Background(), "gorm:prometheus parse float got error: %v", err)
continue
}
gauge, ok := m.status[variableName]
if !ok {
gauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: m.Prefix + variableName,
ConstLabels: p.Labels,
})
m.status[variableName] = gauge
_ = prometheus.Register(gauge)
}
gauge.Set(value)
}
}
return
}