/
managedresource.go
194 lines (159 loc) · 6.18 KB
/
managedresource.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
// Copyright 2024 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 matchers
import (
"context"
"fmt"
"strings"
"github.com/onsi/gomega/format"
"golang.org/x/exp/maps"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
resourcesv1alpha1 "github.com/gardener/gardener/pkg/apis/resources/v1alpha1"
)
type managedResourceObjectsMatcher struct {
ctx context.Context
cl client.Client
expectedObjToSerialized map[client.Object]string
extraObjectsCheck bool
extraObjects []string
missingObjects []string
mismatchExpectedToActual map[string]string
}
func (m *managedResourceObjectsMatcher) FailureMessage(actual interface{}) string {
return m.createMessage(actual, "not to be")
}
func (m *managedResourceObjectsMatcher) NegatedFailureMessage(actual interface{}) string {
return m.createMessage(actual, "to be")
}
func (m *managedResourceObjectsMatcher) createMessage(actual interface{}, addition string) string {
managedResource, ok := actual.(*resourcesv1alpha1.ManagedResource)
if !ok {
return fmt.Sprintf("expected *resourcesv1alpha1.ManagedResource. got:\n%s", format.Object(actual, 1))
}
var message string
switch {
case len(m.mismatchExpectedToActual) > 0:
message = fmt.Sprintf("Expected for ManagedResource %s/%s the following object mismathes %s found:\n", managedResource.Namespace, managedResource.Name, addition)
for expected, actual := range m.mismatchExpectedToActual {
message += format.MessageWithDiff(actual, "to equal", expected)
}
case len(m.missingObjects) > 0:
message = fmt.Sprintf("Expected for ManagedResource %s/%s the following missing elements %s found:\n", managedResource.Namespace, managedResource.Name, addition)
for _, missingObject := range m.missingObjects {
message += format.IndentString(missingObject, 2)
}
case len(m.extraObjects) > 0:
message = fmt.Sprintf("Expected for ManagedResource %s/%s the following extra and unexpected elements %s found:\n", managedResource.Namespace, managedResource.Name, addition)
for _, extraObject := range m.extraObjects {
message += format.IndentString(extraObject, 2)
}
}
return message
}
func (m *managedResourceObjectsMatcher) Match(actual interface{}) (bool, error) {
if actual == nil {
return false, nil
}
managedResource, ok := actual.(*resourcesv1alpha1.ManagedResource)
if !ok {
return false, fmt.Errorf("expected *resourcesv1alpha1.ManagedResource. got:\n%s", format.Object(actual, 1))
}
// Retrieve managed resource secrets.
var secrets = make([]*corev1.Secret, 0, len(managedResource.Spec.SecretRefs))
for _, secretRef := range managedResource.Spec.SecretRefs {
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretRef.Name,
Namespace: managedResource.Namespace,
},
}
if err := m.cl.Get(m.ctx, client.ObjectKeyFromObject(secret), secret); err != nil {
return false, fmt.Errorf("error when retrieving managed resource secret: %w", err)
}
secrets = append(secrets, secret)
}
dataKeyToExpected := make(map[string]string)
// Compare expected and actual results.
for expectedObj, expectedObjSerialized := range m.expectedObjToSerialized {
gvk, err := apiutil.GVKForObject(expectedObj, m.cl.Scheme())
if err != nil {
return false, fmt.Errorf("error when extracting object kind: %w", err)
}
dataKey := fmt.Sprintf(
"%s__%s__%s.yaml",
strings.ToLower(gvk.Kind),
expectedObj.GetNamespace(),
strings.ReplaceAll(expectedObj.GetName(), ":", "_"),
)
if _, ok := dataKeyToExpected[dataKey]; ok {
return false, fmt.Errorf("object is already specified for data key %s", dataKey)
}
dataKeyToExpected[dataKey] = expectedObjSerialized
}
dataKeys := sets.New(maps.Keys(dataKeyToExpected)...)
// Use early returns for the following checks to not overwhelm Gomega output.
m.mismatchExpectedToActual = findMismatchObjects(secrets, dataKeyToExpected)
if len(m.mismatchExpectedToActual) > 0 {
return false, nil
}
m.missingObjects = findMissingObjects(secrets, dataKeyToExpected)
if len(m.missingObjects) > 0 {
return false, nil
}
if m.extraObjectsCheck {
m.extraObjects = findExtraObjects(secrets, dataKeys)
if len(m.extraObjects) > 0 {
return false, nil
}
}
return true, nil
}
func findMismatchObjects(secrets []*corev1.Secret, keysToExpected map[string]string) map[string]string {
mismatches := make(map[string]string)
for _, secret := range secrets {
for dataKey, expected := range keysToExpected {
if actual, ok := secret.Data[dataKey]; ok && string(actual) != expected {
mismatches[expected] = string(actual)
}
}
}
return mismatches
}
func findMissingObjects(secrets []*corev1.Secret, keysToExpected map[string]string) []string {
var (
keysToBeFound = sets.New(maps.Keys(keysToExpected)...)
missingObjects []string
)
for _, secret := range secrets {
keysToBeFound = keysToBeFound.Difference(sets.New(maps.Keys(secret.Data)...))
}
for notFoundKey := range keysToBeFound {
missingObjects = append(missingObjects, keysToExpected[notFoundKey])
}
return missingObjects
}
func findExtraObjects(secrets []*corev1.Secret, keys sets.Set[string]) []string {
var extraObjects []string
for _, secret := range secrets {
extraKeys := sets.New(maps.Keys(secret.Data)...).Difference(keys)
for extraKey := range extraKeys {
extraObjects = append(extraObjects, string(secret.Data[extraKey]))
}
}
return extraObjects
}