-
Notifications
You must be signed in to change notification settings - Fork 1k
/
postgresql_scaler.go
207 lines (178 loc) · 5.71 KB
/
postgresql_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
package scalers
import (
"context"
"database/sql"
"fmt"
"strconv"
// PostreSQL drive required for this scaler
_ "github.com/lib/pq"
"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 postgreSQLScaler struct {
metadata *postgreSQLMetadata
connection *sql.DB
}
type postgreSQLMetadata struct {
targetQueryValue int
connection string
query string
metricName string
scalerIndex int
}
var postgreSQLLog = logf.Log.WithName("postgreSQL_scaler")
// NewPostgreSQLScaler creates a new postgreSQL scaler
func NewPostgreSQLScaler(config *ScalerConfig) (Scaler, error) {
meta, err := parsePostgreSQLMetadata(config)
if err != nil {
return nil, fmt.Errorf("error parsing postgreSQL metadata: %s", err)
}
conn, err := getConnection(meta)
if err != nil {
return nil, fmt.Errorf("error establishing postgreSQL connection: %s", err)
}
return &postgreSQLScaler{
metadata: meta,
connection: conn,
}, nil
}
func parsePostgreSQLMetadata(config *ScalerConfig) (*postgreSQLMetadata, error) {
meta := postgreSQLMetadata{}
if val, ok := config.TriggerMetadata["query"]; ok {
meta.query = val
} else {
return nil, fmt.Errorf("no query given")
}
if val, ok := config.TriggerMetadata["targetQueryValue"]; ok {
targetQueryValue, err := strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("queryValue parsing error %s", err.Error())
}
meta.targetQueryValue = targetQueryValue
} else {
return nil, fmt.Errorf("no targetQueryValue given")
}
switch {
case config.AuthParams["connection"] != "":
meta.connection = config.AuthParams["connection"]
case config.TriggerMetadata["connectionFromEnv"] != "":
meta.connection = config.ResolvedEnv[config.TriggerMetadata["connectionFromEnv"]]
default:
host, err := GetFromAuthOrMeta(config, "host")
if err != nil {
return nil, err
}
port, err := GetFromAuthOrMeta(config, "port")
if err != nil {
return nil, err
}
userName, err := GetFromAuthOrMeta(config, "userName")
if err != nil {
return nil, err
}
dbName, err := GetFromAuthOrMeta(config, "dbName")
if err != nil {
return nil, err
}
sslmode, err := GetFromAuthOrMeta(config, "sslmode")
if err != nil {
return nil, err
}
var password string
if config.AuthParams["password"] != "" {
password = config.AuthParams["password"]
} else if config.TriggerMetadata["passwordFromEnv"] != "" {
password = config.ResolvedEnv[config.TriggerMetadata["passwordFromEnv"]]
}
meta.connection = fmt.Sprintf(
"host=%s port=%s user=%s dbname=%s sslmode=%s password=%s",
host,
port,
userName,
dbName,
sslmode,
password,
)
}
if val, ok := config.TriggerMetadata["metricName"]; ok {
meta.metricName = kedautil.NormalizeString(fmt.Sprintf("postgresql-%s", val))
} else {
meta.metricName = kedautil.NormalizeString("postgresql")
}
meta.scalerIndex = config.ScalerIndex
return &meta, nil
}
func getConnection(meta *postgreSQLMetadata) (*sql.DB, error) {
db, err := sql.Open("postgres", meta.connection)
if err != nil {
postgreSQLLog.Error(err, fmt.Sprintf("Found error opening postgreSQL: %s", err))
return nil, err
}
err = db.Ping()
if err != nil {
postgreSQLLog.Error(err, fmt.Sprintf("Found error pinging postgreSQL: %s", err))
return nil, err
}
return db, nil
}
// Close disposes of postgres connections
func (s *postgreSQLScaler) Close(context.Context) error {
err := s.connection.Close()
if err != nil {
postgreSQLLog.Error(err, "Error closing postgreSQL connection")
return err
}
return nil
}
// IsActive returns true if there are pending messages to be processed
func (s *postgreSQLScaler) IsActive(ctx context.Context) (bool, error) {
messages, err := s.getActiveNumber(ctx)
if err != nil {
return false, fmt.Errorf("error inspecting postgreSQL: %s", err)
}
return messages > 0, nil
}
func (s *postgreSQLScaler) getActiveNumber(ctx context.Context) (int, error) {
var id int
err := s.connection.QueryRowContext(ctx, s.metadata.query).Scan(&id)
if err != nil {
postgreSQLLog.Error(err, fmt.Sprintf("could not query postgreSQL: %s", err))
return 0, fmt.Errorf("could not query postgreSQL: %s", err)
}
return id, nil
}
// GetMetricSpecForScaling returns the MetricSpec for the Horizontal Pod Autoscaler
func (s *postgreSQLScaler) GetMetricSpecForScaling(context.Context) []v2beta2.MetricSpec {
targetQueryValue := resource.NewQuantity(int64(s.metadata.targetQueryValue), resource.DecimalSI)
externalMetric := &v2beta2.ExternalMetricSource{
Metric: v2beta2.MetricIdentifier{
Name: GenerateMetricNameWithIndex(s.metadata.scalerIndex, s.metadata.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 *postgreSQLScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {
num, err := s.getActiveNumber(ctx)
if err != nil {
return []external_metrics.ExternalMetricValue{}, fmt.Errorf("error inspecting postgreSQL: %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
}