-
Notifications
You must be signed in to change notification settings - Fork 800
/
shared.go
427 lines (329 loc) · 11.1 KB
/
shared.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package tests
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
azlog "github.com/Azure/azure-sdk-for-go/sdk/internal/log"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/checkpoints"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs/internal/test"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/joho/godotenv"
"github.com/microsoft/ApplicationInsights-Go/appinsights"
)
const (
endProperty = "End"
partitionProperty = "PartitionID"
numProperty = "Number"
)
// metric names
const (
// standard to all tests
MetricSent = "Sent"
MetricReceived = "Received"
MetricOwnershipLost = "OwnershipLost"
// go specific
MetricDeadlineExceeded = "DeadlineExceeded"
)
type stressTestData struct {
name string
runID string
TC telemetryClient
Namespace string
HubName string
StorageEndpoint string
Cred azcore.TokenCredential
}
func (td *stressTestData) Close() {
td.TC.TrackEvent("end", nil)
td.TC.Channel().Flush()
<-td.TC.Channel().Close()
}
type logf func(format string, v ...any)
func newStressTestData(name string, baggage map[string]string) (*stressTestData, error) {
td := &stressTestData{
name: name,
runID: fmt.Sprintf("%s-%d", name, time.Now().UnixNano()),
}
envFilePath := "../../../.env"
if os.Getenv("ENV_FILE") != "" {
envFilePath = os.Getenv("ENV_FILE")
}
if err := godotenv.Load(envFilePath); err != nil {
return nil, err
}
var missing []string
variables := map[string]*string{
"EVENTHUB_NAMESPACE": &td.Namespace,
"EVENTHUB_NAME_STRESS": &td.HubName,
"CHECKPOINTSTORE_STORAGE_ENDPOINT": &td.StorageEndpoint,
}
for name, dest := range variables {
val := os.Getenv(name)
if val == "" {
missing = append(missing, name)
}
*dest = val
}
if len(missing) > 0 {
return nil, fmt.Errorf("missing environment variables (%s)", strings.Join(missing, ","))
}
tc, err := loadAppInsights()
if err != nil {
return nil, err
}
td.TC = telemetryClient{tc}
td.Cred, err = azidentity.NewDefaultAzureCredential(nil)
if err != nil {
return nil, err
}
if td.TC.Context().CommonProperties == nil {
td.TC.Context().CommonProperties = map[string]string{}
}
td.TC.Context().CommonProperties["TestRunId"] = td.runID
td.TC.Context().CommonProperties["Scenario"] = td.name
log.Printf("Name: %s, TestRunID: %s", td.name, td.runID)
startBaggage := map[string]string{
"Namespace": td.Namespace,
"HubName": td.HubName,
}
for k, v := range baggage {
startBaggage[k] = v
}
td.TC.TrackEvent("start", startBaggage)
return td, nil
}
type sendEventsToPartitionArgs struct {
// required arguments
client *azeventhubs.ProducerClient
partitionID string
messageLimit int
testData *stressTestData
// the number of extra bytes to add to the message - this helps with
// testing conditions that require transfer times to not be instantaneous.
// This is optional.
numExtraBytes int
}
func sendEventsToPartition(ctx context.Context, args sendEventsToPartitionArgs) (azeventhubs.StartPosition, azeventhubs.PartitionProperties, error) {
log.Printf("[BEGIN] Sending %d messages to partition ID %s, with messages of size %db", args.messageLimit, args.partitionID, args.numExtraBytes)
beforeSendProps, err := args.client.GetPartitionProperties(ctx, args.partitionID, nil)
if err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
extraBytes := make([]byte, args.numExtraBytes)
batch, err := args.client.NewEventDataBatch(context.Background(), &azeventhubs.EventDataBatchOptions{
PartitionID: &args.partitionID,
})
if err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
sendFn := func() error {
if err := args.client.SendEventDataBatch(context.Background(), batch, nil); err != nil {
return err
}
args.testData.TC.TrackMetric(MetricSent, float64(batch.NumEvents()), map[string]string{
"PartitionID": args.partitionID,
})
return nil
}
for i := 0; i < args.messageLimit; i++ {
ed := &azeventhubs.EventData{
Body: extraBytes,
Properties: map[string]any{
numProperty: i,
partitionProperty: args.partitionID,
},
}
if i == (args.messageLimit - 1) {
addEndProperty(ed, int64(args.messageLimit))
}
err := batch.AddEventData(ed, nil)
if errors.Is(err, azeventhubs.ErrEventDataTooLarge) {
if batch.NumEvents() == 0 {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, errors.New("single event was too large to fit into batch")
}
if err := sendFn(); err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
tempBatch, err := args.client.NewEventDataBatch(context.Background(), &azeventhubs.EventDataBatchOptions{
PartitionID: &args.partitionID,
})
if err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
batch = tempBatch
i-- // retry adding the same message
} else if err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
}
if batch.NumEvents() > 0 {
if err := sendFn(); err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
}
endProps, err := args.client.GetPartitionProperties(ctx, args.partitionID, nil)
if err != nil {
return azeventhubs.StartPosition{}, azeventhubs.PartitionProperties{}, err
}
sp := azeventhubs.StartPosition{
Inclusive: false,
}
if beforeSendProps.IsEmpty {
log.Printf("Partition %s is empty, starting sequence at 0 (not inclusive)", args.partitionID)
sp.Earliest = to.Ptr(true)
} else {
log.Printf("Partition %s is NOT empty, starting sequence at %d (not inclusive)", args.partitionID, beforeSendProps.LastEnqueuedSequenceNumber)
sp.SequenceNumber = &beforeSendProps.LastEnqueuedSequenceNumber
}
log.Printf("[END] Sending %d messages to partition ID %s, with messages of size %db", args.messageLimit, args.partitionID, args.numExtraBytes)
return sp, endProps, nil
}
// initCheckpointStore creates the blob container and creates checkpoints for
// every partition so the next Processor will start from the end.
//
// Returns the checkpoints we updated, sorted by partition ID.
func initCheckpointStore(ctx context.Context, containerName string, testData *stressTestData) ([]azeventhubs.Checkpoint, error) {
// create the container first - it shouldn't already exist
storageEndpoint := test.URLJoinPaths(testData.StorageEndpoint, containerName)
cc, err := container.NewClient(storageEndpoint, testData.Cred, nil)
if err != nil {
return nil, err
}
if _, err := cc.Create(ctx, nil); err != nil {
return nil, err
}
cps, err := checkpoints.NewBlobStore(cc, nil)
if err != nil {
return nil, err
}
// now grab the current state of the partitions so, when the test starts up, we
// don't read in any old data.
producerClient, err := azeventhubs.NewProducerClient(testData.Namespace, testData.HubName, testData.Cred, nil)
if err != nil {
return nil, err
}
defer producerClient.Close(ctx)
hubProps, err := producerClient.GetEventHubProperties(ctx, nil)
if err != nil {
return nil, err
}
var updatedCheckpoints []azeventhubs.Checkpoint
sort.Strings(hubProps.PartitionIDs)
for _, partitionID := range hubProps.PartitionIDs {
partProps, err := producerClient.GetPartitionProperties(ctx, partitionID, nil)
if err != nil {
return nil, err
}
newCheckpoint := azeventhubs.Checkpoint{
ConsumerGroup: azeventhubs.DefaultConsumerGroup,
EventHubName: testData.HubName,
FullyQualifiedNamespace: testData.Namespace,
PartitionID: partitionID,
}
if partProps.IsEmpty {
newCheckpoint.Offset = to.Ptr[int64](-1)
newCheckpoint.SequenceNumber = to.Ptr[int64](0)
} else {
newCheckpoint.Offset = &partProps.LastEnqueuedOffset
newCheckpoint.SequenceNumber = &partProps.LastEnqueuedSequenceNumber
}
if err = cps.SetCheckpoint(ctx, newCheckpoint, nil); err != nil {
return nil, err
}
updatedCheckpoints = append(updatedCheckpoints, newCheckpoint)
}
return updatedCheckpoints, nil
}
func loadAppInsights() (appinsights.TelemetryClient, error) {
aiKey := os.Getenv("APPINSIGHTS_INSTRUMENTATIONKEY")
if aiKey == "" {
return nil, errors.New("missing APPINSIGHTS_INSTRUMENTATIONKEY environment variable")
}
config := appinsights.NewTelemetryConfiguration(aiKey)
config.MaxBatchInterval = 5 * time.Second
return appinsights.NewTelemetryClientFromConfig(config), nil
}
func addEndProperty(ed *azeventhubs.EventData, expectedCount int64) {
ed.Properties[endProperty] = expectedCount
}
func channelToSortedSlice[T any](ch chan T, less func(i, j T) bool) []T {
var values []T
for v := range ch {
values = append(values, v)
}
sort.Slice(values, func(i, j int) bool {
return less(values[i], values[j])
})
return values
}
func closeOrPanic(closeable interface {
Close(ctx context.Context) error
}) {
if err := closeable.Close(context.Background()); err != nil {
// TODO: there's an interesting thing happening here when I close out the connection
// where it sometimes complains about it being idle. This is "ok" but I'd like to see
// why EH's behavior seems different than expected.
// Issue: https://github.com/Azure/azure-sdk-for-go/issues/19220
var eherr *azeventhubs.Error
if errors.As(err, &eherr) && eherr.Code == azeventhubs.ErrorCodeConnectionLost {
// for now we'll say this is okay - it didn't interfere with the core operation
// of the test.
return
}
panic(err)
}
}
func addSleepAfterFlag(fs *flag.FlagSet) func() {
var durationStr string
fs.StringVar(&durationStr, "sleepAfter", "0m", "Time to sleep after test completes")
return func() {
sleepAfter, err := time.ParseDuration(durationStr)
if err != nil {
log.Printf("Invalid sleepAfter duration given: %s", sleepAfter)
return
}
if sleepAfter > 0 {
log.Printf("Sleeping for %s", sleepAfter)
time.Sleep(sleepAfter)
log.Printf("Done sleeping for %s", sleepAfter)
}
}
}
func addVerboseLoggingFlag(fs *flag.FlagSet, customLogFn func(verbose string, e azlog.Event, s string)) func() {
verbose := fs.String("v", "", "Enable verbose SDK logging. Valid values are test or sdk or all")
logFn := func(e azlog.Event, s string) {
log.Printf("[%s] %s", e, s)
}
if customLogFn != nil {
logFn = func(e azlog.Event, s string) {
customLogFn(*verbose, e, s)
}
}
return func() {
switch *verbose {
case "":
case "test":
azlog.SetEvents(EventBalanceTest)
azlog.SetListener(logFn)
case "sdk":
azlog.SetEvents(EventBalanceTest, azeventhubs.EventConsumer, azeventhubs.EventProducer)
azlog.SetListener(logFn)
case "all":
azlog.SetListener(logFn)
default:
fmt.Printf("%s is not a valid logging value. Valid values are test or sdk or all", *verbose)
}
}
}