This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
forked from kudobuilder/kuttl
-
Notifications
You must be signed in to change notification settings - Fork 5
/
case.go
511 lines (432 loc) · 13.3 KB
/
case.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
package test
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"testing"
"time"
petname "github.com/dustinkirkland/golang-petname"
"github.com/thoas/go-funk"
corev1 "k8s.io/api/core/v1"
eventsv1 "k8s.io/api/events/v1"
eventsbeta1 "k8s.io/api/events/v1beta1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
"sigs.k8s.io/controller-runtime/pkg/client"
"k8s.io/client-go/tools/clientcmd"
"github.com/kyverno/kuttl/pkg/report"
testutils "github.com/kyverno/kuttl/pkg/test/utils"
)
// testStepRegex contains one capturing group to determine the index of a step file.
var testStepRegex = regexp.MustCompile(`^(\d+)-(?:[^\.]+)(?:\.yaml)?$`)
// Case contains all of the test steps and the Kubernetes client and other global configuration
// for a test.
type Case struct {
Steps []*Step
Name string
Dir string
SkipDelete bool
Timeout int
PreferredNamespace string
Client func(forceNew bool) (client.Client, error)
DiscoveryClient func() (discovery.DiscoveryInterface, error)
Logger testutils.Logger
// Suppress is used to suppress logs
Suppress []string
}
type namespace struct {
Name string
AutoCreated bool
}
// DeleteNamespace deletes a namespace in Kubernetes after we are done using it.
func (t *Case) DeleteNamespace(cl client.Client, ns *namespace) error {
if !ns.AutoCreated {
t.Logger.Log("Skipping deletion of user-supplied namespace:", ns.Name)
return nil
}
t.Logger.Log("Deleting namespace:", ns.Name)
ctx := context.Background()
if t.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Duration(t.Timeout)*time.Second)
defer cancel()
}
nsObj := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: ns.Name,
},
TypeMeta: metav1.TypeMeta{
Kind: "Namespace",
},
}
if err := cl.Delete(ctx, nsObj); err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
return err
}
return wait.PollImmediateUntilWithContext(ctx, 100*time.Millisecond, func(ctx context.Context) (bool, error) {
actual := &corev1.Namespace{}
err := cl.Get(ctx, client.ObjectKey{Name: ns.Name}, actual)
if k8serrors.IsNotFound(err) {
return true, nil
}
return false, err
})
}
// CreateNamespace creates a namespace in Kubernetes to use for a test.
func (t *Case) CreateNamespace(test *testing.T, cl client.Client, ns *namespace) error {
if !ns.AutoCreated {
t.Logger.Log("Skipping creation of user-supplied namespace:", ns.Name)
return nil
}
t.Logger.Log("Creating namespace:", ns.Name)
ctx := context.Background()
if t.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Duration(t.Timeout)*time.Second)
defer cancel()
}
if !t.SkipDelete {
test.Cleanup(func() {
if err := t.DeleteNamespace(cl, ns); err != nil {
test.Error(err)
}
})
}
return cl.Create(ctx, &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: ns.Name,
},
TypeMeta: metav1.TypeMeta{
Kind: "Namespace",
},
})
}
// NamespaceExists gets namespace and returns true if it exists
func (t *Case) NamespaceExists(namespace string) (bool, error) {
cl, err := t.Client(false)
if err != nil {
return false, err
}
ns := &corev1.Namespace{}
err = cl.Get(context.TODO(), client.ObjectKey{Name: namespace}, ns)
if err != nil && !k8serrors.IsNotFound(err) {
return false, err
}
return ns.Name == namespace, nil
}
// byFirstTimestamp sorts a slice of events by first timestamp, using their involvedObject's name as a tie breaker.
type byFirstTimestamp []eventsbeta1.Event
func (o byFirstTimestamp) Len() int { return len(o) }
func (o byFirstTimestamp) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o byFirstTimestamp) Less(i, j int) bool {
if o[i].ObjectMeta.CreationTimestamp.Equal(&o[j].ObjectMeta.CreationTimestamp) {
return o[i].Name < o[j].Name
}
return o[i].ObjectMeta.CreationTimestamp.Before(&o[j].ObjectMeta.CreationTimestamp)
}
// byFirstTimestampV1 sorts a slice of eventsv1 by first timestamp, using their involvedObject's name as a tie breaker.
type byFirstTimestampV1 []eventsv1.Event
func (o byFirstTimestampV1) Len() int { return len(o) }
func (o byFirstTimestampV1) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o byFirstTimestampV1) Less(i, j int) bool {
if o[i].ObjectMeta.CreationTimestamp.Equal(&o[j].ObjectMeta.CreationTimestamp) {
return o[i].Name < o[j].Name
}
return o[i].ObjectMeta.CreationTimestamp.Before(&o[j].ObjectMeta.CreationTimestamp)
}
// byFirstTimestampCoreV1 sorts a slice of corev1 by first timestamp, using their involvedObject's name as a tie breaker.
type byFirstTimestampCoreV1 []corev1.Event
func (o byFirstTimestampCoreV1) Len() int { return len(o) }
func (o byFirstTimestampCoreV1) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o byFirstTimestampCoreV1) Less(i, j int) bool {
if o[i].ObjectMeta.CreationTimestamp.Equal(&o[j].ObjectMeta.CreationTimestamp) {
return o[i].Name < o[j].Name
}
return o[i].ObjectMeta.CreationTimestamp.Before(&o[j].ObjectMeta.CreationTimestamp)
}
// CollectEvents gathers all events from namespace and prints it out to log
func (t *Case) CollectEvents(namespace string) {
cl, err := t.Client(false)
if err != nil {
t.Logger.Log("Failed to collect events for %s in ns %s: %v", t.Name, namespace, err)
return
}
err = t.collectEventsV1(cl, namespace)
if err != nil {
t.Logger.Log("Trying with events eventsv1beta1 API...")
err = t.collectEventsBeta1(cl, namespace)
if err != nil {
t.Logger.Log("Trying with events corev1 API...")
err = t.collectEventsCoreV1(cl, namespace)
if err != nil {
t.Logger.Log("All event APIs failed")
}
}
}
}
func (t *Case) collectEventsBeta1(cl client.Client, namespace string) error {
eventsList := &eventsbeta1.EventList{}
err := cl.List(context.TODO(), eventsList, client.InNamespace(namespace))
if err != nil {
t.Logger.Logf("Failed to collect events for %s in ns %s: %v", t.Name, namespace, err)
return err
}
events := eventsList.Items
sort.Sort(byFirstTimestamp(events))
t.Logger.Logf("%s events from ns %s:", t.Name, namespace)
printEventsBeta1(events, t.Logger)
return nil
}
func (t *Case) collectEventsV1(cl client.Client, namespace string) error {
eventsList := &eventsv1.EventList{}
err := cl.List(context.TODO(), eventsList, client.InNamespace(namespace))
if err != nil {
t.Logger.Logf("Failed to collect events for %s in ns %s: %v", t.Name, namespace, err)
return err
}
events := eventsList.Items
sort.Sort(byFirstTimestampV1(events))
t.Logger.Logf("%s events from ns %s:", t.Name, namespace)
printEventsV1(events, t.Logger)
return nil
}
func (t *Case) collectEventsCoreV1(cl client.Client, namespace string) error {
eventsList := &corev1.EventList{}
err := cl.List(context.TODO(), eventsList, client.InNamespace(namespace))
if err != nil {
t.Logger.Logf("Failed to collect events for %s in ns %s: %v", t.Name, namespace, err)
return err
}
events := eventsList.Items
sort.Sort(byFirstTimestampCoreV1(events))
t.Logger.Logf("%s events from ns %s:", t.Name, namespace)
printEventsCoreV1(events, t.Logger)
return nil
}
func printEventsBeta1(events []eventsbeta1.Event, logger testutils.Logger) {
for _, e := range events {
// time type regarding action reason note reportingController related
logger.Logf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
e.ObjectMeta.CreationTimestamp,
e.Type,
shortString(&e.Regarding),
e.Action,
e.Reason,
e.Note,
e.ReportingController,
shortString(e.Related))
}
}
func printEventsV1(events []eventsv1.Event, logger testutils.Logger) {
for _, e := range events {
// time type regarding action reason note reportingController related
logger.Logf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
e.ObjectMeta.CreationTimestamp,
e.Type,
shortString(&e.Regarding),
e.Action,
e.Reason,
e.Note,
e.ReportingController,
shortString(e.Related))
}
}
func printEventsCoreV1(events []corev1.Event, logger testutils.Logger) {
for _, e := range events {
// time type regarding action reason note reportingController related
logger.Logf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
e.ObjectMeta.CreationTimestamp,
e.Type,
shortString(&e.InvolvedObject),
e.Action,
e.Reason,
e.Message,
e.ReportingController,
shortString(e.Related))
}
}
func shortString(obj *corev1.ObjectReference) string {
if obj == nil {
return ""
}
fieldRef := ""
if obj.FieldPath != "" {
fieldRef = "." + obj.FieldPath
}
return fmt.Sprintf("%s %s%s",
obj.GroupVersionKind().GroupKind().String(),
obj.Name,
fieldRef)
}
// Run runs a test case including all of its steps.
func (t *Case) Run(test *testing.T, tc *report.Testcase) {
ns := t.determineNamespace()
cl, err := t.Client(false)
if err != nil {
tc.Failure = report.NewFailure(err.Error(), nil)
test.Fatal(err)
}
clients := map[string]client.Client{"": cl}
for _, testStep := range t.Steps {
if clients[testStep.Kubeconfig] != nil {
continue
}
cl, err := newClient(testStep.Kubeconfig)(false)
if err != nil {
tc.Failure = report.NewFailure(err.Error(), nil)
test.Fatal(err)
}
clients[testStep.Kubeconfig] = cl
}
for _, c := range clients {
if err := t.CreateNamespace(test, c, ns); err != nil {
tc.Failure = report.NewFailure(err.Error(), nil)
test.Fatal(err)
}
}
for _, testStep := range t.Steps {
testStep.Client = t.Client
if testStep.Kubeconfig != "" {
testStep.Client = newClient(testStep.Kubeconfig)
}
testStep.DiscoveryClient = t.DiscoveryClient
if testStep.Kubeconfig != "" {
testStep.DiscoveryClient = newDiscoveryClient(testStep.Kubeconfig)
}
testStep.Logger = t.Logger.WithPrefix(testStep.String())
tc.Assertions += len(testStep.Asserts)
tc.Assertions += len(testStep.Errors)
if errs := testStep.Run(test, ns.Name); len(errs) > 0 {
caseErr := fmt.Errorf("failed in step %s", testStep.String())
tc.Failure = report.NewFailure(caseErr.Error(), errs)
test.Error(caseErr)
for _, err := range errs {
test.Error(err)
}
break
}
}
if funk.Contains(t.Suppress, "events") {
t.Logger.Logf("skipping kubernetes event logging")
} else {
t.CollectEvents(ns.Name)
}
}
func (t *Case) determineNamespace() *namespace {
ns := &namespace{
Name: t.PreferredNamespace,
AutoCreated: false,
}
// no preferred ns, means we auto-create with petnames
if t.PreferredNamespace == "" {
ns.Name = fmt.Sprintf("kuttl-test-%s", petname.Generate(2, "-"))
ns.AutoCreated = true
}
// if we have a preferred namespace, we do NOT auto-create
return ns
}
// CollectTestStepFiles collects a map of test steps and their associated files
// from a directory.
func (t *Case) CollectTestStepFiles() (map[int64][]string, error) {
testStepFiles := map[int64][]string{}
files, err := os.ReadDir(t.Dir)
if err != nil {
return nil, err
}
for _, file := range files {
index, err := getIndexFromFile(file.Name())
if err != nil {
return nil, err
}
if index < 0 {
// t.Logger.Log("Ignoring", file.Name(), "as it does not match file name regexp:", testStepRegex.String())
continue
}
if testStepFiles[index] == nil {
testStepFiles[index] = []string{}
}
testStepPath := filepath.Join(t.Dir, file.Name())
if file.IsDir() {
testStepDir, err := os.ReadDir(testStepPath)
if err != nil {
return nil, err
}
for _, testStepFile := range testStepDir {
testStepFiles[index] = append(testStepFiles[index], filepath.Join(
testStepPath, testStepFile.Name(),
))
}
} else {
testStepFiles[index] = append(testStepFiles[index], testStepPath)
}
}
return testStepFiles, nil
}
// getIndexFromFile returns the index derived from fileName's prefix, ex. "01-foo.yaml" has index 1.
// If an index isn't found, -1 is returned.
func getIndexFromFile(fileName string) (int64, error) {
matches := testStepRegex.FindStringSubmatch(fileName)
if len(matches) != 2 {
return -1, nil
}
i, err := strconv.ParseInt(matches[1], 10, 32)
return i, err
}
// LoadTestSteps loads all of the test steps for a test case.
func (t *Case) LoadTestSteps() error {
testStepFiles, err := t.CollectTestStepFiles()
if err != nil {
return err
}
testSteps := []*Step{}
for index, files := range testStepFiles {
testStep := &Step{
Timeout: t.Timeout,
Index: int(index),
SkipDelete: t.SkipDelete,
Dir: t.Dir,
Asserts: []asserts{},
Apply: []apply{},
Errors: []client.Object{},
}
for _, file := range files {
if err := testStep.LoadYAML(file); err != nil {
return err
}
}
testSteps = append(testSteps, testStep)
}
sort.Slice(testSteps, func(i, j int) bool {
return testSteps[i].Index < testSteps[j].Index
})
t.Steps = testSteps
return nil
}
func newClient(kubeconfig string) func(bool) (client.Client, error) {
return func(bool) (client.Client, error) {
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, err
}
return testutils.NewRetryClient(config, client.Options{
Scheme: testutils.Scheme(),
})
}
}
func newDiscoveryClient(kubeconfig string) func() (discovery.DiscoveryInterface, error) {
return func() (discovery.DiscoveryInterface, error) {
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, err
}
return discovery.NewDiscoveryClientForConfig(config)
}
}