forked from Azure/azure-event-hubs-go
/
suite.go
396 lines (345 loc) · 11.2 KB
/
suite.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
package test
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"flag"
"io"
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/Azure/azure-amqp-common-go"
mgmt "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub"
rm "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
"github.com/Azure/go-autorest/autorest/azure"
azauth "github.com/Azure/go-autorest/autorest/azure/auth"
"github.com/Azure/go-autorest/autorest/to"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/suite"
"go.opencensus.io/exporter/jaeger"
"go.opencensus.io/trace"
)
var (
letterRunes = []rune("abcdefghijklmnopqrstuvwxyz123456789")
debug = flag.Bool("debug", false, "output debug level logging")
)
const (
defaultTimeout = 1 * time.Minute
)
const (
// Location is the Azure geographic location the test suite will use for provisioning
Location = "eastus"
// ResourceGroupName is the name of the resource group the test suite will use for provisioning
ResourceGroupName = "ehtest"
)
type (
// BaseSuite encapsulates a end to end test of Event Hubs with build up and tear down of all EH resources
BaseSuite struct {
suite.Suite
SubscriptionID string
Namespace string
Env azure.Environment
TagID string
closer io.Closer
}
// HubMgmtOption represents an option for configuring an Event Hub.
HubMgmtOption func(model *mgmt.Model) error
// NamespaceMgmtOption represents an option for configuring a Namespace
NamespaceMgmtOption func(ns *mgmt.EHNamespace) error
)
func init() {
rand.Seed(time.Now().Unix())
}
// SetupSuite constructs the test suite from the environment and
func (suite *BaseSuite) SetupSuite() {
flag.Parse()
if *debug {
log.SetLevel(log.DebugLevel)
}
suite.SubscriptionID = mustGetEnv("AZURE_SUBSCRIPTION_ID")
suite.Namespace = mustGetEnv("EVENTHUB_NAMESPACE")
envName := os.Getenv("AZURE_ENVIRONMENT")
suite.TagID = RandomString("tag", 5)
if envName == "" {
suite.Env = azure.PublicCloud
} else {
var err error
env, err := azure.EnvironmentFromName(envName)
if !suite.NoError(err) {
suite.FailNow("could not find env name")
}
suite.Env = env
}
if !suite.NoError(suite.ensureProvisioned(mgmt.SkuTierStandard)) {
suite.FailNow("failed provisioning")
}
if !suite.NoError(suite.setupTracing()) {
suite.FailNow("failed to setup tracing")
}
}
// TearDownSuite might one day destroy all of the resources in the suite, but I'm not sure we want to do that just yet...
func (suite *BaseSuite) TearDownSuite() {
// maybe tear down all existing resource??
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
suite.deleteAllTaggedEventHubs(ctx)
if suite.closer != nil {
suite.closer.Close()
}
}
// RandomHub creates a hub with a random'ish name
func (suite *BaseSuite) RandomHub(opts ...HubMgmtOption) (*mgmt.Model, func()) {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout*2)
defer cancel()
name := suite.RandomName("goehtest", 6)
model, err := suite.ensureEventHub(ctx, name, opts...)
suite.Require().NoError(err)
suite.Require().NotNil(model)
suite.Require().NotNil(model.PartitionIds)
suite.Require().Len(*model.PartitionIds, 4)
return model, func() {
if model != nil {
err := suite.DeleteEventHub(*model.Name)
if err != nil {
suite.T().Log(err)
}
}
}
}
// EnsureEventHub creates an Event Hub if it doesn't exist
func (suite *BaseSuite) ensureEventHub(ctx context.Context, name string, opts ...HubMgmtOption) (*mgmt.Model, error) {
client := suite.getEventHubMgmtClient()
hub, err := client.Get(ctx, ResourceGroupName, suite.Namespace, name)
if err != nil {
newHub := &mgmt.Model{
Name: &name,
Properties: &mgmt.Properties{
PartitionCount: common.PtrInt64(4),
},
}
for _, opt := range opts {
err = opt(newHub)
if err != nil {
return nil, err
}
}
var lastErr error
deadline, _ := ctx.Deadline()
for time.Now().Before(deadline) {
hub, err = suite.tryHubCreate(ctx, client, name, newHub)
if err == nil {
lastErr = nil
break
}
lastErr = err
}
if lastErr != nil {
return nil, lastErr
}
}
return &hub, nil
}
func (suite *BaseSuite) tryHubCreate(ctx context.Context, client *mgmt.EventHubsClient, name string, hub *mgmt.Model) (mgmt.Model, error) {
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
_, err := client.CreateOrUpdate(ctx, ResourceGroupName, suite.Namespace, name, *hub)
if err != nil {
return mgmt.Model{}, err
}
return client.Get(ctx, ResourceGroupName, suite.Namespace, name)
}
// DeleteEventHub deletes an Event Hub within the given Namespace
func (suite *BaseSuite) DeleteEventHub(name string) error {
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
client := suite.getEventHubMgmtClient()
_, err := client.Delete(ctx, ResourceGroupName, suite.Namespace, name)
return err
}
func (suite *BaseSuite) deleteAllTaggedEventHubs(ctx context.Context) {
client := suite.getEventHubMgmtClient()
res, err := client.ListByNamespace(ctx, ResourceGroupName, suite.Namespace, to.Int32Ptr(0), to.Int32Ptr(20))
if err != nil {
suite.T().Log("error listing namespaces")
suite.T().Error(err)
}
for res.NotDone() {
for _, val := range res.Values() {
if strings.Contains(*val.Name, suite.TagID) {
for i := 0; i < 5; i++ {
if _, err := client.Delete(ctx, ResourceGroupName, suite.Namespace, *val.Name); err != nil {
suite.T().Logf("error deleting %q", *val.Name)
suite.T().Error(err)
time.Sleep(3 * time.Second)
} else {
break
}
}
} else {
suite.T().Logf("%q does not contain %q", *val.Name, suite.TagID)
}
}
res.Next()
}
}
func (suite *BaseSuite) ensureProvisioned(tier mgmt.SkuTier) error {
_, err := ensureResourceGroup(context.Background(), suite.SubscriptionID, ResourceGroupName, Location, suite.Env)
if err != nil {
return err
}
_, err = suite.ensureNamespace()
return err
}
// ensureResourceGroup creates a Azure Resource Group if it does not already exist
func ensureResourceGroup(ctx context.Context, subscriptionID, name, location string, env azure.Environment) (*rm.Group, error) {
groupClient := getRmGroupClientWithToken(subscriptionID, env)
group, err := groupClient.Get(ctx, name)
if group.Response.Response == nil {
// tcp dial error or something else where the response was not populated
return nil, err
}
if group.StatusCode == http.StatusNotFound {
group, err = groupClient.CreateOrUpdate(ctx, name, rm.Group{Location: common.PtrString(location)})
if err != nil {
return nil, err
}
} else if group.StatusCode >= 400 {
return nil, err
}
return &group, nil
}
// ensureNamespace creates a Azure Event Hub Namespace if it does not already exist
func ensureNamespace(ctx context.Context, subscriptionID, rg, name, location string, env azure.Environment, opts ...NamespaceMgmtOption) (*mgmt.EHNamespace, error) {
_, err := ensureResourceGroup(ctx, subscriptionID, rg, location, env)
if err != nil {
return nil, err
}
client := getNamespaceMgmtClientWithToken(subscriptionID, env)
namespace, err := client.Get(ctx, rg, name)
if err != nil {
return nil, err
}
if namespace.StatusCode == 404 {
newNamespace := &mgmt.EHNamespace{
Name: &name,
Sku: &mgmt.Sku{
Name: mgmt.Basic,
Tier: mgmt.SkuTierBasic,
Capacity: common.PtrInt32(1),
},
EHNamespaceProperties: &mgmt.EHNamespaceProperties{
IsAutoInflateEnabled: common.PtrBool(false),
MaximumThroughputUnits: common.PtrInt32(1),
},
}
for _, opt := range opts {
err = opt(newNamespace)
if err != nil {
return nil, err
}
}
nsFuture, err := client.CreateOrUpdate(ctx, rg, name, *newNamespace)
if err != nil {
return nil, err
}
err = nsFuture.WaitForCompletionRef(ctx, client.Client)
if err != nil {
return nil, err
}
namespace, err = nsFuture.Result(*client)
if err != nil {
return nil, err
}
} else if namespace.StatusCode >= 400 {
return nil, err
}
return &namespace, nil
}
func (suite *BaseSuite) getEventHubMgmtClient() *mgmt.EventHubsClient {
client := mgmt.NewEventHubsClientWithBaseURI(suite.Env.ResourceManagerEndpoint, suite.SubscriptionID)
a, err := azauth.NewAuthorizerFromEnvironment()
if err != nil {
log.Fatal(err)
}
client.Authorizer = a
return &client
}
func (suite *BaseSuite) ensureNamespace() (*mgmt.EHNamespace, error) {
ns, err := ensureNamespace(context.Background(), suite.SubscriptionID, ResourceGroupName, suite.Namespace, Location, suite.Env)
if err != nil {
return nil, err
}
return ns, err
}
func getNamespaceMgmtClientWithToken(subscriptionID string, env azure.Environment) *mgmt.NamespacesClient {
client := mgmt.NewNamespacesClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID)
a, err := azauth.NewAuthorizerFromEnvironment()
if err != nil {
log.Fatal(err)
}
client.Authorizer = a
return &client
}
func getRmGroupClientWithToken(subscriptionID string, env azure.Environment) *rm.GroupsClient {
groupsClient := rm.NewGroupsClientWithBaseURI(env.ResourceManagerEndpoint, subscriptionID)
a, err := azauth.NewAuthorizerFromEnvironment()
if err != nil {
log.Fatal(err)
}
groupsClient.Authorizer = a
return &groupsClient
}
func (suite *BaseSuite) setupTracing() error {
if os.Getenv("TRACING") != "true" {
return nil
}
exporter, err := jaeger.NewExporter(jaeger.Options{
AgentEndpoint: "localhost:6831",
ServiceName: "eh-trace",
})
if err != nil {
return err
}
trace.RegisterExporter(exporter)
return nil
}
func mustGetEnv(key string) string {
v := os.Getenv(key)
if v == "" {
panic("Env variable '" + key + "' required for integration tests.")
}
return v
}
// RandomName generates a random Event Hub name tagged with the suite id
func (suite *BaseSuite) RandomName(prefix string, length int) string {
return RandomString(prefix, length) + "-" + suite.TagID
}
// RandomString generates a random string with prefix
func RandomString(prefix string, length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return prefix + string(b)
}