forked from kedacore/keda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_scaler.go
234 lines (205 loc) · 6.39 KB
/
mysql_scaler.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
package scalers
import (
"context"
"database/sql"
"fmt"
"strconv"
"github.com/go-sql-driver/mysql"
"k8s.io/api/autoscaling/v2beta2"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/metrics/pkg/apis/external_metrics"
logf "sigs.k8s.io/controller-runtime/pkg/log"
kedautil "github.com/kedacore/keda/v2/pkg/util"
)
type mySQLScaler struct {
metadata *mySQLMetadata
connection *sql.DB
}
type mySQLMetadata struct {
connectionString string // Database connection string
username string
password string
host string
port string
dbName string
query string
queryValue int
}
var mySQLLog = logf.Log.WithName("mysql_scaler")
// NewMySQLScaler creates a new MySQL scaler
func NewMySQLScaler(config *ScalerConfig) (Scaler, error) {
meta, err := parseMySQLMetadata(config)
if err != nil {
return nil, fmt.Errorf("error parsing MySQL metadata: %s", err)
}
conn, err := newMySQLConnection(meta)
if err != nil {
return nil, fmt.Errorf("error establishing MySQL connection: %s", err)
}
return &mySQLScaler{
metadata: meta,
connection: conn,
}, nil
}
func parseMySQLMetadata(config *ScalerConfig) (*mySQLMetadata, error) {
meta := mySQLMetadata{}
if val, ok := config.TriggerMetadata["query"]; ok {
meta.query = val
} else {
return nil, fmt.Errorf("no query given")
}
if val, ok := config.TriggerMetadata["queryValue"]; ok {
queryValue, err := strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("queryValue parsing error %s", err.Error())
}
meta.queryValue = queryValue
} else {
return nil, fmt.Errorf("no queryValue given")
}
switch {
case config.AuthParams["connectionString"] != "":
meta.connectionString = config.AuthParams["connectionString"]
case config.TriggerMetadata["connectionStringFromEnv"] != "":
meta.connectionString = config.ResolvedEnv[config.TriggerMetadata["connectionStringFromEnv"]]
default:
meta.connectionString = ""
var err error
meta.host, err = getFromAuthOrMeta(config, "host")
if err != nil {
return nil, err
}
meta.port, err = getFromAuthOrMeta(config, "port")
if err != nil {
return nil, err
}
meta.username, err = getFromAuthOrMeta(config, "username")
if err != nil {
return nil, err
}
meta.dbName, err = getFromAuthOrMeta(config, "dbName")
if err != nil {
return nil, err
}
if config.AuthParams["password"] != "" {
meta.password = config.AuthParams["password"]
} else if config.TriggerMetadata["passwordFromEnv"] != "" {
meta.password = config.ResolvedEnv[config.TriggerMetadata["passwordFromEnv"]]
}
if len(meta.password) == 0 {
return nil, fmt.Errorf("no password given")
}
}
return &meta, nil
}
// metadataToConnectionStr builds new MySQL connection string
func metadataToConnectionStr(meta *mySQLMetadata) string {
var connStr string
if meta.connectionString != "" {
connStr = meta.connectionString
} else {
// Build connection str
config := mysql.NewConfig()
config.Addr = fmt.Sprintf("%s:%s", meta.host, meta.port)
config.DBName = meta.dbName
config.Passwd = meta.password
config.User = meta.username
config.Net = "tcp"
connStr = config.FormatDSN()
}
return connStr
}
// newMySQLConnection creates MySQL db connection
func newMySQLConnection(meta *mySQLMetadata) (*sql.DB, error) {
connStr := metadataToConnectionStr(meta)
db, err := sql.Open("mysql", connStr)
if err != nil {
mySQLLog.Error(err, fmt.Sprintf("Found error when opening connection: %s", err))
return nil, err
}
err = db.Ping()
if err != nil {
mySQLLog.Error(err, fmt.Sprintf("Found error when pinging database: %s", err))
return nil, err
}
return db, nil
}
// Close disposes of MySQL connections
func (s *mySQLScaler) Close() error {
err := s.connection.Close()
if err != nil {
mySQLLog.Error(err, "Error closing MySQL connection")
return err
}
return nil
}
// IsActive returns true if there are pending messages to be processed
func (s *mySQLScaler) IsActive(ctx context.Context) (bool, error) {
messages, err := s.getQueryResult()
if err != nil {
mySQLLog.Error(err, fmt.Sprintf("Error inspecting MySQL: %s", err))
return false, err
}
return messages > 0, nil
}
// getQueryResult returns result of the scaler query
func (s *mySQLScaler) getQueryResult() (int, error) {
var value int
err := s.connection.QueryRow(s.metadata.query).Scan(&value)
if err != nil {
mySQLLog.Error(err, fmt.Sprintf("Could not query MySQL database: %s", err))
return 0, err
}
return value, nil
}
// GetMetricSpecForScaling returns the MetricSpec for the Horizontal Pod Autoscaler
func (s *mySQLScaler) GetMetricSpecForScaling() []v2beta2.MetricSpec {
targetQueryValue := resource.NewQuantity(int64(s.metadata.queryValue), resource.DecimalSI)
metricName := "mysql"
if s.metadata.connectionString != "" {
metricName = kedautil.NormalizeString(fmt.Sprintf("%s-%s", metricName, s.metadata.connectionString))
} else {
metricName = kedautil.NormalizeString(fmt.Sprintf("%s-%s", metricName, s.metadata.dbName))
}
externalMetric := &v2beta2.ExternalMetricSource{
Metric: v2beta2.MetricIdentifier{
Name: metricName,
},
Target: v2beta2.MetricTarget{
Type: v2beta2.AverageValueMetricType,
AverageValue: targetQueryValue,
},
}
metricSpec := v2beta2.MetricSpec{
External: externalMetric, Type: externalMetricType,
}
return []v2beta2.MetricSpec{metricSpec}
}
// GetMetrics returns value for a supported metric and an error if there is a problem getting the metric
func (s *mySQLScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {
num, err := s.getQueryResult()
if err != nil {
return []external_metrics.ExternalMetricValue{}, fmt.Errorf("error inspecting MySQL: %s", err)
}
metric := external_metrics.ExternalMetricValue{
MetricName: metricName,
Value: *resource.NewQuantity(int64(num), resource.DecimalSI),
Timestamp: metav1.Now(),
}
return append([]external_metrics.ExternalMetricValue{}, metric), nil
}
func getFromAuthOrMeta(config *ScalerConfig, field string) (string, error) {
var result string
var err error
if config.AuthParams[field] != "" {
result = config.AuthParams[field]
} else if config.TriggerMetadata[field] != "" {
result = config.TriggerMetadata[field]
}
if result == "" {
err = fmt.Errorf("no %s given", field)
}
return result, err
}