-
Notifications
You must be signed in to change notification settings - Fork 69
/
main.go
398 lines (322 loc) · 12.9 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
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
/*
Copyright 2023 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 azureservicebus
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
sv "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus"
svadmin "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/admin"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
. "github.com/onsi/ginkgo/v2" //nolint:stylecheck
. "github.com/onsi/gomega" //nolint:stylecheck
cloudevents "github.com/cloudevents/sdk-go/v2"
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"
clientset "k8s.io/client-go/kubernetes"
duckv1 "knative.dev/pkg/apis/duck/v1"
"github.com/triggermesh/triggermesh/test/e2e/framework"
"github.com/triggermesh/triggermesh/test/e2e/framework/apps"
e2eazure "github.com/triggermesh/triggermesh/test/e2e/framework/azure"
"github.com/triggermesh/triggermesh/test/e2e/framework/bridges"
"github.com/triggermesh/triggermesh/test/e2e/framework/ducktypes"
)
/*
This test requires:
- Azure Service Principal Credentials with the Azure ServiceBus 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
These will be done by the e2e test:
- Create an Azure Resource Group, ServiceBus Namespace, and a Topic and Queue
- Send an event from the Azure ServiceBus into the TriggerMesh source
*/
var sourceAPIVersion = schema.GroupVersion{
Group: "sources.triggermesh.io",
Version: "v1alpha1",
}
const (
sourceKind = "AzureServiceBusSource"
sourceResource = "azureservicebussource"
)
/*
Basic flow will resemble:
* Create a resource group to contain our servicebus
* Ensure our service principal can read/write from the servicebus
* Instantiate the AzureServiceBusSource
* Send an event to the AzureServiceBusSource and look for a response
*/
var _ = Describe("Azure ServiceBus", func() {
ctx := context.Background()
subscriptionID := os.Getenv("AZURE_SUBSCRIPTION_ID")
region := os.Getenv("AZURE_REGION")
if region == "" {
region = "westus2"
}
f := framework.New(sourceResource)
var ns string
var srcClient dynamic.ResourceInterface
var sink *duckv1.Destination
BeforeEach(func() {
ns = f.UniqueName
gvr := sourceAPIVersion.WithResource(sourceResource + "s")
srcClient = f.DynamicClient.Resource(gvr).Namespace(ns)
})
Context("a source watches an servicebus topic", func() {
var err error // stubbed
var rg armresources.ResourceGroup
var topicSender *sv.Sender
SendMessageAndAssertReceivedEvent := func() func() {
return func() {
BeforeEach(func() {
err = topicSender.SendMessage(ctx, &sv.Message{
Body: []byte("hello world"),
}, nil)
Expect(err).ToNot(HaveOccurred())
})
Specify("the source generates an event", func() {
const receiveTimeout = 150 * time.Second
const pollInterval = 500 * time.Millisecond
var receivedEvents []cloudevents.Event
readReceivedEvents := readReceivedEvents(f.KubeClient, ns, sink.Ref.Name, &receivedEvents)
Eventually(readReceivedEvents, receiveTimeout, pollInterval).ShouldNot(BeEmpty())
Expect(receivedEvents).To(HaveLen(1))
e := receivedEvents[0]
Expect(e.Type()).To(Equal("com.microsoft.azure.servicebus.message"))
data := make(map[string]interface{})
err = json.Unmarshal(e.Data(), &data)
testID := fmt.Sprintf("%v", data["MessageID"])
Expect(data["MessageID"]).To(Equal(testID))
})
}
}
BeforeEach(func() {
rg = e2eazure.CreateResourceGroup(ctx, subscriptionID, ns, region)
DeferCleanup(func() {
_ = e2eazure.DeleteResourceGroup(ctx, subscriptionID, *rg.Name)
})
nsClient := e2eazure.CreateServiceBusNamespaceClient(ctx, subscriptionID, ns)
err := e2eazure.CreateServiceBusNamespace(ctx, *nsClient, *rg.Name, ns, region)
Expect(err).ToNot(HaveOccurred())
adminClient := e2eazure.CreateAdminClient(ctx, region, ns, nsClient)
By("creating an event sink", func() {
sink = bridges.CreateEventDisplaySink(f.KubeClient, ns)
})
By("creating a topic", func() {
topicSender = createTopic(ctx, ns, e2eazure.CreateClient(ctx, region, ns, nsClient), adminClient)
})
})
Context("the subscription is managed by the source", func() {
BeforeEach(func() {
By("creating a AzureServiceBusSource object", func() {
src, err := createSource(srcClient, ns, "test-", sink,
withServicePrincipal(),
withSubscriptionID(subscriptionID),
withTopicID(createTopicID(subscriptionID, ns)),
)
Expect(err).ToNot(HaveOccurred())
ducktypes.WaitUntilReady(f.DynamicClient, src)
})
})
When("a message is sent to the topic", SendMessageAndAssertReceivedEvent())
})
})
Context("a source watches an servicebus queue", func() {
var err error // stubbed
var rg armresources.ResourceGroup
var queueSender *sv.Sender
SendMessageAndAssertReceivedEvent := func() func() {
return func() {
BeforeEach(func() {
err = queueSender.SendMessage(ctx, &sv.Message{
Body: []byte("hello world"),
}, nil)
Expect(err).ToNot(HaveOccurred())
})
Specify("the source generates an event", func() {
const receiveTimeout = 150 * time.Second
const pollInterval = 500 * time.Millisecond
var receivedEvents []cloudevents.Event
readReceivedEvents := readReceivedEvents(f.KubeClient, ns, sink.Ref.Name, &receivedEvents)
Eventually(readReceivedEvents, receiveTimeout, pollInterval).ShouldNot(BeEmpty())
Expect(receivedEvents).To(HaveLen(1))
e := receivedEvents[0]
Expect(e.Type()).To(Equal("com.microsoft.azure.servicebus.message"))
data := make(map[string]interface{})
err = json.Unmarshal(e.Data(), &data)
testID := fmt.Sprintf("%v", data["MessageID"])
Expect(data["MessageID"]).To(Equal(testID))
})
}
}
BeforeEach(func() {
rg = e2eazure.CreateResourceGroup(ctx, subscriptionID, ns, region)
DeferCleanup(func() {
_ = e2eazure.DeleteResourceGroup(ctx, subscriptionID, *rg.Name)
})
nsClient := e2eazure.CreateServiceBusNamespaceClient(ctx, subscriptionID, ns)
err := e2eazure.CreateServiceBusNamespace(ctx, *nsClient, *rg.Name, ns, region)
Expect(err).ToNot(HaveOccurred())
adminClient := e2eazure.CreateAdminClient(ctx, region, ns, nsClient)
By("creating an event sink", func() {
sink = bridges.CreateEventDisplaySink(f.KubeClient, ns)
})
By("creating a queue", func() {
queueSender = createQueue(ctx, region, ns, e2eazure.CreateClient(ctx, region, ns, nsClient), adminClient)
})
})
Context("the subscription is managed by the source", func() {
BeforeEach(func() {
By("creating a AzureServiceBusSource object", func() {
src, err := createSource(srcClient, ns, "test-", sink,
withServicePrincipal(),
withSubscriptionID(subscriptionID),
withQueueID(createQueueID(subscriptionID, ns)),
)
Expect(err).ToNot(HaveOccurred())
ducktypes.WaitUntilReady(f.DynamicClient, src)
})
})
When("a message is sent to the queue", SendMessageAndAssertReceivedEvent())
})
})
When("a client creates a source object with invalid specs", func() {
// Those tests do not require a real sink
BeforeEach(func() {
sink = &duckv1.Destination{
Ref: &duckv1.KReference{
APIVersion: "fake/v1",
Kind: "Fake",
Name: "fake",
},
}
})
Specify("the API server rejects the creation of that object", func() {
By("setting an invalid topic name", func() {
_, err := createSource(srcClient, ns, "test-invalid-topicName", sink,
withSubscriptionID(subscriptionID),
withTopicID("fakename"),
)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring(
`spec.topicID: Invalid value: "`))
})
})
})
})
type sourceOption func(*unstructured.Unstructured)
// createSource creates an AzureServiceBusSource object initialized with the test parameters
func createSource(srcClient dynamic.ResourceInterface, namespace, namePrefix string,
sink *duckv1.Destination, opts ...sourceOption) (*unstructured.Unstructured, error) {
src := &unstructured.Unstructured{}
src.SetAPIVersion(sourceAPIVersion.String())
src.SetKind(sourceKind)
src.SetNamespace(namespace)
src.SetGenerateName(namePrefix)
// Set spec parameters
if err := unstructured.SetNestedMap(src.Object, ducktypes.DestinationToMap(sink), "spec", "sink"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.sink field: %s", err)
}
for _, opt := range opts {
opt(src)
}
return srcClient.Create(context.Background(), src, metav1.CreateOptions{})
}
// Define the creation parameters to pass along
func withTopicID(id string) sourceOption {
return func(src *unstructured.Unstructured) {
if err := unstructured.SetNestedField(src.Object, id, "spec", "topicID"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.topicID: %s", err)
}
}
}
func withQueueID(id string) sourceOption {
return func(src *unstructured.Unstructured) {
if err := unstructured.SetNestedField(src.Object, id, "spec", "queueID"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.queueID: %s", err)
}
}
}
func withSubscriptionID(id string) sourceOption {
return func(src *unstructured.Unstructured) {
if err := unstructured.SetNestedField(src.Object, id, "spec", "subscriptionID"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.subscriptionID: %s", err)
}
}
}
// withServicePrincipal will create the secret and service principal based on the azure environment variables
func withServicePrincipal() sourceOption {
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(src *unstructured.Unstructured) {
if err := unstructured.SetNestedMap(src.Object, credsMap, "spec", "auth", "servicePrincipal"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.auth.servicePrincipal field: %s", err)
}
}
}
// readReceivedEvents returns a function that reads CloudEvents received by the
// event-display application and stores the result as the value of the given
// `receivedEvents` variable.
// The returned function signature satisfies the contract expected by
// gomega.Eventually: no argument and one or more return values.
func readReceivedEvents(c clientset.Interface, namespace, eventDisplayName string,
receivedEvents *[]cloudevents.Event) func() []cloudevents.Event {
return func() []cloudevents.Event {
ev := bridges.ReceivedEventDisplayEvents(
apps.GetLogs(c, namespace, eventDisplayName),
)
*receivedEvents = ev
return ev
}
}
// createTopic will create a servicebus topic and a sender using the given name
func createTopic(ctx context.Context, name string, client *sv.Client, adminClient *svadmin.Client) *sv.Sender {
if _, err := adminClient.CreateTopic(ctx, name, nil); err != nil {
framework.FailfWithOffset(2, "Error creating topic: %s", err)
return nil
}
sender, err := client.NewSender(name, nil)
if err != nil {
return nil
}
return sender
}
// createTopicID will create the topicID path used by the k8s azureservicebussource
func createTopicID(subscriptionID, name string) string {
return "/subscriptions/" + subscriptionID + "/resourceGroups/" + name + "/providers/Microsoft.ServiceBus/namespaces/" + name + "/topics/" + name
}
// createQueue will create a servicebus queue and a sender using the given name
func createQueue(ctx context.Context, region string, name string, client *sv.Client, adminClient *svadmin.Client) *sv.Sender {
if _, err := adminClient.CreateQueue(ctx, name, nil); err != nil {
framework.FailfWithOffset(2, "Error creating queue: %s", err)
return nil
}
sender, err := client.NewSender(name, nil)
if err != nil {
return nil
}
return sender
}
// createQueueID will create the queueID path used by the k8s azureservicebussource
func createQueueID(subscriptionID, name string) string {
return "/subscriptions/" + subscriptionID + "/resourceGroups/" + name + "/providers/Microsoft.ServiceBus/namespaces/" + name + "/queues/" + name
}