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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
|
/*
Copyright 2014 The Kubernetes 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 handlers
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"testing"
"time"
jsonpatch "github.com/evanphx/json-patch"
fuzz "github.com/google/gofuzz"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
testapigroupv1 "k8s.io/apimachinery/pkg/apis/testapigroup/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/apimachinery/pkg/util/json"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/apis/example"
examplev1 "k8s.io/apiserver/pkg/apis/example/v1"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
utiltrace "k8s.io/utils/trace"
)
var (
scheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(scheme)
)
func init() {
metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion)
utilruntime.Must(example.AddToScheme(scheme))
utilruntime.Must(examplev1.AddToScheme(scheme))
}
type testPatchType struct {
metav1.TypeMeta `json:",inline"`
TestPatchSubType `json:",inline"`
}
// We explicitly make it public as private types doesn't
// work correctly with json inlined types.
type TestPatchSubType struct {
StringField string `json:"theField"`
}
func (obj *testPatchType) DeepCopyObject() runtime.Object {
if obj == nil {
return nil
}
clone := *obj
return &clone
}
func TestPatchAnonymousField(t *testing.T) {
testGV := schema.GroupVersion{Group: "", Version: "v"}
scheme.AddKnownTypes(testGV, &testPatchType{})
defaulter := runtime.ObjectDefaulter(scheme)
original := &testPatchType{
TypeMeta: metav1.TypeMeta{Kind: "testPatchType", APIVersion: "v"},
TestPatchSubType: TestPatchSubType{StringField: "my-value"},
}
patch := `{"theField": "changed!"}`
expected := &testPatchType{
TypeMeta: metav1.TypeMeta{Kind: "testPatchType", APIVersion: "v"},
TestPatchSubType: TestPatchSubType{StringField: "changed!"},
}
actual := &testPatchType{}
err := strategicPatchObject(defaulter, original, []byte(patch), actual, &testPatchType{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !apiequality.Semantic.DeepEqual(actual, expected) {
t.Errorf("expected %#v, got %#v", expected, actual)
}
}
func TestStrategicMergePatchInvalid(t *testing.T) {
testGV := schema.GroupVersion{Group: "", Version: "v"}
scheme.AddKnownTypes(testGV, &testPatchType{})
defaulter := runtime.ObjectDefaulter(scheme)
original := &testPatchType{
TypeMeta: metav1.TypeMeta{Kind: "testPatchType", APIVersion: "v"},
TestPatchSubType: TestPatchSubType{StringField: "my-value"},
}
patch := `barbaz`
expectedError := "invalid character 'b' looking for beginning of value"
actual := &testPatchType{}
err := strategicPatchObject(defaulter, original, []byte(patch), actual, &testPatchType{})
if !apierrors.IsBadRequest(err) {
t.Errorf("expected HTTP status: BadRequest, got: %#v", apierrors.ReasonForError(err))
}
if err.Error() != expectedError {
t.Errorf("expected %#v, got %#v", expectedError, err.Error())
}
}
func TestJSONPatch(t *testing.T) {
for _, test := range []struct {
name string
patch string
expectedError string
expectedErrorType metav1.StatusReason
}{
{
name: "valid",
patch: `[{"op": "test", "value": "podA", "path": "/metadata/name"}]`,
},
{
name: "invalid-syntax",
patch: `invalid json patch`,
expectedError: "invalid character 'i' looking for beginning of value",
expectedErrorType: metav1.StatusReasonBadRequest,
},
{
name: "invalid-semantics",
patch: `[{"op": "test", "value": "podA", "path": "/invalid/path"}]`,
expectedError: "the server rejected our request due to an error in our request",
expectedErrorType: metav1.StatusReasonInvalid,
},
} {
p := &patcher{
patchType: types.JSONPatchType,
patchBytes: []byte(test.patch),
}
jp := jsonPatcher{patcher: p}
codec := codecs.LegacyCodec(examplev1.SchemeGroupVersion)
pod := &examplev1.Pod{}
pod.Name = "podA"
versionedJS, err := runtime.Encode(codec, pod)
if err != nil {
t.Errorf("%s: unexpected error: %v", test.name, err)
continue
}
_, err = jp.applyJSPatch(versionedJS)
if err != nil {
if len(test.expectedError) == 0 {
t.Errorf("%s: expect no error when applying json patch, but got %v", test.name, err)
continue
}
if err.Error() != test.expectedError {
t.Errorf("%s: expected error %v, but got %v", test.name, test.expectedError, err)
}
if test.expectedErrorType != apierrors.ReasonForError(err) {
t.Errorf("%s: expected error type %v, but got %v", test.name, test.expectedErrorType, apierrors.ReasonForError(err))
}
} else if len(test.expectedError) > 0 {
t.Errorf("%s: expected err %s", test.name, test.expectedError)
}
}
}
func TestPatchCustomResource(t *testing.T) {
testGV := schema.GroupVersion{Group: "mygroup.example.com", Version: "v1beta1"}
scheme.AddKnownTypes(testGV, &unstructured.Unstructured{})
defaulter := runtime.ObjectDefaulter(scheme)
original := &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "mygroup.example.com/v1beta1",
"kind": "Noxu",
"metadata": map[string]interface{}{
"namespace": "Namespaced",
"name": "foo",
},
"spec": map[string]interface{}{
"num": "10",
},
},
}
patch := `{"spec":{"num":"20"}}`
expectedError := "strategic merge patch format is not supported"
actual := &unstructured.Unstructured{}
err := strategicPatchObject(defaulter, original, []byte(patch), actual, &unstructured.Unstructured{})
if !apierrors.IsBadRequest(err) {
t.Errorf("expected HTTP status: BadRequest, got: %#v", apierrors.ReasonForError(err))
}
if err.Error() != expectedError {
t.Errorf("expected %#v, got %#v", expectedError, err.Error())
}
}
type testPatcher struct {
t *testing.T
// startingPod is used for the first Update
startingPod *example.Pod
// updatePod is the pod that is used for conflict comparison and used for subsequent Update calls
updatePod *example.Pod
numUpdates int
}
func (p *testPatcher) New() runtime.Object {
return &example.Pod{}
}
func (p *testPatcher) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
// Simulate GuaranteedUpdate behavior (retries internally on etcd changes if the incoming resource doesn't pin resourceVersion)
for {
currentPod := p.startingPod
if p.numUpdates > 0 {
currentPod = p.updatePod
}
p.numUpdates++
// Remember the current resource version
currentResourceVersion := currentPod.ResourceVersion
obj, err := objInfo.UpdatedObject(ctx, currentPod)
if err != nil {
return nil, false, err
}
inPod := obj.(*example.Pod)
if inPod.ResourceVersion == "" || inPod.ResourceVersion == "0" {
inPod.ResourceVersion = p.updatePod.ResourceVersion
}
if inPod.ResourceVersion != p.updatePod.ResourceVersion {
// If the patch didn't have an opinion on the resource version, retry like GuaranteedUpdate does
if inPod.ResourceVersion == currentResourceVersion {
continue
}
// If the patch changed the resource version and it mismatches, conflict
return nil, false, apierrors.NewConflict(example.Resource("pods"), inPod.Name, fmt.Errorf("existing %v, new %v", p.updatePod.ResourceVersion, inPod.ResourceVersion))
}
if currentPod == nil {
if err := createValidation(ctx, currentPod); err != nil {
return nil, false, err
}
} else {
if err := updateValidation(ctx, currentPod, inPod); err != nil {
return nil, false, err
}
}
return inPod, false, nil
}
}
func (p *testPatcher) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
p.t.Fatal("Unexpected call to testPatcher.Get")
return nil, errors.New("Unexpected call to testPatcher.Get")
}
type testNamer struct {
namespace string
name string
}
func (p *testNamer) Namespace(req *http.Request) (namespace string, err error) {
return p.namespace, nil
}
// Name returns the name from the request, and an optional namespace value if this is a namespace
// scoped call. An error is returned if the name is not available.
func (p *testNamer) Name(req *http.Request) (namespace, name string, err error) {
return p.namespace, p.name, nil
}
// ObjectName returns the namespace and name from an object if they exist, or an error if the object
// does not support names.
func (p *testNamer) ObjectName(obj runtime.Object) (namespace, name string, err error) {
return p.namespace, p.name, nil
}
// SetSelfLink sets the provided URL onto the object. The method should return nil if the object
// does not support selfLinks.
func (p *testNamer) SetSelfLink(obj runtime.Object, url string) error {
return errors.New("not implemented")
}
// GenerateLink creates a path and query for a given runtime object that represents the canonical path.
func (p *testNamer) GenerateLink(requestInfo *request.RequestInfo, obj runtime.Object) (uri string, err error) {
return "", errors.New("not implemented")
}
// GenerateListLink creates a path and query for a list that represents the canonical path.
func (p *testNamer) GenerateListLink(req *http.Request) (uri string, err error) {
return "", errors.New("not implemented")
}
type patchTestCase struct {
name string
// admission chain to use, nil is fine
admissionMutation mutateObjectUpdateFunc
admissionValidation rest.ValidateObjectUpdateFunc
// startingPod is used as the starting point for the first Update
startingPod *example.Pod
// changedPod can be set as the "destination" pod for the patch, and the test will compute a patch from the startingPod to the changedPod,
// or patches can be set directly using strategicMergePatch, mergePatch, and jsonPatch
changedPod *example.Pod
strategicMergePatch string
mergePatch string
jsonPatch string
// updatePod is the pod that is used for conflict comparison and as the starting point for the second Update
updatePod *example.Pod
// expectedPod is the pod that you expect to get back after the patch is complete
expectedPod *example.Pod
expectedError string
// if set, indicates the number of times patching was expected to be attempted
expectedTries int
}
func (tc *patchTestCase) Run(t *testing.T) {
t.Logf("Starting test %s", tc.name)
namespace := tc.startingPod.Namespace
name := tc.startingPod.Name
codec := codecs.LegacyCodec(examplev1.SchemeGroupVersion)
admissionMutation := tc.admissionMutation
if admissionMutation == nil {
admissionMutation = func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return nil
}
}
admissionValidation := tc.admissionValidation
if admissionValidation == nil {
admissionValidation = func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return nil
}
}
ctx := request.NewDefaultContext()
ctx = request.WithNamespace(ctx, namespace)
namer := &testNamer{namespace, name}
creater := runtime.ObjectCreater(scheme)
defaulter := runtime.ObjectDefaulter(scheme)
convertor := runtime.UnsafeObjectConvertor(scheme)
objectInterfaces := admission.NewObjectInterfacesFromScheme(scheme)
kind := examplev1.SchemeGroupVersion.WithKind("Pod")
resource := examplev1.SchemeGroupVersion.WithResource("pods")
schemaReferenceObj := &examplev1.Pod{}
hubVersion := example.SchemeGroupVersion
for _, patchType := range []types.PatchType{types.JSONPatchType, types.MergePatchType, types.StrategicMergePatchType} {
// This needs to be reset on each iteration.
testPatcher := &testPatcher{
t: t,
startingPod: tc.startingPod,
updatePod: tc.updatePod,
}
t.Logf("Working with patchType %v", patchType)
patch := []byte{}
switch patchType {
case types.StrategicMergePatchType:
patch = []byte(tc.strategicMergePatch)
if len(patch) == 0 {
originalObjJS, err := runtime.Encode(codec, tc.startingPod)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
changedJS, err := runtime.Encode(codec, tc.changedPod)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
patch, err = strategicpatch.CreateTwoWayMergePatch(originalObjJS, changedJS, schemaReferenceObj)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
}
case types.MergePatchType:
patch = []byte(tc.mergePatch)
if len(patch) == 0 {
originalObjJS, err := runtime.Encode(codec, tc.startingPod)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
changedJS, err := runtime.Encode(codec, tc.changedPod)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
patch, err = jsonpatch.CreateMergePatch(originalObjJS, changedJS)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
}
case types.JSONPatchType:
patch = []byte(tc.jsonPatch)
if len(patch) == 0 {
// TODO SUPPORT THIS!
continue
}
default:
t.Error("unsupported patch type")
}
p := patcher{
namer: namer,
creater: creater,
defaulter: defaulter,
unsafeConvertor: convertor,
kind: kind,
resource: resource,
objectInterfaces: objectInterfaces,
hubGroupVersion: hubVersion,
createValidation: rest.ValidateAllObjectFunc,
updateValidation: admissionValidation,
admissionCheck: admissionMutation,
codec: codec,
timeout: 1 * time.Second,
restPatcher: testPatcher,
name: name,
patchType: patchType,
patchBytes: patch,
trace: utiltrace.New("Patch", utiltrace.Field{"name", name}),
}
resultObj, _, err := p.patchResource(ctx, &RequestScope{})
if len(tc.expectedError) != 0 {
if err == nil || err.Error() != tc.expectedError {
t.Errorf("%s: expected error %v, but got %v", tc.name, tc.expectedError, err)
continue
}
} else {
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
}
if tc.expectedTries > 0 {
if tc.expectedTries != testPatcher.numUpdates {
t.Errorf("%s: expected %d tries, got %d", tc.name, tc.expectedTries, testPatcher.numUpdates)
}
}
if tc.expectedPod == nil {
if resultObj != nil {
t.Errorf("%s: unexpected result: %v", tc.name, resultObj)
}
continue
}
resultPod := resultObj.(*example.Pod)
// roundtrip to get defaulting
expectedJS, err := runtime.Encode(codec, tc.expectedPod)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
expectedObj, err := runtime.Decode(codec, expectedJS)
if err != nil {
t.Errorf("%s: unexpected error: %v", tc.name, err)
continue
}
reallyExpectedPod := expectedObj.(*example.Pod)
if !reflect.DeepEqual(*reallyExpectedPod, *resultPod) {
t.Errorf("%s mismatch: %v\n", tc.name, diff.ObjectGoPrintDiff(reallyExpectedPod, resultPod))
continue
}
}
}
func TestNumberConversion(t *testing.T) {
defaulter := runtime.ObjectDefaulter(scheme)
terminationGracePeriodSeconds := int64(42)
activeDeadlineSeconds := int64(42)
currentVersionedObject := &examplev1.Pod{
TypeMeta: metav1.TypeMeta{Kind: "Example", APIVersion: examplev1.SchemeGroupVersion.String()},
ObjectMeta: metav1.ObjectMeta{Name: "test-example"},
Spec: examplev1.PodSpec{
TerminationGracePeriodSeconds: &terminationGracePeriodSeconds,
ActiveDeadlineSeconds: &activeDeadlineSeconds,
},
}
versionedObjToUpdate := &examplev1.Pod{}
schemaReferenceObj := &examplev1.Pod{}
patchJS := []byte(`{"spec":{"terminationGracePeriodSeconds":42,"activeDeadlineSeconds":120}}`)
err := strategicPatchObject(defaulter, currentVersionedObject, patchJS, versionedObjToUpdate, schemaReferenceObj)
if err != nil {
t.Fatal(err)
}
if versionedObjToUpdate.Spec.TerminationGracePeriodSeconds == nil || *versionedObjToUpdate.Spec.TerminationGracePeriodSeconds != 42 ||
versionedObjToUpdate.Spec.ActiveDeadlineSeconds == nil || *versionedObjToUpdate.Spec.ActiveDeadlineSeconds != 120 {
t.Fatal(errors.New("Ports failed to merge because of number conversion issue"))
}
}
func TestPatchResourceNumberConversion(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
fifteen := int64(15)
thirty := int64(30)
tc := &patchTestCase{
name: "TestPatchResourceNumberConversion",
startingPod: &example.Pod{},
changedPod: &example.Pod{},
updatePod: &example.Pod{},
expectedPod: &example.Pod{},
}
setTcPod(tc.startingPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &fifteen, "")
// Patch tries to change to 30.
setTcPod(tc.changedPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &thirty, "")
// Someone else already changed it to 30.
// This should be fine since it's not a "meaningful conflict".
// Previously this was detected as a meaningful conflict because int64(30) != float64(30).
setTcPod(tc.updatePod, name, namespace, uid, "2", examplev1.SchemeGroupVersion.String(), &thirty, "anywhere")
setTcPod(tc.expectedPod, name, namespace, uid, "2", "", &thirty, "anywhere")
tc.Run(t)
}
func TestPatchResourceWithVersionConflict(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
fifteen := int64(15)
thirty := int64(30)
tc := &patchTestCase{
name: "TestPatchResourceWithVersionConflict",
startingPod: &example.Pod{},
changedPod: &example.Pod{},
updatePod: &example.Pod{},
expectedPod: &example.Pod{},
}
setTcPod(tc.startingPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &fifteen, "")
setTcPod(tc.changedPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &thirty, "")
setTcPod(tc.updatePod, name, namespace, uid, "2", examplev1.SchemeGroupVersion.String(), &fifteen, "anywhere")
setTcPod(tc.expectedPod, name, namespace, uid, "2", "", &thirty, "anywhere")
tc.Run(t)
}
func TestPatchResourceWithStaleVersionConflict(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
tc := &patchTestCase{
name: "TestPatchResourceWithStaleVersionConflict",
startingPod: &example.Pod{},
updatePod: &example.Pod{},
expectedError: `Operation cannot be fulfilled on pods.example.apiserver.k8s.io "foo": existing 2, new 1`,
expectedTries: 1,
}
// starting pod is at rv=2
tc.startingPod.Name = name
tc.startingPod.Namespace = namespace
tc.startingPod.UID = uid
tc.startingPod.ResourceVersion = "2"
tc.startingPod.APIVersion = examplev1.SchemeGroupVersion.String()
// same pod is still in place when attempting to persist the update
tc.updatePod = tc.startingPod
// patches are submitted with a stale rv=1
tc.mergePatch = `{"metadata":{"resourceVersion":"1"},"spec":{"nodeName":"foo"}}`
tc.strategicMergePatch = `{"metadata":{"resourceVersion":"1"},"spec":{"nodeName":"foo"}}`
tc.Run(t)
}
func TestPatchResourceWithRacingVersionConflict(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
tc := &patchTestCase{
name: "TestPatchResourceWithRacingVersionConflict",
startingPod: &example.Pod{},
updatePod: &example.Pod{},
expectedError: `Operation cannot be fulfilled on pods.example.apiserver.k8s.io "foo": existing 3, new 2`,
expectedTries: 2,
}
// starting pod is at rv=2
tc.startingPod.Name = name
tc.startingPod.Namespace = namespace
tc.startingPod.UID = uid
tc.startingPod.ResourceVersion = "2"
tc.startingPod.APIVersion = examplev1.SchemeGroupVersion.String()
// pod with rv=3 is found when attempting to persist the update
tc.updatePod.Name = name
tc.updatePod.Namespace = namespace
tc.updatePod.UID = uid
tc.updatePod.ResourceVersion = "3"
tc.updatePod.APIVersion = examplev1.SchemeGroupVersion.String()
// patches are submitted with a rv=2
tc.mergePatch = `{"metadata":{"resourceVersion":"2"},"spec":{"nodeName":"foo"}}`
tc.strategicMergePatch = `{"metadata":{"resourceVersion":"2"},"spec":{"nodeName":"foo"}}`
tc.Run(t)
}
func TestPatchResourceWithConflict(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
tc := &patchTestCase{
name: "TestPatchResourceWithConflict",
startingPod: &example.Pod{},
changedPod: &example.Pod{},
updatePod: &example.Pod{},
expectedPod: &example.Pod{},
}
// See issue #63104 for discussion of how much sense this makes.
setTcPod(tc.startingPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), nil, "here")
setTcPod(tc.changedPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), nil, "there")
setTcPod(tc.updatePod, name, namespace, uid, "2", examplev1.SchemeGroupVersion.String(), nil, "anywhere")
tc.expectedPod.Name = name
tc.expectedPod.Namespace = namespace
tc.expectedPod.UID = uid
tc.expectedPod.ResourceVersion = "2"
tc.expectedPod.APIVersion = examplev1.SchemeGroupVersion.String()
tc.expectedPod.Spec.NodeName = "there"
tc.Run(t)
}
func TestPatchWithAdmissionRejection(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
fifteen := int64(15)
thirty := int64(30)
type Test struct {
name string
admissionMutation mutateObjectUpdateFunc
admissionValidation rest.ValidateObjectUpdateFunc
expectedError string
}
for _, test := range []Test{
{
name: "TestPatchWithMutatingAdmissionRejection",
admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("mutating admission failure")
},
admissionValidation: rest.ValidateAllObjectUpdateFunc,
expectedError: "mutating admission failure",
},
{
name: "TestPatchWithValidatingAdmissionRejection",
admissionMutation: rest.ValidateAllObjectUpdateFunc,
admissionValidation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("validating admission failure")
},
expectedError: "validating admission failure",
},
{
name: "TestPatchWithBothAdmissionRejections",
admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("mutating admission failure")
},
admissionValidation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("validating admission failure")
},
expectedError: "mutating admission failure",
},
} {
tc := &patchTestCase{
name: test.name,
admissionMutation: test.admissionMutation,
admissionValidation: test.admissionValidation,
startingPod: &example.Pod{},
changedPod: &example.Pod{},
updatePod: &example.Pod{},
expectedError: test.expectedError,
}
setTcPod(tc.startingPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &fifteen, "")
setTcPod(tc.changedPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &thirty, "")
setTcPod(tc.updatePod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &fifteen, "")
tc.Run(t)
}
}
func TestPatchWithVersionConflictThenAdmissionFailure(t *testing.T) {
namespace := "bar"
name := "foo"
uid := types.UID("uid")
fifteen := int64(15)
thirty := int64(30)
seen := false
tc := &patchTestCase{
name: "TestPatchWithVersionConflictThenAdmissionFailure",
admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
if seen {
return errors.New("admission failure")
}
seen = true
return nil
},
startingPod: &example.Pod{},
changedPod: &example.Pod{},
updatePod: &example.Pod{},
expectedError: "admission failure",
}
setTcPod(tc.startingPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &fifteen, "")
setTcPod(tc.changedPod, name, namespace, uid, "1", examplev1.SchemeGroupVersion.String(), &thirty, "")
setTcPod(tc.updatePod, name, namespace, uid, "2", examplev1.SchemeGroupVersion.String(), &fifteen, "anywhere")
tc.Run(t)
}
func TestHasUID(t *testing.T) {
testcases := []struct {
obj runtime.Object
hasUID bool
}{
{obj: nil, hasUID: false},
{obj: &example.Pod{}, hasUID: false},
{obj: nil, hasUID: false},
{obj: runtime.Object(nil), hasUID: false},
{obj: &example.Pod{ObjectMeta: metav1.ObjectMeta{UID: types.UID("A")}}, hasUID: true},
}
for i, tc := range testcases {
actual, err := hasUID(tc.obj)
if err != nil {
t.Errorf("%d: unexpected error %v", i, err)
continue
}
if tc.hasUID != actual {
t.Errorf("%d: expected %v, got %v", i, tc.hasUID, actual)
}
}
}
func TestParseTimeout(t *testing.T) {
if d := parseTimeout(""); d != 34*time.Second {
t.Errorf("blank timeout produces %v", d)
}
if d := parseTimeout("not a timeout"); d != 34*time.Second {
t.Errorf("bad timeout produces %v", d)
}
if d := parseTimeout("10s"); d != 10*time.Second {
t.Errorf("10s timeout produced: %v", d)
}
}
func TestFinishRequest(t *testing.T) {
exampleObj := &example.Pod{}
exampleErr := fmt.Errorf("error")
successStatusObj := &metav1.Status{Status: metav1.StatusSuccess, Message: "success message"}
errorStatusObj := &metav1.Status{Status: metav1.StatusFailure, Message: "error message"}
testcases := []struct {
name string
timeout time.Duration
fn resultFunc
expectedObj runtime.Object
expectedErr error
expectedPanic string
expectedPanicObj interface{}
}{
{
name: "Expected obj is returned",
timeout: time.Second,
fn: func() (runtime.Object, error) {
return exampleObj, nil
},
expectedObj: exampleObj,
expectedErr: nil,
},
{
name: "Expected error is returned",
timeout: time.Second,
fn: func() (runtime.Object, error) {
return nil, exampleErr
},
expectedObj: nil,
expectedErr: exampleErr,
},
{
name: "Successful status object is returned as expected",
timeout: time.Second,
fn: func() (runtime.Object, error) {
return successStatusObj, nil
},
expectedObj: successStatusObj,
expectedErr: nil,
},
{
name: "Error status object is converted to StatusError",
timeout: time.Second,
fn: func() (runtime.Object, error) {
return errorStatusObj, nil
},
expectedObj: nil,
expectedErr: apierrors.FromObject(errorStatusObj),
},
{
name: "Panic is propagated up",
timeout: time.Second,
fn: func() (runtime.Object, error) {
panic("my panic")
},
expectedObj: nil,
expectedErr: nil,
expectedPanic: "my panic",
},
{
name: "Panic is propagated with stack",
timeout: time.Second,
fn: func() (runtime.Object, error) {
panic("my panic")
},
expectedObj: nil,
expectedErr: nil,
expectedPanic: "rest_test.go",
},
{
name: "http.ErrAbortHandler panic is propagated without wrapping with stack",
timeout: time.Second,
fn: func() (runtime.Object, error) {
panic(http.ErrAbortHandler)
},
expectedObj: nil,
expectedErr: nil,
expectedPanic: http.ErrAbortHandler.Error(),
expectedPanicObj: http.ErrAbortHandler,
},
}
for i, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
defer func() {
r := recover()
switch {
case r == nil && len(tc.expectedPanic) > 0:
t.Errorf("expected panic containing '%s', got none", tc.expectedPanic)
case r != nil && len(tc.expectedPanic) == 0:
t.Errorf("unexpected panic: %v", r)
case r != nil && len(tc.expectedPanic) > 0 && !strings.Contains(fmt.Sprintf("%v", r), tc.expectedPanic):
t.Errorf("expected panic containing '%s', got '%v'", tc.expectedPanic, r)
}
if tc.expectedPanicObj != nil && !reflect.DeepEqual(tc.expectedPanicObj, r) {
t.Errorf("expected panic obj %#v, got %#v", tc.expectedPanicObj, r)
}
}()
obj, err := finishRequest(tc.timeout, tc.fn)
if (err == nil && tc.expectedErr != nil) || (err != nil && tc.expectedErr == nil) || (err != nil && tc.expectedErr != nil && err.Error() != tc.expectedErr.Error()) {
t.Errorf("%d: unexpected err. expected: %v, got: %v", i, tc.expectedErr, err)
}
if !apiequality.Semantic.DeepEqual(obj, tc.expectedObj) {
t.Errorf("%d: unexpected obj. expected %#v, got %#v", i, tc.expectedObj, obj)
}
})
}
}
func setTcPod(tcPod *example.Pod, name string, namespace string, uid types.UID, resourceVersion string, apiVersion string, activeDeadlineSeconds *int64, nodeName string) {
tcPod.Name = name
tcPod.Namespace = namespace
tcPod.UID = uid
tcPod.ResourceVersion = resourceVersion
if len(apiVersion) != 0 {
tcPod.APIVersion = apiVersion
}
if activeDeadlineSeconds != nil {
tcPod.Spec.ActiveDeadlineSeconds = activeDeadlineSeconds
}
if len(nodeName) != 0 {
tcPod.Spec.NodeName = nodeName
}
}
func (f mutateObjectUpdateFunc) Handles(operation admission.Operation) bool {
return true
}
func (f mutateObjectUpdateFunc) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return f(ctx, a.GetObject(), a.GetOldObject())
}
func TestTransformDecodeErrorEnsuresBadRequestError(t *testing.T) {
testCases := []struct {
name string
typer runtime.ObjectTyper
decodedGVK *schema.GroupVersionKind
decodeIntoObject runtime.Object
baseErr error
expectedErr error
}{
{
name: "decoding normal objects fails and returns a bad-request error",
typer: clientgoscheme.Scheme,
decodedGVK: &schema.GroupVersionKind{
Group: testapigroupv1.GroupName,
Version: "v1",
Kind: "Carp",
},
decodeIntoObject: &testapigroupv1.Carp{}, // which client-go's scheme doesn't recognize
baseErr: fmt.Errorf("plain error"),
},
{
name: "decoding objects with unknown GVK fails and returns a bad-request error",
typer: alwaysErrorTyper{},
decodedGVK: nil,
decodeIntoObject: &testapigroupv1.Carp{}, // which client-go's scheme doesn't recognize
baseErr: nil,
},
}
for _, testCase := range testCases {
err := transformDecodeError(testCase.typer, testCase.baseErr, testCase.decodeIntoObject, testCase.decodedGVK, []byte(``))
if apiStatus, ok := err.(apierrors.APIStatus); !ok || apiStatus.Status().Code != http.StatusBadRequest {
t.Errorf("expected bad request error but got: %v", err)
}
}
}
var _ runtime.ObjectTyper = alwaysErrorTyper{}
type alwaysErrorTyper struct{}
func (alwaysErrorTyper) ObjectKinds(runtime.Object) ([]schema.GroupVersionKind, bool, error) {
return nil, false, fmt.Errorf("always error")
}
func (alwaysErrorTyper) Recognizes(gvk schema.GroupVersionKind) bool {
return false
}
func TestUpdateToCreateOptions(t *testing.T) {
f := fuzz.New()
for i := 0; i < 100; i++ {
t.Run(fmt.Sprintf("Run %d/100", i), func(t *testing.T) {
update := &metav1.UpdateOptions{}
f.Fuzz(update)
create := updateToCreateOptions(update)
b, err := json.Marshal(create)
if err != nil {
t.Fatalf("failed to marshal CreateOptions (%v): %v", err, create)
}
got := &metav1.UpdateOptions{}
err = json.Unmarshal(b, &got)
if err != nil {
t.Fatalf("failed to unmarshal UpdateOptions: %v", err)
}
got.TypeMeta = metav1.TypeMeta{}
update.TypeMeta = metav1.TypeMeta{}
if !reflect.DeepEqual(*update, *got) {
t.Fatalf(`updateToCreateOptions round-trip failed:
got: %#+v
want: %#+v`, got, update)
}
})
}
}
func TestPatchToUpdateOptions(t *testing.T) {
tests := []struct {
name string
converterFn func(po *metav1.PatchOptions) interface{}
}{
{
name: "patchToUpdateOptions",
converterFn: func(patch *metav1.PatchOptions) interface{} {
return patchToUpdateOptions(patch)
},
},
{
name: "patchToCreateOptions",
converterFn: func(patch *metav1.PatchOptions) interface{} {
return patchToCreateOptions(patch)
},
},
}
f := fuzz.New()
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
for i := 0; i < 100; i++ {
t.Run(fmt.Sprintf("Run %d/100", i), func(t *testing.T) {
patch := &metav1.PatchOptions{}
f.Fuzz(patch)
converted := test.converterFn(patch)
b, err := json.Marshal(converted)
if err != nil {
t.Fatalf("failed to marshal converted object (%v): %v", err, converted)
}
got := &metav1.PatchOptions{}
err = json.Unmarshal(b, &got)
if err != nil {
t.Fatalf("failed to unmarshal converted object: %v", err)
}
// Clear TypeMeta because we expect it to be different between the original and converted type
got.TypeMeta = metav1.TypeMeta{}
patch.TypeMeta = metav1.TypeMeta{}
// clear fields that we know belong in PatchOptions only
patch.Force = nil
if !reflect.DeepEqual(*patch, *got) {
t.Fatalf(`round-trip failed:
got: %#+v
want: %#+v`, got, converted)
}
})
}
})
}
}
func TestDedupOwnerReferences(t *testing.T) {
falseA := false
falseB := false
testCases := []struct {
name string
ownerReferences []metav1.OwnerReference
expected []metav1.OwnerReference
}{
{
name: "simple multiple duplicates",
ownerReferences: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "2",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "2",
},
},
expected: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "2",
},
},
},
{
name: "don't dedup same uid different name entries",
ownerReferences: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name1",
UID: "1",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name2",
UID: "1",
},
},
expected: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name1",
UID: "1",
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name2",
UID: "1",
},
},
},
{
name: "don't dedup same uid different API version entries",
ownerReferences: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion1",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
{
APIVersion: "customresourceVersion2",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
},
expected: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion1",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
{
APIVersion: "customresourceVersion2",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
},
},
{
name: "dedup memory-equal entries",
ownerReferences: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
},
expected: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
},
},
{
name: "dedup semantic-equal entries",
ownerReferences: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseB,
BlockOwnerDeletion: &falseB,
},
},
expected: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
},
},
{
name: "don't dedup semantic-different entries",
ownerReferences: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
},
expected: []metav1.OwnerReference{
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
Controller: &falseA,
BlockOwnerDeletion: &falseA,
},
{
APIVersion: "customresourceVersion",
Kind: "customresourceKind",
Name: "name",
UID: "1",
},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
deduped, _ := dedupOwnerReferences(tc.ownerReferences)
if !apiequality.Semantic.DeepEqual(deduped, tc.expected) {
t.Errorf("diff: %v", diff.ObjectReflectDiff(deduped, tc.expected))
}
})
}
}
|