diff --git a/Makefile b/Makefile index 5fdfa5840..214377f66 100644 --- a/Makefile +++ b/Makefile @@ -302,9 +302,12 @@ clean-cov: ## Remove coverage reports ifdef TEST_NAME test-unit: TEST_PATTERN := --run $(TEST_NAME) endif +ifdef VERBOSE +test-unit: VERBOSE_FLAG = -v +endif test-unit: clean-cov generate fmt vet ## Run Unit tests. mkdir -p $(PROJECT_PATH)/coverage/unit - go test $(UNIT_DIRS) -coverprofile $(PROJECT_PATH)/coverage/unit/cover.out -tags unit -v -timeout 0 $(TEST_PATTERN) + go test $(UNIT_DIRS) -coverprofile $(PROJECT_PATH)/coverage/unit/cover.out -tags unit $(VERBOSE_FLAG) -timeout 0 $(TEST_PATTERN) ##@ Build diff --git a/api/v1alpha1/dnspolicy_types.go b/api/v1alpha1/dnspolicy_types.go index 98b1ac02e..e74801b9f 100644 --- a/api/v1alpha1/dnspolicy_types.go +++ b/api/v1alpha1/dnspolicy_types.go @@ -20,6 +20,7 @@ import ( "context" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" @@ -32,6 +33,14 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) +var ( + DNSPolicyGVK schema.GroupVersionKind = schema.GroupVersionKind{ + Group: GroupVersion.Group, + Version: GroupVersion.Version, + Kind: "DNSPolicy", + } +) + type RoutingStrategy string const ( @@ -180,21 +189,8 @@ func (p *DNSPolicy) GetStatus() kuadrantgatewayapi.PolicyStatus { return &p.Status } -func (p *DNSPolicy) Kind() string { return p.TypeMeta.Kind } - -func (p *DNSPolicy) List(ctx context.Context, c client.Client, namespace string) []kuadrantgatewayapi.Policy { - policyList := &DNSPolicyList{} - listOptions := &client.ListOptions{Namespace: namespace} - err := c.List(ctx, policyList, listOptions) - if err != nil { - return []kuadrantgatewayapi.Policy{} - } - policies := make([]kuadrantgatewayapi.Policy, 0, len(policyList.Items)) - for i := range policyList.Items { - policies = append(policies, &policyList.Items[i]) - } - - return policies +func (p *DNSPolicy) Kind() string { + return NewDNSPolicyType().GetGVK().Kind } func (p *DNSPolicy) TargetProgrammedGatewaysOnly() bool { @@ -206,11 +202,11 @@ func (p *DNSPolicy) PolicyClass() kuadrantgatewayapi.PolicyClass { } func (p *DNSPolicy) BackReferenceAnnotationName() string { - return DNSPolicyBackReferenceAnnotationName + return NewDNSPolicyType().BackReferenceAnnotationName() } func (p *DNSPolicy) DirectReferenceAnnotationName() string { - return DNSPolicyDirectReferenceAnnotationName + return NewDNSPolicyType().DirectReferenceAnnotationName() } //+kubebuilder:object:root=true @@ -302,3 +298,39 @@ func (p *DNSPolicy) WithLoadBalancingFor(defaultWeight Weight, custom []*CustomW }, }) } + +type dnsPolicyType struct{} + +func NewDNSPolicyType() kuadrantgatewayapi.PolicyType { + return &dnsPolicyType{} +} + +func (d dnsPolicyType) GetGVK() schema.GroupVersionKind { + return DNSPolicyGVK +} + +func (d dnsPolicyType) GetInstance() client.Object { + return &DNSPolicy{ + TypeMeta: metav1.TypeMeta{ + Kind: DNSPolicyGVK.Kind, + APIVersion: GroupVersion.String(), + }, + } +} + +func (d dnsPolicyType) GetList(ctx context.Context, cl client.Client, listOpts ...client.ListOption) ([]kuadrantgatewayapi.Policy, error) { + list := &DNSPolicyList{} + err := cl.List(ctx, list, listOpts...) + if err != nil { + return nil, err + } + return utils.Map(list.Items, func(p DNSPolicy) kuadrantgatewayapi.Policy { return &p }), nil +} + +func (d dnsPolicyType) BackReferenceAnnotationName() string { + return DNSPolicyBackReferenceAnnotationName +} + +func (d dnsPolicyType) DirectReferenceAnnotationName() string { + return DNSPolicyDirectReferenceAnnotationName +} diff --git a/api/v1alpha1/tlspolicy_types.go b/api/v1alpha1/tlspolicy_types.go index d79d0c3d8..ebf168a85 100644 --- a/api/v1alpha1/tlspolicy_types.go +++ b/api/v1alpha1/tlspolicy_types.go @@ -22,6 +22,7 @@ import ( certmanv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1" certmanmetav1 "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" @@ -31,6 +32,14 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) +var ( + TLSPolicyGVK schema.GroupVersionKind = schema.GroupVersionKind{ + Group: GroupVersion.Group, + Version: GroupVersion.Version, + Kind: "TLSPolicy", + } +) + const ( TLSPolicyBackReferenceAnnotationName = "kuadrant.io/tlspolicies" TLSPolicyDirectReferenceAnnotationName = "kuadrant.io/tlspolicy" @@ -145,21 +154,8 @@ type TLSPolicy struct { Status TLSPolicyStatus `json:"status,omitempty"` } -func (p *TLSPolicy) Kind() string { return p.TypeMeta.Kind } - -func (p *TLSPolicy) List(ctx context.Context, c client.Client, namespace string) []kuadrantgatewayapi.Policy { - policyList := &TLSPolicyList{} - listOptions := &client.ListOptions{Namespace: namespace} - err := c.List(ctx, policyList, listOptions) - if err != nil { - return []kuadrantgatewayapi.Policy{} - } - policies := make([]kuadrantgatewayapi.Policy, 0, len(policyList.Items)) - for i := range policyList.Items { - policies = append(policies, &policyList.Items[i]) - } - - return policies +func (p *TLSPolicy) Kind() string { + return NewTLSPolicyType().GetGVK().Kind } func (p *TLSPolicy) TargetProgrammedGatewaysOnly() bool { @@ -187,11 +183,11 @@ func (p *TLSPolicy) GetStatus() kuadrantgatewayapi.PolicyStatus { } func (p *TLSPolicy) BackReferenceAnnotationName() string { - return TLSPolicyBackReferenceAnnotationName + return NewTLSPolicyType().BackReferenceAnnotationName() } func (p *TLSPolicy) DirectReferenceAnnotationName() string { - return TLSPolicyDirectReferenceAnnotationName + return NewTLSPolicyType().DirectReferenceAnnotationName() } //+kubebuilder:object:root=true @@ -242,3 +238,38 @@ func (p *TLSPolicy) WithIssuerRef(issuerRef certmanmetav1.ObjectReference) *TLSP p.Spec.IssuerRef = issuerRef return p } + +type tlsPolicyType struct{} + +func NewTLSPolicyType() kuadrantgatewayapi.PolicyType { + return &tlsPolicyType{} +} + +func (t tlsPolicyType) GetGVK() schema.GroupVersionKind { + return TLSPolicyGVK +} +func (t tlsPolicyType) GetInstance() client.Object { + return &TLSPolicy{ + TypeMeta: metav1.TypeMeta{ + Kind: TLSPolicyGVK.Kind, + APIVersion: GroupVersion.String(), + }, + } +} + +func (t tlsPolicyType) GetList(ctx context.Context, cl client.Client, listOpts ...client.ListOption) ([]kuadrantgatewayapi.Policy, error) { + list := &TLSPolicyList{} + err := cl.List(ctx, list, listOpts...) + if err != nil { + return nil, err + } + return utils.Map(list.Items, func(p TLSPolicy) kuadrantgatewayapi.Policy { return &p }), nil +} + +func (t tlsPolicyType) BackReferenceAnnotationName() string { + return TLSPolicyBackReferenceAnnotationName +} + +func (t tlsPolicyType) DirectReferenceAnnotationName() string { + return TLSPolicyDirectReferenceAnnotationName +} diff --git a/api/v1beta2/authpolicy_types.go b/api/v1beta2/authpolicy_types.go index 0ba0c8338..f1e0bb872 100644 --- a/api/v1beta2/authpolicy_types.go +++ b/api/v1beta2/authpolicy_types.go @@ -7,6 +7,7 @@ import ( "github.com/google/go-cmp/cmp" authorinoapi "github.com/kuadrant/authorino/api/v1beta2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" @@ -16,6 +17,14 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) +var ( + AuthPolicyGVK schema.GroupVersionKind = schema.GroupVersionKind{ + Group: GroupVersion.Group, + Version: GroupVersion.Version, + Kind: "AuthPolicy", + } +) + const ( AuthPolicyBackReferenceAnnotationName = "kuadrant.io/authpolicies" AuthPolicyDirectReferenceAnnotationName = "kuadrant.io/authpolicy" @@ -328,22 +337,7 @@ func (ap *AuthPolicy) GetRulesHostnames() (ruleHosts []string) { } func (ap *AuthPolicy) Kind() string { - return ap.TypeMeta.Kind -} - -func (ap *AuthPolicy) List(ctx context.Context, c client.Client, namespace string) []kuadrantgatewayapi.Policy { - policyList := &AuthPolicyList{} - listOptions := &client.ListOptions{Namespace: namespace} - err := c.List(ctx, policyList, listOptions) - if err != nil { - return []kuadrantgatewayapi.Policy{} - } - policies := make([]kuadrantgatewayapi.Policy, 0, len(policyList.Items)) - for i := range policyList.Items { - policies = append(policies, &policyList.Items[i]) - } - - return policies + return NewAuthPolicyType().GetGVK().Kind } func (ap *AuthPolicy) TargetProgrammedGatewaysOnly() bool { @@ -355,11 +349,11 @@ func (ap *AuthPolicy) PolicyClass() kuadrantgatewayapi.PolicyClass { } func (ap *AuthPolicy) BackReferenceAnnotationName() string { - return AuthPolicyBackReferenceAnnotationName + return NewAuthPolicyType().BackReferenceAnnotationName() } func (ap *AuthPolicy) DirectReferenceAnnotationName() string { - return AuthPolicyDirectReferenceAnnotationName + return NewAuthPolicyType().DirectReferenceAnnotationName() } func (ap *AuthPolicySpec) CommonSpec() *AuthPolicyCommonSpec { @@ -389,6 +383,41 @@ func (l *AuthPolicyList) GetItems() []kuadrant.Policy { }) } +type authPolicyType struct{} + +func NewAuthPolicyType() kuadrantgatewayapi.PolicyType { + return &authPolicyType{} +} + +func (a authPolicyType) GetGVK() schema.GroupVersionKind { + return AuthPolicyGVK +} +func (a authPolicyType) GetInstance() client.Object { + return &AuthPolicy{ + TypeMeta: metav1.TypeMeta{ + Kind: AuthPolicyGVK.Kind, + APIVersion: GroupVersion.String(), + }, + } +} + +func (a authPolicyType) GetList(ctx context.Context, cl client.Client, listOpts ...client.ListOption) ([]kuadrantgatewayapi.Policy, error) { + list := &AuthPolicyList{} + err := cl.List(ctx, list, listOpts...) + if err != nil { + return nil, err + } + return utils.Map(list.Items, func(p AuthPolicy) kuadrantgatewayapi.Policy { return &p }), nil +} + +func (a authPolicyType) BackReferenceAnnotationName() string { + return AuthPolicyBackReferenceAnnotationName +} + +func (a authPolicyType) DirectReferenceAnnotationName() string { + return AuthPolicyDirectReferenceAnnotationName +} + func init() { SchemeBuilder.Register(&AuthPolicy{}, &AuthPolicyList{}) } diff --git a/api/v1beta2/ratelimitpolicy_types.go b/api/v1beta2/ratelimitpolicy_types.go index 7443a78c2..6883e7c57 100644 --- a/api/v1beta2/ratelimitpolicy_types.go +++ b/api/v1beta2/ratelimitpolicy_types.go @@ -24,6 +24,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" @@ -37,6 +38,14 @@ import ( // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. +var ( + RateLimitPolicyGVK schema.GroupVersionKind = schema.GroupVersionKind{ + Group: GroupVersion.Group, + Version: GroupVersion.Version, + Kind: "RateLimitPolicy", + } +) + // ContextSelector defines one item from the well known attributes // Attributes: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes // Well-known selectors: https://github.com/Kuadrant/architecture/blob/main/rfcs/0001-rlp-v2.md#well-known-selectors @@ -274,21 +283,7 @@ func (r *RateLimitPolicy) GetRulesHostnames() (ruleHosts []string) { } func (r *RateLimitPolicy) Kind() string { - return r.TypeMeta.Kind -} - -func (r *RateLimitPolicy) List(ctx context.Context, c client.Client, namespace string) []kuadrantgatewayapi.Policy { - policyList := &RateLimitPolicyList{} - err := c.List(ctx, policyList, client.InNamespace(namespace)) - if err != nil { - return []kuadrantgatewayapi.Policy{} - } - policies := make([]kuadrantgatewayapi.Policy, 0, len(policyList.Items)) - for i := range policyList.Items { - policies = append(policies, &policyList.Items[i]) - } - - return policies + return NewRateLimitPolicyType().GetGVK().Kind } func (r *RateLimitPolicy) TargetProgrammedGatewaysOnly() bool { @@ -300,11 +295,11 @@ func (r *RateLimitPolicy) PolicyClass() kuadrantgatewayapi.PolicyClass { } func (r *RateLimitPolicy) BackReferenceAnnotationName() string { - return RateLimitPolicyBackReferenceAnnotationName + return NewRateLimitPolicyType().BackReferenceAnnotationName() } func (r *RateLimitPolicy) DirectReferenceAnnotationName() string { - return RateLimitPolicyDirectReferenceAnnotationName + return NewRateLimitPolicyType().DirectReferenceAnnotationName() } // CommonSpec returns the Default RateLimitPolicyCommonSpec if it is defined. @@ -323,6 +318,41 @@ func (r *RateLimitPolicySpec) CommonSpec() *RateLimitPolicyCommonSpec { return &r.RateLimitPolicyCommonSpec } +type rateLimitPolicyType struct{} + +func NewRateLimitPolicyType() kuadrantgatewayapi.PolicyType { + return &rateLimitPolicyType{} +} + +func (r rateLimitPolicyType) GetGVK() schema.GroupVersionKind { + return RateLimitPolicyGVK +} +func (r rateLimitPolicyType) GetInstance() client.Object { + return &RateLimitPolicy{ + TypeMeta: metav1.TypeMeta{ + Kind: RateLimitPolicyGVK.Kind, + APIVersion: GroupVersion.String(), + }, + } +} + +func (r rateLimitPolicyType) GetList(ctx context.Context, cl client.Client, listOpts ...client.ListOption) ([]kuadrantgatewayapi.Policy, error) { + rlpList := &RateLimitPolicyList{} + err := cl.List(ctx, rlpList, listOpts...) + if err != nil { + return nil, err + } + return utils.Map(rlpList.Items, func(p RateLimitPolicy) kuadrantgatewayapi.Policy { return &p }), nil +} + +func (r rateLimitPolicyType) BackReferenceAnnotationName() string { + return RateLimitPolicyBackReferenceAnnotationName +} + +func (r rateLimitPolicyType) DirectReferenceAnnotationName() string { + return RateLimitPolicyDirectReferenceAnnotationName +} + func init() { SchemeBuilder.Register(&RateLimitPolicy{}, &RateLimitPolicyList{}) } diff --git a/controllers/authpolicy_controller.go b/controllers/authpolicy_controller.go index 98947593e..e5bc41b80 100644 --- a/controllers/authpolicy_controller.go +++ b/controllers/authpolicy_controller.go @@ -266,8 +266,12 @@ func (r *AuthPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { return nil } - httpRouteEventMapper := mappers.NewHTTPRouteEventMapper(mappers.WithLogger(r.Logger().WithName("httpRouteEventMapper")), mappers.WithClient(mgr.GetClient())) - gatewayEventMapper := mappers.NewGatewayEventMapper(mappers.WithLogger(r.Logger().WithName("gatewayEventMapper")), mappers.WithClient(mgr.GetClient())) + httpRouteEventMapper := mappers.NewHTTPRouteEventMapper(mappers.WithLogger(r.Logger().WithName("httproute.mapper")), mappers.WithClient(mgr.GetClient())) + gatewayEventMapper := mappers.NewGatewayEventMapper( + api.NewAuthPolicyType(), + mappers.WithLogger(r.Logger().WithName("gateway.mapper")), + mappers.WithClient(mgr.GetClient()), + ) return ctrl.NewControllerManagedBy(mgr). For(&api.AuthPolicy{}). @@ -275,13 +279,9 @@ func (r *AuthPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { Watches( &gatewayapiv1.HTTPRoute{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - return httpRouteEventMapper.MapToPolicy(ctx, object, &api.AuthPolicy{}) - }), - ). - Watches(&gatewayapiv1.Gateway{}, - handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - return gatewayEventMapper.MapToPolicy(ctx, object, &api.AuthPolicy{}) + return httpRouteEventMapper.MapToPolicy(ctx, object, api.NewAuthPolicyType()) }), ). + Watches(&gatewayapiv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(gatewayEventMapper.Map)). Complete(r) } diff --git a/controllers/dnspolicy_controller.go b/controllers/dnspolicy_controller.go index 5f07f96fb..b7511aec2 100644 --- a/controllers/dnspolicy_controller.go +++ b/controllers/dnspolicy_controller.go @@ -29,7 +29,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/handler" crlog "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" kuadrantdnsv1alpha1 "github.com/kuadrant/dns-operator/api/v1alpha1" @@ -184,18 +183,17 @@ func (r *DNSPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { return nil } - gatewayEventMapper := mappers.NewGatewayEventMapper(mappers.WithLogger(r.Logger().WithName("gatewayEventMapper")), mappers.WithClient(mgr.GetClient())) + gatewayEventMapper := mappers.NewGatewayEventMapper( + v1alpha1.NewDNSPolicyType(), + mappers.WithLogger(r.Logger().WithName("gateway.mapper")), + mappers.WithClient(mgr.GetClient()), + ) r.dnsHelper = dnsHelper{Client: r.Client()} ctrlr := ctrl.NewControllerManagedBy(mgr). For(&v1alpha1.DNSPolicy{}). Owns(&kuadrantdnsv1alpha1.DNSRecord{}). - Watches( - &gatewayapiv1.Gateway{}, - handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - return gatewayEventMapper.MapToPolicy(ctx, object, &v1alpha1.DNSPolicy{}) - }), - ) + Watches(&gatewayapiv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(gatewayEventMapper.Map)) return ctrlr.Complete(r) } diff --git a/controllers/ratelimitpolicy_controller.go b/controllers/ratelimitpolicy_controller.go index 44dd477c6..7ff89970a 100644 --- a/controllers/ratelimitpolicy_controller.go +++ b/controllers/ratelimitpolicy_controller.go @@ -231,24 +231,23 @@ func (r *RateLimitPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { return nil } - httpRouteEventMapper := mappers.NewHTTPRouteEventMapper(mappers.WithLogger(r.Logger().WithName("httpRouteEventMapper")), mappers.WithClient(mgr.GetClient())) - gatewayEventMapper := mappers.NewGatewayEventMapper(mappers.WithLogger(r.Logger().WithName("gatewayEventMapper")), mappers.WithClient(mgr.GetClient())) + httpRouteEventMapper := mappers.NewHTTPRouteEventMapper(mappers.WithLogger(r.Logger().WithName("httproute.mapper")), mappers.WithClient(mgr.GetClient())) + gatewayEventMapper := mappers.NewGatewayEventMapper( + kuadrantv1beta2.NewRateLimitPolicyType(), + mappers.WithLogger(r.Logger().WithName("gateway.mapper")), + mappers.WithClient(mgr.GetClient()), + ) return ctrl.NewControllerManagedBy(mgr). For(&kuadrantv1beta2.RateLimitPolicy{}). Watches( &gatewayapiv1.HTTPRoute{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - return httpRouteEventMapper.MapToPolicy(ctx, object, &kuadrantv1beta2.RateLimitPolicy{}) + return httpRouteEventMapper.MapToPolicy(ctx, object, kuadrantv1beta2.NewRateLimitPolicyType()) }), ). // Currently the purpose is to generate events when rlp references change in gateways // so the status of the rlps targeting a route can be keep in sync - Watches( - &gatewayapiv1.Gateway{}, - handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - return gatewayEventMapper.MapToPolicy(ctx, object, &kuadrantv1beta2.RateLimitPolicy{}) - }), - ). + Watches(&gatewayapiv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(gatewayEventMapper.Map)). Complete(r) } diff --git a/controllers/tlspolicy_controller.go b/controllers/tlspolicy_controller.go index d43328b01..0c6a62076 100644 --- a/controllers/tlspolicy_controller.go +++ b/controllers/tlspolicy_controller.go @@ -205,7 +205,11 @@ func (r *TLSPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { return nil } - gatewayEventMapper := mappers.NewGatewayEventMapper(mappers.WithLogger(r.Logger().WithName("gatewayEventMapper")), mappers.WithClient(mgr.GetClient())) + gatewayEventMapper := mappers.NewGatewayEventMapper( + v1alpha1.NewTLSPolicyType(), + mappers.WithLogger(r.Logger().WithName("gateway.mapper")), + mappers.WithClient(mgr.GetClient()), + ) issuerStatusChangedPredicate := predicate.Funcs{ UpdateFunc: func(ev event.UpdateEvent) bool { @@ -226,12 +230,7 @@ func (r *TLSPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&v1alpha1.TLSPolicy{}). Owns(&certmanagerv1.Certificate{}). - Watches( - &gatewayapiv1.Gateway{}, - handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { - return gatewayEventMapper.MapToPolicy(ctx, object, &v1alpha1.TLSPolicy{}) - }), - ). + Watches(&gatewayapiv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(gatewayEventMapper.Map)). Watches( &certmanagerv1.Issuer{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, object client.Object) []reconcile.Request { diff --git a/pkg/library/gatewayapi/types.go b/pkg/library/gatewayapi/types.go index dd4137692..61e5bd930 100644 --- a/pkg/library/gatewayapi/types.go +++ b/pkg/library/gatewayapi/types.go @@ -5,8 +5,10 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" + gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" ) @@ -22,11 +24,6 @@ type Policy interface { PolicyClass() PolicyClass GetTargetRef() gatewayapiv1alpha2.LocalPolicyTargetReference GetStatus() PolicyStatus - List(context.Context, client.Client, string) []Policy - Kind() string - BackReferenceAnnotationName() string - DirectReferenceAnnotationName() string - TargetProgrammedGatewaysOnly() bool } type PolicyStatus interface { @@ -112,3 +109,62 @@ func (a PolicyByTargetRefKindAndAcceptedStatus) Less(i, j int) bool { // The policy appearing first in alphabetical order by "{namespace}/{name}". return client.ObjectKeyFromObject(a[i]).String() < client.ObjectKeyFromObject(a[j]).String() } + +type PolicyType interface { + GetGVK() schema.GroupVersionKind + GetInstance() client.Object + GetList(context.Context, client.Client, ...client.ListOption) ([]Policy, error) + BackReferenceAnnotationName() string + DirectReferenceAnnotationName() string +} + +type Type interface { + GetGVK() schema.GroupVersionKind + GetInstance() client.Object +} + +type gatewayType struct{} + +func (g gatewayType) GetGVK() schema.GroupVersionKind { + return schema.GroupVersionKind{ + Group: gatewayapiv1.GroupName, + Version: gatewayapiv1.GroupVersion.Version, + Kind: "Gateway", + } +} + +func (g gatewayType) GetInstance() client.Object { + return &gatewayapiv1.Gateway{ + TypeMeta: metav1.TypeMeta{ + Kind: "Gateway", + APIVersion: gatewayapiv1.GroupVersion.String(), + }, + } +} + +func NewGatewayType() Type { + return &gatewayType{} +} + +type httpRouteType struct{} + +func (h httpRouteType) GetGVK() schema.GroupVersionKind { + return schema.GroupVersionKind{ + Group: gatewayapiv1.GroupName, + Version: gatewayapiv1.GroupVersion.Version, + Kind: "HTTPRoute", + } +} + +func (h httpRouteType) GetInstance() client.Object { + return &gatewayapiv1.HTTPRoute{ + TypeMeta: metav1.TypeMeta{ + Kind: "HTTPRoute", + APIVersion: gatewayapiv1.GroupVersion.String(), + }, + } +} + +func NewHTTPRouteType() Type { + return &httpRouteType{} +} diff --git a/pkg/library/kuadrant/gateway_wrapper.go b/pkg/library/kuadrant/gateway_wrapper.go index 7ea41be6b..e4e55b9d1 100644 --- a/pkg/library/kuadrant/gateway_wrapper.go +++ b/pkg/library/kuadrant/gateway_wrapper.go @@ -36,7 +36,7 @@ func (g GatewayWrapper) PolicyRefs() []client.ObjectKey { return make([]client.ObjectKey, 0) } - refs := BackReferencesFromObject(g.Gateway, g.Referrer) + refs := BackReferencesFromObject(g.Gateway, g.BackReferenceAnnotationName()) err := json.Unmarshal([]byte(val), &refs) if err != nil { @@ -50,7 +50,7 @@ func (g GatewayWrapper) ContainsPolicy(policyKey client.ObjectKey) bool { if g.Gateway == nil { return false } - refs := BackReferencesFromObject(g.Gateway, g.Referrer) + refs := BackReferencesFromObject(g.Gateway, g.BackReferenceAnnotationName()) return slices.Contains(refs, policyKey) } @@ -82,7 +82,7 @@ func (g GatewayWrapper) AddPolicy(policyKey client.ObjectKey) bool { } // annotation exists and does not contain a back reference to the policy → add the policy to it - refs := append(BackReferencesFromObject(g.Gateway, g.Referrer), policyKey) + refs := append(BackReferencesFromObject(g.Gateway, g.BackReferenceAnnotationName()), policyKey) serialized, err := json.Marshal(refs) if err != nil { return false diff --git a/pkg/library/kuadrant/gateway_wrapper_test.go b/pkg/library/kuadrant/gateway_wrapper_test.go index ecedecd15..da90afd5a 100644 --- a/pkg/library/kuadrant/gateway_wrapper_test.go +++ b/pkg/library/kuadrant/gateway_wrapper_test.go @@ -162,7 +162,7 @@ func TestBackReferencesFromGatewayWrapper(t *testing.T) { }, Referrer: &PolicyKindStub{}, } - refs := utils.Map(BackReferencesFromObject(gw.Gateway, gw.Referrer), func(ref client.ObjectKey) string { return ref.String() }) + refs := utils.Map(BackReferencesFromObject(gw.Gateway, gw.BackReferenceAnnotationName()), func(ref client.ObjectKey) string { return ref.String() }) if !slices.Contains(refs, "app-ns/policy-1") { t.Error("GatewayWrapper.PolicyRefs() should contain app-ns/policy-1") } diff --git a/pkg/library/kuadrant/referrer.go b/pkg/library/kuadrant/referrer.go index 72fa43c9a..9c658b346 100644 --- a/pkg/library/kuadrant/referrer.go +++ b/pkg/library/kuadrant/referrer.go @@ -20,8 +20,8 @@ type Referrer interface { } // BackReferencesFromObject returns the names of the policies listed in the annotations of a target ref object. -func BackReferencesFromObject(obj client.Object, referrer Referrer) []client.ObjectKey { - backRefs, found := utils.ReadAnnotationsFromObject(obj)[referrer.BackReferenceAnnotationName()] +func BackReferencesFromObject(obj client.Object, backrefAnnotation string) []client.ObjectKey { + backRefs, found := utils.ReadAnnotationsFromObject(obj)[backrefAnnotation] if !found { return make([]client.ObjectKey, 0) } @@ -36,12 +36,11 @@ func BackReferencesFromObject(obj client.Object, referrer Referrer) []client.Obj return refs } -func DirectReferencesFromObject(obj client.Object, referrer Referrer) (client.ObjectKey, error) { +func DirectReferencesFromObject(obj client.Object, directAnnotation string) (client.ObjectKey, error) { annotations := utils.ReadAnnotationsFromObject(obj) - key := referrer.DirectReferenceAnnotationName() - directRefs, found := annotations[key] + directRefs, found := annotations[directAnnotation] if !found { - return client.ObjectKey{}, fmt.Errorf("annotation %s not found", key) + return client.ObjectKey{}, fmt.Errorf("annotation %s not found", directAnnotation) } parts := strings.Split(directRefs, "/") diff --git a/pkg/library/kuadrant/referrer_test.go b/pkg/library/kuadrant/referrer_test.go index 63de37833..0c22c0d34 100644 --- a/pkg/library/kuadrant/referrer_test.go +++ b/pkg/library/kuadrant/referrer_test.go @@ -25,7 +25,7 @@ func TestBackReferencesFromObject(t *testing.T) { policyKind := &PolicyKindStub{} - refs := utils.Map(BackReferencesFromObject(obj, policyKind), func(ref client.ObjectKey) string { return ref.String() }) + refs := utils.Map(BackReferencesFromObject(obj, policyKind.BackReferenceAnnotationName()), func(ref client.ObjectKey) string { return ref.String() }) if !slices.Contains(refs, "app-ns/policy-1") { t.Error("GatewayWrapper.PolicyRefs() should contain app-ns/policy-1") } diff --git a/pkg/library/mappers/event_mapper.go b/pkg/library/mappers/event_mapper.go index ba0c89b71..31b1a4a4b 100644 --- a/pkg/library/mappers/event_mapper.go +++ b/pkg/library/mappers/event_mapper.go @@ -1,20 +1,11 @@ package mappers import ( - "context" - "github.com/go-logr/logr" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - - kuadrantgatewayapi "github.com/kuadrant/kuadrant-operator/pkg/library/gatewayapi" ) -type EventMapper interface { - MapToPolicy(context.Context, client.Object, kuadrantgatewayapi.Policy) []reconcile.Request -} - // options // TODO(@guicassolato): unit test diff --git a/pkg/library/mappers/gateway.go b/pkg/library/mappers/gateway.go index ef381547b..c7a2cb7a9 100644 --- a/pkg/library/mappers/gateway.go +++ b/pkg/library/mappers/gateway.go @@ -14,21 +14,23 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) -func NewGatewayEventMapper(o ...MapperOption) EventMapper { - return &gatewayEventMapper{opts: Apply(o...)} +func NewGatewayEventMapper(policyType kuadrantgatewayapi.PolicyType, o ...MapperOption) *GatewayEventMapper { + return &GatewayEventMapper{ + policyType: policyType, + opts: Apply(o...), + } } -var _ EventMapper = &gatewayEventMapper{} - -type gatewayEventMapper struct { - opts MapperOptions +type GatewayEventMapper struct { + opts MapperOptions + policyType kuadrantgatewayapi.PolicyType } -func (m *gatewayEventMapper) MapToPolicy(ctx context.Context, obj client.Object, policyKind kuadrantgatewayapi.Policy) []reconcile.Request { +func (m *GatewayEventMapper) Map(ctx context.Context, obj client.Object) []reconcile.Request { logger := m.opts.Logger.WithValues("gateway", client.ObjectKeyFromObject(obj)) gateway, ok := obj.(*gatewayapiv1.Gateway) if !ok { - logger.Info("cannot map gateway related event to kuadrant policy", "error", fmt.Sprintf("%T is not a *gatewayapiv1beta1.Gateway", obj)) + logger.Info("cannot map gateway related event", "error", fmt.Sprintf("%T is not a *gatewayapiv1beta1.Gateway", obj)) return []reconcile.Request{} } routeList := &gatewayapiv1.HTTPRouteList{} @@ -38,7 +40,12 @@ func (m *gatewayEventMapper) MapToPolicy(ctx context.Context, obj client.Object, return []reconcile.Request{} } - policies := policyKind.List(ctx, m.opts.Client, obj.GetNamespace()) + policies, err := m.policyType.GetList(ctx, m.opts.Client) + if err != nil { + logger.V(1).Error(err, "unable to list policies") + return []reconcile.Request{} + } + if len(policies) == 0 { logger.V(1).Info("no kuadrant policy possibly affected by the gateway related event") return []reconcile.Request{} @@ -58,7 +65,7 @@ func (m *gatewayEventMapper) MapToPolicy(ctx context.Context, obj client.Object, index := kuadrantgatewayapi.NewTopologyIndexes(topology) return utils.Map(index.PoliciesFromGateway(gateway), func(p kuadrantgatewayapi.Policy) reconcile.Request { policyKey := client.ObjectKeyFromObject(p) - logger.V(1).Info("kuadrant policy possibly affected by the gateway related event found") + logger.V(1).Info("new request", "policy key", policyKey) return reconcile.Request{NamespacedName: policyKey} }) } diff --git a/pkg/library/mappers/gateway_test.go b/pkg/library/mappers/gateway_test.go index ef564a9b3..7017e549b 100644 --- a/pkg/library/mappers/gateway_test.go +++ b/pkg/library/mappers/gateway_test.go @@ -8,10 +8,8 @@ import ( "gotest.tools/assert" appsv1 "k8s.io/api/apps/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/reconcile" @@ -20,82 +18,87 @@ import ( kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/pkg/library/fieldindexers" + kuadrantgatewayapi "github.com/kuadrant/kuadrant-operator/pkg/library/gatewayapi" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/log" ) func TestNewGatewayEventMapper(t *testing.T) { - err := appsv1.AddToScheme(scheme.Scheme) + testScheme := runtime.NewScheme() + + err := appsv1.AddToScheme(testScheme) if err != nil { t.Fatal(err) } - err = gatewayapiv1.AddToScheme(scheme.Scheme) + + err = gatewayapiv1.AddToScheme(testScheme) if err != nil { t.Fatal(err) } - err = kuadrantv1beta2.AddToScheme(scheme.Scheme) + + err = kuadrantv1beta2.AddToScheme(testScheme) if err != nil { t.Fatal(err) } - spec := kuadrantv1beta2.AuthPolicySpec{ - TargetRef: gatewayapiv1alpha2.LocalPolicyTargetReference{ - Group: "gateway.networking.k8s.io", - Kind: "Gateway", - Name: "test-gw", - }, + ctx := context.Background() + + clientBuilder := func(objs []runtime.Object) client.Client { + return fake.NewClientBuilder(). + WithScheme(testScheme). + WithRuntimeObjects(objs...). + WithIndex(&gatewayapiv1.HTTPRoute{}, fieldindexers.HTTPRouteGatewayParentField, func(rawObj client.Object) []string { + route, assertionOk := rawObj.(*gatewayapiv1.HTTPRoute) + if !assertionOk { + return nil + } + + return utils.Map(kuadrantgatewayapi.GetGatewayParentKeys(route), func(key client.ObjectKey) string { + return key.String() + }) + }). + Build() } - routeList := &gatewayapiv1.HTTPRouteList{Items: make([]gatewayapiv1.HTTPRoute, 0)} - authPolicyList := &kuadrantv1beta2.AuthPolicyList{Items: []kuadrantv1beta2.AuthPolicy{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "policy-1", - Namespace: "app-ns", - }, - Spec: spec, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "policy-2", - Namespace: "app-ns", - }, - Spec: spec, - }, - }} - objs := []runtime.Object{routeList, authPolicyList} - cl := fake.NewClientBuilder().WithScheme(scheme.Scheme).WithRuntimeObjects(objs...).WithIndex(&gatewayapiv1.HTTPRoute{}, fieldindexers.HTTPRouteGatewayParentField, func(rawObj client.Object) []string { - return nil - }).Build() - em := NewGatewayEventMapper(WithLogger(log.NewLogger()), WithClient(cl)) t.Run("not gateway related event", func(subT *testing.T) { - requests := em.MapToPolicy(context.Background(), &gatewayapiv1.HTTPRoute{}, &kuadrantv1beta2.RateLimitPolicy{}) + objs := []runtime.Object{} + cl := clientBuilder(objs) + em := NewGatewayEventMapper(kuadrantv1beta2.NewRateLimitPolicyType(), WithClient(cl), WithLogger(log.NewLogger())) + requests := em.Map(ctx, &gatewayapiv1.HTTPRoute{}) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) - t.Run("gateway related event - no requests", func(subT *testing.T) { - requests := em.MapToPolicy(context.Background(), &gatewayapiv1.Gateway{}, &kuadrantv1beta2.RateLimitPolicy{}) + t.Run("gateway related event - no policies - no requests", func(subT *testing.T) { + objs := []runtime.Object{} + cl := clientBuilder(objs) + em := NewGatewayEventMapper(kuadrantv1beta2.NewRateLimitPolicyType(), WithClient(cl), WithLogger(log.NewLogger())) + requests := em.Map(ctx, &gatewayapiv1.Gateway{}) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) t.Run("gateway related event - requests", func(subT *testing.T) { - gateway := &gatewayapiv1.Gateway{ - ObjectMeta: metav1.ObjectMeta{Name: "test-gw", Namespace: "app-ns"}, - Status: gatewayapiv1.GatewayStatus{ - Conditions: []metav1.Condition{ - { - Type: "Programmed", - Status: "True", - }, - }, - }, - } - requests := em.MapToPolicy(context.Background(), gateway, &kuadrantv1beta2.AuthPolicy{}) + gw := gatewayFactory("ns-a", "gw-1") + route := routeFactory("ns-a", "route-1", gatewayapiv1.ParentReference{Name: "gw-1"}) + pGw := policyFactory("ns-a", "pRoute", gatewayapiv1alpha2.LocalPolicyTargetReference{ + Group: gatewayapiv1.GroupName, + Kind: "HTTPRoute", + Name: gatewayapiv1.ObjectName("route-1"), + }) + pRoute := policyFactory("ns-a", "pGw", gatewayapiv1alpha2.LocalPolicyTargetReference{ + Group: gatewayapiv1.GroupName, + Kind: "Gateway", + Name: gatewayapiv1.ObjectName("gw-1"), + }) + objs := []runtime.Object{gw, route, pGw, pRoute} + cl := clientBuilder(objs) + em := NewGatewayEventMapper(kuadrantv1beta2.NewRateLimitPolicyType(), WithClient(cl), WithLogger(log.NewLogger())) + requests := em.Map(ctx, gw) + assert.Equal(subT, len(requests), 2) assert.Assert(subT, utils.Index(requests, func(r reconcile.Request) bool { - return r.NamespacedName == types.NamespacedName{Namespace: "app-ns", Name: "policy-1"} + return r.NamespacedName == types.NamespacedName{Namespace: "ns-a", Name: "pGw"} }) >= 0) assert.Assert(subT, utils.Index(requests, func(r reconcile.Request) bool { - return r.NamespacedName == types.NamespacedName{Namespace: "app-ns", Name: "policy-2"} + return r.NamespacedName == types.NamespacedName{Namespace: "ns-a", Name: "pRoute"} }) >= 0) }) } diff --git a/pkg/library/mappers/httproute.go b/pkg/library/mappers/httproute.go index bcda349c1..01088531b 100644 --- a/pkg/library/mappers/httproute.go +++ b/pkg/library/mappers/httproute.go @@ -15,17 +15,15 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) -func NewHTTPRouteEventMapper(o ...MapperOption) EventMapper { - return &httpRouteEventMapper{opts: Apply(o...)} +func NewHTTPRouteEventMapper(o ...MapperOption) *HTTPRouteEventMapper { + return &HTTPRouteEventMapper{opts: Apply(o...)} } -var _ EventMapper = &httpRouteEventMapper{} - -type httpRouteEventMapper struct { +type HTTPRouteEventMapper struct { opts MapperOptions } -func (m *httpRouteEventMapper) MapToPolicy(ctx context.Context, obj client.Object, policyKind kuadrantgatewayapi.Policy) []reconcile.Request { +func (m *HTTPRouteEventMapper) MapToPolicy(ctx context.Context, obj client.Object, policyType kuadrantgatewayapi.PolicyType) []reconcile.Request { logger := m.opts.Logger.WithValues("httproute", client.ObjectKeyFromObject(obj)) requests := make([]reconcile.Request, 0) httpRoute, ok := obj.(*gatewayapiv1.HTTPRoute) @@ -50,7 +48,12 @@ func (m *httpRouteEventMapper) MapToPolicy(ctx context.Context, obj client.Objec logger.Info("cannot list httproutes", "error", err) continue } - policies := policyKind.List(ctx, m.opts.Client, obj.GetNamespace()) + + policies, err := policyType.GetList(ctx, m.opts.Client, client.InNamespace(obj.GetNamespace())) + if err != nil { + logger.Error(err, "unable to list policies") + continue + } if len(policies) == 0 { logger.Info("no kuadrant policy possibly affected by the gateway related event") continue @@ -78,11 +81,12 @@ func (m *httpRouteEventMapper) MapToPolicy(ctx context.Context, obj client.Objec return requests } - policyKey, err := kuadrant.DirectReferencesFromObject(httpRoute, policyKind) + policyKey, err := kuadrant.DirectReferencesFromObject(httpRoute, policyType.DirectReferenceAnnotationName()) if err != nil { logger.Info("could not create direct reference from object", "error", err) return requests } requests = append(requests, reconcile.Request{NamespacedName: policyKey}) + return requests } diff --git a/pkg/library/mappers/httproute_test.go b/pkg/library/mappers/httproute_test.go index 0a38ac3ba..9f1fa00ba 100644 --- a/pkg/library/mappers/httproute_test.go +++ b/pkg/library/mappers/httproute_test.go @@ -7,7 +7,6 @@ import ( "testing" "gotest.tools/assert" - "istio.io/client-go/pkg/clientset/versioned/scheme" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -27,15 +26,17 @@ import ( ) func TestNewHTTPRouteEventMapper(t *testing.T) { - err := appsv1.AddToScheme(scheme.Scheme) + testScheme := runtime.NewScheme() + + err := appsv1.AddToScheme(testScheme) if err != nil { t.Fatal(err) } - err = gatewayapiv1.AddToScheme(scheme.Scheme) + err = gatewayapiv1.AddToScheme(testScheme) if err != nil { t.Fatal(err) } - err = kuadrantv1beta2.AddToScheme(scheme.Scheme) + err = kuadrantv1beta2.AddToScheme(testScheme) if err != nil { t.Fatal(err) } @@ -69,18 +70,18 @@ func TestNewHTTPRouteEventMapper(t *testing.T) { }, } objs := []runtime.Object{routeList, authPolicyList, gateway} - cl := fake.NewClientBuilder().WithScheme(scheme.Scheme).WithRuntimeObjects(objs...).WithIndex(&gatewayapiv1.HTTPRoute{}, fieldindexers.HTTPRouteGatewayParentField, func(rawObj client.Object) []string { + cl := fake.NewClientBuilder().WithScheme(testScheme).WithRuntimeObjects(objs...).WithIndex(&gatewayapiv1.HTTPRoute{}, fieldindexers.HTTPRouteGatewayParentField, func(rawObj client.Object) []string { return nil }).Build() em := NewHTTPRouteEventMapper(WithLogger(log.NewLogger()), WithClient(cl)) t.Run("not http route related event", func(subT *testing.T) { - requests := em.MapToPolicy(context.Background(), &gatewayapiv1.Gateway{}, &kuadrantv1beta2.AuthPolicy{}) + requests := em.MapToPolicy(context.Background(), &gatewayapiv1.Gateway{}, kuadrantv1beta2.NewAuthPolicyType()) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) t.Run("http route related event - no requests", func(subT *testing.T) { - requests := em.MapToPolicy(context.Background(), &gatewayapiv1.HTTPRoute{}, &kuadrantv1beta2.AuthPolicy{}) + requests := em.MapToPolicy(context.Background(), &gatewayapiv1.HTTPRoute{}, kuadrantv1beta2.NewAuthPolicyType()) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) @@ -118,7 +119,7 @@ func TestNewHTTPRouteEventMapper(t *testing.T) { } objs = []runtime.Object{routeList, authPolicyList, gateway, httpRoute} - cl = fake.NewClientBuilder().WithScheme(scheme.Scheme).WithRuntimeObjects(objs...).WithIndex(&gatewayapiv1.HTTPRoute{}, fieldindexers.HTTPRouteGatewayParentField, func(rawObj client.Object) []string { + cl = fake.NewClientBuilder().WithScheme(testScheme).WithRuntimeObjects(objs...).WithIndex(&gatewayapiv1.HTTPRoute{}, fieldindexers.HTTPRouteGatewayParentField, func(rawObj client.Object) []string { route, assertionOk := rawObj.(*gatewayapiv1.HTTPRoute) if !assertionOk { return nil @@ -129,7 +130,7 @@ func TestNewHTTPRouteEventMapper(t *testing.T) { }) }).Build() em = NewHTTPRouteEventMapper(WithLogger(log.NewLogger()), WithClient(cl)) - requests := em.MapToPolicy(context.Background(), httpRoute, &kuadrantv1beta2.AuthPolicy{}) + requests := em.MapToPolicy(context.Background(), httpRoute, kuadrantv1beta2.NewAuthPolicyType()) expected := []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: "app-ns", Name: "policy-1"}}} assert.DeepEqual(subT, expected, requests) }) diff --git a/pkg/library/mappers/utils_test.go b/pkg/library/mappers/utils_test.go new file mode 100644 index 000000000..eedf7a204 --- /dev/null +++ b/pkg/library/mappers/utils_test.go @@ -0,0 +1,39 @@ +//go:build unit + +package mappers + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + + kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" +) + +func gatewayFactory(ns, name string) *gatewayapiv1.Gateway { + return &gatewayapiv1.Gateway{ + TypeMeta: metav1.TypeMeta{Kind: "Gateway", APIVersion: gatewayapiv1.GroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: ns}, + Spec: gatewayapiv1.GatewaySpec{}, + } +} + +func routeFactory(ns, name string, parentRef gatewayapiv1.ParentReference) *gatewayapiv1.HTTPRoute { + return &gatewayapiv1.HTTPRoute{ + TypeMeta: metav1.TypeMeta{Kind: "HTTPRoute", APIVersion: gatewayapiv1.GroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: ns}, + Spec: gatewayapiv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayapiv1.CommonRouteSpec{ + ParentRefs: []gatewayapiv1.ParentReference{parentRef}, + }, + }, + } +} + +func policyFactory(ns, name string, targetRef gatewayapiv1alpha2.LocalPolicyTargetReference) *kuadrantv1beta2.RateLimitPolicy { + return &kuadrantv1beta2.RateLimitPolicy{ + TypeMeta: metav1.TypeMeta{Kind: "RateLimitPolicy", APIVersion: kuadrantv1beta2.GroupVersion.String()}, + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: ns}, + Spec: kuadrantv1beta2.RateLimitPolicySpec{TargetRef: targetRef}, + } +}