From c0eba4e30f6cb606c2ff84a9bea7429964fb77df Mon Sep 17 00:00:00 2001 From: Gab Satchi Date: Wed, 12 Jan 2022 15:26:54 -0500 Subject: [PATCH] adds WithNamespace ability to contexts --- apis/contexts.go | 16 ++++++++++++++++ apis/contexts_test.go | 15 +++++++++++++++ .../resourcesemantics/defaulting/defaulting.go | 2 +- 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/apis/contexts.go b/apis/contexts.go index b9835fc00c..762c420294 100644 --- a/apis/contexts.go +++ b/apis/contexts.go @@ -141,6 +141,22 @@ func IsWithinParent(ctx context.Context) bool { return ok } +type namespaceKey struct{} +// WithNamespace attaches the request's namespace. Intended to be used +// where defaulting depends on the namespace (eventing channels, brokers) +// and the client may not provide it in the resource ObjectMeta +func WithNamespace(ctx context.Context, ns string) context.Context { + return context.WithValue(ctx, namespaceKey{}, ns) +} + +func GetNamespace(ctx context.Context) string { + if ns, ok := ctx.Value(namespaceKey{}).(string); ok { + return ns + } + + return "" +} + // ParentMeta accesses the ObjectMeta of the enclosing parent resource // from the context. See WithinParent for how to attach the parent's // ObjectMeta to the context. diff --git a/apis/contexts_test.go b/apis/contexts_test.go index 469ada6149..745248a253 100644 --- a/apis/contexts_test.go +++ b/apis/contexts_test.go @@ -241,3 +241,18 @@ func TestGetHTTPRequest(t *testing.T) { t.Errorf("GetHTTPRequest() = %v, wanted %v", got, want) } } + +func TestGetNamespace(t *testing.T) { + ctx := context.Background() + + if got := GetNamespace(ctx); got != "" { + t.Errorf("GetNamespace() = \"%v\", wanted \"\"", got) + } + + ns := "some-namespace" + ctx = WithNamespace(ctx, ns) + + if want, got := ns, GetNamespace(ctx); got != want { + t.Errorf("GetNamespace() = \"%v\", wanted \"%v\"", got, want) + } +} diff --git a/webhook/resourcesemantics/defaulting/defaulting.go b/webhook/resourcesemantics/defaulting/defaulting.go index 504dcaa066..34953d02c1 100644 --- a/webhook/resourcesemantics/defaulting/defaulting.go +++ b/webhook/resourcesemantics/defaulting/defaulting.go @@ -288,7 +288,7 @@ func (ac *reconciler) mutate(ctx context.Context, req *admissionv1.AdmissionRequ ctx = apis.WithinCreate(ctx) } ctx = apis.WithUserInfo(ctx, &req.UserInfo) - + ctx = apis.WithNamespace(ctx, req.Namespace) // Default the new object. if patches, err = setDefaults(ctx, patches, newObj); err != nil { logger.Errorw("Failed the resource specific defaulter", zap.Error(err))