From 61774cd7176cae0c0324d23ab20e6c6b3038153f Mon Sep 17 00:00:00 2001 From: Jordan Liggitt Date: Mon, 19 Aug 2019 10:48:08 -0400 Subject: [PATCH] Plumb context to admission Admit/Validate --- .../admission/initializer_test.go | 3 +- .../apps/deployment/storage/storage.go | 10 ++-- .../apps/deployment/storage/storage_test.go | 3 +- .../apps/replicaset/storage/storage.go | 8 +-- .../apps/statefulset/storage/storage.go | 8 +-- .../authentication/tokenreview/storage.go | 2 +- .../localsubjectaccessreview/rest.go | 2 +- .../selfsubjectaccessreview/rest.go | 2 +- .../selfsubjectrulesreview/rest.go | 2 +- .../authorization/subjectaccessreview/rest.go | 2 +- .../core/namespace/storage/storage.go | 2 +- pkg/registry/core/pod/storage/eviction.go | 2 +- pkg/registry/core/pod/storage/storage.go | 2 +- .../replicationcontroller/storage/storage.go | 7 ++- .../core/serviceaccount/storage/token.go | 2 +- .../extensions/controller/storage/storage.go | 7 ++- plugin/pkg/admission/admit/admission.go | 5 +- plugin/pkg/admission/admit/admission_test.go | 5 +- .../admission/alwayspullimages/admission.go | 5 +- .../alwayspullimages/admission_test.go | 7 ++- .../pkg/admission/antiaffinity/admission.go | 3 +- .../admission/antiaffinity/admission_test.go | 5 +- .../defaulttolerationseconds/admission.go | 3 +- .../admission_test.go | 3 +- plugin/pkg/admission/deny/admission.go | 5 +- plugin/pkg/admission/deny/admission_test.go | 3 +- .../pkg/admission/eventratelimit/admission.go | 3 +- .../eventratelimit/admission_test.go | 3 +- plugin/pkg/admission/exec/admission.go | 3 +- plugin/pkg/admission/exec/admission_test.go | 5 +- .../extendedresourcetoleration/admission.go | 3 +- .../admission_test.go | 3 +- plugin/pkg/admission/gc/gc_admission.go | 3 +- plugin/pkg/admission/gc/gc_admission_test.go | 5 +- plugin/pkg/admission/imagepolicy/admission.go | 3 +- .../admission/imagepolicy/admission_test.go | 15 ++--- plugin/pkg/admission/limitranger/admission.go | 5 +- .../admission/limitranger/admission_test.go | 19 +++--- .../namespace/autoprovision/admission.go | 3 +- .../namespace/autoprovision/admission_test.go | 11 ++-- .../admission/namespace/exists/admission.go | 3 +- .../namespace/exists/admission_test.go | 5 +- .../admission/noderestriction/admission.go | 3 +- .../noderestriction/admission_test.go | 3 +- plugin/pkg/admission/nodetaint/admission.go | 4 +- .../pkg/admission/nodetaint/admission_test.go | 4 +- .../admission/podnodeselector/admission.go | 7 ++- .../podnodeselector/admission_test.go | 5 +- plugin/pkg/admission/podpreset/admission.go | 3 +- .../pkg/admission/podpreset/admission_test.go | 3 +- .../podtolerationrestriction/admission.go | 7 ++- .../admission_test.go | 5 +- plugin/pkg/admission/priority/admission.go | 5 +- .../pkg/admission/priority/admission_test.go | 7 ++- .../pkg/admission/resourcequota/admission.go | 3 +- .../admission/resourcequota/admission_test.go | 59 ++++++++++--------- .../pkg/admission/runtimeclass/admission.go | 5 +- .../admission/runtimeclass/admission_test.go | 8 ++- .../security/podsecuritypolicy/admission.go | 5 +- .../podsecuritypolicy/admission_test.go | 9 +-- .../securitycontext/scdeny/admission.go | 3 +- .../securitycontext/scdeny/admission_test.go | 7 ++- .../pkg/admission/serviceaccount/admission.go | 9 +-- .../serviceaccount/admission_test.go | 57 +++++++++--------- .../persistentvolume/label/admission.go | 2 +- .../persistentvolume/label/admission_test.go | 2 +- .../persistentvolume/resize/admission.go | 3 +- .../persistentvolume/resize/admission_test.go | 3 +- .../storageclass/setdefault/admission.go | 3 +- .../storageclass/setdefault/admission_test.go | 3 +- .../storageobjectinuseprotection/admission.go | 3 +- .../admission_test.go | 3 +- .../pkg/registry/customresource/etcd.go | 8 +-- .../registry/customresourcedefinition/etcd.go | 2 +- .../k8s.io/apiserver/pkg/admission/audit.go | 9 +-- .../apiserver/pkg/admission/audit_test.go | 9 +-- .../k8s.io/apiserver/pkg/admission/chain.go | 10 ++-- .../apiserver/pkg/admission/chain_test.go | 9 +-- .../admission/initializer/initializer_test.go | 9 +-- .../apiserver/pkg/admission/interfaces.go | 9 ++- .../pkg/admission/metrics/metrics.go | 9 +-- .../pkg/admission/metrics/metrics_test.go | 21 +++---- .../plugin/namespace/lifecycle/admission.go | 5 +- .../namespace/lifecycle/admission_test.go | 33 ++++++----- .../plugin/webhook/generic/webhook.go | 5 +- .../plugin/webhook/mutating/plugin.go | 5 +- .../plugin/webhook/mutating/plugin_test.go | 5 +- .../plugin/webhook/validating/plugin.go | 5 +- .../plugin/webhook/validating/plugin_test.go | 5 +- .../apiserver/pkg/admission/reinvocation.go | 12 ++-- .../pkg/admission/testing/helpers.go | 5 +- .../apiserver/pkg/endpoints/apiserver_test.go | 12 ++-- .../pkg/endpoints/handlers/create.go | 2 +- .../apiserver/pkg/endpoints/handlers/patch.go | 4 +- .../apiserver/pkg/endpoints/handlers/rest.go | 4 +- .../pkg/endpoints/handlers/rest_test.go | 22 +++---- .../pkg/endpoints/handlers/update.go | 8 +-- .../pkg/registry/generic/registry/dryrun.go | 2 +- .../pkg/registry/generic/registry/store.go | 8 +-- .../registry/generic/registry/store_test.go | 6 +- .../apiserver/pkg/registry/rest/create.go | 6 +- .../apiserver/pkg/registry/rest/delete.go | 6 +- .../apiserver/pkg/registry/rest/rest.go | 8 +-- .../apiserver/pkg/registry/rest/update.go | 6 +- .../apiserver/pkg/storage/etcd3/store.go | 2 +- .../apiserver/pkg/storage/interfaces.go | 4 +- .../admission/plugin/banflunder/admission.go | 3 +- .../plugin/banflunder/admission_test.go | 3 +- .../wardleinitializer_test.go | 3 +- 109 files changed, 404 insertions(+), 323 deletions(-) diff --git a/pkg/kubeapiserver/admission/initializer_test.go b/pkg/kubeapiserver/admission/initializer_test.go index a1c6d106249..8a37bcbe469 100644 --- a/pkg/kubeapiserver/admission/initializer_test.go +++ b/pkg/kubeapiserver/admission/initializer_test.go @@ -17,6 +17,7 @@ limitations under the License. package admission import ( + "context" "testing" "k8s.io/apiserver/pkg/admission" @@ -24,7 +25,7 @@ import ( type doNothingAdmission struct{} -func (doNothingAdmission) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (doNothingAdmission) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { return nil } func (doNothingAdmission) Handles(o admission.Operation) bool { return false } diff --git a/pkg/registry/apps/deployment/storage/storage.go b/pkg/registry/apps/deployment/storage/storage.go index 8bff82cf9f0..6a76fbf4ca4 100644 --- a/pkg/registry/apps/deployment/storage/storage.go +++ b/pkg/registry/apps/deployment/storage/storage.go @@ -177,7 +177,7 @@ func (r *RollbackREST) Create(ctx context.Context, name string, obj runtime.Obje } if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } @@ -320,17 +320,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update } func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { - return func(obj runtime.Object) error { + return func(ctx context.Context, obj runtime.Object) error { scale, err := scaleFromDeployment(obj.(*apps.Deployment)) if err != nil { return err } - return f(scale) + return f(ctx, scale) } } func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { newScale, err := scaleFromDeployment(obj.(*apps.Deployment)) if err != nil { return err @@ -339,7 +339,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjec if err != nil { return err } - return f(newScale, oldScale) + return f(ctx, newScale, oldScale) } } diff --git a/pkg/registry/apps/deployment/storage/storage_test.go b/pkg/registry/apps/deployment/storage/storage_test.go index a1acf97c3bc..590c9f8af58 100644 --- a/pkg/registry/apps/deployment/storage/storage_test.go +++ b/pkg/registry/apps/deployment/storage/storage_test.go @@ -17,6 +17,7 @@ limitations under the License. package storage import ( + "context" "fmt" "net/http" "reflect" @@ -394,7 +395,7 @@ func TestCreateDeploymentRollbackValidation(t *testing.T) { } validationError := fmt.Errorf("admission deny") - alwaysDenyValidationFunc := func(obj runtime.Object) error { return validationError } + alwaysDenyValidationFunc := func(ctx context.Context, obj runtime.Object) error { return validationError } _, err := rollbackStorage.Create(ctx, rollback.Name, &rollback, alwaysDenyValidationFunc, &metav1.CreateOptions{}) if err == nil || validationError != err { diff --git a/pkg/registry/apps/replicaset/storage/storage.go b/pkg/registry/apps/replicaset/storage/storage.go index 32be92d821b..d34bc9d0302 100644 --- a/pkg/registry/apps/replicaset/storage/storage.go +++ b/pkg/registry/apps/replicaset/storage/storage.go @@ -225,17 +225,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update } func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { - return func(obj runtime.Object) error { + return func(ctx context.Context, obj runtime.Object) error { scale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet)) if err != nil { return err } - return f(scale) + return f(ctx, scale) } } func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { newScale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet)) if err != nil { return err @@ -244,7 +244,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjec if err != nil { return err } - return f(newScale, oldScale) + return f(ctx, newScale, oldScale) } } diff --git a/pkg/registry/apps/statefulset/storage/storage.go b/pkg/registry/apps/statefulset/storage/storage.go index 65c6db82047..cf90cd8dfa2 100644 --- a/pkg/registry/apps/statefulset/storage/storage.go +++ b/pkg/registry/apps/statefulset/storage/storage.go @@ -212,17 +212,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update } func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { - return func(obj runtime.Object) error { + return func(ctx context.Context, obj runtime.Object) error { scale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet)) if err != nil { return err } - return f(scale) + return f(ctx, scale) } } func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { newScale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet)) if err != nil { return err @@ -231,7 +231,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjec if err != nil { return err } - return f(newScale, oldScale) + return f(ctx, newScale, oldScale) } } diff --git a/pkg/registry/authentication/tokenreview/storage.go b/pkg/registry/authentication/tokenreview/storage.go index 8ec84a29853..368998df258 100644 --- a/pkg/registry/authentication/tokenreview/storage.go +++ b/pkg/registry/authentication/tokenreview/storage.go @@ -69,7 +69,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/authorization/localsubjectaccessreview/rest.go b/pkg/registry/authorization/localsubjectaccessreview/rest.go index b2dc7d2c161..587b61a387d 100644 --- a/pkg/registry/authorization/localsubjectaccessreview/rest.go +++ b/pkg/registry/authorization/localsubjectaccessreview/rest.go @@ -64,7 +64,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/authorization/selfsubjectaccessreview/rest.go b/pkg/registry/authorization/selfsubjectaccessreview/rest.go index 1051b80321e..0ceafe7c7b7 100644 --- a/pkg/registry/authorization/selfsubjectaccessreview/rest.go +++ b/pkg/registry/authorization/selfsubjectaccessreview/rest.go @@ -61,7 +61,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/authorization/selfsubjectrulesreview/rest.go b/pkg/registry/authorization/selfsubjectrulesreview/rest.go index be9cb7c652d..82dc7a521b1 100644 --- a/pkg/registry/authorization/selfsubjectrulesreview/rest.go +++ b/pkg/registry/authorization/selfsubjectrulesreview/rest.go @@ -67,7 +67,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/authorization/subjectaccessreview/rest.go b/pkg/registry/authorization/subjectaccessreview/rest.go index 9a69a2b0454..b0a8a3caba9 100644 --- a/pkg/registry/authorization/subjectaccessreview/rest.go +++ b/pkg/registry/authorization/subjectaccessreview/rest.go @@ -56,7 +56,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/core/namespace/storage/storage.go b/pkg/registry/core/namespace/storage/storage.go index ef1c1f7bdf0..b64a4f4abb0 100644 --- a/pkg/registry/core/namespace/storage/storage.go +++ b/pkg/registry/core/namespace/storage/storage.go @@ -178,7 +178,7 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va // wrong type return nil, fmt.Errorf("expected *api.Namespace, got %v", existing) } - if err := deleteValidation(existingNamespace); err != nil { + if err := deleteValidation(ctx, existingNamespace); err != nil { return nil, err } // Set the deletion timestamp if needed diff --git a/pkg/registry/core/pod/storage/eviction.go b/pkg/registry/core/pod/storage/eviction.go index ba105c4c08c..0b20125203b 100644 --- a/pkg/registry/core/pod/storage/eviction.go +++ b/pkg/registry/core/pod/storage/eviction.go @@ -116,7 +116,7 @@ func (r *EvictionREST) Create(ctx context.Context, obj runtime.Object, createVal pod := obj.(*api.Pod) if createValidation != nil { - if err := createValidation(eviction.DeepCopyObject()); err != nil { + if err := createValidation(ctx, eviction.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/core/pod/storage/storage.go b/pkg/registry/core/pod/storage/storage.go index 55abd49bd38..4947cf3d10d 100644 --- a/pkg/registry/core/pod/storage/storage.go +++ b/pkg/registry/core/pod/storage/storage.go @@ -160,7 +160,7 @@ func (r *BindingREST) Create(ctx context.Context, obj runtime.Object, createVali } if createValidation != nil { - if err := createValidation(binding.DeepCopyObject()); err != nil { + if err := createValidation(ctx, binding.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/core/replicationcontroller/storage/storage.go b/pkg/registry/core/replicationcontroller/storage/storage.go index 05887726848..db5c2d1a7ae 100644 --- a/pkg/registry/core/replicationcontroller/storage/storage.go +++ b/pkg/registry/core/replicationcontroller/storage/storage.go @@ -203,14 +203,15 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update } func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { - return func(obj runtime.Object) error { - return f(scaleFromRC(obj.(*api.ReplicationController))) + return func(ctx context.Context, obj runtime.Object) error { + return f(ctx, scaleFromRC(obj.(*api.ReplicationController))) } } func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { return f( + ctx, scaleFromRC(obj.(*api.ReplicationController)), scaleFromRC(old.(*api.ReplicationController)), ) diff --git a/pkg/registry/core/serviceaccount/storage/token.go b/pkg/registry/core/serviceaccount/storage/token.go index 881b5f26e40..fe8c9bf9063 100644 --- a/pkg/registry/core/serviceaccount/storage/token.go +++ b/pkg/registry/core/serviceaccount/storage/token.go @@ -59,7 +59,7 @@ var gvk = schema.GroupVersionKind{ func (r *TokenREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) { if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } diff --git a/pkg/registry/extensions/controller/storage/storage.go b/pkg/registry/extensions/controller/storage/storage.go index 2c710064fee..32fe895207a 100644 --- a/pkg/registry/extensions/controller/storage/storage.go +++ b/pkg/registry/extensions/controller/storage/storage.go @@ -115,14 +115,15 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update } func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { - return func(obj runtime.Object) error { - return f(scaleFromRC(obj.(*api.ReplicationController))) + return func(ctx context.Context, obj runtime.Object) error { + return f(ctx, scaleFromRC(obj.(*api.ReplicationController))) } } func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { return f( + ctx, scaleFromRC(obj.(*api.ReplicationController)), scaleFromRC(old.(*api.ReplicationController)), ) diff --git a/plugin/pkg/admission/admit/admission.go b/plugin/pkg/admission/admit/admission.go index 83d8c639030..ca04ce00cee 100644 --- a/plugin/pkg/admission/admit/admission.go +++ b/plugin/pkg/admission/admit/admission.go @@ -17,6 +17,7 @@ limitations under the License. package admit import ( + "context" "io" "k8s.io/apiserver/pkg/admission" @@ -40,12 +41,12 @@ var _ admission.MutationInterface = alwaysAdmit{} var _ admission.ValidationInterface = alwaysAdmit{} // Admit makes an admission decision based on the request attributes -func (alwaysAdmit) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (alwaysAdmit) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return nil } // Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate. -func (alwaysAdmit) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (alwaysAdmit) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return nil } diff --git a/plugin/pkg/admission/admit/admission_test.go b/plugin/pkg/admission/admit/admission_test.go index 81f22b26831..0c7bca07e38 100644 --- a/plugin/pkg/admission/admit/admission_test.go +++ b/plugin/pkg/admission/admit/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package admit import ( + "context" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -27,7 +28,7 @@ import ( func TestAdmissionNonNilAttribute(t *testing.T) { handler := admissiontesting.WithReinvocationTesting(t, NewAlwaysAdmit().(*alwaysAdmit)) - err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error returned from admission handler") } @@ -35,7 +36,7 @@ func TestAdmissionNonNilAttribute(t *testing.T) { func TestAdmissionNilAttribute(t *testing.T) { handler := NewAlwaysAdmit() - err := handler.(*alwaysAdmit).Admit(nil, nil) + err := handler.(*alwaysAdmit).Admit(context.TODO(), nil, nil) if err != nil { t.Errorf("Unexpected error returned from admission handler") } diff --git a/plugin/pkg/admission/alwayspullimages/admission.go b/plugin/pkg/admission/alwayspullimages/admission.go index 335b403629c..0b78124cebb 100644 --- a/plugin/pkg/admission/alwayspullimages/admission.go +++ b/plugin/pkg/admission/alwayspullimages/admission.go @@ -25,6 +25,7 @@ limitations under the License. package alwayspullimages import ( + "context" "io" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -55,7 +56,7 @@ var _ admission.MutationInterface = &AlwaysPullImages{} var _ admission.ValidationInterface = &AlwaysPullImages{} // Admit makes an admission decision based on the request attributes -func (a *AlwaysPullImages) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (a *AlwaysPullImages) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { // Ignore all calls to subresources or resources other than pods. if shouldIgnore(attributes) { return nil @@ -74,7 +75,7 @@ func (a *AlwaysPullImages) Admit(attributes admission.Attributes, o admission.Ob } // Validate makes sure that all containers are set to always pull images -func (*AlwaysPullImages) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (*AlwaysPullImages) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { if shouldIgnore(attributes) { return nil } diff --git a/plugin/pkg/admission/alwayspullimages/admission_test.go b/plugin/pkg/admission/alwayspullimages/admission_test.go index fb348bbfa2b..4b15c390c0b 100644 --- a/plugin/pkg/admission/alwayspullimages/admission_test.go +++ b/plugin/pkg/admission/alwayspullimages/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package alwayspullimages import ( + "context" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -48,7 +49,7 @@ func TestAdmission(t *testing.T) { }, }, } - err := handler.Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error returned from admission handler") } @@ -91,7 +92,7 @@ func TestValidate(t *testing.T) { `pods "123" is forbidden: spec.containers[0].imagePullPolicy: Unsupported value: "": supported values: "Always", ` + `pods "123" is forbidden: spec.containers[1].imagePullPolicy: Unsupported value: "Never": supported values: "Always", ` + `pods "123" is forbidden: spec.containers[2].imagePullPolicy: Unsupported value: "IfNotPresent": supported values: "Always"]` - err := handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Fatal("missing expected error") } @@ -146,7 +147,7 @@ func TestOtherResources(t *testing.T) { for _, tc := range tests { handler := admissiontesting.WithReinvocationTesting(t, &AlwaysPullImages{}) - err := handler.Admit(admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil) if tc.expectError { if err == nil { diff --git a/plugin/pkg/admission/antiaffinity/admission.go b/plugin/pkg/admission/antiaffinity/admission.go index 94225fd6528..6c961c56847 100644 --- a/plugin/pkg/admission/antiaffinity/admission.go +++ b/plugin/pkg/admission/antiaffinity/admission.go @@ -17,6 +17,7 @@ limitations under the License. package antiaffinity import ( + "context" "fmt" "io" @@ -52,7 +53,7 @@ func NewInterPodAntiAffinity() *Plugin { // Validate will deny any pod that defines AntiAffinity topology key other than v1.LabelHostname i.e. "kubernetes.io/hostname" // in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution. -func (p *Plugin) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (p *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { // Ignore all calls to subresources or resources other than pods. if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource("pods") { return nil diff --git a/plugin/pkg/admission/antiaffinity/admission_test.go b/plugin/pkg/admission/antiaffinity/admission_test.go index b531b6a6aeb..5ba8bdc5161 100644 --- a/plugin/pkg/admission/antiaffinity/admission_test.go +++ b/plugin/pkg/admission/antiaffinity/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package antiaffinity import ( + "context" "testing" v1 "k8s.io/api/core/v1" @@ -199,7 +200,7 @@ func TestInterPodAffinityAdmission(t *testing.T) { } for _, test := range tests { pod.Spec.Affinity = test.affinity - err := handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) if test.errorExpected && err == nil { t.Errorf("Expected error for Anti Affinity %+v but did not get an error", test.affinity) @@ -267,7 +268,7 @@ func TestOtherResources(t *testing.T) { for _, tc := range tests { handler := &Plugin{} - err := handler.Validate(admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil) if tc.expectError { if err == nil { diff --git a/plugin/pkg/admission/defaulttolerationseconds/admission.go b/plugin/pkg/admission/defaulttolerationseconds/admission.go index 1bff0d701b2..f8984410d10 100644 --- a/plugin/pkg/admission/defaulttolerationseconds/admission.go +++ b/plugin/pkg/admission/defaulttolerationseconds/admission.go @@ -17,6 +17,7 @@ limitations under the License. package defaulttolerationseconds import ( + "context" "flag" "fmt" "io" @@ -81,7 +82,7 @@ func NewDefaultTolerationSeconds() *Plugin { } // Admit makes an admission decision based on the request attributes -func (p *Plugin) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (p *Plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { if attributes.GetResource().GroupResource() != api.Resource("pods") { return nil } diff --git a/plugin/pkg/admission/defaulttolerationseconds/admission_test.go b/plugin/pkg/admission/defaulttolerationseconds/admission_test.go index 624fe5440df..d03342ef221 100644 --- a/plugin/pkg/admission/defaulttolerationseconds/admission_test.go +++ b/plugin/pkg/admission/defaulttolerationseconds/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package defaulttolerationseconds import ( + "context" "testing" "k8s.io/apiserver/pkg/admission" @@ -264,7 +265,7 @@ func TestForgivenessAdmission(t *testing.T) { } for _, test := range tests { - err := handler.Admit(admission.NewAttributesRecord(&test.requestedPod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(&test.requestedPod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) if err != nil { t.Errorf("[%s]: unexpected error %v for pod %+v", test.description, err, test.requestedPod) } diff --git a/plugin/pkg/admission/deny/admission.go b/plugin/pkg/admission/deny/admission.go index 4c9a85e366c..ee0712b8633 100644 --- a/plugin/pkg/admission/deny/admission.go +++ b/plugin/pkg/admission/deny/admission.go @@ -17,6 +17,7 @@ limitations under the License. package deny import ( + "context" "errors" "io" @@ -42,12 +43,12 @@ var _ admission.MutationInterface = alwaysDeny{} var _ admission.ValidationInterface = alwaysDeny{} // Admit makes an admission decision based on the request attributes. -func (alwaysDeny) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (alwaysDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return admission.NewForbidden(a, errors.New("admission control is denying all modifications")) } // Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate. -func (alwaysDeny) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (alwaysDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return admission.NewForbidden(a, errors.New("admission control is denying all modifications")) } diff --git a/plugin/pkg/admission/deny/admission_test.go b/plugin/pkg/admission/deny/admission_test.go index 0e916d1b7e4..a5273da7643 100644 --- a/plugin/pkg/admission/deny/admission_test.go +++ b/plugin/pkg/admission/deny/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package deny import ( + "context" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -27,7 +28,7 @@ import ( func TestAdmission(t *testing.T) { handler := admissiontesting.WithReinvocationTesting(t, NewAlwaysDeny().(*alwaysDeny)) - err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Error("Expected error returned from admission handler") } diff --git a/plugin/pkg/admission/eventratelimit/admission.go b/plugin/pkg/admission/eventratelimit/admission.go index 00506240556..0ba7e9d6882 100644 --- a/plugin/pkg/admission/eventratelimit/admission.go +++ b/plugin/pkg/admission/eventratelimit/admission.go @@ -17,6 +17,7 @@ limitations under the License. package eventratelimit import ( + "context" "io" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -81,7 +82,7 @@ func newEventRateLimit(config *eventratelimitapi.Configuration, clock flowcontro } // Validate makes admission decisions while enforcing event rate limits -func (a *Plugin) Validate(attr admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) { // ignore all operations that do not correspond to an Event kind if attr.GetKind().GroupKind() != api.Kind("Event") { return nil diff --git a/plugin/pkg/admission/eventratelimit/admission_test.go b/plugin/pkg/admission/eventratelimit/admission_test.go index 17a72d44b38..4f8c014ff8d 100644 --- a/plugin/pkg/admission/eventratelimit/admission_test.go +++ b/plugin/pkg/admission/eventratelimit/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package eventratelimit import ( + "context" "net/http" "testing" "time" @@ -507,7 +508,7 @@ func TestEventRateLimiting(t *testing.T) { clock.Step(rq.delay) } attributes := attributesForRequest(rq) - err = eventratelimit.Validate(attributes, nil) + err = eventratelimit.Validate(context.TODO(), attributes, nil) if rq.accepted != (err == nil) { expectedAction := "admitted" if !rq.accepted { diff --git a/plugin/pkg/admission/exec/admission.go b/plugin/pkg/admission/exec/admission.go index 620cfd1e5c2..4d782a53533 100644 --- a/plugin/pkg/admission/exec/admission.go +++ b/plugin/pkg/admission/exec/admission.go @@ -17,6 +17,7 @@ limitations under the License. package exec import ( + "context" "fmt" "io" @@ -112,7 +113,7 @@ func (d *DenyExec) ValidateInitialization() error { } // Validate makes an admission decision based on the request attributes -func (d *DenyExec) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (d *DenyExec) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { path := a.GetResource().Resource if subresource := a.GetSubresource(); subresource != "" { path = path + "/" + subresource diff --git a/plugin/pkg/admission/exec/admission_test.go b/plugin/pkg/admission/exec/admission_test.go index 4d48e8c11dc..3eafcec4187 100644 --- a/plugin/pkg/admission/exec/admission_test.go +++ b/plugin/pkg/admission/exec/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package exec import ( + "context" "testing" corev1 "k8s.io/api/core/v1" @@ -120,7 +121,7 @@ func testAdmission(t *testing.T, pod *corev1.Pod, handler *DenyExec, shouldAccep // pods/exec { - err := handler.Validate(admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "exec", admission.Connect, nil, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "exec", admission.Connect, nil, false, nil), nil) if shouldAccept && err != nil { t.Errorf("Unexpected error returned from admission handler: %v", err) } @@ -131,7 +132,7 @@ func testAdmission(t *testing.T, pod *corev1.Pod, handler *DenyExec, shouldAccep // pods/attach { - err := handler.Validate(admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "attach", admission.Connect, nil, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "attach", admission.Connect, nil, false, nil), nil) if shouldAccept && err != nil { t.Errorf("Unexpected error returned from admission handler: %v", err) } diff --git a/plugin/pkg/admission/extendedresourcetoleration/admission.go b/plugin/pkg/admission/extendedresourcetoleration/admission.go index b0bff24518e..bdada75d44c 100644 --- a/plugin/pkg/admission/extendedresourcetoleration/admission.go +++ b/plugin/pkg/admission/extendedresourcetoleration/admission.go @@ -17,6 +17,7 @@ limitations under the License. package extendedresourcetoleration import ( + "context" "fmt" "io" @@ -56,7 +57,7 @@ type plugin struct { // a toleration with key "example.com/device", operator "Exists" and effect "NoSchedule". // The rationale for this is described in: // https://github.com/kubernetes/kubernetes/issues/55080 -func (p *plugin) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) error { +func (p *plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error { // Ignore all calls to subresources or resources other than pods. if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != core.Resource("pods") { return nil diff --git a/plugin/pkg/admission/extendedresourcetoleration/admission_test.go b/plugin/pkg/admission/extendedresourcetoleration/admission_test.go index b45e8ef65f5..e4121c69fe2 100644 --- a/plugin/pkg/admission/extendedresourcetoleration/admission_test.go +++ b/plugin/pkg/admission/extendedresourcetoleration/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package extendedresourcetoleration import ( + "context" "testing" "k8s.io/apimachinery/pkg/api/resource" @@ -355,7 +356,7 @@ func TestAdmit(t *testing.T) { }, } for i, test := range tests { - err := plugin.Admit(admission.NewAttributesRecord(&test.requestedPod, nil, core.Kind("Pod").WithVersion("version"), "foo", "name", core.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) + err := plugin.Admit(context.TODO(), admission.NewAttributesRecord(&test.requestedPod, nil, core.Kind("Pod").WithVersion("version"), "foo", "name", core.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) if err != nil { t.Errorf("[%d: %s] unexpected error %v for pod %+v", i, test.description, err, test.requestedPod) } diff --git a/plugin/pkg/admission/gc/gc_admission.go b/plugin/pkg/admission/gc/gc_admission.go index 4036a2642c6..e383719d58a 100644 --- a/plugin/pkg/admission/gc/gc_admission.go +++ b/plugin/pkg/admission/gc/gc_admission.go @@ -17,6 +17,7 @@ limitations under the License. package gc import ( + "context" "fmt" "io" @@ -84,7 +85,7 @@ func (a *gcPermissionsEnforcement) isWhiteListed(groupResource schema.GroupResou return false } -func (a *gcPermissionsEnforcement) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (a *gcPermissionsEnforcement) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { // // if the request is in the whitelist, we skip mutation checks for this resource. if a.isWhiteListed(attributes.GetResource().GroupResource(), attributes.GetSubresource()) { return nil diff --git a/plugin/pkg/admission/gc/gc_admission_test.go b/plugin/pkg/admission/gc/gc_admission_test.go index 501e13a4154..96a30a962f8 100644 --- a/plugin/pkg/admission/gc/gc_admission_test.go +++ b/plugin/pkg/admission/gc/gc_admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package gc import ( + "context" "fmt" "strings" "testing" @@ -310,7 +311,7 @@ func TestGCAdmission(t *testing.T) { user := &user.DefaultInfo{Name: tc.username} attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, options, false, user) - err = gcAdmit.Validate(attributes, nil) + err = gcAdmit.Validate(context.TODO(), attributes, nil) if !tc.checkError(err) { t.Errorf("unexpected err: %v", err) } @@ -615,7 +616,7 @@ func TestBlockOwnerDeletionAdmission(t *testing.T) { user := &user.DefaultInfo{Name: tc.username} attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, options, false, user) - err := gcAdmit.Validate(attributes, nil) + err := gcAdmit.Validate(context.TODO(), attributes, nil) if !tc.checkError(err) { t.Errorf("%v: unexpected err: %v", tc.name, err) } diff --git a/plugin/pkg/admission/imagepolicy/admission.go b/plugin/pkg/admission/imagepolicy/admission.go index bf79294022a..7c988aead47 100644 --- a/plugin/pkg/admission/imagepolicy/admission.go +++ b/plugin/pkg/admission/imagepolicy/admission.go @@ -19,6 +19,7 @@ limitations under the License. package imagepolicy import ( + "context" "encoding/json" "errors" "fmt" @@ -131,7 +132,7 @@ func (a *Plugin) webhookError(pod *api.Pod, attributes admission.Attributes, err } // Validate makes an admission decision based on the request attributes -func (a *Plugin) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (a *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { // Ignore all calls to subresources or resources other than pods. if attributes.GetSubresource() != "" || attributes.GetResource().GroupResource() != api.Resource("pods") { return nil diff --git a/plugin/pkg/admission/imagepolicy/admission_test.go b/plugin/pkg/admission/imagepolicy/admission_test.go index cfa9d0c1174..4d9f5ad870b 100644 --- a/plugin/pkg/admission/imagepolicy/admission_test.go +++ b/plugin/pkg/admission/imagepolicy/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package imagepolicy import ( + "context" "crypto/tls" "crypto/x509" "encoding/json" @@ -488,7 +489,7 @@ func TestTLSConfig(t *testing.T) { // Allow all and see if we get an error. service.Allow() - err = wh.Validate(attr, nil) + err = wh.Validate(context.TODO(), attr, nil) if tt.wantAllowed { if err != nil { t.Errorf("expected successful admission") @@ -510,7 +511,7 @@ func TestTLSConfig(t *testing.T) { } service.Deny() - if err := wh.Validate(attr, nil); err == nil { + if err := wh.Validate(context.TODO(), attr, nil); err == nil { t.Errorf("%s: incorrectly admitted with DenyAll policy", tt.test) } }) @@ -527,7 +528,7 @@ type webhookCacheTestCase struct { func testWebhookCacheCases(t *testing.T, serv *mockService, wh *Plugin, attr admission.Attributes, tests []webhookCacheTestCase) { for _, test := range tests { serv.statusCode = test.statusCode - err := wh.Validate(attr, nil) + err := wh.Validate(context.TODO(), attr, nil) authorized := err == nil if test.expectedErr && err == nil { @@ -760,7 +761,7 @@ func TestContainerCombinations(t *testing.T) { attr := admission.NewAttributesRecord(tt.pod, nil, api.Kind("Pod").WithVersion("version"), "namespace", "", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) - err = wh.Validate(attr, nil) + err = wh.Validate(context.TODO(), attr, nil) if tt.wantAllowed { if err != nil { t.Errorf("expected successful admission: %s", tt.test) @@ -856,7 +857,7 @@ func TestDefaultAllow(t *testing.T) { annotations := make(map[string]string) attr = &fakeAttributes{attr, annotations} - err = wh.Validate(attr, nil) + err = wh.Validate(context.TODO(), attr, nil) if tt.wantAllowed { if err != nil { t.Errorf("expected successful admission") @@ -964,7 +965,7 @@ func TestAnnotationFiltering(t *testing.T) { attr := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "namespace", "", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) - err = wh.Validate(attr, nil) + err = wh.Validate(context.TODO(), attr, nil) if err != nil { t.Errorf("expected successful admission") } @@ -1056,7 +1057,7 @@ func TestReturnedAnnotationAdd(t *testing.T) { annotations := make(map[string]string) attr = &fakeAttributes{attr, annotations} - err = wh.Validate(attr, nil) + err = wh.Validate(context.TODO(), attr, nil) if !reflect.DeepEqual(annotations, tt.expectedAnnotations) { t.Errorf("got audit annotations: %v; want: %v", annotations, tt.expectedAnnotations) } diff --git a/plugin/pkg/admission/limitranger/admission.go b/plugin/pkg/admission/limitranger/admission.go index 762cf28936f..59214d18b3c 100644 --- a/plugin/pkg/admission/limitranger/admission.go +++ b/plugin/pkg/admission/limitranger/admission.go @@ -17,6 +17,7 @@ limitations under the License. package limitranger import ( + "context" "fmt" "io" "sort" @@ -102,12 +103,12 @@ func (l *LimitRanger) ValidateInitialization() error { } // Admit admits resources into cluster that do not violate any defined LimitRange in the namespace -func (l *LimitRanger) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (l *LimitRanger) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return l.runLimitFunc(a, l.actions.MutateLimit) } // Validate admits resources into cluster that do not violate any defined LimitRange in the namespace -func (l *LimitRanger) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (l *LimitRanger) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return l.runLimitFunc(a, l.actions.ValidateLimit) } diff --git a/plugin/pkg/admission/limitranger/admission_test.go b/plugin/pkg/admission/limitranger/admission_test.go index afd648f0039..4071e914e12 100644 --- a/plugin/pkg/admission/limitranger/admission_test.go +++ b/plugin/pkg/admission/limitranger/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package limitranger import ( + "context" "fmt" "strconv" "testing" @@ -706,20 +707,20 @@ func TestLimitRangerIgnoresSubresource(t *testing.T) { informerFactory.Start(wait.NeverStop) testPod := validPod("testPod", 1, api.ResourceRequirements{}) - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Fatal(err) } - err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error since the pod did not specify resource limits in its create call") } - err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Expected not to call limitranger actions on pod updates") } - err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Should have ignored calls to any subresource of pod %v", err) } @@ -736,20 +737,20 @@ func TestLimitRangerAdmitPod(t *testing.T) { informerFactory.Start(wait.NeverStop) testPod := validPod("testPod", 1, api.ResourceRequirements{}) - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Fatal(err) } - err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error since the pod did not specify resource limits in its create call") } - err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Expected not to call limitranger actions on pod updates") } - err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Should have ignored calls to any subresource of pod %v", err) } @@ -758,7 +759,7 @@ func TestLimitRangerAdmitPod(t *testing.T) { terminatingPod := validPod("terminatingPod", 1, api.ResourceRequirements{}) now := metav1.Now() terminatingPod.DeletionTimestamp = &now - err = handler.Validate(admission.NewAttributesRecord(&terminatingPod, &terminatingPod, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "terminatingPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&terminatingPod, &terminatingPod, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "terminatingPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("LimitRange should ignore a pod marked for termination") } diff --git a/plugin/pkg/admission/namespace/autoprovision/admission.go b/plugin/pkg/admission/namespace/autoprovision/admission.go index 54e021df77d..fd5dc275779 100644 --- a/plugin/pkg/admission/namespace/autoprovision/admission.go +++ b/plugin/pkg/admission/namespace/autoprovision/admission.go @@ -17,6 +17,7 @@ limitations under the License. package autoprovision import ( + "context" "fmt" "io" @@ -55,7 +56,7 @@ var _ = genericadmissioninitializer.WantsExternalKubeInformerFactory(&Provision{ var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Provision{}) // Admit makes an admission decision based on the request attributes -func (p *Provision) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Provision) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { // Don't create a namespace if the request is for a dry-run. if a.IsDryRun() { return nil diff --git a/plugin/pkg/admission/namespace/autoprovision/admission_test.go b/plugin/pkg/admission/namespace/autoprovision/admission_test.go index 343cf522435..1a45140c484 100644 --- a/plugin/pkg/admission/namespace/autoprovision/admission_test.go +++ b/plugin/pkg/admission/namespace/autoprovision/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package autoprovision import ( + "context" "fmt" "testing" "time" @@ -100,7 +101,7 @@ func TestAdmission(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } @@ -120,7 +121,7 @@ func TestAdmissionNamespaceExists(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } @@ -140,7 +141,7 @@ func TestAdmissionDryRun(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } @@ -161,7 +162,7 @@ func TestIgnoreAdmission(t *testing.T) { chainHandler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(handler)) pod := newPod(namespace) - err = admissiontesting.WithReinvocationTesting(t, chainHandler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, chainHandler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } @@ -183,7 +184,7 @@ func TestAdmissionWithLatentCache(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } diff --git a/plugin/pkg/admission/namespace/exists/admission.go b/plugin/pkg/admission/namespace/exists/admission.go index e14ead89c61..61314f729ba 100644 --- a/plugin/pkg/admission/namespace/exists/admission.go +++ b/plugin/pkg/admission/namespace/exists/admission.go @@ -17,6 +17,7 @@ limitations under the License. package exists import ( + "context" "fmt" "io" @@ -54,7 +55,7 @@ var _ = genericadmissioninitializer.WantsExternalKubeInformerFactory(&Exists{}) var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Exists{}) // Validate makes an admission decision based on the request attributes -func (e *Exists) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (e *Exists) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { // if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do // if we're here, then the API server has found a route, which means that if we have a non-empty namespace // its a namespaced resource. diff --git a/plugin/pkg/admission/namespace/exists/admission_test.go b/plugin/pkg/admission/namespace/exists/admission_test.go index 7ba55539e88..ce077a0957b 100644 --- a/plugin/pkg/admission/namespace/exists/admission_test.go +++ b/plugin/pkg/admission/namespace/exists/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package exists import ( + "context" "fmt" "testing" "time" @@ -88,7 +89,7 @@ func TestAdmissionNamespaceExists(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } @@ -108,7 +109,7 @@ func TestAdmissionNamespaceDoesNotExist(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { actions := "" for _, action := range mockClient.Actions() { diff --git a/plugin/pkg/admission/noderestriction/admission.go b/plugin/pkg/admission/noderestriction/admission.go index d4816c24ef4..20596cdab4c 100644 --- a/plugin/pkg/admission/noderestriction/admission.go +++ b/plugin/pkg/admission/noderestriction/admission.go @@ -17,6 +17,7 @@ limitations under the License. package noderestriction import ( + "context" "fmt" "io" "strings" @@ -105,7 +106,7 @@ var ( ) // Admit checks the admission policy and triggers corresponding actions -func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { nodeName, isNode := p.nodeIdentifier.NodeIdentity(a.GetUserInfo()) // Our job is just to restrict nodes diff --git a/plugin/pkg/admission/noderestriction/admission_test.go b/plugin/pkg/admission/noderestriction/admission_test.go index 57cb5845860..656fe363db3 100644 --- a/plugin/pkg/admission/noderestriction/admission_test.go +++ b/plugin/pkg/admission/noderestriction/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package noderestriction import ( + "context" "fmt" "reflect" "strings" @@ -1210,7 +1211,7 @@ func Test_nodePlugin_Admit(t *testing.T) { c.features = tt.features } c.podsGetter = tt.podsGetter - err := c.Admit(tt.attributes, nil) + err := c.Admit(context.TODO(), tt.attributes, nil) if (err == nil) != (len(tt.err) == 0) { t.Errorf("nodePlugin.Admit() error = %v, expected %v", err, tt.err) return diff --git a/plugin/pkg/admission/nodetaint/admission.go b/plugin/pkg/admission/nodetaint/admission.go index a56027eb357..84a1e0f4224 100644 --- a/plugin/pkg/admission/nodetaint/admission.go +++ b/plugin/pkg/admission/nodetaint/admission.go @@ -17,8 +17,10 @@ limitations under the License. package nodetaint import ( + "context" "fmt" "io" + "k8s.io/apiserver/pkg/admission" utilfeature "k8s.io/apiserver/pkg/util/feature" "k8s.io/component-base/featuregate" @@ -65,7 +67,7 @@ var ( ) // Admit is the main function that checks node identity and adds taints as needed. -func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { // If TaintNodesByCondition is not enabled, we don't need to do anything. if !p.features.Enabled(features.TaintNodesByCondition) { return nil diff --git a/plugin/pkg/admission/nodetaint/admission_test.go b/plugin/pkg/admission/nodetaint/admission_test.go index 6dd56c506d6..ec2ca7299ba 100644 --- a/plugin/pkg/admission/nodetaint/admission_test.go +++ b/plugin/pkg/admission/nodetaint/admission_test.go @@ -17,7 +17,9 @@ limitations under the License. package nodetaint import ( + "context" "reflect" + "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -106,7 +108,7 @@ func Test_nodeTaints(t *testing.T) { if tt.features != nil { c.features = tt.features } - err := c.Admit(attributes, nil) + err := c.Admit(context.TODO(), attributes, nil) if err != nil { t.Errorf("nodePlugin.Admit() error = %v", err) } diff --git a/plugin/pkg/admission/podnodeselector/admission.go b/plugin/pkg/admission/podnodeselector/admission.go index e5ad477bfb9..2c5c4aa96f8 100644 --- a/plugin/pkg/admission/podnodeselector/admission.go +++ b/plugin/pkg/admission/podnodeselector/admission.go @@ -17,6 +17,7 @@ limitations under the License. package podnodeselector import ( + "context" "fmt" "io" "reflect" @@ -96,7 +97,7 @@ func readConfig(config io.Reader) *pluginConfig { } // Admit enforces that pod and its namespace node label selectors matches at least a node in the cluster. -func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if shouldIgnore(a) { return nil } @@ -119,11 +120,11 @@ func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) err // second selector wins podNodeSelectorLabels := labels.Merge(namespaceNodeSelector, pod.Spec.NodeSelector) pod.Spec.NodeSelector = map[string]string(podNodeSelectorLabels) - return p.Validate(a, o) + return p.Validate(ctx, a, o) } // Validate ensures that the pod node selector is allowed -func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if shouldIgnore(a) { return nil } diff --git a/plugin/pkg/admission/podnodeselector/admission_test.go b/plugin/pkg/admission/podnodeselector/admission_test.go index 0444b07010a..9aae482e8e0 100644 --- a/plugin/pkg/admission/podnodeselector/admission_test.go +++ b/plugin/pkg/admission/podnodeselector/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package podnodeselector import ( + "context" "testing" "time" @@ -161,7 +162,7 @@ func TestPodAdmission(t *testing.T) { handler.clusterNodeSelectors[namespace.Name] = test.whitelist pod.Spec = api.PodSpec{NodeSelector: test.podNodeSelector} - err := handler.Admit(admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if test.admit && err != nil { t.Errorf("Test: %s, expected no error but got: %s", test.testName, err) } else if !test.admit && err == nil { @@ -170,7 +171,7 @@ func TestPodAdmission(t *testing.T) { if test.admit && !labels.Equals(test.mergedNodeSelector, labels.Set(pod.Spec.NodeSelector)) { t.Errorf("Test: %s, expected: %s but got: %s", test.testName, test.mergedNodeSelector, pod.Spec.NodeSelector) } - err = handler.Validate(admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if test.admit && err != nil { t.Errorf("Test: %s, expected no error but got: %s", test.testName, err) } else if !test.admit && err == nil { diff --git a/plugin/pkg/admission/podpreset/admission.go b/plugin/pkg/admission/podpreset/admission.go index a5b4139b38e..53e4a61b3f2 100644 --- a/plugin/pkg/admission/podpreset/admission.go +++ b/plugin/pkg/admission/podpreset/admission.go @@ -17,6 +17,7 @@ limitations under the License. package podpreset import ( + "context" "fmt" "io" "reflect" @@ -96,7 +97,7 @@ func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactor } // Admit injects a pod with the specific fields for each pod preset it matches. -func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { // Ignore all calls to subresources or resources other than pods. // Ignore all operations other than CREATE. if len(a.GetSubresource()) != 0 || a.GetResource().GroupResource() != api.Resource("pods") || a.GetOperation() != admission.Create { diff --git a/plugin/pkg/admission/podpreset/admission_test.go b/plugin/pkg/admission/podpreset/admission_test.go index 381a721695c..4b883b70376 100644 --- a/plugin/pkg/admission/podpreset/admission_test.go +++ b/plugin/pkg/admission/podpreset/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package podpreset import ( + "context" "fmt" "reflect" "testing" @@ -828,7 +829,7 @@ func admitPod(t *testing.T, pod *api.Pod, pip *settingsv1alpha1.PodPreset) error &user.DefaultInfo{}, ) - err := plugin.Admit(attrs, nil) + err := plugin.Admit(context.TODO(), attrs, nil) if err != nil { return err } diff --git a/plugin/pkg/admission/podtolerationrestriction/admission.go b/plugin/pkg/admission/podtolerationrestriction/admission.go index 27b183d8e43..dfc20260472 100644 --- a/plugin/pkg/admission/podtolerationrestriction/admission.go +++ b/plugin/pkg/admission/podtolerationrestriction/admission.go @@ -17,6 +17,7 @@ limitations under the License. package podtolerationrestriction import ( + "context" "encoding/json" "fmt" "io" @@ -73,7 +74,7 @@ type Plugin struct { } // Admit checks the admission policy and triggers corresponding actions -func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if shouldIgnore(a) { return nil } @@ -127,11 +128,11 @@ func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) err // Final merge of tolerations irrespective of pod type, if the user while creating pods gives // conflicting tolerations(with same key+effect), the existing ones should be overwritten by latest one pod.Spec.Tolerations = tolerations.MergeTolerations(finalTolerations, []api.Toleration{}) - return p.Validate(a, o) + return p.Validate(ctx, a, o) } // Validate we can obtain a whitelist of tolerations -func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if shouldIgnore(a) { return nil } diff --git a/plugin/pkg/admission/podtolerationrestriction/admission_test.go b/plugin/pkg/admission/podtolerationrestriction/admission_test.go index e958d50f2bb..2fde37fa5c5 100644 --- a/plugin/pkg/admission/podtolerationrestriction/admission_test.go +++ b/plugin/pkg/admission/podtolerationrestriction/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package podtolerationrestriction import ( + "context" "encoding/json" "testing" "time" @@ -266,7 +267,7 @@ func TestPodAdmission(t *testing.T) { handler.pluginConfig = &pluginapi.Configuration{Default: test.defaultClusterTolerations, Whitelist: test.clusterWhitelist} pod := test.pod pod.Spec.Tolerations = test.podTolerations - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if test.admit && err != nil { t.Errorf("Test: %s, expected no error but got: %s", test.testName, err) } else if !test.admit && err == nil { @@ -343,7 +344,7 @@ func TestIgnoreUpdatingInitializedPod(t *testing.T) { } // if the update of initialized pod is not ignored, an error will be returned because the pod's Tolerations conflicts with namespace's Tolerations. - err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(pod, pod, api.Kind("Pod").WithVersion("version"), "testNamespace", pod.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil) + err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(pod, pod, api.Kind("Pod").WithVersion("version"), "testNamespace", pod.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("expected no error, got: %v", err) } diff --git a/plugin/pkg/admission/priority/admission.go b/plugin/pkg/admission/priority/admission.go index 481f4f893ee..b4420d86a38 100644 --- a/plugin/pkg/admission/priority/admission.go +++ b/plugin/pkg/admission/priority/admission.go @@ -17,6 +17,7 @@ limitations under the License. package priority import ( + "context" "fmt" "io" @@ -98,7 +99,7 @@ var ( // Admit checks Pods and admits or rejects them. It also resolves the priority of pods based on their PriorityClass. // Note that pod validation mechanism prevents update of a pod priority. -func (p *priorityPlugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *priorityPlugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { operation := a.GetOperation() // Ignore all calls to subresources if len(a.GetSubresource()) != 0 { @@ -118,7 +119,7 @@ func (p *priorityPlugin) Admit(a admission.Attributes, o admission.ObjectInterfa } // Validate checks PriorityClasses and admits or rejects them. -func (p *priorityPlugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *priorityPlugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { operation := a.GetOperation() // Ignore all calls to subresources if len(a.GetSubresource()) != 0 { diff --git a/plugin/pkg/admission/priority/admission_test.go b/plugin/pkg/admission/priority/admission_test.go index 1feff4318b5..20e122b38a9 100644 --- a/plugin/pkg/admission/priority/admission_test.go +++ b/plugin/pkg/admission/priority/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package priority import ( + "context" "testing" "k8s.io/klog" @@ -191,7 +192,7 @@ func TestPriorityClassAdmission(t *testing.T) { false, test.userInfo, ) - err := ctrl.Validate(attrs, nil) + err := ctrl.Validate(context.TODO(), attrs, nil) klog.Infof("Got %v", err) if err != nil && !test.expectError { t.Errorf("Test %q: unexpected error received: %v", test.name, err) @@ -287,7 +288,7 @@ func TestDefaultPriority(t *testing.T) { test.name, test.expectedDefaultNameBefore, test.expectedDefaultBefore, pcName, defaultPriority) } if test.attributes != nil { - err := ctrl.Validate(test.attributes, nil) + err := ctrl.Validate(context.TODO(), test.attributes, nil) if err != nil { t.Errorf("Test %q: unexpected error received: %v", test.name, err) } @@ -701,7 +702,7 @@ func TestPodAdmission(t *testing.T) { false, nil, ) - err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(context.TODO(), attrs, nil) klog.Infof("Got %v", err) if !test.expectError { if err != nil { diff --git a/plugin/pkg/admission/resourcequota/admission.go b/plugin/pkg/admission/resourcequota/admission.go index 0865ef3345f..0d3eccbfefe 100644 --- a/plugin/pkg/admission/resourcequota/admission.go +++ b/plugin/pkg/admission/resourcequota/admission.go @@ -17,6 +17,7 @@ limitations under the License. package resourcequota import ( + "context" "fmt" "io" "time" @@ -131,7 +132,7 @@ func (a *QuotaAdmission) ValidateInitialization() error { } // Validate makes admission decisions while enforcing quota -func (a *QuotaAdmission) Validate(attr admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (a *QuotaAdmission) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) { // ignore all operations that correspond to sub-resource actions if attr.GetSubresource() != "" { return nil diff --git a/plugin/pkg/admission/resourcequota/admission_test.go b/plugin/pkg/admission/resourcequota/admission_test.go index 57e6aa948fe..bb62571c84a 100644 --- a/plugin/pkg/admission/resourcequota/admission_test.go +++ b/plugin/pkg/admission/resourcequota/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package resourcequota import ( + "context" "fmt" "strconv" "strings" @@ -153,7 +154,7 @@ func TestAdmissionIgnoresDelete(t *testing.T) { evaluator: evaluator, } namespace := "default" - err := handler.Validate(admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), namespace, "name", corev1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), namespace, "name", corev1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) if err != nil { t.Errorf("ResourceQuota should admit all deletes: %v", err) } @@ -190,11 +191,11 @@ func TestAdmissionIgnoresSubresources(t *testing.T) { } informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) newPod := validPod("123", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error because the pod exceeded allowed quota") } - err = handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Did not expect an error because the action went to a subresource: %v", err) } @@ -235,7 +236,7 @@ func TestAdmitBelowQuotaLimit(t *testing.T) { } informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -318,13 +319,13 @@ func TestAdmitDryRun(t *testing.T) { informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } newPod = validPod("too-large-pod", 1, getResourceRequirements(getResourceList("100m", "60Gi"), getResourceList("", ""))) - err = handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) if err == nil { t.Errorf("Expected error but got none") } @@ -384,7 +385,7 @@ func TestAdmitHandlesOldObjects(t *testing.T) { Ports: []api.ServicePort{{Port: 1234}}, }, } - err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -485,7 +486,7 @@ func TestAdmitHandlesNegativePVCUpdates(t *testing.T) { }, } - err := handler.Validate(admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -544,7 +545,7 @@ func TestAdmitHandlesPVCUpdates(t *testing.T) { }, } - err := handler.Validate(admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -641,7 +642,7 @@ func TestAdmitHandlesCreatingUpdates(t *testing.T) { Ports: []api.ServicePort{{Port: 1234}}, }, } - err := handler.Validate(admission.NewAttributesRecord(newService, oldService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, oldService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -724,7 +725,7 @@ func TestAdmitExceedQuotaLimit(t *testing.T) { } informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error exceeding quota") } @@ -770,7 +771,7 @@ func TestAdmitEnforceQuotaConstraints(t *testing.T) { informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) // verify all values are specified as required on the quota newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("200m", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error because the pod does not specify a memory limit") } @@ -821,7 +822,7 @@ func TestAdmitPodInNamespaceWithoutQuota(t *testing.T) { newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("200m", ""))) // Add to the lru cache so we do not do a live client lookup liveLookupCache.Add(newPod.Namespace, liveLookupEntry{expiry: time.Now().Add(time.Duration(30 * time.Second)), items: []*corev1.ResourceQuota{}}) - err = handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Did not expect an error because the pod is in a different namespace than the quota") } @@ -890,7 +891,7 @@ func TestAdmitBelowTerminatingQuotaLimit(t *testing.T) { newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) activeDeadlineSeconds := int64(30) newPod.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -994,7 +995,7 @@ func TestAdmitBelowBestEffortQuotaLimit(t *testing.T) { // create a pod that is best effort because it does not make a request for anything newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("", ""), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -1084,7 +1085,7 @@ func TestAdmitBestEffortQuotaLimitIgnoresBurstable(t *testing.T) { } informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -1193,7 +1194,7 @@ func TestAdmissionSetsMissingNamespace(t *testing.T) { // unset the namespace newPod.ObjectMeta.Namespace = "" - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Got unexpected error: %v", err) } @@ -1236,14 +1237,14 @@ func TestAdmitRejectsNegativeUsage(t *testing.T) { informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) // verify quota rejects negative pvc storage requests newPvc := validPersistentVolumeClaim("not-allowed-pvc", getResourceRequirements(api.ResourceList{api.ResourceStorage: resource.MustParse("-1Gi")}, api.ResourceList{})) - err := handler.Validate(admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error because the pvc has negative storage usage") } // verify quota accepts non-negative pvc storage requests newPvc = validPersistentVolumeClaim("not-allowed-pvc", getResourceRequirements(api.ResourceList{api.ResourceStorage: resource.MustParse("1Gi")}, api.ResourceList{})) - err = handler.Validate(admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -1284,7 +1285,7 @@ func TestAdmitWhenUnrelatedResourceExceedsQuota(t *testing.T) { // create a pod that should pass existing quota newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("", ""), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -1318,7 +1319,7 @@ func TestAdmitLimitedResourceNoQuota(t *testing.T) { evaluator: evaluator, } newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error for consuming a limited resource without quota.") } @@ -1352,7 +1353,7 @@ func TestAdmitLimitedResourceNoQuotaIgnoresNonMatchingResources(t *testing.T) { evaluator: evaluator, } newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } @@ -1400,7 +1401,7 @@ func TestAdmitLimitedResourceWithQuota(t *testing.T) { } indexer.Add(resourceQuota) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error: %v", err) } @@ -1460,7 +1461,7 @@ func TestAdmitLimitedResourceWithMultipleQuota(t *testing.T) { indexer.Add(resourceQuota1) indexer.Add(resourceQuota2) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error: %v", err) } @@ -1508,7 +1509,7 @@ func TestAdmitLimitedResourceWithQuotaThatDoesNotCover(t *testing.T) { } indexer.Add(resourceQuota) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Fatalf("Expected an error since the quota did not cover cpu") } @@ -2169,7 +2170,7 @@ func TestAdmitLimitedScopeWithCoverQuota(t *testing.T) { if testCase.anotherQuota != nil { indexer.Add(testCase.anotherQuota) } - err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if testCase.expErr == "" { if err != nil { t.Fatalf("Testcase, %v, failed with unexpected error: %v. ExpErr: %v", testCase.description, err, testCase.expErr) @@ -2221,7 +2222,7 @@ func TestAdmitZeroDeltaUsageWithoutCoveringQuota(t *testing.T) { Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer}, } - err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error: %v", err) } @@ -2267,7 +2268,7 @@ func TestAdmitRejectIncreaseUsageWithoutCoveringQuota(t *testing.T) { Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer}, } - err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error for consuming a limited resource without quota.") } @@ -2313,7 +2314,7 @@ func TestAdmitAllowDecreaseUsageWithoutCoveringQuota(t *testing.T) { }, } - err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Expected no error for decreasing a limited resource without quota, got %v", err) } diff --git a/plugin/pkg/admission/runtimeclass/admission.go b/plugin/pkg/admission/runtimeclass/admission.go index b4876c0b444..ac68de7f829 100644 --- a/plugin/pkg/admission/runtimeclass/admission.go +++ b/plugin/pkg/admission/runtimeclass/admission.go @@ -22,6 +22,7 @@ limitations under the License. package runtimeclass import ( + "context" "fmt" "io" @@ -79,7 +80,7 @@ func (r *RuntimeClass) ValidateInitialization() error { } // Admit makes an admission decision based on the request attributes -func (r *RuntimeClass) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) error { +func (r *RuntimeClass) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error { // Ignore all calls to subresources or resources other than pods. if shouldIgnore(attributes) { @@ -101,7 +102,7 @@ func (r *RuntimeClass) Admit(attributes admission.Attributes, o admission.Object } // Validate makes sure that pod adhere's to RuntimeClass's definition -func (r *RuntimeClass) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) error { +func (r *RuntimeClass) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error { // Ignore all calls to subresources or resources other than pods. if shouldIgnore(attributes) { diff --git a/plugin/pkg/admission/runtimeclass/admission_test.go b/plugin/pkg/admission/runtimeclass/admission_test.go index 0bff4d5d9d0..d3db68e7091 100644 --- a/plugin/pkg/admission/runtimeclass/admission_test.go +++ b/plugin/pkg/admission/runtimeclass/admission_test.go @@ -17,6 +17,10 @@ limitations under the License. package runtimeclass import ( + "context" + "strconv" + "testing" + corev1 "k8s.io/api/core/v1" "k8s.io/api/node/v1beta1" "k8s.io/apimachinery/pkg/api/resource" @@ -28,8 +32,6 @@ import ( featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/features" - "strconv" - "testing" "github.com/stretchr/testify/assert" ) @@ -217,7 +219,7 @@ func TestValidate(t *testing.T) { attrs := admission.NewAttributesRecord(tc.pod, nil, core.Kind("Pod").WithVersion("version"), tc.pod.Namespace, tc.pod.Name, core.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) - errs := rt.Validate(attrs, o) + errs := rt.Validate(context.TODO(), attrs, o) if tc.expectError { assert.NotEmpty(t, errs) } else { diff --git a/plugin/pkg/admission/security/podsecuritypolicy/admission.go b/plugin/pkg/admission/security/podsecuritypolicy/admission.go index 132a07d2332..bfcc70bcefe 100644 --- a/plugin/pkg/admission/security/podsecuritypolicy/admission.go +++ b/plugin/pkg/admission/security/podsecuritypolicy/admission.go @@ -17,6 +17,7 @@ limitations under the License. package podsecuritypolicy import ( + "context" "fmt" "io" "sort" @@ -109,7 +110,7 @@ func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactor // 3. Try to generate and validate a PSP with providers. If we find one then admit the pod // with the validated PSP. If we don't find any reject the pod and give all errors from the // failed attempts. -func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if ignore, err := shouldIgnore(a); err != nil { return err } else if ignore { @@ -150,7 +151,7 @@ func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) err } // Validate verifies attributes against the PodSecurityPolicy -func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if ignore, err := shouldIgnore(a); err != nil { return err } else if ignore { diff --git a/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go b/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go index 91081e69c61..a313305aa96 100644 --- a/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go +++ b/plugin/pkg/admission/security/podsecuritypolicy/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package podsecuritypolicy import ( + "context" "fmt" "reflect" "strings" @@ -479,7 +480,7 @@ func TestFailClosedOnInvalidPod(t *testing.T) { pod := &v1.Pod{} attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, kapi.Resource("pods").WithVersion("version"), "", kadmission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) - err := plugin.Admit(attrs, nil) + err := plugin.Admit(context.TODO(), attrs, nil) if err == nil { t.Fatalf("expected versioned pod object to fail mutating admission") } @@ -487,7 +488,7 @@ func TestFailClosedOnInvalidPod(t *testing.T) { t.Errorf("expected type error on Admit but got: %v", err) } - err = plugin.Validate(attrs, nil) + err = plugin.Validate(context.TODO(), attrs, nil) if err == nil { t.Fatalf("expected versioned pod object to fail validating admission") } @@ -1785,7 +1786,7 @@ func testPSPAdmitAdvanced(testCaseName string, op kadmission.Operation, psps []* attrs := kadmission.NewAttributesRecord(pod, oldPod, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, "", kapi.Resource("pods").WithVersion("version"), "", op, nil, false, userInfo) annotations := make(map[string]string) attrs = &fakeAttributes{attrs, annotations} - err := admissiontesting.WithReinvocationTesting(t, plugin).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, plugin).Admit(context.TODO(), attrs, nil) if shouldPassAdmit && err != nil { t.Errorf("%s: expected no errors on Admit but received %v", testCaseName, err) @@ -1813,7 +1814,7 @@ func testPSPAdmitAdvanced(testCaseName string, op kadmission.Operation, psps []* t.Errorf("%s: expected errors on Admit but received none", testCaseName) } - err = plugin.Validate(attrs, nil) + err = plugin.Validate(context.TODO(), attrs, nil) psp := "" if shouldPassAdmit && op == kadmission.Create { psp = expectedPSP diff --git a/plugin/pkg/admission/securitycontext/scdeny/admission.go b/plugin/pkg/admission/securitycontext/scdeny/admission.go index f17ce851573..c5da558c7bf 100644 --- a/plugin/pkg/admission/securitycontext/scdeny/admission.go +++ b/plugin/pkg/admission/securitycontext/scdeny/admission.go @@ -17,6 +17,7 @@ limitations under the License. package scdeny import ( + "context" "fmt" "io" @@ -50,7 +51,7 @@ func NewSecurityContextDeny() *Plugin { } // Validate will deny any pod that defines SupplementalGroups, SELinuxOptions, RunAsUser or FSGroup -func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if a.GetSubresource() != "" || a.GetResource().GroupResource() != api.Resource("pods") { return nil } diff --git a/plugin/pkg/admission/securitycontext/scdeny/admission_test.go b/plugin/pkg/admission/securitycontext/scdeny/admission_test.go index 0111341d00b..210d2844705 100644 --- a/plugin/pkg/admission/securitycontext/scdeny/admission_test.go +++ b/plugin/pkg/admission/securitycontext/scdeny/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package scdeny import ( + "context" "testing" "k8s.io/apiserver/pkg/admission" @@ -82,7 +83,7 @@ func TestAdmission(t *testing.T) { p.Spec.SecurityContext = tc.podSc p.Spec.Containers[0].SecurityContext = tc.sc - err := handler.Validate(admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) if err != nil && !tc.expectError { t.Errorf("%v: unexpected error: %v", tc.name, err) } else if err == nil && tc.expectError { @@ -96,7 +97,7 @@ func TestAdmission(t *testing.T) { p.Spec.InitContainers = p.Spec.Containers p.Spec.Containers = nil - err = handler.Validate(admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) + err = handler.Validate(context.TODO(), admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) if err != nil && !tc.expectError { t.Errorf("%v: unexpected error: %v", tc.name, err) } else if err == nil && tc.expectError { @@ -140,7 +141,7 @@ func TestPodSecurityContextAdmission(t *testing.T) { } for _, test := range tests { pod.Spec.SecurityContext = &test.securityContext - err := handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) + err := handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) if test.errorExpected && err == nil { t.Errorf("Expected error for security context %+v but did not get an error", test.securityContext) diff --git a/plugin/pkg/admission/serviceaccount/admission.go b/plugin/pkg/admission/serviceaccount/admission.go index 974940f1016..11de1ad1005 100644 --- a/plugin/pkg/admission/serviceaccount/admission.go +++ b/plugin/pkg/admission/serviceaccount/admission.go @@ -17,6 +17,7 @@ limitations under the License. package serviceaccount import ( + "context" "fmt" "io" "math/rand" @@ -154,7 +155,7 @@ func (s *Plugin) ValidateInitialization() error { } // Admit verifies if the pod should be admitted -func (s *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (s *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if shouldIgnore(a) { return nil } @@ -165,7 +166,7 @@ func (s *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) (er // That makes the kubelet very angry and confused, and it immediately deletes the pod (because the spec doesn't match) // That said, don't allow mirror pods to reference ServiceAccounts or SecretVolumeSources either if _, isMirrorPod := pod.Annotations[api.MirrorPodAnnotationKey]; isMirrorPod { - return s.Validate(a, o) + return s.Validate(ctx, a, o) } // Set the default service account if needed @@ -192,11 +193,11 @@ func (s *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) (er } } - return s.Validate(a, o) + return s.Validate(ctx, a, o) } // Validate the data we obtained -func (s *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (s *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if shouldIgnore(a) { return nil } diff --git a/plugin/pkg/admission/serviceaccount/admission_test.go b/plugin/pkg/admission/serviceaccount/admission_test.go index 4a8e2ca89b1..029c6a53fdc 100644 --- a/plugin/pkg/admission/serviceaccount/admission_test.go +++ b/plugin/pkg/admission/serviceaccount/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package serviceaccount import ( + "context" "reflect" "strings" "testing" @@ -66,7 +67,7 @@ func TestIgnoresNonPodResource(t *testing.T) { pod := &api.Pod{} attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("CustomResource").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()) - err := handler.Admit(attrs, nil) + err := handler.Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Expected non-pod resource allowed, got err: %v", err) } @@ -75,7 +76,7 @@ func TestIgnoresNonPodResource(t *testing.T) { func TestIgnoresNilObject(t *testing.T) { attrs := admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()) - err := handler.Admit(attrs, nil) + err := handler.Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Expected nil object allowed allowed, got err: %v", err) } @@ -85,7 +86,7 @@ func TestIgnoresNonPodObject(t *testing.T) { obj := &api.Namespace{} attrs := admission.NewAttributesRecord(obj, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()) - err := handler.Admit(attrs, nil) + err := handler.Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Expected non pod object allowed, got err: %v", err) } @@ -105,7 +106,7 @@ func TestIgnoresMirrorPod(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Expected mirror pod without service account or secrets allowed, got err: %v", err) } @@ -123,7 +124,7 @@ func TestRejectsMirrorPodWithServiceAccount(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil) if err == nil { t.Errorf("Expected a mirror pod to be prevented from referencing a service account") } @@ -143,7 +144,7 @@ func TestRejectsMirrorPodWithSecretVolumes(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil) if err == nil { t.Errorf("Expected a mirror pod to be prevented from referencing a secret volume") } @@ -168,7 +169,7 @@ func TestRejectsMirrorPodWithServiceAccountTokenVolumeProjections(t *testing.T) }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil) if err == nil { t.Errorf("Expected a mirror pod to be prevented from referencing a ServiceAccountToken volume projection") } @@ -193,7 +194,7 @@ func TestAssignsDefaultServiceAccountAndToleratesMissingAPIToken(t *testing.T) { pod := &api.Pod{} attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -221,7 +222,7 @@ func TestAssignsDefaultServiceAccountAndRejectsMissingAPIToken(t *testing.T) { pod := &api.Pod{} attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err == nil || !errors.IsServerTimeout(err) { t.Errorf("Expected server timeout error for missing API token: %v", err) } @@ -246,7 +247,7 @@ func TestFetchesUncachedServiceAccount(t *testing.T) { pod := &api.Pod{} attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -268,7 +269,7 @@ func TestDeniesInvalidServiceAccount(t *testing.T) { pod := &api.Pod{} attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err == nil { t.Errorf("Expected error for missing service account, got none") } @@ -334,7 +335,7 @@ func TestAutomountsAPIToken(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -363,7 +364,7 @@ func TestAutomountsAPIToken(t *testing.T) { }, } attrs = admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil { t.Errorf("Unexpected error: %v", err) } if pod.Spec.ServiceAccountName != DefaultServiceAccountName { @@ -445,7 +446,7 @@ func TestRespectsExistingMount(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -475,7 +476,7 @@ func TestRespectsExistingMount(t *testing.T) { }, } attrs = admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil { t.Errorf("Unexpected error: %v", err) } if pod.Spec.ServiceAccountName != DefaultServiceAccountName { @@ -521,7 +522,7 @@ func TestAllowsReferencedSecret(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod1, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil { t.Errorf("Unexpected error: %v", err) } @@ -545,7 +546,7 @@ func TestAllowsReferencedSecret(t *testing.T) { }, } attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil { t.Errorf("Unexpected error: %v", err) } @@ -569,7 +570,7 @@ func TestAllowsReferencedSecret(t *testing.T) { }, } attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil { t.Errorf("Unexpected error: %v", err) } } @@ -599,7 +600,7 @@ func TestRejectsUnreferencedSecretVolumes(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod1, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err == nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err == nil { t.Errorf("Expected rejection for using a secret the service account does not reference") } @@ -623,7 +624,7 @@ func TestRejectsUnreferencedSecretVolumes(t *testing.T) { }, } attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") { t.Errorf("Unexpected error: %v", err) } @@ -647,7 +648,7 @@ func TestRejectsUnreferencedSecretVolumes(t *testing.T) { }, } attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") { t.Errorf("Unexpected error: %v", err) } } @@ -678,7 +679,7 @@ func TestAllowUnreferencedSecretVolumesForPermissiveSAs(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err == nil { t.Errorf("Expected rejection for using a secret the service account does not reference") } @@ -710,7 +711,7 @@ func TestAllowsReferencedImagePullSecrets(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -739,7 +740,7 @@ func TestRejectsUnreferencedImagePullSecrets(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err == nil { t.Errorf("Expected rejection for using a secret the service account does not reference") } @@ -772,7 +773,7 @@ func TestDoNotAddImagePullSecrets(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -806,7 +807,7 @@ func TestAddImagePullSecrets(t *testing.T) { pod := &api.Pod{} attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } @@ -887,7 +888,7 @@ func TestMultipleReferencedSecrets(t *testing.T) { } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { + if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil { t.Fatal(err) } @@ -1041,7 +1042,7 @@ func TestAutomountIsBackwardsCompatible(t *testing.T) { }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) - err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Unexpected error: %v", err) } diff --git a/plugin/pkg/admission/storage/persistentvolume/label/admission.go b/plugin/pkg/admission/storage/persistentvolume/label/admission.go index e0b11581012..ce42d676906 100644 --- a/plugin/pkg/admission/storage/persistentvolume/label/admission.go +++ b/plugin/pkg/admission/storage/persistentvolume/label/admission.go @@ -97,7 +97,7 @@ func nodeSelectorRequirementKeysExistInNodeSelectorTerms(reqs []api.NodeSelector return false } -func (l *persistentVolumeLabel) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (l *persistentVolumeLabel) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if a.GetResource().GroupResource() != api.Resource("persistentvolumes") { return nil } diff --git a/plugin/pkg/admission/storage/persistentvolume/label/admission_test.go b/plugin/pkg/admission/storage/persistentvolume/label/admission_test.go index 2fb219836ef..eff70238b2e 100644 --- a/plugin/pkg/admission/storage/persistentvolume/label/admission_test.go +++ b/plugin/pkg/admission/storage/persistentvolume/label/admission_test.go @@ -757,7 +757,7 @@ func Test_PVLAdmission(t *testing.T) { setPVLabeler(testcase.handler, testcase.pvlabeler) handler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(testcase.handler)) - err := handler.Admit(admission.NewAttributesRecord(testcase.preAdmissionPV, nil, api.Kind("PersistentVolume").WithVersion("version"), testcase.preAdmissionPV.Namespace, testcase.preAdmissionPV.Name, api.Resource("persistentvolumes").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err := handler.Admit(context.TODO(), admission.NewAttributesRecord(testcase.preAdmissionPV, nil, api.Kind("PersistentVolume").WithVersion("version"), testcase.preAdmissionPV.Namespace, testcase.preAdmissionPV.Name, api.Resource("persistentvolumes").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if !reflect.DeepEqual(err, testcase.err) { t.Logf("expected error: %q", testcase.err) t.Logf("actual error: %q", err) diff --git a/plugin/pkg/admission/storage/persistentvolume/resize/admission.go b/plugin/pkg/admission/storage/persistentvolume/resize/admission.go index e616826faea..398781661ea 100644 --- a/plugin/pkg/admission/storage/persistentvolume/resize/admission.go +++ b/plugin/pkg/admission/storage/persistentvolume/resize/admission.go @@ -17,6 +17,7 @@ limitations under the License. package resize import ( + "context" "fmt" "io" @@ -71,7 +72,7 @@ func (pvcr *persistentVolumeClaimResize) ValidateInitialization() error { return nil } -func (pvcr *persistentVolumeClaimResize) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (pvcr *persistentVolumeClaimResize) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if a.GetResource().GroupResource() != api.Resource("persistentvolumeclaims") { return nil } diff --git a/plugin/pkg/admission/storage/persistentvolume/resize/admission_test.go b/plugin/pkg/admission/storage/persistentvolume/resize/admission_test.go index 699a24abff3..01089b97db3 100644 --- a/plugin/pkg/admission/storage/persistentvolume/resize/admission_test.go +++ b/plugin/pkg/admission/storage/persistentvolume/resize/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package resize import ( + "context" "fmt" "strings" "testing" @@ -257,7 +258,7 @@ func TestPVCResizeAdmission(t *testing.T) { operationOptions := &metav1.CreateOptions{} attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, operationOptions, false, nil) - err := ctrl.Validate(attributes, nil) + err := ctrl.Validate(context.TODO(), attributes, nil) if !tc.checkError(err) { t.Errorf("%v: unexpected err: %v", tc.name, err) } diff --git a/plugin/pkg/admission/storage/storageclass/setdefault/admission.go b/plugin/pkg/admission/storage/storageclass/setdefault/admission.go index 9366312c935..8302efb77e1 100644 --- a/plugin/pkg/admission/storage/storageclass/setdefault/admission.go +++ b/plugin/pkg/admission/storage/storageclass/setdefault/admission.go @@ -17,6 +17,7 @@ limitations under the License. package setdefault import ( + "context" "fmt" "io" @@ -85,7 +86,7 @@ func (a *claimDefaulterPlugin) ValidateInitialization() error { // 1. Find available StorageClasses. // 2. Figure which is the default // 3. Write to the PVClaim -func (a *claimDefaulterPlugin) Admit(attr admission.Attributes, o admission.ObjectInterfaces) error { +func (a *claimDefaulterPlugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error { if attr.GetResource().GroupResource() != api.Resource("persistentvolumeclaims") { return nil } diff --git a/plugin/pkg/admission/storage/storageclass/setdefault/admission_test.go b/plugin/pkg/admission/storage/storageclass/setdefault/admission_test.go index e47bb825857..01bf5314633 100644 --- a/plugin/pkg/admission/storage/storageclass/setdefault/admission_test.go +++ b/plugin/pkg/admission/storage/storageclass/setdefault/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package setdefault import ( + "context" "testing" "k8s.io/klog" @@ -213,7 +214,7 @@ func TestAdmission(t *testing.T) { false, // dryRun nil, // userInfo ) - err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(attrs, nil) + err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(context.TODO(), attrs, nil) klog.Infof("Got %v", err) if err != nil && !test.expectError { t.Errorf("Test %q: unexpected error received: %v", test.name, err) diff --git a/plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go b/plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go index 8c70d927c8f..764e0a815c7 100644 --- a/plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go +++ b/plugin/pkg/admission/storage/storageobjectinuseprotection/admission.go @@ -17,6 +17,7 @@ limitations under the License. package storageobjectinuseprotection import ( + "context" "io" "k8s.io/klog" @@ -65,7 +66,7 @@ var ( // // This prevents users from deleting a PVC that's used by a running pod. // This also prevents admin from deleting a PV that's bound by a PVC -func (c *storageProtectionPlugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (c *storageProtectionPlugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { if !feature.DefaultFeatureGate.Enabled(features.StorageObjectInUseProtection) { return nil } diff --git a/plugin/pkg/admission/storage/storageobjectinuseprotection/admission_test.go b/plugin/pkg/admission/storage/storageobjectinuseprotection/admission_test.go index 15f77f8af70..7b86621c55a 100644 --- a/plugin/pkg/admission/storage/storageobjectinuseprotection/admission_test.go +++ b/plugin/pkg/admission/storage/storageobjectinuseprotection/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package storageobjectinuseprotection import ( + "context" "reflect" "testing" @@ -136,7 +137,7 @@ func TestAdmit(t *testing.T) { nil, // userInfo ) - err := ctrl.Admit(attrs, nil) + err := ctrl.Admit(context.TODO(), attrs, nil) if err != nil { t.Errorf("Test %q: got unexpected error: %v", test.name, err) } diff --git a/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go b/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go index 4c5165c69b7..ef4c4f84eeb 100644 --- a/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go +++ b/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource/etcd.go @@ -297,17 +297,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update } func toScaleCreateValidation(f rest.ValidateObjectFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectFunc { - return func(obj runtime.Object) error { + return func(ctx context.Context, obj runtime.Object) error { scale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath) if err != nil { return err } - return f(scale) + return f(ctx, scale) } } func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectUpdateFunc { - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { newScale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath) if err != nil { return err @@ -316,7 +316,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath, if err != nil { return err } - return f(newScale, oldScale) + return f(ctx, newScale, oldScale) } } diff --git a/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go b/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go index 6d36d37bddc..0368678e120 100644 --- a/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go +++ b/staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition/etcd.go @@ -119,7 +119,7 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va // wrong type return nil, fmt.Errorf("expected *apiextensions.CustomResourceDefinition, got %v", existing) } - if err := deleteValidation(existingCRD); err != nil { + if err := deleteValidation(ctx, existingCRD); err != nil { return nil, err } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/audit.go b/staging/src/k8s.io/apiserver/pkg/admission/audit.go index d81622b9217..6762f53dbf0 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/audit.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/audit.go @@ -17,6 +17,7 @@ limitations under the License. package admission import ( + "context" "fmt" auditinternal "k8s.io/apiserver/pkg/apis/audit" @@ -44,7 +45,7 @@ func WithAudit(i Interface, ae *auditinternal.Event) Interface { return &auditHandler{i, ae} } -func (handler auditHandler) Admit(a Attributes, o ObjectInterfaces) error { +func (handler auditHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error { if !handler.Interface.Handles(a.GetOperation()) { return nil } @@ -53,13 +54,13 @@ func (handler auditHandler) Admit(a Attributes, o ObjectInterfaces) error { } var err error if mutator, ok := handler.Interface.(MutationInterface); ok { - err = mutator.Admit(a, o) + err = mutator.Admit(ctx, a, o) handler.logAnnotations(a) } return err } -func (handler auditHandler) Validate(a Attributes, o ObjectInterfaces) error { +func (handler auditHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error { if !handler.Interface.Handles(a.GetOperation()) { return nil } @@ -68,7 +69,7 @@ func (handler auditHandler) Validate(a Attributes, o ObjectInterfaces) error { } var err error if validator, ok := handler.Interface.(ValidationInterface); ok { - err = validator.Validate(a, o) + err = validator.Validate(ctx, a, o) handler.logAnnotations(a) } return err diff --git a/staging/src/k8s.io/apiserver/pkg/admission/audit_test.go b/staging/src/k8s.io/apiserver/pkg/admission/audit_test.go index 4ead632f6ed..3e1d3d20126 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/audit_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/audit_test.go @@ -17,6 +17,7 @@ limitations under the License. package admission import ( + "context" "fmt" "testing" @@ -45,14 +46,14 @@ var _ Interface = &fakeHandler{} var _ MutationInterface = &fakeHandler{} var _ ValidationInterface = &fakeHandler{} -func (h fakeHandler) Admit(a Attributes, o ObjectInterfaces) error { +func (h fakeHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error { for k, v := range h.admitAnnotations { a.AddAnnotation(k, v) } return h.admit } -func (h fakeHandler) Validate(a Attributes, o ObjectInterfaces) error { +func (h fakeHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error { for k, v := range h.validateAnnotations { a.AddAnnotation(k, v) } @@ -149,13 +150,13 @@ func TestWithAudit(t *testing.T) { require.True(t, ok) auditMutator, ok := auditHandler.(MutationInterface) require.True(t, ok) - assert.Equal(t, mutator.Admit(a, nil), auditMutator.Admit(a, nil), tcName+": WithAudit decorator should not effect the return value") + assert.Equal(t, mutator.Admit(context.TODO(), a, nil), auditMutator.Admit(context.TODO(), a, nil), tcName+": WithAudit decorator should not effect the return value") validator, ok := handler.(ValidationInterface) require.True(t, ok) auditValidator, ok := auditHandler.(ValidationInterface) require.True(t, ok) - assert.Equal(t, validator.Validate(a, nil), auditValidator.Validate(a, nil), tcName+": WithAudit decorator should not effect the return value") + assert.Equal(t, validator.Validate(context.TODO(), a, nil), auditValidator.Validate(context.TODO(), a, nil), tcName+": WithAudit decorator should not effect the return value") annotations := make(map[string]string, len(tc.admitAnnotations)+len(tc.validateAnnotations)) for k, v := range tc.admitAnnotations { diff --git a/staging/src/k8s.io/apiserver/pkg/admission/chain.go b/staging/src/k8s.io/apiserver/pkg/admission/chain.go index 37405aeaf04..f2af01ef3c5 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/chain.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/chain.go @@ -16,6 +16,8 @@ limitations under the License. package admission +import "context" + // chainAdmissionHandler is an instance of admission.NamedHandler that performs admission control using // a chain of admission handlers type chainAdmissionHandler []Interface @@ -26,13 +28,13 @@ func NewChainHandler(handlers ...Interface) chainAdmissionHandler { } // Admit performs an admission control check using a chain of handlers, and returns immediately on first error -func (admissionHandler chainAdmissionHandler) Admit(a Attributes, o ObjectInterfaces) error { +func (admissionHandler chainAdmissionHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error { for _, handler := range admissionHandler { if !handler.Handles(a.GetOperation()) { continue } if mutator, ok := handler.(MutationInterface); ok { - err := mutator.Admit(a, o) + err := mutator.Admit(ctx, a, o) if err != nil { return err } @@ -42,13 +44,13 @@ func (admissionHandler chainAdmissionHandler) Admit(a Attributes, o ObjectInterf } // Validate performs an admission control check using a chain of handlers, and returns immediately on first error -func (admissionHandler chainAdmissionHandler) Validate(a Attributes, o ObjectInterfaces) error { +func (admissionHandler chainAdmissionHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error { for _, handler := range admissionHandler { if !handler.Handles(a.GetOperation()) { continue } if validator, ok := handler.(ValidationInterface); ok { - err := validator.Validate(a, o) + err := validator.Validate(ctx, a, o) if err != nil { return err } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/chain_test.go b/staging/src/k8s.io/apiserver/pkg/admission/chain_test.go index 490a0af171e..ec72a28ad51 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/chain_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/chain_test.go @@ -17,6 +17,7 @@ limitations under the License. package admission import ( + "context" "fmt" "testing" @@ -32,7 +33,7 @@ type FakeHandler struct { validate, validateCalled bool } -func (h *FakeHandler) Admit(a Attributes, o ObjectInterfaces) (err error) { +func (h *FakeHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) (err error) { h.admitCalled = true if h.admit { return nil @@ -40,7 +41,7 @@ func (h *FakeHandler) Admit(a Attributes, o ObjectInterfaces) (err error) { return fmt.Errorf("Don't admit") } -func (h *FakeHandler) Validate(a Attributes, o ObjectInterfaces) (err error) { +func (h *FakeHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) (err error) { h.validateCalled = true if h.validate { return nil @@ -125,7 +126,7 @@ func TestAdmitAndValidate(t *testing.T) { for _, test := range tests { t.Logf("testcase = %s", test.name) // call admit and check that validate was not called at all - err := test.chain.Admit(NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) + err := test.chain.Admit(context.TODO(), NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) accepted := (err == nil) if accepted != test.accept { t.Errorf("unexpected result of admit call: %v", accepted) @@ -146,7 +147,7 @@ func TestAdmitAndValidate(t *testing.T) { } // call validate and check that admit was not called at all - err = test.chain.Validate(NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) + err = test.chain.Validate(context.TODO(), NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) accepted = (err == nil) if accepted != test.accept { t.Errorf("unexpected result of validate call: %v\n", accepted) diff --git a/staging/src/k8s.io/apiserver/pkg/admission/initializer/initializer_test.go b/staging/src/k8s.io/apiserver/pkg/admission/initializer/initializer_test.go index fd2d500619f..2726671d5f7 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/initializer/initializer_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/initializer/initializer_test.go @@ -17,6 +17,7 @@ limitations under the License. package initializer_test import ( + "context" "testing" "time" @@ -72,7 +73,7 @@ type WantExternalKubeInformerFactory struct { func (self *WantExternalKubeInformerFactory) SetExternalKubeInformerFactory(sf informers.SharedInformerFactory) { self.sf = sf } -func (self *WantExternalKubeInformerFactory) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (self *WantExternalKubeInformerFactory) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { return nil } func (self *WantExternalKubeInformerFactory) Handles(o admission.Operation) bool { return false } @@ -87,7 +88,7 @@ type WantExternalKubeClientSet struct { } func (self *WantExternalKubeClientSet) SetExternalKubeClientSet(cs kubernetes.Interface) { self.cs = cs } -func (self *WantExternalKubeClientSet) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (self *WantExternalKubeClientSet) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { return nil } func (self *WantExternalKubeClientSet) Handles(o admission.Operation) bool { return false } @@ -102,7 +103,7 @@ type WantAuthorizerAdmission struct { } func (self *WantAuthorizerAdmission) SetAuthorizer(a authorizer.Authorizer) { self.auth = a } -func (self *WantAuthorizerAdmission) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (self *WantAuthorizerAdmission) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { return nil } func (self *WantAuthorizerAdmission) Handles(o admission.Operation) bool { return false } @@ -124,7 +125,7 @@ type clientCertWanter struct { } func (s *clientCertWanter) SetClientCert(cert, key []byte) { s.gotCert, s.gotKey = cert, key } -func (s *clientCertWanter) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (s *clientCertWanter) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { return nil } func (s *clientCertWanter) Handles(o admission.Operation) bool { return false } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/interfaces.go b/staging/src/k8s.io/apiserver/pkg/admission/interfaces.go index 5f6d703b216..a3e3cbdbe2a 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/interfaces.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/interfaces.go @@ -17,6 +17,7 @@ limitations under the License. package admission import ( + "context" "io" "k8s.io/apimachinery/pkg/runtime" @@ -120,8 +121,9 @@ type Interface interface { type MutationInterface interface { Interface - // Admit makes an admission decision based on the request attributes - Admit(a Attributes, o ObjectInterfaces) (err error) + // Admit makes an admission decision based on the request attributes. + // Context is used only for timeout/deadline/cancellation and tracing information. + Admit(ctx context.Context, a Attributes, o ObjectInterfaces) (err error) } // ValidationInterface is an abstract, pluggable interface for Admission Control decisions. @@ -129,7 +131,8 @@ type ValidationInterface interface { Interface // Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate - Validate(a Attributes, o ObjectInterfaces) (err error) + // Context is used only for timeout/deadline/cancellation and tracing information. + Validate(ctx context.Context, a Attributes, o ObjectInterfaces) (err error) } // Operation is the type of resource operation being checked for admission control diff --git a/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go b/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go index 56cc07edd39..dbdc5db783c 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics.go @@ -17,6 +17,7 @@ limitations under the License. package metrics import ( + "context" "fmt" "strconv" "time" @@ -75,27 +76,27 @@ type pluginHandlerWithMetrics struct { } // Admit performs a mutating admission control check and emit metrics. -func (p pluginHandlerWithMetrics) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p pluginHandlerWithMetrics) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { mutatingHandler, ok := p.Interface.(admission.MutationInterface) if !ok { return nil } start := time.Now() - err := mutatingHandler.Admit(a, o) + err := mutatingHandler.Admit(ctx, a, o) p.observer(time.Since(start), err != nil, a, stepAdmit, p.extraLabels...) return err } // Validate performs a non-mutating admission control check and emits metrics. -func (p pluginHandlerWithMetrics) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { +func (p pluginHandlerWithMetrics) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { validatingHandler, ok := p.Interface.(admission.ValidationInterface) if !ok { return nil } start := time.Now() - err := validatingHandler.Validate(a, o) + err := validatingHandler.Validate(ctx, a, o) p.observer(time.Since(start), err != nil, a, stepValidate, p.extraLabels...) return err } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics_test.go b/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics_test.go index 2934b624b9b..1b96d25a217 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/metrics/metrics_test.go @@ -17,6 +17,7 @@ limitations under the License. package metrics import ( + "context" "fmt" "testing" "time" @@ -36,8 +37,8 @@ var ( func TestObserveAdmissionStep(t *testing.T) { Metrics.reset() handler := WithStepMetrics(&mutatingAndValidatingFakeHandler{admission.NewHandler(admission.Create), true, true}) - handler.(admission.MutationInterface).Admit(attr, nil) - handler.(admission.ValidationInterface).Validate(attr, nil) + handler.(admission.MutationInterface).Admit(context.TODO(), attr, nil) + handler.(admission.ValidationInterface).Validate(context.TODO(), attr, nil) wantLabels := map[string]string{ "operation": string(admission.Create), "type": "admit", @@ -54,8 +55,8 @@ func TestObserveAdmissionStep(t *testing.T) { func TestObserveAdmissionController(t *testing.T) { Metrics.reset() handler := WithControllerMetrics(&mutatingAndValidatingFakeHandler{admission.NewHandler(admission.Create), true, true}, "a") - handler.(admission.MutationInterface).Admit(attr, nil) - handler.(admission.ValidationInterface).Validate(attr, nil) + handler.(admission.MutationInterface).Admit(context.TODO(), attr, nil) + handler.(admission.ValidationInterface).Validate(context.TODO(), attr, nil) wantLabels := map[string]string{ "name": "a", "operation": string(admission.Create), @@ -154,7 +155,7 @@ func TestWithMetrics(t *testing.T) { h := WithMetrics(test.handler, Metrics.ObserveAdmissionController, test.name) // test mutation - err := h.(admission.MutationInterface).Admit(admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) + err := h.(admission.MutationInterface).Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) if test.admit && err != nil { t.Errorf("expected admit to succeed, but failed: %v", err) continue @@ -179,7 +180,7 @@ func TestWithMetrics(t *testing.T) { } // test validation - err = h.(admission.ValidationInterface).Validate(admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) + err = h.(admission.ValidationInterface).Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) if test.validate && err != nil { t.Errorf("expected admit to succeed, but failed: %v", err) continue @@ -206,14 +207,14 @@ type mutatingAndValidatingFakeHandler struct { validate bool } -func (h *mutatingAndValidatingFakeHandler) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (h *mutatingAndValidatingFakeHandler) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if h.admit { return nil } return fmt.Errorf("don't admit") } -func (h *mutatingAndValidatingFakeHandler) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (h *mutatingAndValidatingFakeHandler) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if h.validate { return nil } @@ -225,7 +226,7 @@ type validatingFakeHandler struct { validate bool } -func (h *validatingFakeHandler) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (h *validatingFakeHandler) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if h.validate { return nil } @@ -237,7 +238,7 @@ type mutatingFakeHandler struct { admit bool } -func (h *mutatingFakeHandler) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (h *mutatingFakeHandler) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { if h.admit { return nil } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go index c6517bee31e..1fbac451742 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission.go @@ -17,13 +17,14 @@ limitations under the License. package lifecycle import ( + "context" "fmt" "io" "time" "k8s.io/klog" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -73,7 +74,7 @@ var _ = initializer.WantsExternalKubeInformerFactory(&Lifecycle{}) var _ = initializer.WantsExternalKubeClientSet(&Lifecycle{}) // Admit makes an admission decision based on the request attributes -func (l *Lifecycle) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (l *Lifecycle) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { // prevent deletion of immortal namespaces if a.GetOperation() == admission.Delete && a.GetKind().GroupKind() == v1.SchemeGroupVersion.WithKind("Namespace").GroupKind() && l.immortalNamespaces.Has(a.GetName()) { return errors.NewForbidden(a.GetResource().GroupResource(), a.GetName(), fmt.Errorf("this namespace may not be deleted")) diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission_test.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission_test.go index ccc17392ee0..0ab9bf3e797 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package lifecycle import ( + "context" "fmt" "testing" "time" @@ -104,7 +105,7 @@ func TestAccessReviewCheckOnMissingNamespace(t *testing.T) { } informerFactory.Start(wait.NeverStop) - err = handler.Admit(admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{Group: "authorization.k8s.io", Version: "v1", Kind: "LocalSubjectAccesReview"}, namespace, "", schema.GroupVersionResource{Group: "authorization.k8s.io", Version: "v1", Resource: "localsubjectaccessreviews"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{Group: "authorization.k8s.io", Version: "v1", Kind: "LocalSubjectAccesReview"}, namespace, "", schema.GroupVersionResource{Group: "authorization.k8s.io", Version: "v1", Resource: "localsubjectaccessreviews"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Error(err) } @@ -124,7 +125,7 @@ func TestAdmissionNamespaceDoesNotExist(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { actions := "" for _, action := range mockClient.Actions() { @@ -134,19 +135,19 @@ func TestAdmissionNamespaceDoesNotExist(t *testing.T) { } // verify create operations in the namespace cause an error - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected error rejecting creates in a namespace when it is missing") } // verify update operations in the namespace cause an error - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected error rejecting updates in a namespace when it is missing") } // verify delete operations in the namespace can proceed - err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error returned from admission handler: %v", err) } @@ -166,7 +167,7 @@ func TestAdmissionNamespaceActive(t *testing.T) { informerFactory.Start(wait.NeverStop) pod := newPod(namespace) - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("unexpected error returned from admission handler") } @@ -187,31 +188,31 @@ func TestAdmissionNamespaceTerminating(t *testing.T) { pod := newPod(namespace) // verify create operations in the namespace cause an error - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected error rejecting creates in a namespace when it is terminating") } // verify update operations in the namespace can proceed - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error returned from admission handler: %v", err) } // verify delete operations in the namespace can proceed - err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error returned from admission handler: %v", err) } // verify delete of namespace default can never proceed - err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", metav1.NamespaceDefault, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", metav1.NamespaceDefault, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected an error that this namespace can never be deleted") } // verify delete of namespace other than default can proceed - err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", "other", v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", "other", v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) if err != nil { t.Errorf("Did not expect an error %v", err) } @@ -238,7 +239,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) { pod := newPod(namespace) // verify create operations in the namespace is allowed - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err != nil { t.Errorf("Unexpected error rejecting creates in an active namespace") } @@ -248,7 +249,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) { getCalls = 0 // verify delete of namespace can proceed - err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), namespace, namespace, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), namespace, namespace, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) if err != nil { t.Errorf("Expected namespace deletion to be allowed") } @@ -261,7 +262,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) { phases[namespace] = v1.NamespaceTerminating // verify create operations in the namespace cause an error - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected error rejecting creates in a namespace right after deleting it") } @@ -274,7 +275,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) { fakeClock.Step(forceLiveLookupTTL) // verify create operations in the namespace cause an error - err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if err == nil { t.Errorf("Expected error rejecting creates in a namespace right after deleting it") } @@ -287,7 +288,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) { fakeClock.Step(time.Millisecond) // verify create operations in the namespace don't force a live lookup after the timeout - handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) + handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) if getCalls != 0 { t.Errorf("Expected no live lookup of the namespace at t=forceLiveLookupTTL+1ms, got %d", getCalls) } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go index 51453a35895..a4a6aff51a5 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/webhook.go @@ -211,7 +211,7 @@ type attrWithResourceOverride struct { func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource } // Dispatch is called by the downstream Validate or Admit methods. -func (a *Webhook) Dispatch(attr admission.Attributes, o admission.ObjectInterfaces) error { +func (a *Webhook) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error { if rules.IsWebhookConfigurationResource(attr) { return nil } @@ -219,8 +219,5 @@ func (a *Webhook) Dispatch(attr admission.Attributes, o admission.ObjectInterfac return admission.NewForbidden(attr, fmt.Errorf("not yet ready to handle request")) } hooks := a.hookSource.Webhooks() - // TODO: Figure out if adding one second timeout make sense here. - ctx := context.TODO() - return a.dispatcher.Dispatch(ctx, attr, o, hooks) } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go index 6202fbc63fe..fb07a61c1b8 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin.go @@ -17,6 +17,7 @@ limitations under the License. package mutating import ( + "context" "io" "k8s.io/apiserver/pkg/admission" @@ -70,6 +71,6 @@ func (a *Plugin) ValidateInitialization() error { } // Admit makes an admission decision based on the request attributes. -func (a *Plugin) Admit(attr admission.Attributes, o admission.ObjectInterfaces) error { - return a.Webhook.Dispatch(attr, o) +func (a *Plugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error { + return a.Webhook.Dispatch(ctx, attr, o) } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin_test.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin_test.go index db178eeca23..a24087360ea 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating/plugin_test.go @@ -17,6 +17,7 @@ limitations under the License. package mutating import ( + "context" "fmt" "net/url" "reflect" @@ -80,7 +81,7 @@ func TestAdmit(t *testing.T) { attr = webhooktesting.NewAttribute(ns, tt.AdditionalLabels, tt.IsDryRun) } - err = wh.Admit(attr, objectInterfaces) + err = wh.Admit(context.TODO(), attr, objectInterfaces) if tt.ExpectAllow != (err == nil) { t.Errorf("expected allowed=%v, but got err=%v", tt.ExpectAllow, err) } @@ -163,7 +164,7 @@ func TestAdmitCachedClient(t *testing.T) { continue } - err = wh.Admit(webhooktesting.NewAttribute(ns, nil, false), objectInterfaces) + err = wh.Admit(context.TODO(), webhooktesting.NewAttribute(ns, nil, false), objectInterfaces) if tt.ExpectAllow != (err == nil) { t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err) } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go index 30e5c9d3319..6972877b185 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin.go @@ -17,6 +17,7 @@ limitations under the License. package validating import ( + "context" "io" "k8s.io/apiserver/pkg/admission" @@ -61,6 +62,6 @@ func NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) { } // Validate makes an admission decision based on the request attributes. -func (a *Plugin) Validate(attr admission.Attributes, o admission.ObjectInterfaces) error { - return a.Webhook.Dispatch(attr, o) +func (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error { + return a.Webhook.Dispatch(ctx, attr, o) } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin_test.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin_test.go index a2aec191e39..0734600f7e6 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin_test.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/validating/plugin_test.go @@ -17,6 +17,7 @@ limitations under the License. package validating import ( + "context" "net/url" "strings" "testing" @@ -67,7 +68,7 @@ func TestValidate(t *testing.T) { } attr := webhooktesting.NewAttribute(ns, nil, tt.IsDryRun) - err = wh.Validate(attr, objectInterfaces) + err = wh.Validate(context.TODO(), attr, objectInterfaces) if tt.ExpectAllow != (err == nil) { t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err) } @@ -132,7 +133,7 @@ func TestValidateCachedClient(t *testing.T) { continue } - err = wh.Validate(webhooktesting.NewAttribute(ns, nil, false), objectInterfaces) + err = wh.Validate(context.TODO(), webhooktesting.NewAttribute(ns, nil, false), objectInterfaces) if tt.ExpectAllow != (err == nil) { t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err) } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go b/staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go index b99e604e05c..f93c703a11c 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/reinvocation.go @@ -16,6 +16,8 @@ limitations under the License. package admission +import "context" + // newReinvocationHandler creates a handler that wraps the provided admission chain and reinvokes it // if needed according to re-invocation policy of the webhooks. func newReinvocationHandler(admissionChain Interface) Interface { @@ -30,9 +32,9 @@ type reinvoker struct { // admission chain if needed according to the reinvocation policy. Plugins are expected to check // the admission attributes' reinvocation context against their reinvocation policy to decide if // they should re-run, and to update the reinvocation context if they perform any mutations. -func (r *reinvoker) Admit(a Attributes, o ObjectInterfaces) error { +func (r *reinvoker) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error { if mutator, ok := r.admissionChain.(MutationInterface); ok { - err := mutator.Admit(a, o) + err := mutator.Admit(ctx, a, o) if err != nil { return err } @@ -42,16 +44,16 @@ func (r *reinvoker) Admit(a Attributes, o ObjectInterfaces) error { // Calling admit a second time will reinvoke all in-tree plugins // as well as any webhook plugins that need to be reinvoked based on the // reinvocation policy. - return mutator.Admit(a, o) + return mutator.Admit(ctx, a, o) } } return nil } // Validate performs an admission control check using the wrapped admission chain, and returns immediately on first error. -func (r *reinvoker) Validate(a Attributes, o ObjectInterfaces) error { +func (r *reinvoker) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error { if validator, ok := r.admissionChain.(ValidationInterface); ok { - return validator.Validate(a, o) + return validator.Validate(ctx, a, o) } return nil } diff --git a/staging/src/k8s.io/apiserver/pkg/admission/testing/helpers.go b/staging/src/k8s.io/apiserver/pkg/admission/testing/helpers.go index 8ab448f77f2..45e126dabf6 100644 --- a/staging/src/k8s.io/apiserver/pkg/admission/testing/helpers.go +++ b/staging/src/k8s.io/apiserver/pkg/admission/testing/helpers.go @@ -17,6 +17,7 @@ limitations under the License. package testing import ( + "context" "reflect" "testing" @@ -40,11 +41,11 @@ type reinvoker struct { // Admit reinvokes the admission handler and reports a test error if the admission handler performs // non-idempotent mutatations to the admission object. -func (r *reinvoker) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (r *reinvoker) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { r.t.Helper() outputs := []runtime.Object{} for i := 0; i < 2; i++ { - err := r.admission.Admit(a, o) + err := r.admission.Admit(ctx, a, o) if err != nil { return err } diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/apiserver_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/apiserver_test.go index 1da6f6c47c2..dd6a8224e5e 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/apiserver_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/apiserver_test.go @@ -77,7 +77,7 @@ import ( type alwaysMutatingDeny struct{} -func (alwaysMutatingDeny) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (alwaysMutatingDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return admission.NewForbidden(a, errors.New("Mutating admission control is denying all modifications")) } @@ -87,7 +87,7 @@ func (alwaysMutatingDeny) Handles(operation admission.Operation) bool { type alwaysValidatingDeny struct{} -func (alwaysValidatingDeny) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { +func (alwaysValidatingDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) { return admission.NewForbidden(a, errors.New("Validating admission control is denying all modifications")) } @@ -448,7 +448,7 @@ func (storage *SimpleRESTStorage) Delete(ctx context.Context, id string, deleteV if err := storage.errors["delete"]; err != nil { return nil, false, err } - if err := deleteValidation(&storage.item); err != nil { + if err := deleteValidation(ctx, &storage.item); err != nil { return nil, false, err } var obj runtime.Object = &metav1.Status{Status: metav1.StatusSuccess} @@ -477,7 +477,7 @@ func (storage *SimpleRESTStorage) Create(ctx context.Context, obj runtime.Object if storage.injectedFunction != nil { obj, err = storage.injectedFunction(obj) } - if err := createValidation(obj); err != nil { + if err := createValidation(ctx, obj); err != nil { return nil, err } return obj, err @@ -496,7 +496,7 @@ func (storage *SimpleRESTStorage) Update(ctx context.Context, name string, objIn if storage.injectedFunction != nil { obj, err = storage.injectedFunction(obj) } - if err := updateValidation(&storage.item, obj); err != nil { + if err := updateValidation(ctx, &storage.item, obj); err != nil { return nil, false, err } return obj, false, err @@ -654,7 +654,7 @@ func (storage *NamedCreaterRESTStorage) Create(ctx context.Context, name string, if storage.injectedFunction != nil { obj, err = storage.injectedFunction(obj) } - if err := createValidation(obj); err != nil { + if err := createValidation(ctx, obj); err != nil { return nil, err } return obj, err diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go index 5f52acfc857..8f1201c28f8 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go @@ -132,7 +132,7 @@ func createHandler(r rest.NamedCreater, scope *RequestScope, admit admission.Int userInfo, _ := request.UserFrom(ctx) admissionAttributes := admission.NewAttributesRecord(obj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, options, dryrun.IsDryRun(options.DryRun), userInfo) if mutatingAdmission, ok := admit.(admission.MutationInterface); ok && mutatingAdmission.Handles(admission.Create) { - err = mutatingAdmission.Admit(admissionAttributes, scope) + err = mutatingAdmission.Admit(ctx, admissionAttributes, scope) if err != nil { scope.err(err, w, req) return diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go index fdaba2629ca..80570f80ae2 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/patch.go @@ -239,7 +239,7 @@ func PatchResource(r rest.Patcher, scope *RequestScope, admit admission.Interfac } } -type mutateObjectUpdateFunc func(obj, old runtime.Object) error +type mutateObjectUpdateFunc func(ctx context.Context, obj, old runtime.Object) error // patcher breaks the process of patch application and retries into smaller // pieces of functionality. @@ -515,7 +515,7 @@ func (p *patcher) applyAdmission(ctx context.Context, patchedObject runtime.Obje } if p.admissionCheck != nil && p.admissionCheck.Handles(operation) { attributes := p.admissionAttributes(ctx, patchedObject, currentObject, operation, options) - return patchedObject, p.admissionCheck.Admit(attributes, p.objectInterfaces) + return patchedObject, p.admissionCheck.Admit(ctx, attributes, p.objectInterfaces) } return patchedObject, nil } diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go index 8aecd4c14a5..75764597f49 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go @@ -163,14 +163,14 @@ func ConnectResource(connecter rest.Connecter, scope *RequestScope, admit admiss userInfo, _ := request.UserFrom(ctx) // TODO: remove the mutating admission here as soon as we have ported all plugin that handle CONNECT if mutatingAdmission, ok := admit.(admission.MutationInterface); ok { - err = mutatingAdmission.Admit(admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope) + err = mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope) if err != nil { scope.err(err, w, req) return } } if validatingAdmission, ok := admit.(admission.ValidationInterface); ok { - err = validatingAdmission.Validate(admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope) + err = validatingAdmission.Validate(ctx, admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope) if err != nil { scope.err(err, w, req) return diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest_test.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest_test.go index d3a18805960..924990a8c2a 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest_test.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest_test.go @@ -260,11 +260,11 @@ func (p *testPatcher) Update(ctx context.Context, name string, objInfo rest.Upda } if currentPod == nil { - if err := createValidation(currentPod); err != nil { + if err := createValidation(ctx, currentPod); err != nil { return nil, false, err } } else { - if err := updateValidation(currentPod, inPod); err != nil { + if err := updateValidation(ctx, currentPod, inPod); err != nil { return nil, false, err } } @@ -351,13 +351,13 @@ func (tc *patchTestCase) Run(t *testing.T) { admissionMutation := tc.admissionMutation if admissionMutation == nil { - admissionMutation = func(updatedObject runtime.Object, currentObject runtime.Object) error { + admissionMutation = func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error { return nil } } admissionValidation := tc.admissionValidation if admissionValidation == nil { - admissionValidation = func(updatedObject runtime.Object, currentObject runtime.Object) error { + admissionValidation = func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error { return nil } } @@ -718,7 +718,7 @@ func TestPatchWithAdmissionRejection(t *testing.T) { for _, test := range []Test{ { name: "TestPatchWithMutatingAdmissionRejection", - admissionMutation: func(updatedObject runtime.Object, currentObject runtime.Object) error { + admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error { return errors.New("mutating admission failure") }, admissionValidation: rest.ValidateAllObjectUpdateFunc, @@ -727,17 +727,17 @@ func TestPatchWithAdmissionRejection(t *testing.T) { { name: "TestPatchWithValidatingAdmissionRejection", admissionMutation: rest.ValidateAllObjectUpdateFunc, - admissionValidation: func(updatedObject runtime.Object, currentObject runtime.Object) error { + 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(updatedObject runtime.Object, currentObject runtime.Object) error { + admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error { return errors.New("mutating admission failure") }, - admissionValidation: func(updatedObject runtime.Object, currentObject runtime.Object) error { + admissionValidation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error { return errors.New("validating admission failure") }, expectedError: "mutating admission failure", @@ -777,7 +777,7 @@ func TestPatchWithVersionConflictThenAdmissionFailure(t *testing.T) { tc := &patchTestCase{ name: "TestPatchWithVersionConflictThenAdmissionFailure", - admissionMutation: func(updatedObject runtime.Object, currentObject runtime.Object) error { + admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error { if seen { return errors.New("admission failure") } @@ -951,8 +951,8 @@ func (f mutateObjectUpdateFunc) Handles(operation admission.Operation) bool { return true } -func (f mutateObjectUpdateFunc) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { - return f(a.GetObject(), a.GetOldObject()) +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) { diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go index 61a004aea9d..b7c2dbcd4f5 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/update.go @@ -140,11 +140,11 @@ func UpdateResource(r rest.Updater, scope *RequestScope, admit admission.Interfa return nil, fmt.Errorf("unexpected error when extracting UID from oldObj: %v", err.Error()) } else if !isNotZeroObject { if mutatingAdmission.Handles(admission.Create) { - return newObj, mutatingAdmission.Admit(admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope) + return newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope) } } else { if mutatingAdmission.Handles(admission.Update) { - return newObj, mutatingAdmission.Admit(admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope) + return newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope) } } return newObj, nil @@ -205,7 +205,7 @@ func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer var authorizerDecision authorizer.Decision var authorizerReason string var authorizerErr error - return func(obj runtime.Object) error { + return func(ctx context.Context, obj runtime.Object) error { if a == nil { return errors.NewInternalError(fmt.Errorf("no authorizer provided, unable to authorize a create on update")) } @@ -215,7 +215,7 @@ func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer // an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here. if authorizerDecision == authorizer.DecisionAllow { // Continue to validating admission - return validate(obj) + return validate(ctx, obj) } if authorizerErr != nil { return errors.NewInternalError(authorizerErr) diff --git a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go index 24a1b1ec288..3ff84038006 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/dryrun.go @@ -52,7 +52,7 @@ func (s *DryRunnableStorage) Delete(ctx context.Context, key string, out runtime if err := preconditions.Check(key, out); err != nil { return err } - return deleteValidation(out) + return deleteValidation(ctx, out) } return s.Storage.Delete(ctx, key, out, preconditions, deleteValidation) } diff --git a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go index be03caa41b1..95d0ad3f484 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store.go @@ -342,7 +342,7 @@ func (e *Store) Create(ctx context.Context, obj runtime.Object, createValidation // at this point we have a fully formed object. It is time to call the validators that the apiserver // handling chain wants to enforce. if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, err } } @@ -504,7 +504,7 @@ func (e *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObj // at this point we have a fully formed object. It is time to call the validators that the apiserver // handling chain wants to enforce. if createValidation != nil { - if err := createValidation(obj.DeepCopyObject()); err != nil { + if err := createValidation(ctx, obj.DeepCopyObject()); err != nil { return nil, nil, err } } @@ -546,7 +546,7 @@ func (e *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObj // at this point we have a fully formed object. It is time to call the validators that the apiserver // handling chain wants to enforce. if updateValidation != nil { - if err := updateValidation(obj.DeepCopyObject(), existing.DeepCopyObject()); err != nil { + if err := updateValidation(ctx, obj.DeepCopyObject(), existing.DeepCopyObject()); err != nil { return nil, nil, err } } @@ -812,7 +812,7 @@ func (e *Store) updateForGracefulDeletionAndFinalizers(ctx context.Context, name false, /* ignoreNotFound */ &preconditions, storage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) { - if err := deleteValidation(existing); err != nil { + if err := deleteValidation(ctx, existing); err != nil { return nil, err } graceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, existing, options) diff --git a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store_test.go b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store_test.go index 32f050415e8..e498afc4a06 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store_test.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/generic/registry/store_test.go @@ -1713,11 +1713,11 @@ func TestQualifiedResource(t *testing.T) { } } -func denyCreateValidation(obj runtime.Object) error { +func denyCreateValidation(ctx context.Context, obj runtime.Object) error { return fmt.Errorf("admission denied") } -func denyUpdateValidation(obj, old runtime.Object) error { +func denyUpdateValidation(ctx context.Context, obj, old runtime.Object) error { return fmt.Errorf("admission denied") } @@ -1933,7 +1933,7 @@ func TestRetryDeleteValidation(t *testing.T) { updated := make(chan struct{}) var readyOnce, updatedOnce sync.Once var called int - deleteValidation := func(runtime.Object) error { + deleteValidation := func(ctx context.Context, obj runtime.Object) error { readyOnce.Do(func() { close(ready) }) diff --git a/staging/src/k8s.io/apiserver/pkg/registry/rest/create.go b/staging/src/k8s.io/apiserver/pkg/registry/rest/create.go index 2fc47d9db93..e5ae7562daf 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/rest/create.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/rest/create.go @@ -160,9 +160,9 @@ type NamespaceScopedStrategy interface { func AdmissionToValidateObjectFunc(admit admission.Interface, staticAttributes admission.Attributes, o admission.ObjectInterfaces) ValidateObjectFunc { validatingAdmission, ok := admit.(admission.ValidationInterface) if !ok { - return func(obj runtime.Object) error { return nil } + return func(ctx context.Context, obj runtime.Object) error { return nil } } - return func(obj runtime.Object) error { + return func(ctx context.Context, obj runtime.Object) error { finalAttributes := admission.NewAttributesRecord( obj, staticAttributes.GetOldObject(), @@ -179,6 +179,6 @@ func AdmissionToValidateObjectFunc(admit admission.Interface, staticAttributes a if !validatingAdmission.Handles(finalAttributes.GetOperation()) { return nil } - return validatingAdmission.Validate(finalAttributes, o) + return validatingAdmission.Validate(ctx, finalAttributes, o) } } diff --git a/staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go b/staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go index 2b5038b210d..3e7ca85b761 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/rest/delete.go @@ -150,7 +150,7 @@ func AdmissionToValidateObjectDeleteFunc(admit admission.Interface, staticAttrib mutating := isMutatingAdmission && mutatingAdmission.Handles(staticAttributes.GetOperation()) validating := isValidatingAdmission && validatingAdmission.Handles(staticAttributes.GetOperation()) - return func(old runtime.Object) error { + return func(ctx context.Context, old runtime.Object) error { if !mutating && !validating { return nil } @@ -169,12 +169,12 @@ func AdmissionToValidateObjectDeleteFunc(admit admission.Interface, staticAttrib staticAttributes.GetUserInfo(), ) if mutating { - if err := mutatingAdmission.Admit(finalAttributes, objInterfaces); err != nil { + if err := mutatingAdmission.Admit(ctx, finalAttributes, objInterfaces); err != nil { return err } } if validating { - if err := validatingAdmission.Validate(finalAttributes, objInterfaces); err != nil { + if err := validatingAdmission.Validate(ctx, finalAttributes, objInterfaces); err != nil { return err } } diff --git a/staging/src/k8s.io/apiserver/pkg/registry/rest/rest.go b/staging/src/k8s.io/apiserver/pkg/registry/rest/rest.go index 08c7cafc6b7..28f4bf07cf0 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/rest/rest.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/rest/rest.go @@ -210,20 +210,20 @@ type UpdatedObjectInfo interface { // ValidateObjectFunc is a function to act on a given object. An error may be returned // if the hook cannot be completed. An ObjectFunc may NOT transform the provided // object. -type ValidateObjectFunc func(obj runtime.Object) error +type ValidateObjectFunc func(ctx context.Context, obj runtime.Object) error // ValidateAllObjectFunc is a "admit everything" instance of ValidateObjectFunc. -func ValidateAllObjectFunc(obj runtime.Object) error { +func ValidateAllObjectFunc(ctx context.Context, obj runtime.Object) error { return nil } // ValidateObjectUpdateFunc is a function to act on a given object and its predecessor. // An error may be returned if the hook cannot be completed. An UpdateObjectFunc // may NOT transform the provided object. -type ValidateObjectUpdateFunc func(obj, old runtime.Object) error +type ValidateObjectUpdateFunc func(ctx context.Context, obj, old runtime.Object) error // ValidateAllObjectUpdateFunc is a "admit everything" instance of ValidateObjectUpdateFunc. -func ValidateAllObjectUpdateFunc(obj, old runtime.Object) error { +func ValidateAllObjectUpdateFunc(ctx context.Context, obj, old runtime.Object) error { return nil } diff --git a/staging/src/k8s.io/apiserver/pkg/registry/rest/update.go b/staging/src/k8s.io/apiserver/pkg/registry/rest/update.go index a15d975ad27..0741b84ec29 100644 --- a/staging/src/k8s.io/apiserver/pkg/registry/rest/update.go +++ b/staging/src/k8s.io/apiserver/pkg/registry/rest/update.go @@ -255,9 +255,9 @@ func (i *wrappedUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj run func AdmissionToValidateObjectUpdateFunc(admit admission.Interface, staticAttributes admission.Attributes, o admission.ObjectInterfaces) ValidateObjectUpdateFunc { validatingAdmission, ok := admit.(admission.ValidationInterface) if !ok { - return func(obj, old runtime.Object) error { return nil } + return func(ctx context.Context, obj, old runtime.Object) error { return nil } } - return func(obj, old runtime.Object) error { + return func(ctx context.Context, obj, old runtime.Object) error { finalAttributes := admission.NewAttributesRecord( obj, old, @@ -274,6 +274,6 @@ func AdmissionToValidateObjectUpdateFunc(admit admission.Interface, staticAttrib if !validatingAdmission.Handles(finalAttributes.GetOperation()) { return nil } - return validatingAdmission.Validate(finalAttributes, o) + return validatingAdmission.Validate(ctx, finalAttributes, o) } } diff --git a/staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go b/staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go index ba1953f4919..425590aa886 100644 --- a/staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go +++ b/staging/src/k8s.io/apiserver/pkg/storage/etcd3/store.go @@ -208,7 +208,7 @@ func (s *store) conditionalDelete(ctx context.Context, key string, out runtime.O return err } } - if err := validateDeletion(origState.obj); err != nil { + if err := validateDeletion(ctx, origState.obj); err != nil { return err } startTime := time.Now() diff --git a/staging/src/k8s.io/apiserver/pkg/storage/interfaces.go b/staging/src/k8s.io/apiserver/pkg/storage/interfaces.go index f5d3b3ea789..f3ca36118fe 100644 --- a/staging/src/k8s.io/apiserver/pkg/storage/interfaces.go +++ b/staging/src/k8s.io/apiserver/pkg/storage/interfaces.go @@ -95,10 +95,10 @@ type UpdateFunc func(input runtime.Object, res ResponseMeta) (output runtime.Obj // ValidateObjectFunc is a function to act on a given object. An error may be returned // if the hook cannot be completed. The function may NOT transform the provided // object. -type ValidateObjectFunc func(obj runtime.Object) error +type ValidateObjectFunc func(ctx context.Context, obj runtime.Object) error // ValidateAllObjectFunc is a "admit everything" instance of ValidateObjectFunc. -func ValidateAllObjectFunc(obj runtime.Object) error { +func ValidateAllObjectFunc(ctx context.Context, obj runtime.Object) error { return nil } diff --git a/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission.go b/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission.go index 474c1a58d10..b5c1c0261e4 100644 --- a/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission.go +++ b/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission.go @@ -17,6 +17,7 @@ limitations under the License. package banflunder import ( + "context" "fmt" "io" @@ -47,7 +48,7 @@ var _ = wardleinitializer.WantsInternalWardleInformerFactory(&DisallowFlunder{}) // Admit ensures that the object in-flight is of kind Flunder. // In addition checks that the Name is not on the banned list. // The list is stored in Fischers API objects. -func (d *DisallowFlunder) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (d *DisallowFlunder) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { // we are only interested in flunders if a.GetKind().GroupKind() != wardle.Kind("Flunder") { return nil diff --git a/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission_test.go b/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission_test.go index c4c2d8628e1..f62d43c8abf 100644 --- a/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission_test.go +++ b/staging/src/k8s.io/sample-apiserver/pkg/admission/plugin/banflunder/admission_test.go @@ -17,6 +17,7 @@ limitations under the License. package banflunder_test import ( + "context" "testing" "time" @@ -127,7 +128,7 @@ func TestBanflunderAdmissionPlugin(t *testing.T) { informersFactory.WaitForCacheSync(stop) // act - err = target.Admit(admission.NewAttributesRecord( + err = target.Admit(context.TODO(), admission.NewAttributesRecord( &scenario.admissionInput, nil, scenario.admissionInputKind, diff --git a/staging/src/k8s.io/sample-apiserver/pkg/admission/wardleinitializer/wardleinitializer_test.go b/staging/src/k8s.io/sample-apiserver/pkg/admission/wardleinitializer/wardleinitializer_test.go index 8e994d71e14..12c8891f2a3 100644 --- a/staging/src/k8s.io/sample-apiserver/pkg/admission/wardleinitializer/wardleinitializer_test.go +++ b/staging/src/k8s.io/sample-apiserver/pkg/admission/wardleinitializer/wardleinitializer_test.go @@ -17,6 +17,7 @@ limitations under the License. package wardleinitializer_test import ( + "context" "testing" "time" @@ -48,7 +49,7 @@ type wantInternalWardleInformerFactory struct { func (self *wantInternalWardleInformerFactory) SetInternalWardleInformerFactory(sf informers.SharedInformerFactory) { self.sf = sf } -func (self *wantInternalWardleInformerFactory) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { +func (self *wantInternalWardleInformerFactory) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error { return nil } func (self *wantInternalWardleInformerFactory) Handles(o admission.Operation) bool { return false }