-
Notifications
You must be signed in to change notification settings - Fork 69
/
main.go
363 lines (293 loc) · 11.7 KB
/
main.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
/*
Copyright 2022 TriggerMesh Inc.
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.
*/
package azureeventhubs
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azeventhubs"
cloudevents "github.com/cloudevents/sdk-go/v2"
. "github.com/onsi/ginkgo/v2" //nolint:stylecheck
. "github.com/onsi/gomega" //nolint:stylecheck
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"github.com/triggermesh/triggermesh/test/e2e/framework"
"github.com/triggermesh/triggermesh/test/e2e/framework/apps"
"github.com/triggermesh/triggermesh/test/e2e/framework/azure"
e2ece "github.com/triggermesh/triggermesh/test/e2e/framework/cloudevents"
"github.com/triggermesh/triggermesh/test/e2e/framework/ducktypes"
)
var targetAPIVersion = schema.GroupVersion{
Group: "targets.triggermesh.io",
Version: "v1alpha1",
}
const (
targetKind = "AzureEventHubsTarget"
)
/*
This test requires:
- Azure Service Principal Credentials with the Azure Event Hubs Data Owner role assigned at the subscription level
The following environment variables _MUST_ be set:
- AZURE_SUBSCRIPTION_ID - Common subscription for the test to run against
- AZURE_TENANT_ID - Azure tenant to create the resources against
- AZURE_CLIENT_ID - The Azure ServicePrincipal Client ID
- AZURE_CLIENT_SECRET - The Azure ServicePrincipal Client Secret
- AZURE_REGION - Define the Azure region to run the test (default westus2)
These will be done by the e2e test:
- Create an Azure Resource Group, Event Hubs Namespace, and Event Hub
- Send an event to the Azure Event Hub via the Azure Event Hub Target and verify the event was sent
*/
var _ = Describe("Azure Event Hubs target", func() {
ctx := context.Background()
f := framework.New("azureeventhubstarget")
var ns string
var tgtClient dynamic.ResourceInterface
BeforeEach(func() {
ns = f.UniqueName
gvr := targetAPIVersion.WithResource("azureeventhubstargets")
tgtClient = f.DynamicClient.Resource(gvr).Namespace(ns)
})
Context("a target is deployed", func() {
var rg string
var consumerClient *azeventhubs.ConsumerClient
subscriptionID := os.Getenv("AZURE_SUBSCRIPTION_ID")
region := os.Getenv("AZURE_REGION")
if region == "" {
region = "westus2"
}
BeforeEach(func() {
By("creating an Azure resource group", func() {
r := azure.CreateResourceGroup(ctx, subscriptionID, ns, region)
rg = *r.Name
DeferCleanup(func() {
By("deleting the Azure resource group", func() {
_ = azure.DeleteResourceGroup(ctx, subscriptionID, rg)
})
})
})
By("creating an Azure Event Hub", func() {
azure.CreateEventHubComponents(ctx, subscriptionID, ns, region, rg)
})
By("creating Azure Event Hub Consumer Client", func() {
defaultAzureCred, err := azidentity.NewDefaultAzureCredential(nil)
Expect(err).ToNot(HaveOccurred())
nsfqdn := fmt.Sprintf("%s.servicebus.windows.net", ns)
consumerClient, err = azeventhubs.NewConsumerClient(nsfqdn, ns, azeventhubs.DefaultConsumerGroup, defaultAzureCred, nil)
Expect(err).ToNot(HaveOccurred())
DeferCleanup(func() {
err = consumerClient.Close(ctx)
Expect(err).ToNot(HaveOccurred())
})
})
})
When("the spec contains default settings", func() {
var tgtURL *url.URL
BeforeEach(func() {
By("creating an AzureEventHubsTarget object", func() {
tgt, err := createTarget(tgtClient, ns, "test-",
withServicePrincipal(),
withEventHubID(subscriptionID, rg, ns, ns))
Expect(err).ToNot(HaveOccurred())
tgt = ducktypes.WaitUntilReady(f.DynamicClient, tgt)
tgtURL = ducktypes.Address(tgt)
Expect(tgtURL).ToNot(BeNil())
})
})
It("receives an event on the Event Hub", func() {
var event *cloudevents.Event
var receivedEvents []*azeventhubs.ReceivedEventData
var partitionIDs []string
var evCtx context.Context // Used to set a timeout for reading events
By("retrieving Event Hub partition details", func() {
info, err := consumerClient.GetEventHubProperties(ctx, nil)
Expect(err).NotTo(HaveOccurred())
partitionIDs = info.PartitionIDs
Expect(len(partitionIDs)).To(Equal(1))
})
By("starting the handler to consume events", func() {
// Set a context with a timeout to ensure the event handler isn't waiting forever
var evCancel context.CancelFunc // Used to cancel the reading context
evCtx, evCancel = context.WithTimeout(ctx, time.Second*15)
partitionClient, err := consumerClient.NewPartitionClient(partitionIDs[0], nil)
Expect(err).ToNot(HaveOccurred())
go func() {
receivedEvents, err = partitionClient.ReceiveEvents(
evCtx,
1,
nil,
)
Expect(err).ToNot(HaveOccurred())
}()
DeferCleanup(func() {
evCancel()
err = partitionClient.Close(ctx)
Expect(err).ToNot(HaveOccurred())
})
})
By("sending an event", func() {
event = e2ece.NewHelloEvent(f)
j := e2ece.RunEventSender(f.KubeClient, ns, tgtURL.String(), event)
apps.WaitForCompletion(f.KubeClient, j)
})
By("verifying the sent event", func() {
if receivedEvents == nil {
framework.FailfWithOffset(2, "no events received")
}
Expect(len(receivedEvents)).To(BeNumerically(">", 0))
var ce cloudevents.Event
err := json.Unmarshal(receivedEvents[0].Body, &ce)
Expect(err).ToNot(HaveOccurred())
Expect(ce.Data()).To(Equal(event.Data()))
Expect(ce.ID()).To(Equal(event.ID()))
Expect(ce.Type()).To(Equal(event.Type()))
Expect(ce.Subject()).To(Equal(event.Subject()))
Expect(ce.Source()).To(Equal(event.Source()))
Expect(ce.Extensions()[e2ece.E2ECeExtension]).
To(Equal(event.Extensions()[e2ece.E2ECeExtension]))
})
})
})
When("the spec contains default settings and the CloudEvent Context disabled", func() {
var tgtURL *url.URL
BeforeEach(func() {
By("creating an AzureEventHubsTarget object", func() {
tgt, err := createTarget(tgtClient, ns, "test-",
withServicePrincipal(),
withDiscardCEContextEnabled(),
withEventHubID(subscriptionID, rg, ns, ns))
Expect(err).ToNot(HaveOccurred())
tgt = ducktypes.WaitUntilReady(f.DynamicClient, tgt)
tgtURL = ducktypes.Address(tgt)
Expect(tgtURL).ToNot(BeNil())
})
})
It("receives an event on the Event Hub", func() {
var event *cloudevents.Event
var receivedEvents []*azeventhubs.ReceivedEventData
var partitionIDs []string
var evCtx context.Context // Used to set a timeout for reading events
By("retrieving Event Hub partition details", func() {
info, err := consumerClient.GetEventHubProperties(ctx, nil)
Expect(err).NotTo(HaveOccurred())
partitionIDs = info.PartitionIDs
Expect(len(partitionIDs)).To(Equal(1))
})
By("starting the handler to consume events", func() {
// Set a context with a timeout to ensure the event handler isn't waiting forever
var evCancel context.CancelFunc // Used to cancel the reading context
evCtx, evCancel = context.WithTimeout(ctx, time.Second*15)
partitionClient, err := consumerClient.NewPartitionClient(partitionIDs[0], nil)
Expect(err).ToNot(HaveOccurred())
go func() {
events, err := partitionClient.ReceiveEvents(
evCtx,
1,
nil,
)
Expect(err).ToNot(HaveOccurred())
if len(events) > 0 {
receivedEvents = append(receivedEvents, events...)
}
}()
DeferCleanup(func() {
evCancel()
})
})
By("sending an event", func() {
event = e2ece.NewHelloEvent(f)
j := e2ece.RunEventSender(f.KubeClient, ns, tgtURL.String(), event)
apps.WaitForCompletion(f.KubeClient, j)
})
By("verify the events received", func() {
if receivedEvents == nil {
framework.FailfWithOffset(2, "no events received")
}
Expect(len(receivedEvents)).To(BeNumerically(">", 0))
Expect(receivedEvents[0].Body).To(Equal(event.Data()))
})
})
})
})
When("a client creates a target with invalid details", func() {
subscriptionID := "00000000-0000-0000-0000-000000000000"
It("should reject the creation of the target", func() {
By("setting an invalid eventHubID", func() {
invalidEventHubID := "im-just-a-random-string!"
_, err := createTarget(tgtClient, ns, "test-invalid-eventhubid",
withServicePrincipal(),
withEventHubID(subscriptionID, ns, ns, invalidEventHubID))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("spec.eventHubID: Invalid value: "))
})
By("omitting the eventHubID", func() {
_, err := createTarget(tgtClient, ns, "test-missing-eventhubid",
withServicePrincipal())
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("spec.eventHubID: Required value"))
})
By("omitting the credentials", func() {
_, err := createTarget(tgtClient, ns, "test-missing-service-principal",
withEventHubID(subscriptionID, ns, ns, ns))
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("spec.auth: Required value"))
})
})
})
})
// createTarget creates an AzureEventHubsTarget object initialized with the given options.
func createTarget(tgtClient dynamic.ResourceInterface, namespace, namePrefix string, opts ...targetOption) (*unstructured.Unstructured, error) {
tgt := &unstructured.Unstructured{}
tgt.SetAPIVersion(targetAPIVersion.String())
tgt.SetKind(targetKind)
tgt.SetNamespace(namespace)
tgt.SetGenerateName(namePrefix)
for _, opt := range opts {
opt(tgt)
}
return tgtClient.Create(context.Background(), tgt, metav1.CreateOptions{})
}
type targetOption func(*unstructured.Unstructured)
// withServicePrincipal will create the secret and service principal based on the azure environment variables
func withServicePrincipal() targetOption {
credsMap := map[string]interface{}{
"tenantID": map[string]interface{}{"value": os.Getenv("AZURE_TENANT_ID")},
"clientID": map[string]interface{}{"value": os.Getenv("AZURE_CLIENT_ID")},
"clientSecret": map[string]interface{}{"value": os.Getenv("AZURE_CLIENT_SECRET")},
}
return func(tgt *unstructured.Unstructured) {
if err := unstructured.SetNestedMap(tgt.Object, credsMap, "spec", "auth", "servicePrincipal"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.auth.servicePrincipal field: %s", err)
}
}
}
func withEventHubID(subscriptionID, resourceGroup, eventHubNS, eventHub string) targetOption {
eventHubID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.EventHub/namespaces/%s/eventHubs/%s", subscriptionID, resourceGroup, eventHubNS, eventHub)
return func(tgt *unstructured.Unstructured) {
if err := unstructured.SetNestedField(tgt.Object, eventHubID, "spec", "eventHubID"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.eventHubID field: %s", err)
}
}
}
func withDiscardCEContextEnabled() targetOption {
return func(tgt *unstructured.Unstructured) {
if err := unstructured.SetNestedField(tgt.Object, true, "spec", "discardCloudEventContext"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.discardCloudEventContext field: %s", err)
}
}
}