| 1 |
/* |
| 2 |
Copyright 2024 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package patch |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"github.com/google/go-cmp/cmp" |
| 22 |
"strings" |
| 23 |
"testing" |
| 24 |
"time" |
| 25 |
|
| 26 |
appsv1 "k8s.io/api/apps/v1" |
| 27 |
corev1 "k8s.io/api/core/v1" |
| 28 |
"k8s.io/apimachinery/pkg/api/equality" |
| 29 |
"k8s.io/apimachinery/pkg/api/meta" |
| 30 |
"k8s.io/apimachinery/pkg/api/resource" |
| 31 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 32 |
"k8s.io/apimachinery/pkg/runtime" |
| 33 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 34 |
"k8s.io/apimachinery/pkg/util/wait" |
| 35 |
"k8s.io/apiserver/pkg/admission" |
| 36 |
"k8s.io/apiserver/pkg/admission/plugin/cel" |
| 37 |
celconfig "k8s.io/apiserver/pkg/apis/cel" |
| 38 |
"k8s.io/apiserver/pkg/cel/environment" |
| 39 |
"k8s.io/client-go/openapi/openapitest" |
| 40 |
"k8s.io/utils/ptr" |
| 41 |
) |
| 42 |
|
| 43 |
func TestApplyConfiguration(t *testing.T) { |
| 44 |
deploymentGVR := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"} |
| 45 |
deploymentGVK := schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"} |
| 46 |
tests := []struct { |
| 47 |
name string |
| 48 |
expression string |
| 49 |
gvr schema.GroupVersionResource |
| 50 |
object, oldObject runtime.Object |
| 51 |
expectedResult runtime.Object |
| 52 |
expectedErr string |
| 53 |
}{ |
| 54 |
{ |
| 55 |
name: "apply configuration add to listType=map", |
| 56 |
expression: `Object{ |
| 57 |
spec: Object.spec{ |
| 58 |
template: Object.spec.template{ |
| 59 |
spec: Object.spec.template.spec{ |
| 60 |
volumes: [Object.spec.template.spec.volumes{ |
| 61 |
name: "y" |
| 62 |
}] |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
}`, |
| 67 |
gvr: deploymentGVR, |
| 68 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{ |
| 69 |
Template: corev1.PodTemplateSpec{ |
| 70 |
Spec: corev1.PodSpec{ |
| 71 |
Volumes: []corev1.Volume{{Name: "x"}}, |
| 72 |
}, |
| 73 |
}, |
| 74 |
}}, |
| 75 |
expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{ |
| 76 |
Template: corev1.PodTemplateSpec{ |
| 77 |
Spec: corev1.PodSpec{ |
| 78 |
Volumes: []corev1.Volume{{Name: "x"}, {Name: "y"}}, |
| 79 |
}, |
| 80 |
}, |
| 81 |
}}, |
| 82 |
}, |
| 83 |
{ |
| 84 |
name: "apply configuration update listType=map entry", |
| 85 |
expression: `Object{ |
| 86 |
spec: Object.spec{ |
| 87 |
template: Object.spec.template{ |
| 88 |
spec: Object.spec.template.spec{ |
| 89 |
volumes: [Object.spec.template.spec.volumes{ |
| 90 |
name: "y", |
| 91 |
hostPath: Object.spec.template.spec.volumes.hostPath{ |
| 92 |
path: "a" |
| 93 |
} |
| 94 |
}] |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
}`, |
| 99 |
gvr: deploymentGVR, |
| 100 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{ |
| 101 |
Template: corev1.PodTemplateSpec{ |
| 102 |
Spec: corev1.PodSpec{ |
| 103 |
Volumes: []corev1.Volume{{Name: "x"}, {Name: "y"}}, |
| 104 |
}, |
| 105 |
}, |
| 106 |
}}, |
| 107 |
expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{ |
| 108 |
Template: corev1.PodTemplateSpec{ |
| 109 |
Spec: corev1.PodSpec{ |
| 110 |
Volumes: []corev1.Volume{{Name: "x"}, {Name: "y", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "a"}}}}, |
| 111 |
}, |
| 112 |
}, |
| 113 |
}}, |
| 114 |
}, |
| 115 |
{ |
| 116 |
name: "apply configuration with conditionals", |
| 117 |
expression: `Object{ |
| 118 |
spec: Object.spec{ |
| 119 |
replicas: object.spec.replicas % 2 == 0?object.spec.replicas + 1:object.spec.replicas |
| 120 |
} |
| 121 |
}`, |
| 122 |
gvr: deploymentGVR, |
| 123 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](2)}}, |
| 124 |
expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](3)}}, |
| 125 |
}, |
| 126 |
{ |
| 127 |
name: "apply configuration with old object", |
| 128 |
expression: `Object{ |
| 129 |
spec: Object.spec{ |
| 130 |
replicas: oldObject.spec.replicas % 2 == 0?oldObject.spec.replicas + 1:oldObject.spec.replicas |
| 131 |
} |
| 132 |
}`, |
| 133 |
gvr: deploymentGVR, |
| 134 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}}, |
| 135 |
oldObject: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](2)}}, |
| 136 |
expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](3)}}, |
| 137 |
}, |
| 138 |
{ |
| 139 |
name: "complex apply configuration initialization", |
| 140 |
expression: `Object{ |
| 141 |
spec: Object.spec{ |
| 142 |
replicas: 1, |
| 143 |
template: Object.spec.template{ |
| 144 |
metadata: Object.spec.template.metadata{ |
| 145 |
labels: {"app": "nginx"} |
| 146 |
}, |
| 147 |
spec: Object.spec.template.spec{ |
| 148 |
containers: [Object.spec.template.spec.containers{ |
| 149 |
name: "nginx", |
| 150 |
image: "nginx:1.14.2", |
| 151 |
ports: [Object.spec.template.spec.containers.ports{ |
| 152 |
containerPort: 80 |
| 153 |
}], |
| 154 |
resources: Object.spec.template.spec.containers.resources{ |
| 155 |
limits: {"cpu": "128M"}, |
| 156 |
} |
| 157 |
}] |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
}`, |
| 162 |
|
| 163 |
gvr: deploymentGVR, |
| 164 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{}}, |
| 165 |
expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{ |
| 166 |
Replicas: ptr.To[int32](1), |
| 167 |
Template: corev1.PodTemplateSpec{ |
| 168 |
ObjectMeta: metav1.ObjectMeta{ |
| 169 |
Labels: map[string]string{"app": "nginx"}, |
| 170 |
}, |
| 171 |
Spec: corev1.PodSpec{ |
| 172 |
Containers: []corev1.Container{{ |
| 173 |
Name: "nginx", |
| 174 |
Image: "nginx:1.14.2", |
| 175 |
Ports: []corev1.ContainerPort{ |
| 176 |
{ContainerPort: 80}, |
| 177 |
}, |
| 178 |
Resources: corev1.ResourceRequirements{ |
| 179 |
Limits: corev1.ResourceList{corev1.ResourceName("cpu"): resource.MustParse("128M")}, |
| 180 |
}, |
| 181 |
}}, |
| 182 |
}, |
| 183 |
}, |
| 184 |
}}, |
| 185 |
}, |
| 186 |
{ |
| 187 |
name: "apply configuration with change to atomic", |
| 188 |
expression: `Object{ |
| 189 |
spec: Object.spec{ |
| 190 |
selector: Object.spec.selector{ |
| 191 |
matchLabels: {"l": "v"} |
| 192 |
} |
| 193 |
} |
| 194 |
}`, |
| 195 |
gvr: deploymentGVR, |
| 196 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}}, |
| 197 |
expectedErr: "error applying patch: invalid ApplyConfiguration: may not mutate atomic arrays, maps or structs: .spec.selector", |
| 198 |
}, |
| 199 |
{ |
| 200 |
name: "apply configuration with invalid type name", |
| 201 |
expression: `Object{ |
| 202 |
spec: Object.specx{ |
| 203 |
replicas: 1 |
| 204 |
} |
| 205 |
}`, |
| 206 |
gvr: deploymentGVR, |
| 207 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}}, |
| 208 |
expectedErr: "type mismatch: unexpected type name \"Object.specx\", expected \"Object.spec\", which matches field name path from root Object type", |
| 209 |
}, |
| 210 |
{ |
| 211 |
name: "apply configuration with invalid field name", |
| 212 |
expression: `Object{ |
| 213 |
spec: Object.spec{ |
| 214 |
replicasx: 1 |
| 215 |
} |
| 216 |
}`, |
| 217 |
gvr: deploymentGVR, |
| 218 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}}, |
| 219 |
expectedErr: "error applying patch: failed to convert patch object to typed object: .spec.replicasx: field not declared in schema", |
| 220 |
}, |
| 221 |
{ |
| 222 |
name: "apply configuration with invalid return type", |
| 223 |
expression: `"I'm a teapot!"`, |
| 224 |
gvr: deploymentGVR, |
| 225 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}}, |
| 226 |
expectedErr: "must evaluate to Object but got string", |
| 227 |
}, |
| 228 |
{ |
| 229 |
name: "apply configuration with invalid initializer return type", |
| 230 |
expression: `Object.spec.metadata{}`, |
| 231 |
gvr: deploymentGVR, |
| 232 |
object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}}, |
| 233 |
expectedErr: "must evaluate to Object but got Object.spec.metadata", |
| 234 |
}, |
| 235 |
} |
| 236 |
|
| 237 |
compiler, err := cel.NewCompositedCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion(), true)) |
| 238 |
if err != nil { |
| 239 |
t.Fatal(err) |
| 240 |
} |
| 241 |
|
| 242 |
ctx, cancel := context.WithCancel(context.Background()) |
| 243 |
defer cancel() |
| 244 |
tcManager := NewTypeConverterManager(nil, openapitest.NewEmbeddedFileClient()) |
| 245 |
go tcManager.Run(ctx) |
| 246 |
|
| 247 |
err = wait.PollUntilContextTimeout(ctx, 100*time.Millisecond, time.Second, true, func(context.Context) (done bool, err error) { |
| 248 |
converter := tcManager.GetTypeConverter(deploymentGVK) |
| 249 |
return converter != nil, nil |
| 250 |
}) |
| 251 |
if err != nil { |
| 252 |
t.Fatal(err) |
| 253 |
} |
| 254 |
|
| 255 |
for _, tc := range tests { |
| 256 |
t.Run(tc.name, func(t *testing.T) { |
| 257 |
accessor := &ApplyConfigurationCondition{Expression: tc.expression} |
| 258 |
compileResult := compiler.CompileMutatingEvaluator(accessor, cel.OptionalVariableDeclarations{StrictCost: true, HasPatchTypes: true}, environment.StoredExpressions) |
| 259 |
|
| 260 |
patcher := applyConfigPatcher{expressionEvaluator: compileResult} |
| 261 |
|
| 262 |
scheme := runtime.NewScheme() |
| 263 |
err := appsv1.AddToScheme(scheme) |
| 264 |
if err != nil { |
| 265 |
t.Fatal(err) |
| 266 |
} |
| 267 |
|
| 268 |
var gvk schema.GroupVersionKind |
| 269 |
gvks, _, err := scheme.ObjectKinds(tc.object) |
| 270 |
if err != nil { |
| 271 |
t.Fatal(err) |
| 272 |
} |
| 273 |
if len(gvks) == 1 { |
| 274 |
gvk = gvks[0] |
| 275 |
} else { |
| 276 |
t.Fatalf("Failed to find gvk for type: %T", tc.object) |
| 277 |
} |
| 278 |
|
| 279 |
metaAccessor, err := meta.Accessor(tc.object) |
| 280 |
if err != nil { |
| 281 |
t.Fatal(err) |
| 282 |
} |
| 283 |
|
| 284 |
typeAccessor, err := meta.TypeAccessor(tc.object) |
| 285 |
if err != nil { |
| 286 |
t.Fatal(err) |
| 287 |
} |
| 288 |
typeAccessor.SetKind(gvk.Kind) |
| 289 |
typeAccessor.SetAPIVersion(gvk.GroupVersion().String()) |
| 290 |
|
| 291 |
attrs := admission.NewAttributesRecord(tc.object, tc.oldObject, gvk, |
| 292 |
metaAccessor.GetNamespace(), metaAccessor.GetName(), tc.gvr, |
| 293 |
"", admission.Create, &metav1.CreateOptions{}, false, nil) |
| 294 |
vAttrs := &admission.VersionedAttributes{ |
| 295 |
Attributes: attrs, |
| 296 |
VersionedKind: gvk, |
| 297 |
VersionedObject: tc.object, |
| 298 |
VersionedOldObject: tc.oldObject, |
| 299 |
} |
| 300 |
|
| 301 |
r := Request{ |
| 302 |
MatchedResource: tc.gvr, |
| 303 |
VersionedAttributes: vAttrs, |
| 304 |
ObjectInterfaces: admission.NewObjectInterfacesFromScheme(scheme), |
| 305 |
OptionalVariables: cel.OptionalVariableBindings{}, |
| 306 |
TypeConverter: tcManager.GetTypeConverter(gvk), |
| 307 |
} |
| 308 |
|
| 309 |
patched, err := patcher.Patch(ctx, r, celconfig.RuntimeCELCostBudget) |
| 310 |
if len(tc.expectedErr) > 0 { |
| 311 |
if err == nil { |
| 312 |
t.Fatalf("expected error: %s", tc.expectedErr) |
| 313 |
} else { |
| 314 |
if !strings.Contains(err.Error(), tc.expectedErr) { |
| 315 |
t.Fatalf("expected error: %s, got: %s", tc.expectedErr, err.Error()) |
| 316 |
} |
| 317 |
return |
| 318 |
} |
| 319 |
} |
| 320 |
if err != nil && len(tc.expectedErr) == 0 { |
| 321 |
t.Fatalf("unexpected error: %v", err) |
| 322 |
} |
| 323 |
|
| 324 |
got, err := runtime.DefaultUnstructuredConverter.ToUnstructured(patched) |
| 325 |
if err != nil { |
| 326 |
t.Fatal(err) |
| 327 |
} |
| 328 |
|
| 329 |
wantTypeAccessor, err := meta.TypeAccessor(tc.expectedResult) |
| 330 |
if err != nil { |
| 331 |
t.Fatal(err) |
| 332 |
} |
| 333 |
wantTypeAccessor.SetKind(gvk.Kind) |
| 334 |
wantTypeAccessor.SetAPIVersion(gvk.GroupVersion().String()) |
| 335 |
|
| 336 |
want, err := runtime.DefaultUnstructuredConverter.ToUnstructured(tc.expectedResult) |
| 337 |
|
| 338 |
if err != nil { |
| 339 |
t.Fatal(err) |
| 340 |
} |
| 341 |
if !equality.Semantic.DeepEqual(want, got) { |
| 342 |
t.Errorf("unexpected result, got diff:\n%s\n", cmp.Diff(want, got)) |
| 343 |
} |
| 344 |
}) |
| 345 |
} |
| 346 |
} |