-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
azure_eventhub_scaler.go
405 lines (328 loc) · 15.8 KB
/
azure_eventhub_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
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
package scalers
/*
Copyright 2021 The KEDA Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import (
"context"
"fmt"
"math"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
az "github.com/Azure/go-autorest/autorest/azure"
"github.com/go-logr/logr"
v2 "k8s.io/api/autoscaling/v2"
"k8s.io/metrics/pkg/apis/external_metrics"
"github.com/kedacore/keda/v2/apis/keda/v1alpha1"
"github.com/kedacore/keda/v2/pkg/scalers/azure"
"github.com/kedacore/keda/v2/pkg/scalers/scalersconfig"
kedautil "github.com/kedacore/keda/v2/pkg/util"
)
const (
defaultEventHubMessageThreshold = 64
eventHubMetricType = "External"
thresholdMetricName = "unprocessedEventThreshold"
activationThresholdMetricName = "activationUnprocessedEventThreshold"
defaultEventHubConsumerGroup = "$Default"
defaultBlobContainer = ""
defaultCheckpointStrategy = ""
defaultStalePartitionInfoThreshold = 10000
)
type azureEventHubScaler struct {
metricType v2.MetricTargetType
metadata *eventHubMetadata
eventHubClient *azeventhubs.ProducerClient
blobStorageClient *azblob.Client
logger logr.Logger
}
type eventHubMetadata struct {
eventHubInfo azure.EventHubInfo
threshold int64
activationThreshold int64
stalePartitionInfoThreshold int64
triggerIndex int
}
// NewAzureEventHubScaler creates a new scaler for eventHub
func NewAzureEventHubScaler(config *scalersconfig.ScalerConfig) (Scaler, error) {
metricType, err := GetMetricTargetType(config)
if err != nil {
return nil, fmt.Errorf("error getting scaler metric type: %w", err)
}
logger := InitializeLogger(config, "azure_eventhub_scaler")
parsedMetadata, err := parseAzureEventHubMetadata(logger, config)
if err != nil {
return nil, fmt.Errorf("unable to get eventhub metadata: %w", err)
}
eventHubClient, err := azure.GetEventHubClient(parsedMetadata.eventHubInfo, logger)
if err != nil {
return nil, fmt.Errorf("unable to get eventhub client: %w", err)
}
blobStorageClient, err := azure.GetStorageBlobClient(logger, config.PodIdentity, parsedMetadata.eventHubInfo.StorageConnection, parsedMetadata.eventHubInfo.StorageAccountName, parsedMetadata.eventHubInfo.BlobStorageEndpoint, config.GlobalHTTPTimeout)
if err != nil {
return nil, fmt.Errorf("unable to get eventhub client: %w", err)
}
return &azureEventHubScaler{
metricType: metricType,
metadata: parsedMetadata,
eventHubClient: eventHubClient,
blobStorageClient: blobStorageClient,
logger: logger,
}, nil
}
// parseAzureEventHubMetadata parses metadata
func parseAzureEventHubMetadata(logger logr.Logger, config *scalersconfig.ScalerConfig) (*eventHubMetadata, error) {
meta := eventHubMetadata{
eventHubInfo: azure.EventHubInfo{},
}
err := parseCommonAzureEventHubMetadata(config, &meta)
if err != nil {
return nil, err
}
err = parseAzureEventHubAuthenticationMetadata(logger, config, &meta)
if err != nil {
return nil, err
}
return &meta, nil
}
func parseCommonAzureEventHubMetadata(config *scalersconfig.ScalerConfig, meta *eventHubMetadata) error {
meta.threshold = defaultEventHubMessageThreshold
if val, ok := config.TriggerMetadata[thresholdMetricName]; ok {
threshold, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return fmt.Errorf("error parsing azure eventhub metadata %s: %w", thresholdMetricName, err)
}
meta.threshold = threshold
}
meta.activationThreshold = 0
if val, ok := config.TriggerMetadata[activationThresholdMetricName]; ok {
activationThreshold, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return fmt.Errorf("error parsing azure eventhub metadata %s: %w", activationThresholdMetricName, err)
}
meta.activationThreshold = activationThreshold
}
if config.AuthParams["storageConnection"] != "" {
meta.eventHubInfo.StorageConnection = config.AuthParams["storageConnection"]
} else if config.TriggerMetadata["storageConnectionFromEnv"] != "" {
meta.eventHubInfo.StorageConnection = config.ResolvedEnv[config.TriggerMetadata["storageConnectionFromEnv"]]
}
meta.eventHubInfo.EventHubConsumerGroup = defaultEventHubConsumerGroup
if val, ok := config.TriggerMetadata["consumerGroup"]; ok {
meta.eventHubInfo.EventHubConsumerGroup = val
}
meta.eventHubInfo.CheckpointStrategy = defaultCheckpointStrategy
if val, ok := config.TriggerMetadata["checkpointStrategy"]; ok {
meta.eventHubInfo.CheckpointStrategy = val
}
meta.eventHubInfo.BlobContainer = defaultBlobContainer
if val, ok := config.TriggerMetadata["blobContainer"]; ok {
meta.eventHubInfo.BlobContainer = val
}
serviceBusEndpointSuffixProvider := func(env az.Environment) (string, error) {
return env.ServiceBusEndpointSuffix, nil
}
serviceBusEndpointSuffix, err := azure.ParseEnvironmentProperty(config.TriggerMetadata, azure.DefaultEndpointSuffixKey, serviceBusEndpointSuffixProvider)
if err != nil {
return err
}
meta.eventHubInfo.ServiceBusEndpointSuffix = serviceBusEndpointSuffix
meta.stalePartitionInfoThreshold = defaultStalePartitionInfoThreshold
if val, ok := config.TriggerMetadata["stalePartitionInfoThreshold"]; ok {
stalePartitionInfoThreshold, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return fmt.Errorf("error parsing azure eventhub metadata stalePartitionInfoThreshold: %w", err)
}
meta.stalePartitionInfoThreshold = stalePartitionInfoThreshold
}
meta.triggerIndex = config.TriggerIndex
return nil
}
func parseAzureEventHubAuthenticationMetadata(logger logr.Logger, config *scalersconfig.ScalerConfig, meta *eventHubMetadata) error {
meta.eventHubInfo.PodIdentity = config.PodIdentity
switch config.PodIdentity.Provider {
case "", v1alpha1.PodIdentityProviderNone:
if len(meta.eventHubInfo.StorageConnection) == 0 {
return fmt.Errorf("no storage connection string given")
}
connection := ""
if config.AuthParams["connection"] != "" {
connection = config.AuthParams["connection"]
} else if config.TriggerMetadata["connectionFromEnv"] != "" {
connection = config.ResolvedEnv[config.TriggerMetadata["connectionFromEnv"]]
}
if len(connection) == 0 {
return fmt.Errorf("no event hub connection string given")
}
if !strings.Contains(connection, "EntityPath") {
eventHubName := ""
if config.TriggerMetadata["eventHubName"] != "" {
eventHubName = config.TriggerMetadata["eventHubName"]
} else if config.TriggerMetadata["eventHubNameFromEnv"] != "" {
eventHubName = config.ResolvedEnv[config.TriggerMetadata["eventHubNameFromEnv"]]
}
if eventHubName == "" {
return fmt.Errorf("connection string does not contain event hub name, and parameter eventHubName not provided")
}
connection = fmt.Sprintf("%s;EntityPath=%s", connection, eventHubName)
}
meta.eventHubInfo.EventHubConnection = connection
case v1alpha1.PodIdentityProviderAzureWorkload:
meta.eventHubInfo.StorageAccountName = ""
if val, ok := config.TriggerMetadata["storageAccountName"]; ok {
meta.eventHubInfo.StorageAccountName = val
} else {
logger.Info("no 'storageAccountName' provided to enable identity based authentication to Blob Storage. Attempting to use connection string instead")
}
if len(meta.eventHubInfo.StorageAccountName) != 0 {
storageEndpointSuffixProvider := func(env az.Environment) (string, error) {
return env.StorageEndpointSuffix, nil
}
storageEndpointSuffix, err := azure.ParseEnvironmentProperty(config.TriggerMetadata, azure.DefaultStorageSuffixKey, storageEndpointSuffixProvider)
if err != nil {
return err
}
meta.eventHubInfo.BlobStorageEndpoint = "blob." + storageEndpointSuffix
}
if len(meta.eventHubInfo.StorageConnection) == 0 && len(meta.eventHubInfo.StorageAccountName) == 0 {
return fmt.Errorf("no storage connection string or storage account name for pod identity based authentication given")
}
if config.TriggerMetadata["eventHubNamespace"] != "" {
meta.eventHubInfo.Namespace = config.TriggerMetadata["eventHubNamespace"]
} else if config.TriggerMetadata["eventHubNamespaceFromEnv"] != "" {
meta.eventHubInfo.Namespace = config.ResolvedEnv[config.TriggerMetadata["eventHubNamespaceFromEnv"]]
}
if len(meta.eventHubInfo.Namespace) == 0 {
return fmt.Errorf("no event hub namespace string given")
}
if config.TriggerMetadata["eventHubName"] != "" {
meta.eventHubInfo.EventHubName = config.TriggerMetadata["eventHubName"]
} else if config.TriggerMetadata["eventHubNameFromEnv"] != "" {
meta.eventHubInfo.EventHubName = config.ResolvedEnv[config.TriggerMetadata["eventHubNameFromEnv"]]
}
if len(meta.eventHubInfo.EventHubName) == 0 {
return fmt.Errorf("no event hub name string given")
}
}
return nil
}
// GetUnprocessedEventCountInPartition gets number of unprocessed events in a given partition
func (s *azureEventHubScaler) GetUnprocessedEventCountInPartition(ctx context.Context, partitionInfo azeventhubs.PartitionProperties) (newEventCount int64, checkpoint azure.Checkpoint, err error) {
// if partitionInfo.LastEnqueuedSequenceNumber = -1, that means event hub partition is empty
if partitionInfo.LastEnqueuedSequenceNumber == -1 {
return 0, azure.Checkpoint{}, nil
}
checkpoint, err = azure.GetCheckpointFromBlobStorage(ctx, s.blobStorageClient, s.metadata.eventHubInfo, partitionInfo.PartitionID)
if err != nil {
// if blob not found return the total partition event count
if bloberror.HasCode(err, bloberror.BlobNotFound, bloberror.ContainerNotFound) {
s.logger.V(1).Error(err, fmt.Sprintf("Blob container : %s not found to use checkpoint strategy, getting unprocessed event count without checkpoint", s.metadata.eventHubInfo.BlobContainer))
return GetUnprocessedEventCountWithoutCheckpoint(partitionInfo), azure.Checkpoint{}, nil
}
return -1, azure.Checkpoint{}, fmt.Errorf("unable to get checkpoint from storage: %w", err)
}
unprocessedEventCountInPartition := calculateUnprocessedEvents(partitionInfo, checkpoint, s.metadata.stalePartitionInfoThreshold)
return unprocessedEventCountInPartition, checkpoint, nil
}
func calculateUnprocessedEvents(partitionInfo azeventhubs.PartitionProperties, checkpoint azure.Checkpoint, stalePartitionInfoThreshold int64) int64 {
unprocessedEventCount := int64(0)
if partitionInfo.LastEnqueuedSequenceNumber >= checkpoint.SequenceNumber {
unprocessedEventCount = partitionInfo.LastEnqueuedSequenceNumber - checkpoint.SequenceNumber
} else {
// Partition is a circular buffer, so it is possible that
// partitionInfo.LastSequenceNumber < blob checkpoint's SequenceNumber
// Checkpointing may or may not be always behind partition's LastSequenceNumber.
// The partition information read could be stale compared to checkpoint,
// especially when load is very small and checkpointing is happening often.
// This also results in partitionInfo.LastSequenceNumber < blob checkpoint's SequenceNumber
// e.g., (9223372036854775807 - 15) + 10 = 9223372036854775802
// Calculate the unprocessed events
unprocessedEventCount = (math.MaxInt64 - checkpoint.SequenceNumber) + partitionInfo.LastEnqueuedSequenceNumber
}
// If the result is greater than the buffer size - stale partition threshold
// we assume the partition info is stale.
if unprocessedEventCount > (math.MaxInt64 - stalePartitionInfoThreshold) {
return 0
}
return unprocessedEventCount
}
// GetUnprocessedEventCountWithoutCheckpoint returns the number of messages on the without a checkoutpoint info
func GetUnprocessedEventCountWithoutCheckpoint(partitionInfo azeventhubs.PartitionProperties) int64 {
// if both values are 0 then there is exactly one message inside the hub. First message after init
if (partitionInfo.BeginningSequenceNumber == 0 && partitionInfo.LastEnqueuedSequenceNumber == 0) || (partitionInfo.BeginningSequenceNumber != partitionInfo.LastEnqueuedSequenceNumber) {
return (partitionInfo.LastEnqueuedSequenceNumber - partitionInfo.BeginningSequenceNumber) + 1
}
return 0
}
// GetMetricSpecForScaling returns metric spec
func (s *azureEventHubScaler) GetMetricSpecForScaling(context.Context) []v2.MetricSpec {
externalMetric := &v2.ExternalMetricSource{
Metric: v2.MetricIdentifier{
Name: GenerateMetricNameWithIndex(s.metadata.triggerIndex, kedautil.NormalizeString(fmt.Sprintf("azure-eventhub-%s", s.metadata.eventHubInfo.EventHubConsumerGroup))),
},
Target: GetMetricTarget(s.metricType, s.metadata.threshold),
}
metricSpec := v2.MetricSpec{External: externalMetric, Type: eventHubMetricType}
return []v2.MetricSpec{metricSpec}
}
func getTotalLagRelatedToPartitionAmount(unprocessedEventsCount int64, partitionCount int64, threshold int64) int64 {
if (unprocessedEventsCount / threshold) > partitionCount {
return partitionCount * threshold
}
return unprocessedEventsCount
}
// Close closes Azure Event Hub Scaler
func (s *azureEventHubScaler) Close(ctx context.Context) error {
if s.eventHubClient != nil {
err := s.eventHubClient.Close(ctx)
if err != nil {
s.logger.Error(err, "error closing azure event hub client")
return err
}
}
return nil
}
// GetMetricsAndActivity returns value for a supported metric and an error if there is a problem getting the metric
func (s *azureEventHubScaler) GetMetricsAndActivity(ctx context.Context, metricName string) ([]external_metrics.ExternalMetricValue, bool, error) {
totalUnprocessedEventCount := int64(0)
runtimeInfo, err := s.eventHubClient.GetEventHubProperties(ctx, nil)
if err != nil {
return []external_metrics.ExternalMetricValue{}, false, fmt.Errorf("unable to get runtimeInfo for metrics: %w", err)
}
partitionIDs := runtimeInfo.PartitionIDs
for i := 0; i < len(partitionIDs); i++ {
partitionID := partitionIDs[i]
partitionRuntimeInfo, err := s.eventHubClient.GetPartitionProperties(ctx, partitionID, nil)
if err != nil {
return []external_metrics.ExternalMetricValue{}, false, fmt.Errorf("unable to get partitionRuntimeInfo for metrics: %w", err)
}
unprocessedEventCount := int64(0)
unprocessedEventCount, checkpoint, err := s.GetUnprocessedEventCountInPartition(ctx, partitionRuntimeInfo)
if err != nil {
return []external_metrics.ExternalMetricValue{}, false, fmt.Errorf("unable to get unprocessedEventCount for metrics: %w", err)
}
totalUnprocessedEventCount += unprocessedEventCount
s.logger.V(1).Info(fmt.Sprintf("Partition ID: %s, Last SequenceNumber: %d, Checkpoint SequenceNumber: %d, Total new events in partition: %d",
partitionRuntimeInfo.PartitionID, partitionRuntimeInfo.LastEnqueuedSequenceNumber, checkpoint.SequenceNumber, unprocessedEventCount))
}
// set count to max if the sum is negative (Int64 overflow) to prevent negative metric values
// e.g., 9223372036854775797 (Partition 1) + 20 (Partition 2) = -9223372036854775799
if totalUnprocessedEventCount < 0 {
totalUnprocessedEventCount = math.MaxInt64
}
// don't scale out beyond the number of partitions
lagRelatedToPartitionCount := getTotalLagRelatedToPartitionAmount(totalUnprocessedEventCount, int64(len(partitionIDs)), s.metadata.threshold)
s.logger.V(1).Info(fmt.Sprintf("Unprocessed events in event hub total: %d, scaling for a lag of %d related to %d partitions", totalUnprocessedEventCount, lagRelatedToPartitionCount, len(partitionIDs)))
metric := GenerateMetricInMili(metricName, float64(lagRelatedToPartitionCount))
return []external_metrics.ExternalMetricValue{metric}, totalUnprocessedEventCount > s.metadata.activationThreshold, nil
}