-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathprober.go
569 lines (485 loc) · 15.8 KB
/
prober.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/*
Copyright 2021 The Knative Authors
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 eventshub
import (
"context"
"errors"
"fmt"
"strconv"
"sync"
"time"
conformanceevent "github.com/cloudevents/conformance/pkg/event"
cetest "github.com/cloudevents/sdk-go/v2/test"
"github.com/google/uuid"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait"
duckv1 "knative.dev/pkg/apis/duck/v1"
"knative.dev/reconciler-test/pkg/environment"
"knative.dev/reconciler-test/pkg/feature"
"knative.dev/reconciler-test/pkg/k8s"
"knative.dev/reconciler-test/pkg/resources/service"
)
func NewProber() *EventProber {
return &EventProber{
shortNameToName: make(map[string]string),
}
}
type EventProber struct {
target target
targetMu sync.Mutex
shortNameToName map[string]string
shortNameToNameMu sync.Mutex
ids []string
idsMu sync.Mutex
senderOptions []EventsHubOption
senderOptionsMu sync.Mutex
receiverOptions []EventsHubOption
receiverOptionsMu sync.Mutex
}
type target struct {
// Need [GVR + Name] OR [URI]
gvr schema.GroupVersionResource
name string
uri string
}
type EventInfoCombined struct {
Sent EventInfo
Response EventInfo
}
// SetTargetResource configures the senders target as a GVR and name, used when sender is installed.
func (p *EventProber) SetTargetResource(targetGVR schema.GroupVersionResource, targetName string) {
p.targetMu.Lock()
defer p.targetMu.Unlock()
p.target = target{
gvr: targetGVR,
name: targetName,
}
}
// SetTargetKRef configures the senders target as KRef, used when sender is installed.
// Note: namespace is ignored.
func (p *EventProber) SetTargetKRef(ref *duckv1.KReference) error {
gv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return err
}
gvk := schema.GroupVersionKind{
Group: gv.Group,
Version: gv.Version,
Kind: ref.Kind,
}
gvr, _ := meta.UnsafeGuessKindToResource(gvk)
p.SetTargetResource(gvr, ref.Name)
return nil
}
// SetTargetURI configures the senders target as a URI, used when sender is installed.
func (p *EventProber) SetTargetURI(targetURI string) {
p.targetMu.Lock()
defer p.targetMu.Unlock()
p.target = target{
uri: targetURI,
}
}
// ReceiversRejectFirstN adds DropFirstN to the default config for new receivers.
func (p *EventProber) ReceiversRejectFirstN(n uint) {
p.appendReceiverOptions(DropFirstN(n))
}
// ReceiversRejectResponseCode adds DropEventsResponseCode to the default config for new receivers.
func (p *EventProber) ReceiversRejectResponseCode(code int) {
p.appendReceiverOptions(DropEventsResponseCode(code))
}
// ReceiversHaveResponseDelay adds ResponseWaitTime to the default config for
// new receivers.
func (p *EventProber) ReceiversHaveResponseDelay(delay time.Duration) {
p.appendReceiverOptions(ResponseWaitTime(delay))
}
// ReceiverInstall installs an eventshub receiver into the test env.
func (p *EventProber) ReceiverInstall(prefix string, opts ...EventsHubOption) feature.StepFn {
name := feature.MakeRandomK8sName(prefix)
p.setShortNameToName(prefix, name)
opts = append(p.getReceiverOptions(), opts...)
opts = append(opts, StartReceiver)
return Install(name, opts...)
}
// SenderInstall installs an eventshub sender resource into the test env.
func (p *EventProber) SenderInstall(prefix string, opts ...EventsHubOption) feature.StepFn {
name := feature.MakeRandomK8sName(prefix)
p.setShortNameToName(prefix, name)
return func(ctx context.Context, t feature.T) {
opts := append(opts, p.getSenderOptions()...)
if len(p.getTarget().uri) > 0 {
opts = append(opts, StartSenderURL(p.getTarget().uri))
} else if !p.getTarget().gvr.Empty() {
k8s.IsAddressable(p.getTarget().gvr, p.getTarget().name)(ctx, t)
opts = append(opts, StartSenderToResource(p.getTarget().gvr, p.getTarget().name))
} else {
t.Fatal("no target is configured for event loop")
}
// Install into the env.
Install(name, opts...)(ctx, t)
p.SenderDone(prefix)(ctx, t)
}
}
// SenderDone will poll until the sender sends all expected events.
func (p *EventProber) SenderDone(prefix string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
interval, timeout := environment.PollTimingsFromContext(ctx)
var events []EventInfoCombined
err := wait.PollImmediate(interval, timeout, func() (bool, error) {
expected := p.getIdsCopy()
events = p.SentBy(ctx, prefix)
t.Log(p.getNameFromPrefix(prefix), "has sent", len(events), "expected", len(expected))
if len(events) == len(expected) {
return true, nil
}
return false, nil
})
if err != nil {
t.Fatalf("timeout while waiting for sender to deliver all expected events [prefix: %s]: %v\n\n%s\n",
prefix,
err,
stringify("sent", events),
)
}
}
}
// ReceiverDone will poll until the receiver has received all expected events.
func (p *EventProber) ReceiverDone(from, to string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
interval, timeout := environment.PollTimingsFromContext(ctx)
var (
sent []EventInfoCombined
received []EventInfo
rejected []EventInfo
)
err := wait.PollImmediate(interval, timeout, func() (bool, error) {
sent = p.SentBy(ctx, from)
t.Log(p.getNameFromPrefix(from), "has sent", len(sent))
received = p.ReceivedBy(ctx, to)
t.Log(p.getNameFromPrefix(to), "has received", len(received))
rejected = p.RejectedBy(ctx, to)
t.Log(p.getNameFromPrefix(to), "has rejected", len(rejected))
if len(sent) == len(received)+len(rejected) {
return true, nil
}
return false, nil
})
if err != nil {
t.Fatalf("timeout while waiting for receiver to receive all expected events [from: %s, to: %s]: %v\n%s\n%s\n%s\n",
from,
to,
err,
stringify("sent", sent),
stringify("received", combine(received)),
stringify("rejected", combine(rejected)),
)
}
}
}
// CorrelateSent takes in an array of mixed Sent / Response events (matched with sentEventMatcher for example)
// and correlates them based on the sequence into a pair.
func CorrelateSent(origin string, in []EventInfo) []EventInfoCombined {
var out []EventInfoCombined
// not too many events, this will suffice...
for i, e := range in {
if e.Origin == origin && e.Kind == EventSent {
looking := e.Sequence
for j := i + 1; j <= len(in)-1; j++ {
if in[j].Kind == EventResponse && in[j].Sequence == looking {
out = append(out, EventInfoCombined{Sent: e, Response: in[j]})
}
}
}
}
return out
}
// SentBy returns events sent by the named sender.
func (p *EventProber) SentBy(ctx context.Context, prefix string) []EventInfoCombined {
name := p.getNameFromPrefix(prefix)
store := StoreFromContext(ctx, name)
return CorrelateSent(name, store.Collected())
}
// ReceivedBy returns events received by the named receiver.
func (p *EventProber) ReceivedBy(ctx context.Context, prefix string) []EventInfo {
name := p.getNameFromPrefix(prefix)
store := StoreFromContext(ctx, name)
events, _, _, _ := store.Find(func(info EventInfo) error {
if info.Observer == name && info.Kind == EventReceived {
return nil
}
return errors.New("not a match")
})
return events
}
// RejectedBy returns events rejected by the named receiver.
func (p *EventProber) RejectedBy(ctx context.Context, prefix string) []EventInfo {
name := p.shortNameToName[prefix]
store := StoreFromContext(ctx, name)
events, _, _, _ := store.Find(func(info EventInfo) error {
if info.Observer == name && info.Kind == EventRejected {
return nil
}
return errors.New("not a match")
})
return events
}
// ReceivedOrRejectedBy returns events received or rejected by the named receiver.
func (p *EventProber) ReceivedOrRejectedBy(ctx context.Context, prefix string) []EventInfo {
name := p.getNameFromPrefix(prefix)
store := StoreFromContext(ctx, name)
events, _, _, _ := store.Find(func(info EventInfo) error {
if info.Observer == name && (info.Kind == EventReceived || info.Kind == EventRejected) {
return nil
}
return errors.New("not a match")
})
return events
}
// ExpectYAMLEvents registered expected events into the prober.
func (p *EventProber) ExpectYAMLEvents(path string) error {
events, err := conformanceevent.FromYaml(path, true)
if err != nil {
return err
}
if len(events) == 0 {
return fmt.Errorf("failed to load events from %q", path)
}
for _, event := range events {
p.appendIds(event.Attributes.ID)
}
return nil
}
// ExpectEvents registers event IDs into the prober.
func (p *EventProber) ExpectEvents(ids []string) {
p.appendIds(ids...)
}
// SenderEventsFromURI configures a sender to send a url/yaml based events.
func (p *EventProber) SenderEventsFromURI(uri string) {
p.appendSenderOptions(InputYAML(uri))
}
// SenderEventsFromSVC configures a sender to send a yaml based events fetched
// a service in the testing environment. Namespace of the svc will come from
// env.Namespace(), based on context from the StepFn.
func (p *EventProber) SenderEventsFromSVC(svcName, path string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
u, err := service.Address(ctx, svcName)
if err != nil {
t.Error(err)
}
u.URL.Path = path
p.appendSenderOptions(InputYAML(u.URL.String()))
}
}
// SenderFullEvents creates `count` cloudevents.FullEvent events with new IDs into a
// sender and registers them for the prober.
// Warning: only call once.
func (p *EventProber) SenderFullEvents(count int) {
event := cetest.FullEvent()
if count == 1 {
id := uuid.New().String()
event.SetID(id)
p.appendIds(id)
p.appendSenderOptions(InputEvent(event))
} else {
p.appendSenderOptions(
InputEvent(event),
SendMultipleEvents(count, 10*time.Millisecond),
EnableIncrementalId,
)
for i := 1; i <= count; i++ {
p.appendIds(strconv.Itoa(i))
}
}
}
// SenderMinEvents creates `count` cloudevents.MinEvent events with new IDs into a
// sender and registers them for the prober.
// Warning: only call once.
func (p *EventProber) SenderMinEvents(count int) {
event := cetest.MinEvent()
if count == 1 {
id := uuid.New().String()
event.SetID(id)
p.appendIds(id)
p.appendSenderOptions(InputEvent(event))
} else {
p.appendSenderOptions(InputEvent(event), SendMultipleEvents(count, 10*time.Millisecond))
for i := 1; i <= count; i++ {
p.appendIds(strconv.Itoa(i))
}
}
}
// AsKReference returns the short-named component as a KReference.
func (p *EventProber) AsKReference(prefix string) *duckv1.KReference {
return service.AsKReference(p.getNameFromPrefix(prefix))
}
// AssertSentAll tests that `fromPrefix` sent all known events known to the prober.
func (p *EventProber) AssertSentAll(fromPrefix string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
p.SenderDone(fromPrefix)(ctx, t)
events := p.SentBy(ctx, fromPrefix)
expected := p.getIdsCopy()
if len(expected) != len(events) {
t.Errorf("expected %q to have sent %d events, actually sent %d",
fromPrefix, len(expected), len(events))
}
for _, id := range expected {
found := false
for _, event := range events {
if id == event.Sent.SentId {
found = true
if event.Response.StatusCode < 200 || event.Response.StatusCode > 299 {
t.Errorf("Failed to send event id=%s, %s", id, event.Response.String())
}
break
}
}
if !found {
t.Errorf("Failed to send event id=%s", id)
}
}
}
}
// AssertReceivedAll tests that all events sent by `fromPrefix` were received by `toPrefix`.
func (p *EventProber) AssertReceivedAll(fromPrefix, toPrefix string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
p.ReceiverDone(fromPrefix, toPrefix)(ctx, t)
sent := p.SentBy(ctx, fromPrefix)
ids := make([]string, len(sent))
for i, s := range sent {
ids[i] = s.Sent.SentId
}
events := p.ReceivedBy(ctx, toPrefix)
if len(ids) != len(events) {
t.Errorf("expected %q to have received %d events, actually received %d",
toPrefix, len(ids), len(events))
}
for _, id := range ids {
found := false
for _, event := range events {
if event.Event != nil && id == event.Event.ID() {
found = true
break
}
}
if !found {
t.Errorf("Failed to receive event id=%s", id)
}
}
}
}
// AssertReceivedAll tests that all events sent by `fromPrefix` were received by `toPrefix`.
func (p *EventProber) AssertReceivedOrRejectedAll(fromPrefix, toPrefix string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
p.ReceiverDone(fromPrefix, toPrefix)(ctx, t)
sent := p.SentBy(ctx, fromPrefix)
ids := make([]string, len(sent))
for i, s := range sent {
ids[i] = s.Sent.SentId
}
events := p.ReceivedOrRejectedBy(ctx, toPrefix)
if len(ids) != len(events) {
t.Errorf("expected %q to have received %d events, actually received %d",
fromPrefix, len(ids), len(events))
}
for _, id := range ids {
found := false
for _, event := range events {
if event.Event != nil && id == event.Event.ID() {
found = true
break
}
}
if !found {
t.Errorf("Failed to receive event id=%s", id)
}
}
}
}
func stringify(title string, events []EventInfoCombined) string {
errorMsg := title + "\n"
for _, e := range events {
errorMsg += "Sent: " + e.Sent.String() + "\nResponse: " + e.Response.String() + "\n\n"
}
return errorMsg
}
func combine(ei []EventInfo) []EventInfoCombined {
var c []EventInfoCombined
for _, e := range ei {
c = append(c, EventInfoCombined{Sent: e})
}
return c
}
// AssertReceivedNone tests that no events sent by `fromPrefix` were received by `toPrefix`.
func (p *EventProber) AssertReceivedNone(fromPrefix, toPrefix string) feature.StepFn {
return func(ctx context.Context, t feature.T) {
events := p.ReceivedBy(ctx, toPrefix)
if len(events) > 0 {
t.Errorf("expected %q to not have received any events from %s, actually received %d",
toPrefix, fromPrefix, len(events))
}
}
}
func (p *EventProber) setShortNameToName(k, v string) {
p.shortNameToNameMu.Lock()
defer p.shortNameToNameMu.Unlock()
p.shortNameToName[k] = v
}
func (p *EventProber) getNameFromPrefix(prefix string) string {
p.shortNameToNameMu.Lock()
defer p.shortNameToNameMu.Unlock()
return p.shortNameToName[prefix]
}
func (p *EventProber) getSenderOptions() []EventsHubOption {
p.senderOptionsMu.Lock()
defer p.senderOptionsMu.Unlock()
return p.senderOptions
}
func (p *EventProber) getReceiverOptions() []EventsHubOption {
p.receiverOptionsMu.Lock()
defer p.receiverOptionsMu.Unlock()
return p.receiverOptions
}
func (p *EventProber) appendReceiverOptions(opt ...EventsHubOption) {
p.receiverOptionsMu.Lock()
defer p.receiverOptionsMu.Unlock()
p.receiverOptions = append(p.receiverOptions, opt...)
}
func (p *EventProber) appendSenderOptions(opt ...EventsHubOption) {
p.senderOptionsMu.Lock()
defer p.senderOptionsMu.Unlock()
p.senderOptions = append(p.senderOptions, opt...)
}
func (p *EventProber) appendIds(ids ...string) {
p.idsMu.Lock()
defer p.idsMu.Unlock()
p.ids = append(p.ids, ids...)
}
func (p *EventProber) getIdsCopy() []string {
p.idsMu.Lock()
defer p.idsMu.Unlock()
ids := make([]string, len(p.ids))
copy(ids, p.ids)
return ids
}
func (p *EventProber) getTarget() target {
p.targetMu.Lock()
defer p.targetMu.Unlock()
return p.target
}
func (p *EventProber) DumpState(ctx context.Context, t feature.T) {
p.shortNameToNameMu.Lock()
defer p.shortNameToNameMu.Unlock()
for k, v := range p.shortNameToName {
t.Logf("collected for %s (%s)\n", v, k, StoreFromContext(ctx, v).dumpCollected())
}
}