/
helpers.go
465 lines (408 loc) · 13.5 KB
/
helpers.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package helpers
import (
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"sync/atomic"
"testing"
"time"
"github.com/appcelerator/amp/api/auth"
"github.com/appcelerator/amp/api/rpc/account"
"github.com/appcelerator/amp/api/rpc/cluster/constants"
"github.com/appcelerator/amp/api/rpc/logs"
"github.com/appcelerator/amp/api/rpc/resource"
"github.com/appcelerator/amp/api/rpc/stack"
"github.com/appcelerator/amp/cmd/amplifier/server/configuration"
"github.com/appcelerator/amp/data/accounts"
"github.com/appcelerator/amp/docker/docker/pkg/stringid"
"github.com/appcelerator/amp/pkg/nats-streaming"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"gopkg.in/yaml.v2"
)
const testAmplifierConfig = "test.amplifier.yml"
// AmplifierConnection returns a grpc connection to amplifier
func AmplifierConnection() (*grpc.ClientConn, error) {
amplifierEndpoint := "amplifier" + configuration.DefaultPort
log.Println("Connecting to amplifier")
tlsConfig := &tls.Config{InsecureSkipVerify: true}
creds := credentials.NewTLS(tlsConfig)
conn, err := grpc.Dial(amplifierEndpoint,
grpc.WithTransportCredentials(creds),
grpc.WithBlock(),
grpc.WithTimeout(60*time.Second),
grpc.WithCompressor(grpc.NewGZIPCompressor()),
grpc.WithDecompressor(grpc.NewGZIPDecompressor()),
)
if err != nil {
return nil, fmt.Errorf("Unable to connect to amplifier on: %store\n%v", amplifierEndpoint, err)
}
log.Println("Connected to amplifier")
return conn, nil
}
// Helper is a test helper
type Helper struct {
accounts account.AccountClient
logs logs.LogsClient
resources resource.ResourceClient
stacks stack.StackClient
tokens *auth.Tokens
suPassword string
}
// New returns a new test helper
func New() (*Helper, error) {
conn, err := AmplifierConnection()
if err != nil {
return nil, err
}
data, err := ioutil.ReadFile("../../" + testAmplifierConfig)
if err != nil {
return nil, err
}
cfg := configuration.Configuration{}
if err := yaml.Unmarshal(data, &cfg); err != nil {
return nil, err
}
h := &Helper{
accounts: account.NewAccountClient(conn),
logs: logs.NewLogsClient(conn),
stacks: stack.NewStackClient(conn),
resources: resource.NewResourceClient(conn),
tokens: auth.New(cfg.JWTSecretKey),
suPassword: cfg.SUPassword,
}
return h, nil
}
// Accounts returns an account client
func (h *Helper) Accounts() account.AccountClient {
return h.accounts
}
// Logs returns a log client
func (h *Helper) Logs() logs.LogsClient {
return h.logs
}
// Stacks returns a stack client
func (h *Helper) Stacks() stack.StackClient {
return h.stacks
}
// Resources returns a resource client
func (h *Helper) Resources() resource.ResourceClient {
return h.resources
}
// Tokens returns a token manager instance
func (h *Helper) Tokens() *auth.Tokens {
return h.tokens
}
// Login sign-up, verify and log-in a random user and returns the associated credentials
func (h *Helper) Login() (metadata.MD, error) {
randomUser := h.RandomUser()
conn, err := AmplifierConnection()
if err != nil {
return nil, err
}
client := account.NewAccountClient(conn)
ctx := context.Background()
// SignUp
_, err = client.SignUp(ctx, &randomUser)
if err != nil {
return nil, fmt.Errorf("SignUp error: %v", err)
}
// Login
header := metadata.MD{}
_, err = client.Login(ctx, &account.LogInRequest{Name: randomUser.Name, Password: randomUser.Password}, grpc.Header(&header))
if err != nil {
return nil, fmt.Errorf("Login error: %v", err)
}
// Extract token from header
tokens := header[auth.TokenKey]
if len(tokens) == 0 {
return nil, errors.New("No token in response header")
}
token := tokens[0]
return metadata.Pairs(auth.AuthorizationHeader, auth.ForgeAuthorizationHeader(token)), nil
}
// SuperLogin logs in as super user and returns the associated credentials
func (h *Helper) SuperLogin() (context.Context, error) {
su := h.SuperUser()
conn, err := AmplifierConnection()
if err != nil {
return nil, err
}
client := account.NewAccountClient(conn)
// Login
header := metadata.MD{}
_, err = client.Login(context.Background(), &account.LogInRequest{Name: su.Name, Password: su.Password}, grpc.Header(&header))
if err != nil {
return nil, fmt.Errorf("Login error: %v", err)
}
// Extract token from header
tokens := header[auth.TokenKey]
if len(tokens) == 0 {
return nil, errors.New("No token in response header")
}
token := tokens[0]
credentials := metadata.Pairs(auth.AuthorizationHeader, auth.ForgeAuthorizationHeader(token))
return metadata.NewOutgoingContext(context.Background(), credentials), nil
}
// SuperUser returns the super user SignUpRequest
func (h *Helper) SuperUser() account.SignUpRequest {
return account.SignUpRequest{
Name: "su",
Password: h.suPassword,
Email: "super@user.amp",
}
}
// RandomUser returns a random user SignUpRequest
func (h *Helper) RandomUser() account.SignUpRequest {
id := stringid.GenerateNonCryptoID()
return account.SignUpRequest{
Name: id,
Password: "password",
Email: id + "@user.email",
}
}
// RandomOrg returns a random organization CreateOrganizationRequest
func (h *Helper) RandomOrg() account.CreateOrganizationRequest {
id := stringid.GenerateNonCryptoID()
return account.CreateOrganizationRequest{
Name: id,
Email: id + "@org.email",
}
}
// RandomTeam returns a random team CreateTeamRequest
func (h *Helper) RandomTeam(org string) account.CreateTeamRequest {
id := stringid.GenerateNonCryptoID()
return account.CreateTeamRequest{
OrganizationName: org,
TeamName: id,
}
}
// DefaultOrg returns the default organization CreateOrganizationRequest
func (h *Helper) DefaultOrg() account.CreateOrganizationRequest {
return account.CreateOrganizationRequest{
Name: accounts.DefaultOrganization,
Email: accounts.DefaultOrganizationEmail,
}
}
// DeployStack deploys a stack with given name and file location
func (h *Helper) DeployStack(ctx context.Context, name string, composeFile string) (string, error) {
contents, err := ioutil.ReadFile(composeFile)
if err != nil {
return "", err
}
request := &stack.DeployRequest{
Name: name,
Compose: contents,
}
reply, err := h.stacks.StackDeploy(ctx, request)
if err != nil {
return "", err
}
return reply.Id, err
}
// CreateUser signs up and logs in the given user
func (h *Helper) CreateUser(t *testing.T, user *account.SignUpRequest) context.Context {
ctx := context.Background()
// SignUp
_, err := h.accounts.SignUp(ctx, user)
assert.NoError(t, err)
// Login
header := metadata.MD{}
_, err = h.accounts.Login(ctx, &account.LogInRequest{Name: user.Name, Password: user.Password}, grpc.Header(&header))
assert.NoError(t, err)
// Extract token from header
tokens := header[auth.TokenKey]
assert.NotEmpty(t, tokens)
token := tokens[0]
assert.NotEmpty(t, token)
return metadata.NewOutgoingContext(ctx, metadata.Pairs(auth.AuthorizationHeader, auth.ForgeAuthorizationHeader(token)))
}
// CreateOrganization signs up and logs in the given user and creates an organization
func (h *Helper) CreateOrganization(t *testing.T, org *account.CreateOrganizationRequest, owner *account.SignUpRequest) context.Context {
// Create a user
ownerCtx := h.CreateUser(t, owner)
// CreateOrganization
_, err := h.accounts.CreateOrganization(ownerCtx, org)
assert.NoError(t, err)
return ownerCtx
}
// CreateAndAddUserToOrganization signs up and logs in the given user and adds them to the given organization
func (h *Helper) CreateAndAddUserToOrganization(ownerCtx context.Context, t *testing.T, org *account.CreateOrganizationRequest, user *account.SignUpRequest) context.Context {
// Create a user
userCtx := h.CreateUser(t, user)
// AddUserToOrganization
_, err := h.accounts.AddUserToOrganization(ownerCtx, &account.AddUserToOrganizationRequest{
OrganizationName: org.Name,
UserName: user.Name,
})
assert.NoError(t, err)
return userCtx
}
// CreateTeam creates the given owner, creates the given organization and creates a team in this organization
func (h *Helper) CreateTeam(t *testing.T, org *account.CreateOrganizationRequest, owner *account.SignUpRequest, team *account.CreateTeamRequest) context.Context {
// Create a user
ownerCtx := h.CreateUser(t, owner)
// CreateTeam
_, err := h.accounts.CreateTeam(ownerCtx, team)
assert.NoError(t, err)
return ownerCtx
}
func (h *Helper) AddUserToTeam(ownerCtx context.Context, t *testing.T, team *account.CreateTeamRequest, user *account.SignUpRequest) {
_, err := h.Accounts().AddUserToTeam(ownerCtx, &account.AddUserToTeamRequest{
OrganizationName: team.OrganizationName,
TeamName: team.TeamName,
UserName: user.Name,
})
assert.NoError(t, err)
}
func (h *Helper) RemoveUserFromTeam(ownerCtx context.Context, t *testing.T, team *account.CreateTeamRequest, user *account.SignUpRequest) {
_, err := h.Accounts().RemoveUserFromTeam(ownerCtx, &account.RemoveUserFromTeamRequest{
OrganizationName: team.OrganizationName,
TeamName: team.TeamName,
UserName: user.Name,
})
assert.NoError(t, err)
}
// Switch switches from the given user context to the given account name
func (h *Helper) Switch(userCtx context.Context, t *testing.T, accountName string) context.Context {
header := metadata.MD{}
_, err := h.accounts.Switch(userCtx, &account.SwitchRequest{Account: accountName}, grpc.Header(&header))
assert.NoError(t, err)
// Extract token from header
tokens := header[auth.TokenKey]
assert.NotEmpty(t, tokens)
token := tokens[0]
assert.NotEmpty(t, token)
return metadata.NewOutgoingContext(context.Background(), metadata.Pairs(auth.AuthorizationHeader, auth.ForgeAuthorizationHeader(token)))
}
// Log Producer constants
var (
TestMessage = "test message "
TestContainerID = stringid.GenerateNonCryptoID()
TestContainerName = "testcontainer"
TestContainerShortName = "testcontainershortname"
TestContainerState = "testcontainerstate"
TestServiceID = stringid.GenerateNonCryptoID()
TestServiceName = "testservice"
TestStackID = stringid.GenerateNonCryptoID()
TestStackName = "teststack"
TestNodeID = stringid.GenerateNonCryptoID()
TestTaskID = stringid.GenerateNonCryptoID()
)
// LogProducer is a test log producer
type LogProducer struct {
ns *ns.NatsStreaming
asyncProduction int32
counter int64
h *Helper
}
// NewLogProducer instantiates a new log producer
func NewLogProducer(h *Helper) *LogProducer {
lp := &LogProducer{
ns: ns.NewClient(ns.DefaultURL, ns.ClusterID, stringid.GenerateNonCryptoID(), 60*time.Second),
counter: 0,
h: h,
}
if err := lp.ns.Connect(); err != nil {
log.Fatalln("Cannot connect to NATS", err)
}
go func(lp *LogProducer) {
for {
time.Sleep(50 * time.Millisecond)
if atomic.LoadInt32(&lp.asyncProduction) > 0 {
if err := lp.produce(logs.NumberOfEntries); err != nil {
log.Println("error producing async messages", err)
}
}
}
}(lp)
return lp
}
func (lp *LogProducer) buildLogEntry(infrastructure bool) *logs.LogEntry {
atomic.AddInt64(&lp.counter, 1)
entry := &logs.LogEntry{
Timestamp: time.Now().UTC().Format(time.RFC3339Nano),
ContainerId: TestContainerID,
ContainerName: TestContainerName,
ContainerShortName: TestContainerShortName,
ContainerState: TestContainerState,
ServiceName: TestServiceName,
ServiceId: TestServiceID,
TaskId: TestTaskID,
StackName: TestStackName,
StackId: TestStackID,
NodeId: TestNodeID,
TimeId: fmt.Sprintf("%016X", lp.counter),
Labels: make(map[string]string),
Msg: TestMessage + fmt.Sprintf("%016X", lp.counter),
}
if infrastructure {
entry.Labels[constants.LabelKeyRole] = "infra"
}
return entry
}
func (lp *LogProducer) produce(howMany int) error {
entries := logs.GetReply{}
for i := 0; i < howMany; i++ {
// User log entry
user := lp.buildLogEntry(false)
entries.Entries = append(entries.Entries, user)
// Infrastructure log entry
infra := lp.buildLogEntry(true)
entries.Entries = append(entries.Entries, infra)
}
message, err := proto.Marshal(&entries)
if err != nil {
return err
}
if err := lp.ns.GetClient().Publish(ns.LogsSubject, message); err != nil {
return err
}
return nil
}
// StartAsyncProducer starts producing log messages in the background
func (lp *LogProducer) StartAsyncProducer() {
atomic.CompareAndSwapInt32(&lp.asyncProduction, 0, 1)
}
// StopAsyncProducer stops producing log messages in the background
func (lp *LogProducer) StopAsyncProducer() {
atomic.CompareAndSwapInt32(&lp.asyncProduction, 1, 0)
}
// PopulateLogs populate elasticsearch with log entries, by producing test messages and making sure their got indexed
func (lp *LogProducer) PopulateLogs() error {
// Connect to amplifier
conn, err := AmplifierConnection()
if err != nil {
return err
}
client := logs.NewLogsClient(conn)
// Login context
credentials, err := lp.h.Login()
if err != nil {
return err
}
ctx := metadata.NewOutgoingContext(context.Background(), credentials)
// Populate logs
if err := lp.produce(logs.NumberOfEntries); err != nil {
return err
}
// Wait for them to be indexed in elasticsearch
for {
time.Sleep(1 * time.Second)
r, err := client.LogsGet(ctx, &logs.GetRequest{Service: TestServiceID})
if err != nil {
log.Println(err)
continue
}
if len(r.Entries) == logs.NumberOfEntries {
break
}
}
return nil
}