-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rabbitmq_scaler.go
257 lines (211 loc) · 6.52 KB
/
rabbitmq_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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package scalers
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
"github.com/streadway/amqp"
v2beta2 "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"
)
const (
rabbitQueueLengthMetricName = "queueLength"
defaultRabbitMQQueueLength = 20
rabbitMetricType = "External"
)
const (
httpProtocol = "http"
amqpProtocol = "amqp"
defaultProtocol = amqpProtocol
)
type rabbitMQScaler struct {
metadata *rabbitMQMetadata
connection *amqp.Connection
channel *amqp.Channel
}
type rabbitMQMetadata struct {
queueName string
queueLength int
host string // connection string for either HTTP or AMQP protocol
protocol string // either http or amqp protocol
}
type queueInfo struct {
Messages int `json:"messages"`
MessagesUnacknowledged int `json:"messages_unacknowledged"`
Name string `json:"name"`
}
var rabbitmqLog = logf.Log.WithName("rabbitmq_scaler")
// NewRabbitMQScaler creates a new rabbitMQ scaler
func NewRabbitMQScaler(config *ScalerConfig) (Scaler, error) {
meta, err := parseRabbitMQMetadata(config)
if err != nil {
return nil, fmt.Errorf("error parsing rabbitmq metadata: %s", err)
}
if meta.protocol == httpProtocol {
return &rabbitMQScaler{metadata: meta}, nil
}
conn, ch, err := getConnectionAndChannel(meta.host)
if err != nil {
return nil, fmt.Errorf("error establishing rabbitmq connection: %s", err)
}
return &rabbitMQScaler{
metadata: meta,
connection: conn,
channel: ch,
}, nil
}
func parseRabbitMQMetadata(config *ScalerConfig) (*rabbitMQMetadata, error) {
meta := rabbitMQMetadata{}
// Resolve protocol type
meta.protocol = defaultProtocol
if val, ok := config.TriggerMetadata["protocol"]; ok {
if val == amqpProtocol || val == httpProtocol {
meta.protocol = val
} else {
return nil, fmt.Errorf("the protocol has to be either `%s` or `%s` but is `%s`", amqpProtocol, httpProtocol, val)
}
}
// Resolve host value
switch {
case config.AuthParams["host"] != "":
meta.host = config.AuthParams["host"]
case config.TriggerMetadata["host"] != "":
meta.host = config.TriggerMetadata["host"]
case config.TriggerMetadata["hostFromEnv"] != "":
meta.host = config.ResolvedEnv[config.TriggerMetadata["hostFromEnv"]]
default:
return nil, fmt.Errorf("no host setting given")
}
// Resolve queueName
if val, ok := config.TriggerMetadata["queueName"]; ok {
meta.queueName = val
} else {
return nil, fmt.Errorf("no queue name given")
}
// Resolve queueLength
if val, ok := config.TriggerMetadata[rabbitQueueLengthMetricName]; ok {
queueLength, err := strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("can't parse %s: %s", rabbitQueueLengthMetricName, err)
}
meta.queueLength = queueLength
} else {
meta.queueLength = defaultRabbitMQQueueLength
}
return &meta, nil
}
func getConnectionAndChannel(host string) (*amqp.Connection, *amqp.Channel, error) {
conn, err := amqp.Dial(host)
if err != nil {
return nil, nil, err
}
channel, err := conn.Channel()
if err != nil {
return nil, nil, err
}
return conn, channel, nil
}
// Close disposes of RabbitMQ connections
func (s *rabbitMQScaler) Close() error {
if s.connection != nil {
err := s.connection.Close()
if err != nil {
rabbitmqLog.Error(err, "Error closing rabbitmq connection")
return err
}
}
return nil
}
// IsActive returns true if there are pending messages to be processed
func (s *rabbitMQScaler) IsActive(ctx context.Context) (bool, error) {
messages, err := s.getQueueMessages()
if err != nil {
return false, fmt.Errorf("error inspecting rabbitMQ: %s", err)
}
return messages > 0, nil
}
func (s *rabbitMQScaler) getQueueMessages() (int, error) {
if s.metadata.protocol == httpProtocol {
info, err := s.getQueueInfoViaHTTP()
if err != nil {
return -1, err
}
// messages count includes count of ready and unack-ed
return info.Messages, nil
}
items, err := s.channel.QueueInspect(s.metadata.queueName)
if err != nil {
return -1, err
}
return items.Messages, nil
}
func getJSON(url string, target interface{}) error {
var client = &http.Client{Timeout: 5 * time.Second}
r, err := client.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
if r.StatusCode == 200 {
return json.NewDecoder(r.Body).Decode(target)
}
body, _ := ioutil.ReadAll(r.Body)
return fmt.Errorf("error requesting rabbitMQ API status: %s, response: %s, from: %s", r.Status, body, url)
}
func (s *rabbitMQScaler) getQueueInfoViaHTTP() (*queueInfo, error) {
parsedURL, err := url.Parse(s.metadata.host)
if err != nil {
return nil, err
}
vhost := parsedURL.Path
if vhost == "" || vhost == "/" || vhost == "//" {
vhost = "/%2F"
}
parsedURL.Path = ""
getQueueInfoManagementURI := fmt.Sprintf("%s/%s%s/%s", parsedURL.String(), "api/queues", vhost, s.metadata.queueName)
info := queueInfo{}
err = getJSON(getQueueInfoManagementURI, &info)
if err != nil {
return nil, err
}
return &info, nil
}
// GetMetricSpecForScaling returns the MetricSpec for the Horizontal Pod Autoscaler
func (s *rabbitMQScaler) GetMetricSpecForScaling() []v2beta2.MetricSpec {
targetMetricValue := resource.NewQuantity(int64(s.metadata.queueLength), resource.DecimalSI)
externalMetric := &v2beta2.ExternalMetricSource{
Metric: v2beta2.MetricIdentifier{
Name: kedautil.NormalizeString(fmt.Sprintf("%s-%s", "rabbitmq", s.metadata.queueName)),
},
Target: v2beta2.MetricTarget{
Type: v2beta2.AverageValueMetricType,
AverageValue: targetMetricValue,
},
}
metricSpec := v2beta2.MetricSpec{
External: externalMetric, Type: rabbitMetricType,
}
return []v2beta2.MetricSpec{metricSpec}
}
// GetMetrics returns value for a supported metric and an error if there is a problem getting the metric
func (s *rabbitMQScaler) GetMetrics(ctx context.Context, metricName string, metricSelector labels.Selector) ([]external_metrics.ExternalMetricValue, error) {
messages, err := s.getQueueMessages()
if err != nil {
return []external_metrics.ExternalMetricValue{}, fmt.Errorf("error inspecting rabbitMQ: %s", err)
}
metric := external_metrics.ExternalMetricValue{
MetricName: metricName,
Value: *resource.NewQuantity(int64(messages), resource.DecimalSI),
Timestamp: metav1.Now(),
}
return append([]external_metrics.ExternalMetricValue{}, metric), nil
}