From b0117074f43d5a1aae138e30f8aa3989d11a79d7 Mon Sep 17 00:00:00 2001 From: KevFan Date: Thu, 22 Feb 2024 10:56:42 +0000 Subject: [PATCH] refactor: kuadrant package in library package --- api/v1alpha1/dnspolicy_types.go | 6 ++-- api/v1alpha1/tlspolicy_types.go | 6 ++-- api/v1beta1/kuadrant_types.go | 6 ++-- api/v1beta2/authpolicy_types.go | 13 ++++---- api/v1beta2/authpolicy_types_test.go | 6 ++-- api/v1beta2/ratelimitpolicy_types.go | 13 ++++---- api/v1beta2/ratelimitpolicy_types_test.go | 6 ++-- api/v1beta2/route_selectors.go | 3 +- api/v1beta2/route_selectors_test.go | 3 +- controllers/authpolicy_authconfig.go | 9 +++--- controllers/authpolicy_controller.go | 12 ++++---- controllers/authpolicy_controller_test.go | 18 +++++------ .../authpolicy_istio_authorizationpolicy.go | 3 +- controllers/authpolicy_status.go | 17 ++++++----- controllers/dns_helper.go | 3 +- .../dnshealthcheckprobe_eventmapper.go | 6 ++-- controllers/dnspolicy_controller.go | 4 +-- controllers/dnspolicy_controller_test.go | 4 +-- controllers/dnspolicy_healthchecks.go | 4 +-- controllers/dnspolicy_status.go | 6 ++-- controllers/gateway_kuadrant_controller.go | 6 ++-- .../gateway_kuadrant_controller_test.go | 6 ++-- controllers/helper_test.go | 3 +- .../httprouteparentrefs_eventmapper.go | 8 ++--- controllers/kuadrant_controller.go | 8 ++--- ...imitador_cluster_envoyfilter_controller.go | 6 ++-- controllers/ratelimitpolicy_controller.go | 10 +++---- .../ratelimitpolicy_istio_wasmplugin.go | 7 +++-- controllers/ratelimitpolicy_limits.go | 7 +++-- controllers/ratelimitpolicy_status.go | 4 +-- controllers/suite_test.go | 4 +-- controllers/tlspolicy_controller.go | 4 +-- controllers/tlspolicy_status.go | 6 ++-- main.go | 4 +-- pkg/common/istio_utils.go | 4 +-- .../apimachinery_status_conditions.go | 18 +++++------ .../apimachinery_status_conditions_test.go | 6 ++-- pkg/library/{utils => kuadrant}/errors.go | 2 +- .../{utils => kuadrant}/errors_test.go | 2 +- .../{utils => kuadrant}/gateway_wrapper.go | 10 ++++--- .../gateway_wrapper_test.go | 8 +++-- .../{utils => kuadrant}/gatewayapi_utils.go | 30 ++++++++++--------- .../gatewayapi_utils_test.go | 2 +- pkg/library/{utils => kuadrant}/kuadrant.go | 8 ++--- pkg/library/{utils => kuadrant}/referrer.go | 6 ++-- .../{utils => kuadrant}/referrer_test.go | 6 ++-- pkg/library/{utils => kuadrant}/test_utils.go | 2 +- pkg/library/mappers/event_mapper.go | 4 +-- pkg/library/mappers/gateway.go | 6 ++-- pkg/library/mappers/gateway_test.go | 8 ++--- pkg/library/mappers/httproute.go | 6 ++-- pkg/library/mappers/httproute_test.go | 8 ++--- pkg/library/reconcilers/gateway_diffs.go | 28 ++++++++--------- pkg/library/reconcilers/gateway_diffs_test.go | 13 ++++---- .../reconcilers/target_ref_reconciler.go | 13 ++++---- .../reconcilers/target_ref_reconciler_test.go | 4 +-- 56 files changed, 225 insertions(+), 200 deletions(-) rename pkg/library/{utils => kuadrant}/apimachinery_status_conditions.go (78%) rename pkg/library/{utils => kuadrant}/apimachinery_status_conditions_test.go (99%) rename pkg/library/{utils => kuadrant}/errors.go (99%) rename pkg/library/{utils => kuadrant}/errors_test.go (97%) rename pkg/library/{utils => kuadrant}/gateway_wrapper.go (94%) rename pkg/library/{utils => kuadrant}/gateway_wrapper_test.go (94%) rename pkg/library/{utils => kuadrant}/gatewayapi_utils.go (91%) rename pkg/library/{utils => kuadrant}/gatewayapi_utils_test.go (99%) rename pkg/library/{utils => kuadrant}/kuadrant.go (82%) rename pkg/library/{utils => kuadrant}/referrer.go (84%) rename pkg/library/{utils => kuadrant}/referrer_test.go (80%) rename pkg/library/{utils => kuadrant}/test_utils.go (98%) diff --git a/api/v1alpha1/dnspolicy_types.go b/api/v1alpha1/dnspolicy_types.go index 4ca25e621..625e91214 100644 --- a/api/v1alpha1/dnspolicy_types.go +++ b/api/v1alpha1/dnspolicy_types.go @@ -26,7 +26,7 @@ import ( kuadrantdnsv1alpha1 "github.com/kuadrant/dns-operator/api/v1alpha1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) type RoutingStrategy string @@ -129,8 +129,8 @@ type DNSPolicyStatus struct { HealthCheck *HealthCheckStatus `json:"healthCheck,omitempty"` } -var _ utils.KuadrantPolicy = &DNSPolicy{} -var _ utils.Referrer = &DNSPolicy{} +var _ kuadrant.Policy = &DNSPolicy{} +var _ kuadrant.Referrer = &DNSPolicy{} // +kubebuilder:object:root=true // +kubebuilder:subresource:status diff --git a/api/v1alpha1/tlspolicy_types.go b/api/v1alpha1/tlspolicy_types.go index a3211e887..6952b0954 100644 --- a/api/v1alpha1/tlspolicy_types.go +++ b/api/v1alpha1/tlspolicy_types.go @@ -25,7 +25,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) const ( @@ -116,8 +116,8 @@ type TLSPolicyStatus struct { ObservedGeneration int64 `json:"observedGeneration,omitempty"` } -var _ utils.KuadrantPolicy = &TLSPolicy{} -var _ utils.Referrer = &TLSPolicy{} +var _ kuadrant.Policy = &TLSPolicy{} +var _ kuadrant.Referrer = &TLSPolicy{} // +kubebuilder:object:root=true // +kubebuilder:subresource:status diff --git a/api/v1beta1/kuadrant_types.go b/api/v1beta1/kuadrant_types.go index ca44a60e4..152d43b83 100644 --- a/api/v1beta1/kuadrant_types.go +++ b/api/v1beta1/kuadrant_types.go @@ -23,7 +23,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! @@ -76,8 +76,8 @@ func (r *KuadrantStatus) Equals(other *KuadrantStatus, logger logr.Logger) bool } // Marshalling sorts by condition type - currentMarshaledJSON, _ := utils.ConditionMarshal(r.Conditions) - otherMarshaledJSON, _ := utils.ConditionMarshal(other.Conditions) + currentMarshaledJSON, _ := kuadrant.ConditionMarshal(r.Conditions) + otherMarshaledJSON, _ := kuadrant.ConditionMarshal(other.Conditions) if string(currentMarshaledJSON) != string(otherMarshaledJSON) { diff := cmp.Diff(string(currentMarshaledJSON), string(otherMarshaledJSON)) logger.V(1).Info("Conditions not equal", "difference", diff) diff --git a/api/v1beta2/authpolicy_types.go b/api/v1beta2/authpolicy_types.go index 7555ccda0..aac60eb66 100644 --- a/api/v1beta2/authpolicy_types.go +++ b/api/v1beta2/authpolicy_types.go @@ -11,6 +11,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -191,8 +192,8 @@ func (s *AuthPolicyStatus) Equals(other *AuthPolicyStatus, logger logr.Logger) b } // Marshalling sorts by condition type - currentMarshaledJSON, _ := utils.ConditionMarshal(s.Conditions) - otherMarshaledJSON, _ := utils.ConditionMarshal(other.Conditions) + currentMarshaledJSON, _ := kuadrant.ConditionMarshal(s.Conditions) + otherMarshaledJSON, _ := kuadrant.ConditionMarshal(other.Conditions) if string(currentMarshaledJSON) != string(otherMarshaledJSON) { diff := cmp.Diff(string(currentMarshaledJSON), string(otherMarshaledJSON)) logger.V(1).Info("Conditions not equal", "difference", diff) @@ -202,8 +203,8 @@ func (s *AuthPolicyStatus) Equals(other *AuthPolicyStatus, logger logr.Logger) b return true } -var _ utils.KuadrantPolicy = &AuthPolicy{} -var _ utils.Referrer = &AuthPolicy{} +var _ kuadrant.Policy = &AuthPolicy{} +var _ kuadrant.Referrer = &AuthPolicy{} // +kubebuilder:object:root=true // +kubebuilder:subresource:status @@ -307,8 +308,8 @@ type AuthPolicyList struct { Items []AuthPolicy `json:"items"` } -func (l *AuthPolicyList) GetItems() []utils.KuadrantPolicy { - return utils.Map(l.Items, func(item AuthPolicy) utils.KuadrantPolicy { +func (l *AuthPolicyList) GetItems() []kuadrant.Policy { + return utils.Map(l.Items, func(item AuthPolicy) kuadrant.Policy { return &item }) } diff --git a/api/v1beta2/authpolicy_types_test.go b/api/v1beta2/authpolicy_types_test.go index ef3d0d773..4e9fbd3be 100644 --- a/api/v1beta2/authpolicy_types_test.go +++ b/api/v1beta2/authpolicy_types_test.go @@ -12,7 +12,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func TestCommonAuthRuleSpecGetRouteSelectors(t *testing.T) { @@ -86,9 +86,9 @@ func TestAuthPolicyListGetItems(t *testing.T) { if len(result) != 1 { t.Errorf("Expected 1 item, got %d", len(result)) } - _, ok := result[0].(utils.KuadrantPolicy) + _, ok := result[0].(kuadrant.Policy) if !ok { - t.Errorf("Expected item to be a KuadrantPolicy") + t.Errorf("Expected item to be a Policy") } } diff --git a/api/v1beta2/ratelimitpolicy_types.go b/api/v1beta2/ratelimitpolicy_types.go index 03bdad808..38c537611 100644 --- a/api/v1beta2/ratelimitpolicy_types.go +++ b/api/v1beta2/ratelimitpolicy_types.go @@ -26,6 +26,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -154,8 +155,8 @@ func (s *RateLimitPolicyStatus) Equals(other *RateLimitPolicyStatus, logger logr } // Marshalling sorts by condition type - currentMarshaledJSON, _ := utils.ConditionMarshal(s.Conditions) - otherMarshaledJSON, _ := utils.ConditionMarshal(other.Conditions) + currentMarshaledJSON, _ := kuadrant.ConditionMarshal(s.Conditions) + otherMarshaledJSON, _ := kuadrant.ConditionMarshal(other.Conditions) if string(currentMarshaledJSON) != string(otherMarshaledJSON) { if logger.V(1).Enabled() { diff := cmp.Diff(string(currentMarshaledJSON), string(otherMarshaledJSON)) @@ -167,8 +168,8 @@ func (s *RateLimitPolicyStatus) Equals(other *RateLimitPolicyStatus, logger logr return true } -var _ utils.KuadrantPolicy = &RateLimitPolicy{} -var _ utils.Referrer = &RateLimitPolicy{} +var _ kuadrant.Policy = &RateLimitPolicy{} +var _ kuadrant.Referrer = &RateLimitPolicy{} // +kubebuilder:object:root=true // +kubebuilder:subresource:status @@ -217,8 +218,8 @@ type RateLimitPolicyList struct { Items []RateLimitPolicy `json:"items"` } -func (l *RateLimitPolicyList) GetItems() []utils.KuadrantPolicy { - return utils.Map(l.Items, func(item RateLimitPolicy) utils.KuadrantPolicy { +func (l *RateLimitPolicyList) GetItems() []kuadrant.Policy { + return utils.Map(l.Items, func(item RateLimitPolicy) kuadrant.Policy { return &item }) } diff --git a/api/v1beta2/ratelimitpolicy_types_test.go b/api/v1beta2/ratelimitpolicy_types_test.go index 65ee7bcdc..5cd7b28a9 100644 --- a/api/v1beta2/ratelimitpolicy_types_test.go +++ b/api/v1beta2/ratelimitpolicy_types_test.go @@ -10,7 +10,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func testBuildBasicRLP(name string, kind gatewayapiv1.Kind) *RateLimitPolicy { @@ -70,8 +70,8 @@ func TestRateLimitPolicyListGetItems(t *testing.T) { if len(result) != 1 { t.Errorf("Expected 1 item, got %d", len(result)) } - _, ok := result[0].(utils.KuadrantPolicy) + _, ok := result[0].(kuadrant.Policy) if !ok { - t.Errorf("Expected item to be a KuadrantPolicy") + t.Errorf("Expected item to be a Policy") } } diff --git a/api/v1beta2/route_selectors.go b/api/v1beta2/route_selectors.go index 57e2eceaf..ef494effa 100644 --- a/api/v1beta2/route_selectors.go +++ b/api/v1beta2/route_selectors.go @@ -4,6 +4,7 @@ import ( "github.com/elliotchance/orderedmap/v2" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -40,7 +41,7 @@ func (s *RouteSelector) SelectRules(route *gatewayapiv1.HTTPRoute) (rules []gate for idx := range s.Matches { routeSelectorMatch := s.Matches[idx] for idx, rule := range route.Spec.Rules { - rs := utils.HTTPRouteRuleSelector{HTTPRouteMatch: &routeSelectorMatch} + rs := kuadrant.HTTPRouteRuleSelector{HTTPRouteMatch: &routeSelectorMatch} if rs.Selects(rule) { rulesIndices.Set(idx, rule) } diff --git a/api/v1beta2/route_selectors_test.go b/api/v1beta2/route_selectors_test.go index cb3ea07e5..c3934b86f 100644 --- a/api/v1beta2/route_selectors_test.go +++ b/api/v1beta2/route_selectors_test.go @@ -11,6 +11,7 @@ import ( "k8s.io/utils/ptr" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -144,7 +145,7 @@ func TestRouteSelectors(t *testing.T) { t.Run(tc.name, func(t *testing.T) { rules := tc.routeSelector.SelectRules(tc.route) rulesToStringSlice := func(rules []gatewayapiv1.HTTPRouteRule) []string { - return utils.Map(utils.Map(rules, utils.HTTPRouteRuleToString), func(r string) string { return fmt.Sprintf("{%s}", r) }) + return utils.Map(utils.Map(rules, kuadrant.HTTPRouteRuleToString), func(r string) string { return fmt.Sprintf("{%s}", r) }) } if !reflect.DeepEqual(rules, tc.expected) { t.Errorf("expected %v, got %v", rulesToStringSlice(tc.expected), rulesToStringSlice(rules)) diff --git a/controllers/authpolicy_authconfig.go b/controllers/authpolicy_authconfig.go index 293c7a972..a3da417b9 100644 --- a/controllers/authpolicy_authconfig.go +++ b/controllers/authpolicy_authconfig.go @@ -8,15 +8,16 @@ import ( "strings" "github.com/go-logr/logr" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + authorinoapi "github.com/kuadrant/authorino/api/v1beta2" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - authorinoapi "github.com/kuadrant/authorino/api/v1beta2" api "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/pkg/common" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" + "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) func (r *AuthPolicyReconciler) reconcileAuthConfigs(ctx context.Context, ap *api.AuthPolicy, targetNetworkObject client.Object) error { @@ -66,14 +67,14 @@ func (r *AuthPolicyReconciler) desiredAuthConfig(ctx context.Context, ap *api.Au case *gatewayapiv1.HTTPRoute: route = obj var err error - hosts, err = utils.HostnamesFromHTTPRoute(ctx, obj, r.Client()) + hosts, err = kuadrant.HostnamesFromHTTPRoute(ctx, obj, r.Client()) if err != nil { return nil, err } case *gatewayapiv1.Gateway: // fake a single httproute with all rules from all httproutes accepted by the gateway, // that do not have an authpolicy of its own, so we can generate wasm rules for those cases - gw := utils.GatewayWrapper{Gateway: obj} + gw := kuadrant.GatewayWrapper{Gateway: obj} gwHostnames := gw.Hostnames() if len(gwHostnames) == 0 { gwHostnames = []gatewayapiv1.Hostname{"*"} diff --git a/controllers/authpolicy_controller.go b/controllers/authpolicy_controller.go index 814cda312..7124e143d 100644 --- a/controllers/authpolicy_controller.go +++ b/controllers/authpolicy_controller.go @@ -15,9 +15,9 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" api "github.com/kuadrant/kuadrant-operator/api/v1beta2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/mappers" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -28,7 +28,7 @@ type AuthPolicyReconciler struct { *reconcilers.BaseReconciler TargetRefReconciler reconcilerutils.TargetRefReconciler // OverriddenPolicyMap tracks the overridden policies to report their status. - OverriddenPolicyMap *utils.OverriddenPolicyMap + OverriddenPolicyMap *kuadrant.OverriddenPolicyMap } //+kubebuilder:rbac:groups=kuadrant.io,resources=authpolicies,verbs=get;list;watch;create;update;patch;delete @@ -73,7 +73,7 @@ func (r *AuthPolicyReconciler) Reconcile(eventCtx context.Context, req ctrl.Requ if delResErr == nil { delResErr = err } - return r.reconcileStatus(ctx, ap, targetNetworkObject, utils.NewErrTargetNotFound(ap.Kind(), ap.GetTargetRef(), delResErr)) + return r.reconcileStatus(ctx, ap, targetNetworkObject, kuadrant.NewErrTargetNotFound(ap.Kind(), ap.GetTargetRef(), delResErr)) } return ctrl.Result{}, err } @@ -139,11 +139,11 @@ func (r *AuthPolicyReconciler) Reconcile(eventCtx context.Context, req ctrl.Requ // validate performs validation before proceeding with the reconcile loop, returning a common.ErrInvalid on any failing validation func (r *AuthPolicyReconciler) validate(ap *api.AuthPolicy, targetNetworkObject client.Object) error { if err := ap.Validate(); err != nil { - return utils.NewErrInvalid(ap.Kind(), err) + return kuadrant.NewErrInvalid(ap.Kind(), err) } - if err := utils.ValidateHierarchicalRules(ap, targetNetworkObject); err != nil { - return utils.NewErrInvalid(ap.Kind(), err) + if err := kuadrant.ValidateHierarchicalRules(ap, targetNetworkObject); err != nil { + return kuadrant.NewErrInvalid(ap.Kind(), err) } return nil diff --git a/controllers/authpolicy_controller_test.go b/controllers/authpolicy_controller_test.go index eb34149da..3ac0bf529 100644 --- a/controllers/authpolicy_controller_test.go +++ b/controllers/authpolicy_controller_test.go @@ -28,7 +28,7 @@ import ( kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1" api "github.com/kuadrant/kuadrant-operator/api/v1beta2" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) const ( @@ -335,7 +335,7 @@ var _ = Describe("AuthPolicy controller", func() { return false } condition := meta.FindStatusCondition(existingPolicy.Status.Conditions, string(gatewayapiv1alpha2.PolicyConditionAccepted)) - return condition != nil && condition.Reason == string(utils.PolicyReasonUnknown) && strings.Contains(condition.Message, "cannot match any route rules, check for invalid route selectors in the policy") + return condition != nil && condition.Reason == string(kuadrant.PolicyReasonUnknown) && strings.Contains(condition.Message, "cannot match any route rules, check for invalid route selectors in the policy") }, 30*time.Second, 5*time.Second).Should(BeTrue()) // check istio authorizationpolicy @@ -380,7 +380,7 @@ var _ = Describe("AuthPolicy controller", func() { return false } condition := meta.FindStatusCondition(existingPolicy.Status.Conditions, string(gatewayapiv1alpha2.PolicyConditionAccepted)) - return condition != nil && condition.Reason == string(utils.PolicyReasonUnknown) && strings.Contains(condition.Message, "cannot match any route rules, check for invalid route selectors in the policy") + return condition != nil && condition.Reason == string(kuadrant.PolicyReasonUnknown) && strings.Contains(condition.Message, "cannot match any route rules, check for invalid route selectors in the policy") }, 30*time.Second, 5*time.Second).Should(BeTrue()) iapKey := types.NamespacedName{Name: istioAuthorizationPolicyName(testGatewayName, policy.Spec.TargetRef), Namespace: testNamespace} @@ -1075,7 +1075,7 @@ var _ = Describe("AuthPolicy controller", func() { acceptedCondMatch := acceptedCond.Status == metav1.ConditionFalse && acceptedCond.Reason == reason && acceptedCond.Message == message - enforcedCond := meta.FindStatusCondition(existingPolicy.Status.Conditions, string(utils.PolicyReasonEnforced)) + enforcedCond := meta.FindStatusCondition(existingPolicy.Status.Conditions, string(kuadrant.PolicyReasonEnforced)) enforcedCondMatch := enforcedCond == nil return acceptedCondMatch && enforcedCondMatch @@ -1152,7 +1152,7 @@ var _ = Describe("AuthPolicy controller", func() { acceptedCondMatch := acceptedCond.Status == metav1.ConditionTrue && acceptedCond.Reason == string(gatewayapiv1alpha2.PolicyReasonAccepted) - enforcedCond := meta.FindStatusCondition(existingPolicy.Status.Conditions, string(utils.PolicyReasonEnforced)) + enforcedCond := meta.FindStatusCondition(existingPolicy.Status.Conditions, string(kuadrant.PolicyReasonEnforced)) if enforcedCond == nil { return false } @@ -1179,7 +1179,7 @@ var _ = Describe("AuthPolicy controller", func() { logf.Log.V(1).Info("Creating AuthPolicy", "key", client.ObjectKeyFromObject(policy).String(), "error", err) Expect(err).ToNot(HaveOccurred()) - Eventually(assertAcceptedCondTrueAndEnforcedCond(policy, metav1.ConditionTrue, string(utils.PolicyReasonEnforced), + Eventually(assertAcceptedCondTrueAndEnforcedCond(policy, metav1.ConditionTrue, string(kuadrant.PolicyReasonEnforced), "AuthPolicy has been successfully enforced"), 30*time.Second, 5*time.Second).Should(BeTrue()) }) @@ -1198,7 +1198,7 @@ var _ = Describe("AuthPolicy controller", func() { logf.Log.V(1).Info("Creating AuthPolicy", "key", client.ObjectKeyFromObject(policy).String(), "error", err) Expect(err).ToNot(HaveOccurred()) - Eventually(assertAcceptedCondTrueAndEnforcedCond(policy, metav1.ConditionFalse, string(utils.PolicyReasonUnknown), + Eventually(assertAcceptedCondTrueAndEnforcedCond(policy, metav1.ConditionFalse, string(kuadrant.PolicyReasonUnknown), "AuthPolicy has encountered some issues: AuthScheme is not ready yet"), 30*time.Second, 5*time.Second).Should(BeTrue()) }) @@ -1228,7 +1228,7 @@ var _ = Describe("AuthPolicy controller", func() { // check policy status Eventually(isAuthPolicyAccepted(gwPolicy), 30*time.Second, 5*time.Second).Should(BeTrue()) Eventually( - assertAcceptedCondTrueAndEnforcedCond(gwPolicy, metav1.ConditionFalse, string(utils.PolicyReasonOverridden), + assertAcceptedCondTrueAndEnforcedCond(gwPolicy, metav1.ConditionFalse, string(kuadrant.PolicyReasonOverridden), fmt.Sprintf("AuthPolicy is overridden by [{\"Namespace\":\"%s\",\"Name\":\"%s\"}]", testNamespace, routePolicy.Name)), 30*time.Second, 5*time.Second).Should(BeTrue()) @@ -1527,7 +1527,7 @@ func isAuthPolicyAccepted(policy *api.AuthPolicy) func() bool { } func isAuthPolicyEnforced(policy *api.AuthPolicy) func() bool { - return isAuthPolicyConditionTrue(policy, string(utils.PolicyConditionEnforced)) + return isAuthPolicyConditionTrue(policy, string(kuadrant.PolicyConditionEnforced)) } func isAuthPolicyConditionTrue(policy *api.AuthPolicy, condition string) func() bool { diff --git a/controllers/authpolicy_istio_authorizationpolicy.go b/controllers/authpolicy_istio_authorizationpolicy.go index f9bd91a73..b44c56a64 100644 --- a/controllers/authpolicy_istio_authorizationpolicy.go +++ b/controllers/authpolicy_istio_authorizationpolicy.go @@ -19,6 +19,7 @@ import ( api "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/pkg/common" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -78,7 +79,7 @@ func (r *AuthPolicyReconciler) deleteIstioAuthorizationPolicies(ctx context.Cont return nil } -func (r *AuthPolicyReconciler) istioAuthorizationPolicy(ctx context.Context, ap *api.AuthPolicy, targetNetworkObject client.Object, gw utils.GatewayWrapper) (*istio.AuthorizationPolicy, error) { +func (r *AuthPolicyReconciler) istioAuthorizationPolicy(ctx context.Context, ap *api.AuthPolicy, targetNetworkObject client.Object, gw kuadrant.GatewayWrapper) (*istio.AuthorizationPolicy, error) { logger, _ := logr.FromContext(ctx) logger = logger.WithName("istioAuthorizationPolicy") diff --git a/controllers/authpolicy_status.go b/controllers/authpolicy_status.go index 0245510cb..7fb323aa2 100644 --- a/controllers/authpolicy_status.go +++ b/controllers/authpolicy_status.go @@ -18,6 +18,7 @@ import ( gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" api "github.com/kuadrant/kuadrant-operator/api/v1beta2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -78,8 +79,8 @@ func (r *AuthPolicyReconciler) calculateStatus(ctx context.Context, ap *api.Auth return newStatus } -func (r *AuthPolicyReconciler) acceptedCondition(policy utils.KuadrantPolicy, specErr error) *metav1.Condition { - return utils.AcceptedCondition(policy, specErr) +func (r *AuthPolicyReconciler) acceptedCondition(policy kuadrant.Policy, specErr error) *metav1.Condition { + return kuadrant.AcceptedCondition(policy, specErr) } // enforcedCondition checks if the provided AuthPolicy is enforced, ensuring it is properly configured and applied based @@ -100,16 +101,16 @@ func (r *AuthPolicyReconciler) enforcedCondition(ctx context.Context, policy *ap authConfigReady, err := r.isAuthConfigReady(ctx, policy) if err != nil { logger.Error(err, "Failed to check AuthConfig and Gateway") - return utils.EnforcedCondition(policy, utils.NewErrUnknown(policy.Kind(), err)) + return kuadrant.EnforcedCondition(policy, kuadrant.NewErrUnknown(policy.Kind(), err)) } if !authConfigReady { logger.V(1).Info("AuthConfig is not ready") - return utils.EnforcedCondition(policy, utils.NewErrUnknown(policy.Kind(), errors.New("AuthScheme is not ready yet"))) + return kuadrant.EnforcedCondition(policy, kuadrant.NewErrUnknown(policy.Kind(), errors.New("AuthScheme is not ready yet"))) } logger.V(1).Info("AuthPolicy is enforced") - return utils.EnforcedCondition(policy, nil) + return kuadrant.EnforcedCondition(policy, nil) } // isAuthConfigReady checks if the AuthConfig is ready. @@ -133,7 +134,7 @@ func (r *AuthPolicyReconciler) isAuthConfigReady(ctx context.Context, policy *ap // and creating a corresponding error condition. func (r *AuthPolicyReconciler) handleGatewayPolicyOverride(logger logr.Logger, policy *api.AuthPolicy, targetNetworkObject client.Object) *metav1.Condition { obj := targetNetworkObject.(*gatewayapiv1.Gateway) - gatewayWrapper := utils.GatewayWrapper{Gateway: obj, Referrer: policy} + gatewayWrapper := kuadrant.GatewayWrapper{Gateway: obj, Referrer: policy} refs := gatewayWrapper.PolicyRefs() filteredRef := utils.Filter(refs, func(key client.ObjectKey) bool { return key != client.ObjectKeyFromObject(policy) @@ -141,7 +142,7 @@ func (r *AuthPolicyReconciler) handleGatewayPolicyOverride(logger logr.Logger, p jsonData, err := json.Marshal(filteredRef) if err != nil { logger.Error(err, "Failed to marshal filtered references") - return utils.EnforcedCondition(policy, utils.NewErrUnknown(policy.Kind(), err)) + return kuadrant.EnforcedCondition(policy, kuadrant.NewErrUnknown(policy.Kind(), err)) } - return utils.EnforcedCondition(policy, utils.NewErrOverridden(policy.Kind(), string(jsonData))) + return kuadrant.EnforcedCondition(policy, kuadrant.NewErrOverridden(policy.Kind(), string(jsonData))) } diff --git a/controllers/dns_helper.go b/controllers/dns_helper.go index 469e64dd6..ca9124d49 100644 --- a/controllers/dns_helper.go +++ b/controllers/dns_helper.go @@ -18,6 +18,7 @@ import ( kuadrantdnsv1alpha1 "github.com/kuadrant/dns-operator/api/v1alpha1" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/multicluster" ) @@ -102,7 +103,7 @@ func gatewayDNSRecordLabels(gwKey client.ObjectKey) map[string]string { } } -func withGatewayListener[T metav1.Object](gateway utils.GatewayWrapper, listener gatewayapiv1.Listener, obj T) T { +func withGatewayListener[T metav1.Object](gateway kuadrant.GatewayWrapper, listener gatewayapiv1.Listener, obj T) T { if obj.GetAnnotations() == nil { obj.SetAnnotations(map[string]string{}) } diff --git a/controllers/dnshealthcheckprobe_eventmapper.go b/controllers/dnshealthcheckprobe_eventmapper.go index 2b2d28eb1..8b4ecf037 100644 --- a/controllers/dnshealthcheckprobe_eventmapper.go +++ b/controllers/dnshealthcheckprobe_eventmapper.go @@ -10,10 +10,12 @@ import ( kuadrantdnsv1alpha1 "github.com/kuadrant/dns-operator/api/v1alpha1" "github.com/kuadrant/kuadrant-operator/pkg/common" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/mappers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) +var _ mappers.EventMapper = &DNSHealthCheckProbeEventMapper{} + func NewDNSHealthCheckProbeEventMapper(o ...mappers.MapperOption) mappers.EventMapper { return &DNSHealthCheckProbeEventMapper{opts: mappers.Apply(o...)} } @@ -23,7 +25,7 @@ type DNSHealthCheckProbeEventMapper struct { opts mappers.MapperOptions } -func (m *DNSHealthCheckProbeEventMapper) MapToPolicy(obj client.Object, policyKind utils.Referrer) []reconcile.Request { +func (m *DNSHealthCheckProbeEventMapper) MapToPolicy(obj client.Object, policyKind kuadrant.Referrer) []reconcile.Request { logger := m.opts.Logger.V(1).WithValues("object", client.ObjectKeyFromObject(obj)) probe, ok := obj.(*kuadrantdnsv1alpha1.DNSHealthCheckProbe) if !ok { diff --git a/controllers/dnspolicy_controller.go b/controllers/dnspolicy_controller.go index 1617d1242..0dad8e486 100644 --- a/controllers/dnspolicy_controller.go +++ b/controllers/dnspolicy_controller.go @@ -37,9 +37,9 @@ import ( kuadrantdnsv1alpha1 "github.com/kuadrant/dns-operator/api/v1alpha1" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/mappers" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -96,7 +96,7 @@ func (r *DNSPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( if delResErr == nil { delResErr = err } - return r.reconcileStatus(ctx, dnsPolicy, utils.NewErrTargetNotFound(dnsPolicy.Kind(), dnsPolicy.GetTargetRef(), delResErr)) + return r.reconcileStatus(ctx, dnsPolicy, kuadrant.NewErrTargetNotFound(dnsPolicy.Kind(), dnsPolicy.GetTargetRef(), delResErr)) } return ctrl.Result{}, err } diff --git a/controllers/dnspolicy_controller_test.go b/controllers/dnspolicy_controller_test.go index aced9c5a7..6ebf5e669 100644 --- a/controllers/dnspolicy_controller_test.go +++ b/controllers/dnspolicy_controller_test.go @@ -21,7 +21,7 @@ import ( gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/multicluster" ) @@ -187,7 +187,7 @@ var _ = Describe("DNSPolicy controller", func() { ContainElement(MatchFields(IgnoreExtras, Fields{ "Type": Equal(string(gatewayapiv1alpha2.PolicyConditionAccepted)), "Status": Equal(metav1.ConditionFalse), - "Reason": Equal(string(utils.PolicyReasonUnknown)), + "Reason": Equal(string(kuadrant.PolicyReasonUnknown)), "Message": ContainSubstring("gateway is invalid: inconsistent status addresses"), })), ) diff --git a/controllers/dnspolicy_healthchecks.go b/controllers/dnspolicy_healthchecks.go index c2fb5ceab..8eab4bef4 100644 --- a/controllers/dnspolicy_healthchecks.go +++ b/controllers/dnspolicy_healthchecks.go @@ -17,8 +17,8 @@ import ( kuadrantdnsv1alpha1 "github.com/kuadrant/dns-operator/api/v1alpha1" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/multicluster" ) @@ -110,7 +110,7 @@ func (r *DNSPolicyReconciler) deleteUnexpectedGatewayHealthCheckProbes(ctx conte return nil } -func (r *DNSPolicyReconciler) expectedHealthCheckProbesForGateway(ctx context.Context, gw utils.GatewayWrapper, dnsPolicy *v1alpha1.DNSPolicy) []*kuadrantdnsv1alpha1.DNSHealthCheckProbe { +func (r *DNSPolicyReconciler) expectedHealthCheckProbesForGateway(ctx context.Context, gw kuadrant.GatewayWrapper, dnsPolicy *v1alpha1.DNSPolicy) []*kuadrantdnsv1alpha1.DNSHealthCheckProbe { log := crlog.FromContext(ctx) var healthChecks []*kuadrantdnsv1alpha1.DNSHealthCheckProbe if dnsPolicy.Spec.HealthCheck == nil { diff --git a/controllers/dnspolicy_status.go b/controllers/dnspolicy_status.go index 78cf4307c..7bc0426fd 100644 --- a/controllers/dnspolicy_status.go +++ b/controllers/dnspolicy_status.go @@ -27,7 +27,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func (r *DNSPolicyReconciler) reconcileStatus(ctx context.Context, dnsPolicy *v1alpha1.DNSPolicy, specErr error) (ctrl.Result, error) { @@ -50,7 +50,7 @@ func (r *DNSPolicyReconciler) reconcileStatus(ctx context.Context, dnsPolicy *v1 return ctrl.Result{}, updateErr } - if utils.IsTargetNotFound(specErr) { + if kuadrant.IsTargetNotFound(specErr) { return ctrl.Result{Requeue: true}, nil } @@ -64,7 +64,7 @@ func (r *DNSPolicyReconciler) calculateStatus(dnsPolicy *v1alpha1.DNSPolicy, spe ObservedGeneration: dnsPolicy.Status.ObservedGeneration, } - acceptedCond := utils.AcceptedCondition(dnsPolicy, specErr) + acceptedCond := kuadrant.AcceptedCondition(dnsPolicy, specErr) meta.SetStatusCondition(&newStatus.Conditions, *acceptedCond) return newStatus diff --git a/controllers/gateway_kuadrant_controller.go b/controllers/gateway_kuadrant_controller.go index 19de0ee8e..b0d25e87d 100644 --- a/controllers/gateway_kuadrant_controller.go +++ b/controllers/gateway_kuadrant_controller.go @@ -30,7 +30,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -98,7 +98,7 @@ func (r *GatewayKuadrantReconciler) reconcileKuadrantNamespaceAnnotation(ctx con return false, err } - if utils.IsKuadrantManaged(gw) { + if kuadrant.IsKuadrantManaged(gw) { return false, nil } @@ -122,7 +122,7 @@ func (r *GatewayKuadrantReconciler) reconcileKuadrantNamespaceAnnotation(ctx con return false, nil } - utils.AnnotateObject(gw, kuadrantList.Items[0].Namespace) + kuadrant.AnnotateObject(gw, kuadrantList.Items[0].Namespace) return true, nil } diff --git a/controllers/gateway_kuadrant_controller_test.go b/controllers/gateway_kuadrant_controller_test.go index e924bd43d..20e731287 100644 --- a/controllers/gateway_kuadrant_controller_test.go +++ b/controllers/gateway_kuadrant_controller_test.go @@ -15,7 +15,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) var _ = Describe("Kuadrant Gateway controller", func() { @@ -63,7 +63,7 @@ var _ = Describe("Kuadrant Gateway controller", func() { logf.Log.V(1).Info("[WARN] Getting gateway failed", "error", err) return false } - return utils.IsKuadrantManaged(existingGateway) + return kuadrant.IsKuadrantManaged(existingGateway) }, 15*time.Second, 5*time.Second).Should(BeTrue()) }) }) @@ -125,7 +125,7 @@ var _ = Describe("Kuadrant Gateway controller", func() { logf.Log.V(1).Info("[WARN] Getting gateway failed", "error", err) return false } - return !utils.IsKuadrantManaged(existingGateway) + return !kuadrant.IsKuadrantManaged(existingGateway) }, 15*time.Second, 5*time.Second).Should(BeTrue()) }) }) diff --git a/controllers/helper_test.go b/controllers/helper_test.go index d8b6371b6..9c39f090b 100644 --- a/controllers/helper_test.go +++ b/controllers/helper_test.go @@ -38,6 +38,7 @@ import ( kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1" kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -308,7 +309,7 @@ func testRouteIsAccepted(routeKey client.ObjectKey) func() bool { return func() bool { route := &gatewayapiv1.HTTPRoute{} err := k8sClient.Get(context.Background(), routeKey, route) - return err == nil && utils.IsHTTPRouteAccepted(route) + return err == nil && kuadrant.IsHTTPRouteAccepted(route) } } diff --git a/controllers/httprouteparentrefs_eventmapper.go b/controllers/httprouteparentrefs_eventmapper.go index e79441d3c..bd606416d 100644 --- a/controllers/httprouteparentrefs_eventmapper.go +++ b/controllers/httprouteparentrefs_eventmapper.go @@ -10,7 +10,7 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" api "github.com/kuadrant/kuadrant-operator/api/v1beta2" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) // HTTPRouteParentRefsEventMapper is an EventHandler that maps HTTPRoute events to policy events, @@ -58,14 +58,14 @@ func (m *HTTPRouteParentRefsEventMapper) mapToPolicyRequest(obj client.Object, p logger.Error(err, "failed to list policies") } // triggers the reconciliation of any policy that targets the parent gateway of the route - policies, ok := policyList.(utils.KuadrantPolicyList) + policies, ok := policyList.(kuadrant.PolicyList) if !ok { - logger.Info("mapToPolicyRequest:", "error", fmt.Sprintf("%T is not a KuadrantPolicyList", policyList)) + logger.Info("mapToPolicyRequest:", "error", fmt.Sprintf("%T is not a PolicyList", policyList)) continue } for _, policy := range policies.GetItems() { targetRef := policy.GetTargetRef() - if !utils.IsTargetRefGateway(targetRef) { + if !kuadrant.IsTargetRefGateway(targetRef) { continue } targetRefNamespace := targetRef.Namespace diff --git a/controllers/kuadrant_controller.go b/controllers/kuadrant_controller.go index 748826b7b..9ba1e01c0 100644 --- a/controllers/kuadrant_controller.go +++ b/controllers/kuadrant_controller.go @@ -44,7 +44,7 @@ import ( "github.com/kuadrant/kuadrant-operator/pkg/common" "github.com/kuadrant/kuadrant-operator/pkg/istio" "github.com/kuadrant/kuadrant-operator/pkg/kuadranttools" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/log" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -421,8 +421,8 @@ func (r *KuadrantReconciler) reconcileClusterGateways(ctx context.Context, kObj for i := range gwList.Items { gw := &gwList.Items[i] - if !utils.IsKuadrantManaged(gw) { - utils.AnnotateObject(gw, kObj.Namespace) + if !kuadrant.IsKuadrantManaged(gw) { + kuadrant.AnnotateObject(gw, kObj.Namespace) errGroup.Go(func() error { select { case <-gctx.Done(): @@ -457,7 +457,7 @@ func (r *KuadrantReconciler) removeAnnotationFromGateways(ctx context.Context, k return nil default: // When RFC defined, we could indicate which gateways based on a specific annotation/label - utils.DeleteKuadrantAnnotationFromGateway(gw, kObj.Namespace) + kuadrant.DeleteKuadrantAnnotationFromGateway(gw, kObj.Namespace) if err := r.Client().Update(ctx, gw); err != nil { return err } diff --git a/controllers/limitador_cluster_envoyfilter_controller.go b/controllers/limitador_cluster_envoyfilter_controller.go index 77b2b78e1..ede8de209 100644 --- a/controllers/limitador_cluster_envoyfilter_controller.go +++ b/controllers/limitador_cluster_envoyfilter_controller.go @@ -37,7 +37,7 @@ import ( "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/pkg/common" kuadrantistioutils "github.com/kuadrant/kuadrant-operator/pkg/istio" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -122,7 +122,7 @@ func (r *LimitadorClusterEnvoyFilterReconciler) desiredRateLimitingClusterEnvoyF }, } - gateway := utils.GatewayWrapper{Gateway: gw, Referrer: &v1beta2.RateLimitPolicy{}} + gateway := kuadrant.GatewayWrapper{Gateway: gw, Referrer: &v1beta2.RateLimitPolicy{}} rlpRefs := gateway.PolicyRefs() logger.V(1).Info("desiredRateLimitingClusterEnvoyFilter", "rlpRefs", rlpRefs) @@ -131,7 +131,7 @@ func (r *LimitadorClusterEnvoyFilterReconciler) desiredRateLimitingClusterEnvoyF return ef, nil } - kuadrantNamespace, err := utils.GetKuadrantNamespace(gw) + kuadrantNamespace, err := kuadrant.GetKuadrantNamespace(gw) if err != nil { return nil, err } diff --git a/controllers/ratelimitpolicy_controller.go b/controllers/ratelimitpolicy_controller.go index da0a23cd6..e316126e5 100644 --- a/controllers/ratelimitpolicy_controller.go +++ b/controllers/ratelimitpolicy_controller.go @@ -30,9 +30,9 @@ import ( gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/mappers" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -97,7 +97,7 @@ func (r *RateLimitPolicyReconciler) Reconcile(eventCtx context.Context, req ctrl if delResErr == nil { delResErr = err } - return r.reconcileStatus(ctx, rlp, utils.NewErrTargetNotFound(rlp.Kind(), rlp.GetTargetRef(), delResErr)) + return r.reconcileStatus(ctx, rlp, kuadrant.NewErrTargetNotFound(rlp.Kind(), rlp.GetTargetRef(), delResErr)) } return ctrl.Result{}, err } @@ -156,11 +156,11 @@ func (r *RateLimitPolicyReconciler) Reconcile(eventCtx context.Context, req ctrl // validate performs validation before proceeding with the reconcile loop, returning a common.ErrInvalid on failing validation func (r *RateLimitPolicyReconciler) validate(rlp *kuadrantv1beta2.RateLimitPolicy, targetNetworkObject client.Object) error { if err := rlp.Validate(); err != nil { - return utils.NewErrInvalid(rlp.Kind(), err) + return kuadrant.NewErrInvalid(rlp.Kind(), err) } - if err := utils.ValidateHierarchicalRules(rlp, targetNetworkObject); err != nil { - return utils.NewErrInvalid(rlp.Kind(), err) + if err := kuadrant.ValidateHierarchicalRules(rlp, targetNetworkObject); err != nil { + return kuadrant.NewErrInvalid(rlp.Kind(), err) } return nil diff --git a/controllers/ratelimitpolicy_istio_wasmplugin.go b/controllers/ratelimitpolicy_istio_wasmplugin.go index 0fb28ec68..452aa4dfe 100644 --- a/controllers/ratelimitpolicy_istio_wasmplugin.go +++ b/controllers/ratelimitpolicy_istio_wasmplugin.go @@ -14,6 +14,7 @@ import ( kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/pkg/common" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/rlptools" @@ -74,7 +75,7 @@ func (r *RateLimitPolicyReconciler) reconcileWASMPluginConf(ctx context.Context, return nil } -func (r *RateLimitPolicyReconciler) gatewayWASMPlugin(ctx context.Context, gw utils.GatewayWrapper, rlpRefs []client.ObjectKey) (*istioclientgoextensionv1alpha1.WasmPlugin, error) { +func (r *RateLimitPolicyReconciler) gatewayWASMPlugin(ctx context.Context, gw kuadrant.GatewayWrapper, rlpRefs []client.ObjectKey) (*istioclientgoextensionv1alpha1.WasmPlugin, error) { logger, _ := logr.FromContext(ctx) logger.V(1).Info("gatewayWASMPlugin", "gwKey", gw.Key(), "rlpRefs", rlpRefs) @@ -122,7 +123,7 @@ func (r *RateLimitPolicyReconciler) gatewayWASMPlugin(ctx context.Context, gw ut } // returns nil when there is no rate limit policy to apply -func (r *RateLimitPolicyReconciler) wasmPluginConfig(ctx context.Context, gw utils.GatewayWrapper, rlpRefs []client.ObjectKey) (*wasm.Plugin, error) { +func (r *RateLimitPolicyReconciler) wasmPluginConfig(ctx context.Context, gw kuadrant.GatewayWrapper, rlpRefs []client.ObjectKey) (*wasm.Plugin, error) { logger, _ := logr.FromContext(ctx) logger = logger.WithName("wasmPluginConfig").WithValues("gateway", gw.Key()) @@ -145,7 +146,7 @@ func (r *RateLimitPolicyReconciler) wasmPluginConfig(ctx context.Context, gw uti } // target ref is a HTTPRoute - if utils.IsTargetRefHTTPRoute(rlp.Spec.TargetRef) { + if kuadrant.IsTargetRefHTTPRoute(rlp.Spec.TargetRef) { route, err := reconcilers.FetchTargetRefObject(ctx, r.Client(), rlp.GetTargetRef(), rlp.Namespace) if err != nil { return nil, err diff --git a/controllers/ratelimitpolicy_limits.go b/controllers/ratelimitpolicy_limits.go index 937689631..f8b421962 100644 --- a/controllers/ratelimitpolicy_limits.go +++ b/controllers/ratelimitpolicy_limits.go @@ -9,6 +9,7 @@ import ( kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/pkg/common" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/rlptools" ) @@ -46,15 +47,15 @@ func (r *RateLimitPolicyReconciler) reconcileLimitador(ctx context.Context, rlp // get the current limitador cr for the kuadrant instance so we can compare if it needs to be updated logger.V(1).Info("get kuadrant namespace") var kuadrantNamespace string - kuadrantNamespace, isSet := utils.GetKuadrantNamespaceFromPolicy(rlp) + kuadrantNamespace, isSet := kuadrant.GetKuadrantNamespaceFromPolicy(rlp) if !isSet { var err error - kuadrantNamespace, err = utils.GetKuadrantNamespaceFromPolicyTargetRef(ctx, r.Client(), rlp) + kuadrantNamespace, err = kuadrant.GetKuadrantNamespaceFromPolicyTargetRef(ctx, r.Client(), rlp) if err != nil { logger.Error(err, "failed to get kuadrant namespace") return err } - utils.AnnotateObject(rlp, kuadrantNamespace) + kuadrant.AnnotateObject(rlp, kuadrantNamespace) err = r.UpdateResource(ctx, rlp) // @guicassolato: not sure if this belongs to here if err != nil { logger.Error(err, "failed to update policy, re-queuing") diff --git a/controllers/ratelimitpolicy_status.go b/controllers/ratelimitpolicy_status.go index 30e874500..0edffd78e 100644 --- a/controllers/ratelimitpolicy_status.go +++ b/controllers/ratelimitpolicy_status.go @@ -12,7 +12,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func (r *RateLimitPolicyReconciler) reconcileStatus(ctx context.Context, rlp *kuadrantv1beta2.RateLimitPolicy, specErr error) (ctrl.Result, error) { @@ -58,7 +58,7 @@ func (r *RateLimitPolicyReconciler) calculateStatus(_ context.Context, rlp *kuad ObservedGeneration: rlp.Status.ObservedGeneration, } - acceptedCond := utils.AcceptedCondition(rlp, specErr) + acceptedCond := kuadrant.AcceptedCondition(rlp, specErr) meta.SetStatusCondition(&newStatus.Conditions, *acceptedCond) diff --git a/controllers/suite_test.go b/controllers/suite_test.go index 0964c708b..c92c05829 100644 --- a/controllers/suite_test.go +++ b/controllers/suite_test.go @@ -48,8 +48,8 @@ import ( kuadrantv1alpha1 "github.com/kuadrant/kuadrant-operator/api/v1alpha1" kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1" kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/log" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" //+kubebuilder:scaffold:imports @@ -148,7 +148,7 @@ var _ = BeforeSuite(func() { err = (&AuthPolicyReconciler{ BaseReconciler: authPolicyBaseReconciler, TargetRefReconciler: reconcilerutils.TargetRefReconciler{Client: mgr.GetClient()}, - OverriddenPolicyMap: utils.NewOverriddenPolicyMap(), + OverriddenPolicyMap: kuadrant.NewOverriddenPolicyMap(), }).SetupWithManager(mgr) Expect(err).NotTo(HaveOccurred()) diff --git a/controllers/tlspolicy_controller.go b/controllers/tlspolicy_controller.go index 87dd7bcbd..5d79bdc7c 100644 --- a/controllers/tlspolicy_controller.go +++ b/controllers/tlspolicy_controller.go @@ -37,9 +37,9 @@ import ( gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/mappers" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" ) @@ -91,7 +91,7 @@ func (r *TLSPolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( if delResErr == nil { delResErr = err } - return r.reconcileStatus(ctx, tlsPolicy, utils.NewErrTargetNotFound(tlsPolicy.Kind(), tlsPolicy.GetTargetRef(), delResErr)) + return r.reconcileStatus(ctx, tlsPolicy, kuadrant.NewErrTargetNotFound(tlsPolicy.Kind(), tlsPolicy.GetTargetRef(), delResErr)) } return ctrl.Result{}, err } diff --git a/controllers/tlspolicy_status.go b/controllers/tlspolicy_status.go index 1803908c4..43384cf5d 100644 --- a/controllers/tlspolicy_status.go +++ b/controllers/tlspolicy_status.go @@ -27,7 +27,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/kuadrant/kuadrant-operator/api/v1alpha1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func (r *TLSPolicyReconciler) reconcileStatus(ctx context.Context, tlsPolicy *v1alpha1.TLSPolicy, specErr error) (ctrl.Result, error) { @@ -50,7 +50,7 @@ func (r *TLSPolicyReconciler) reconcileStatus(ctx context.Context, tlsPolicy *v1 return ctrl.Result{}, updateErr } - if utils.IsTargetNotFound(specErr) { + if kuadrant.IsTargetNotFound(specErr) { return ctrl.Result{Requeue: true}, nil } @@ -64,7 +64,7 @@ func (r *TLSPolicyReconciler) calculateStatus(tlsPolicy *v1alpha1.TLSPolicy, spe ObservedGeneration: tlsPolicy.Status.ObservedGeneration, } - acceptedCond := utils.AcceptedCondition(tlsPolicy, specErr) + acceptedCond := kuadrant.AcceptedCondition(tlsPolicy, specErr) meta.SetStatusCondition(&newStatus.Conditions, *acceptedCond) return newStatus diff --git a/main.go b/main.go index ddba79f04..d9cd5b24a 100644 --- a/main.go +++ b/main.go @@ -52,8 +52,8 @@ import ( kuadrantv1beta1 "github.com/kuadrant/kuadrant-operator/api/v1beta1" kuadrantv1beta2 "github.com/kuadrant/kuadrant-operator/api/v1beta2" "github.com/kuadrant/kuadrant-operator/controllers" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" reconcilerutils "github.com/kuadrant/kuadrant-operator/pkg/library/reconcilers" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" "github.com/kuadrant/kuadrant-operator/pkg/log" "github.com/kuadrant/kuadrant-operator/pkg/reconcilers" //+kubebuilder:scaffold:imports @@ -172,7 +172,7 @@ func main() { if err = (&controllers.AuthPolicyReconciler{ TargetRefReconciler: reconcilerutils.TargetRefReconciler{Client: mgr.GetClient()}, BaseReconciler: authPolicyBaseReconciler, - OverriddenPolicyMap: utils.NewOverriddenPolicyMap(), + OverriddenPolicyMap: kuadrant.NewOverriddenPolicyMap(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AuthPolicy") os.Exit(1) diff --git a/pkg/common/istio_utils.go b/pkg/common/istio_utils.go index 50a70cb53..a89e5f8bb 100644 --- a/pkg/common/istio_utils.go +++ b/pkg/common/istio_utils.go @@ -8,12 +8,12 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func IstioWorkloadSelectorFromGateway(ctx context.Context, k8sClient client.Client, gateway *gatewayapiv1.Gateway) *istiocommon.WorkloadSelector { logger, _ := logr.FromContext(ctx) - gatewayWorkloadSelector, err := utils.GetGatewayWorkloadSelector(ctx, k8sClient, gateway) + gatewayWorkloadSelector, err := kuadrant.GetGatewayWorkloadSelector(ctx, k8sClient, gateway) if err != nil { logger.V(1).Info("failed to build Istio WorkloadSelector from Gateway service - falling back to Gateway labels") gatewayWorkloadSelector = gateway.Labels diff --git a/pkg/library/utils/apimachinery_status_conditions.go b/pkg/library/kuadrant/apimachinery_status_conditions.go similarity index 78% rename from pkg/library/utils/apimachinery_status_conditions.go rename to pkg/library/kuadrant/apimachinery_status_conditions.go index bf318c823..e16da4ce8 100644 --- a/pkg/library/utils/apimachinery_status_conditions.go +++ b/pkg/library/kuadrant/apimachinery_status_conditions.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "encoding/json" @@ -32,8 +32,8 @@ type OverriddenPolicyMap struct { mu sync.RWMutex } -// SetOverriddenPolicy sets the provided KuadrantPolicy as overridden in the tracking map. -func (o *OverriddenPolicyMap) SetOverriddenPolicy(p KuadrantPolicy) { +// SetOverriddenPolicy sets the provided Policy as overridden in the tracking map. +func (o *OverriddenPolicyMap) SetOverriddenPolicy(p Policy) { o.mu.Lock() defer o.mu.Unlock() @@ -43,16 +43,16 @@ func (o *OverriddenPolicyMap) SetOverriddenPolicy(p KuadrantPolicy) { o.policies[p.GetUID()] = true } -// RemoveOverriddenPolicy removes the provided KuadrantPolicy from the tracking map of overridden policies. -func (o *OverriddenPolicyMap) RemoveOverriddenPolicy(p KuadrantPolicy) { +// RemoveOverriddenPolicy removes the provided Policy from the tracking map of overridden policies. +func (o *OverriddenPolicyMap) RemoveOverriddenPolicy(p Policy) { o.mu.Lock() defer o.mu.Unlock() delete(o.policies, p.GetUID()) } -// IsPolicyOverridden checks if the provided KuadrantPolicy is overridden based on the tracking map maintained. -func (o *OverriddenPolicyMap) IsPolicyOverridden(p KuadrantPolicy) bool { +// IsPolicyOverridden checks if the provided Policy is overridden based on the tracking map maintained. +func (o *OverriddenPolicyMap) IsPolicyOverridden(p Policy) bool { return o.policies[p.GetUID()] && IsTargetRefGateway(p.GetTargetRef()) } @@ -66,7 +66,7 @@ func ConditionMarshal(conditions []metav1.Condition) ([]byte, error) { } // AcceptedCondition returns an accepted conditions with common reasons for a kuadrant policy -func AcceptedCondition(p KuadrantPolicy, err error) *metav1.Condition { +func AcceptedCondition(p Policy, err error) *metav1.Condition { // Accepted cond := &metav1.Condition{ Type: string(gatewayapiv1alpha2.PolicyConditionAccepted), @@ -92,7 +92,7 @@ func AcceptedCondition(p KuadrantPolicy, err error) *metav1.Condition { } // EnforcedCondition returns an enforced conditions with common reasons for a kuadrant policy -func EnforcedCondition(policy KuadrantPolicy, err PolicyError) *metav1.Condition { +func EnforcedCondition(policy Policy, err PolicyError) *metav1.Condition { // Enforced cond := &metav1.Condition{ Type: string(PolicyConditionEnforced), diff --git a/pkg/library/utils/apimachinery_status_conditions_test.go b/pkg/library/kuadrant/apimachinery_status_conditions_test.go similarity index 99% rename from pkg/library/utils/apimachinery_status_conditions_test.go rename to pkg/library/kuadrant/apimachinery_status_conditions_test.go index 974480023..ffb6819a0 100644 --- a/pkg/library/utils/apimachinery_status_conditions_test.go +++ b/pkg/library/kuadrant/apimachinery_status_conditions_test.go @@ -1,6 +1,6 @@ //go:build unit -package utils +package kuadrant import ( "errors" @@ -122,7 +122,7 @@ func TestConditionMarshal(t *testing.T) { func TestAcceptedCondition(t *testing.T) { type args struct { - policy KuadrantPolicy + policy Policy err error } tests := []struct { @@ -227,7 +227,7 @@ func TestAcceptedCondition(t *testing.T) { func TestEnforcedCondition(t *testing.T) { type args struct { - policy KuadrantPolicy + policy Policy err PolicyError } policy := &FakePolicy{} diff --git a/pkg/library/utils/errors.go b/pkg/library/kuadrant/errors.go similarity index 99% rename from pkg/library/utils/errors.go rename to pkg/library/kuadrant/errors.go index 7a7e873ea..42847d823 100644 --- a/pkg/library/utils/errors.go +++ b/pkg/library/kuadrant/errors.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "errors" diff --git a/pkg/library/utils/errors_test.go b/pkg/library/kuadrant/errors_test.go similarity index 97% rename from pkg/library/utils/errors_test.go rename to pkg/library/kuadrant/errors_test.go index 85452dc8e..aa20d1bee 100644 --- a/pkg/library/utils/errors_test.go +++ b/pkg/library/kuadrant/errors_test.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "errors" diff --git a/pkg/library/utils/gateway_wrapper.go b/pkg/library/kuadrant/gateway_wrapper.go similarity index 94% rename from pkg/library/utils/gateway_wrapper.go rename to pkg/library/kuadrant/gateway_wrapper.go index c79e10186..72ea38379 100644 --- a/pkg/library/utils/gateway_wrapper.go +++ b/pkg/library/kuadrant/gateway_wrapper.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "encoding/json" @@ -6,6 +6,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) // GatewayWrapper wraps a Gateway API Gateway adding methods and configs to manage policy references in annotations @@ -26,7 +28,7 @@ func (g GatewayWrapper) PolicyRefs() []client.ObjectKey { return make([]client.ObjectKey, 0) } - gwAnnotations := ReadAnnotationsFromObject(g) + gwAnnotations := utils.ReadAnnotationsFromObject(g) val, ok := gwAnnotations[g.BackReferenceAnnotationName()] if !ok { @@ -63,7 +65,7 @@ func (g GatewayWrapper) AddPolicy(policyKey client.ObjectKey) bool { return false } - gwAnnotations := ReadAnnotationsFromObject(g) + gwAnnotations := utils.ReadAnnotationsFromObject(g) _, annotationFound := gwAnnotations[g.BackReferenceAnnotationName()] // annotation does not exist → create it @@ -96,7 +98,7 @@ func (g GatewayWrapper) DeletePolicy(policyKey client.ObjectKey) bool { return false } - gwAnnotations := ReadAnnotationsFromObject(g) + gwAnnotations := utils.ReadAnnotationsFromObject(g) // annotation does not exist → nothing to do refsAsStr, annotationFound := gwAnnotations[g.BackReferenceAnnotationName()] diff --git a/pkg/library/utils/gateway_wrapper_test.go b/pkg/library/kuadrant/gateway_wrapper_test.go similarity index 94% rename from pkg/library/utils/gateway_wrapper_test.go rename to pkg/library/kuadrant/gateway_wrapper_test.go index 00583190c..40a98f59f 100644 --- a/pkg/library/utils/gateway_wrapper_test.go +++ b/pkg/library/kuadrant/gateway_wrapper_test.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "slices" @@ -8,6 +8,8 @@ import ( k8stypes "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + + "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) func TestGatewayWrapperKey(t *testing.T) { @@ -37,7 +39,7 @@ func TestGatewayWrapperPolicyRefs(t *testing.T) { }, Referrer: &PolicyKindStub{}, } - refs := Map(gw.PolicyRefs(), func(ref k8stypes.NamespacedName) string { return ref.String() }) + refs := utils.Map(gw.PolicyRefs(), func(ref k8stypes.NamespacedName) string { return ref.String() }) if !slices.Contains(refs, "app-ns/policy-1") { t.Error("GatewayWrapper.PolicyRefs() should contain app-ns/policy-1") } @@ -158,7 +160,7 @@ func TestBackReferencesFromGatewayWrapper(t *testing.T) { }, Referrer: &PolicyKindStub{}, } - refs := Map(BackReferencesFromObject(gw.Gateway, gw.Referrer), func(ref client.ObjectKey) string { return ref.String() }) + refs := utils.Map(BackReferencesFromObject(gw.Gateway, gw.Referrer), 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/utils/gatewayapi_utils.go b/pkg/library/kuadrant/gatewayapi_utils.go similarity index 91% rename from pkg/library/utils/gatewayapi_utils.go rename to pkg/library/kuadrant/gatewayapi_utils.go index 292e6ffc3..fcaaa17e0 100644 --- a/pkg/library/utils/gatewayapi_utils.go +++ b/pkg/library/kuadrant/gatewayapi_utils.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "context" @@ -13,6 +13,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" gatewayapiv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + + "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) type HTTPRouteRule struct { @@ -98,7 +100,7 @@ func (s *HTTPRouteRuleSelector) Selects(rule gatewayapiv1.HTTPRouteRule) bool { return true } - _, found := Find(rule.Matches, func(ruleMatch gatewayapiv1.HTTPRouteMatch) bool { + _, found := utils.Find(rule.Matches, func(ruleMatch gatewayapiv1.HTTPRouteMatch) bool { // path if s.Path != nil && !reflect.DeepEqual(s.Path, ruleMatch.Path) { return false @@ -111,7 +113,7 @@ func (s *HTTPRouteRuleSelector) Selects(rule gatewayapiv1.HTTPRouteRule) bool { // headers for _, header := range s.Headers { - if _, found := Find(ruleMatch.Headers, func(otherHeader gatewayapiv1.HTTPHeaderMatch) bool { + if _, found := utils.Find(ruleMatch.Headers, func(otherHeader gatewayapiv1.HTTPHeaderMatch) bool { return reflect.DeepEqual(header, otherHeader) }); !found { return false @@ -120,7 +122,7 @@ func (s *HTTPRouteRuleSelector) Selects(rule gatewayapiv1.HTTPRouteRule) bool { // query params for _, param := range s.QueryParams { - if _, found := Find(ruleMatch.QueryParams, func(otherParam gatewayapiv1.HTTPQueryParamMatch) bool { + if _, found := utils.Find(ruleMatch.QueryParams, func(otherParam gatewayapiv1.HTTPQueryParamMatch) bool { return reflect.DeepEqual(param, otherParam) }); !found { return false @@ -135,7 +137,7 @@ func (s *HTTPRouteRuleSelector) Selects(rule gatewayapiv1.HTTPRouteRule) bool { // HTTPRouteRuleToString prints the matches of a HTTPRouteRule as string func HTTPRouteRuleToString(rule gatewayapiv1.HTTPRouteRule) string { - matches := Map(rule.Matches, HTTPRouteMatchToString) + matches := utils.Map(rule.Matches, HTTPRouteMatchToString) return fmt.Sprintf("{matches:[%s]}", strings.Join(matches, ",")) } @@ -148,11 +150,11 @@ func HTTPRouteMatchToString(match gatewayapiv1.HTTPRouteMatch) string { patterns = append(patterns, fmt.Sprintf("path:%s", HTTPPathMatchToString(path))) } if len(match.QueryParams) > 0 { - queryParams := Map(match.QueryParams, HTTPQueryParamMatchToString) + queryParams := utils.Map(match.QueryParams, HTTPQueryParamMatchToString) patterns = append(patterns, fmt.Sprintf("queryParams:[%s]", strings.Join(queryParams, ","))) } if len(match.Headers) > 0 { - headers := Map(match.Headers, HTTPHeaderMatchToString) + headers := utils.Map(match.Headers, HTTPHeaderMatchToString) patterns = append(patterns, fmt.Sprintf("headers:[%s]", strings.Join(headers, ","))) } return fmt.Sprintf("{%s}", strings.Join(patterns, ",")) @@ -200,7 +202,7 @@ func HTTPMethodToString(method *gatewayapiv1.HTTPMethod) string { return string(*method) } -func GetKuadrantNamespaceFromPolicyTargetRef(ctx context.Context, cli client.Client, policy KuadrantPolicy) (string, error) { +func GetKuadrantNamespaceFromPolicyTargetRef(ctx context.Context, cli client.Client, policy Policy) (string, error) { targetRef := policy.GetTargetRef() gwNamespacedName := types.NamespacedName{Namespace: string(ptr.Deref(targetRef.Namespace, policy.GetWrappedNamespace())), Name: string(targetRef.Name)} if IsTargetRefHTTPRoute(targetRef) { @@ -223,7 +225,7 @@ func GetKuadrantNamespaceFromPolicyTargetRef(ctx context.Context, cli client.Cli return GetKuadrantNamespace(gw) } -func GetKuadrantNamespaceFromPolicy(p KuadrantPolicy) (string, bool) { +func GetKuadrantNamespaceFromPolicy(p Policy) (string, bool) { if kuadrantNamespace, isSet := p.GetAnnotations()[KuadrantNamespaceLabel]; isSet { return kuadrantNamespace, true } @@ -330,7 +332,7 @@ func HostnamesFromHTTPRoute(ctx context.Context, route *gatewayapiv1.HTTPRoute, if err := cli.Get(ctx, types.NamespacedName{Namespace: ns, Name: string(ref.Name)}, gw); err != nil { return nil, err } - gwHostanmes := HostnamesToStrings(GatewayWrapper{Gateway: gw}.Hostnames()) + gwHostanmes := utils.HostnamesToStrings(GatewayWrapper{Gateway: gw}.Hostnames()) hosts = append(hosts, gwHostanmes...) } @@ -338,13 +340,13 @@ func HostnamesFromHTTPRoute(ctx context.Context, route *gatewayapiv1.HTTPRoute, } // ValidateHierarchicalRules returns error if the policy rules hostnames fail to match the target network hosts -func ValidateHierarchicalRules(policy KuadrantPolicy, targetNetworkObject client.Object) error { +func ValidateHierarchicalRules(policy Policy, targetNetworkObject client.Object) error { targetHostnames, err := TargetHostnames(targetNetworkObject) if err != nil { return err } - if valid, invalidHost := ValidSubdomains(targetHostnames, policy.GetRulesHostnames()); !valid { + if valid, invalidHost := utils.ValidSubdomains(targetHostnames, policy.GetRulesHostnames()); !valid { return fmt.Errorf( "rule host (%s) does not follow any hierarchical constraints, "+ "for the %T to be validated, it must match with at least one of the target network hostnames %+q", @@ -358,7 +360,7 @@ func ValidateHierarchicalRules(policy KuadrantPolicy, targetNetworkObject client } func GetGatewayWorkloadSelector(ctx context.Context, cli client.Client, gateway *gatewayapiv1.Gateway) (map[string]string, error) { - address, found := Find( + address, found := utils.Find( gateway.Status.Addresses, func(address gatewayapiv1.GatewayStatusAddress) bool { return address.Type != nil && *address.Type == gatewayapiv1.HostnameAddressType @@ -372,7 +374,7 @@ func GetGatewayWorkloadSelector(ctx context.Context, cli client.Client, gateway Name: serviceNameParts[0], Namespace: serviceNameParts[1], } - return GetServiceWorkloadSelector(ctx, cli, serviceKey) + return utils.GetServiceWorkloadSelector(ctx, cli, serviceKey) } func IsHTTPRouteAccepted(httpRoute *gatewayapiv1.HTTPRoute) bool { diff --git a/pkg/library/utils/gatewayapi_utils_test.go b/pkg/library/kuadrant/gatewayapi_utils_test.go similarity index 99% rename from pkg/library/utils/gatewayapi_utils_test.go rename to pkg/library/kuadrant/gatewayapi_utils_test.go index 652973515..3eb3a96ee 100644 --- a/pkg/library/utils/gatewayapi_utils_test.go +++ b/pkg/library/kuadrant/gatewayapi_utils_test.go @@ -1,6 +1,6 @@ //go:build unit -package utils +package kuadrant import ( "context" diff --git a/pkg/library/utils/kuadrant.go b/pkg/library/kuadrant/kuadrant.go similarity index 82% rename from pkg/library/utils/kuadrant.go rename to pkg/library/kuadrant/kuadrant.go index 52fdb47ab..b01f71d94 100644 --- a/pkg/library/utils/kuadrant.go +++ b/pkg/library/kuadrant/kuadrant.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "sigs.k8s.io/controller-runtime/pkg/client" @@ -10,7 +10,7 @@ const ( KuadrantNamespaceLabel = "kuadrant.io/namespace" ) -type KuadrantPolicy interface { +type Policy interface { client.Object GetTargetRef() gatewayapiv1alpha2.PolicyTargetReference GetWrappedNamespace() gatewayapiv1.Namespace @@ -18,8 +18,8 @@ type KuadrantPolicy interface { Kind() string } -type KuadrantPolicyList interface { - GetItems() []KuadrantPolicy +type PolicyList interface { + GetItems() []Policy } func IsKuadrantManaged(obj client.Object) bool { diff --git a/pkg/library/utils/referrer.go b/pkg/library/kuadrant/referrer.go similarity index 84% rename from pkg/library/utils/referrer.go rename to pkg/library/kuadrant/referrer.go index ff2847ef4..5fce0d01c 100644 --- a/pkg/library/utils/referrer.go +++ b/pkg/library/kuadrant/referrer.go @@ -1,9 +1,11 @@ -package utils +package kuadrant import ( "encoding/json" "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) type Referrer interface { @@ -17,7 +19,7 @@ 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 := ReadAnnotationsFromObject(obj)[referrer.BackReferenceAnnotationName()] + backRefs, found := utils.ReadAnnotationsFromObject(obj)[referrer.BackReferenceAnnotationName()] if !found { return make([]client.ObjectKey, 0) } diff --git a/pkg/library/utils/referrer_test.go b/pkg/library/kuadrant/referrer_test.go similarity index 80% rename from pkg/library/utils/referrer_test.go rename to pkg/library/kuadrant/referrer_test.go index 82958b7de..3fd4d7d6e 100644 --- a/pkg/library/utils/referrer_test.go +++ b/pkg/library/kuadrant/referrer_test.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "slices" @@ -7,6 +7,8 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) func TestBackReferencesFromObject(t *testing.T) { @@ -21,7 +23,7 @@ func TestBackReferencesFromObject(t *testing.T) { policyKind := &PolicyKindStub{} - refs := Map(BackReferencesFromObject(obj, policyKind), func(ref client.ObjectKey) string { return ref.String() }) + refs := utils.Map(BackReferencesFromObject(obj, policyKind), 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/utils/test_utils.go b/pkg/library/kuadrant/test_utils.go similarity index 98% rename from pkg/library/utils/test_utils.go rename to pkg/library/kuadrant/test_utils.go index 2abdbaca4..ea7c419f2 100644 --- a/pkg/library/utils/test_utils.go +++ b/pkg/library/kuadrant/test_utils.go @@ -1,4 +1,4 @@ -package utils +package kuadrant import ( "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/pkg/library/mappers/event_mapper.go b/pkg/library/mappers/event_mapper.go index 0a4e4dc9e..0fc8a2a9f 100644 --- a/pkg/library/mappers/event_mapper.go +++ b/pkg/library/mappers/event_mapper.go @@ -5,11 +5,11 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) type EventMapper interface { - MapToPolicy(client.Object, utils.Referrer) []reconcile.Request + MapToPolicy(client.Object, kuadrant.Referrer) []reconcile.Request } // options diff --git a/pkg/library/mappers/gateway.go b/pkg/library/mappers/gateway.go index e6afe5495..431d4dbfe 100644 --- a/pkg/library/mappers/gateway.go +++ b/pkg/library/mappers/gateway.go @@ -7,7 +7,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func NewGatewayEventMapper(o ...MapperOption) EventMapper { @@ -20,7 +20,7 @@ type gatewayEventMapper struct { opts MapperOptions } -func (m *gatewayEventMapper) MapToPolicy(obj client.Object, policyKind utils.Referrer) []reconcile.Request { +func (m *gatewayEventMapper) MapToPolicy(obj client.Object, policyKind kuadrant.Referrer) []reconcile.Request { logger := m.opts.Logger.WithValues("gateway", client.ObjectKeyFromObject(obj)) gateway, ok := obj.(*gatewayapiv1.Gateway) @@ -31,7 +31,7 @@ func (m *gatewayEventMapper) MapToPolicy(obj client.Object, policyKind utils.Ref requests := make([]reconcile.Request, 0) - for _, policyKey := range utils.BackReferencesFromObject(gateway, policyKind) { + for _, policyKey := range kuadrant.BackReferencesFromObject(gateway, policyKind) { logger.V(1).Info("kuadrant policy possibly affected by the gateway related event found", policyKind.Kind(), policyKey) requests = append(requests, reconcile.Request{NamespacedName: policyKey}) } diff --git a/pkg/library/mappers/gateway_test.go b/pkg/library/mappers/gateway_test.go index f737699f4..3b4477971 100644 --- a/pkg/library/mappers/gateway_test.go +++ b/pkg/library/mappers/gateway_test.go @@ -8,7 +8,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/log" ) @@ -16,19 +16,19 @@ func TestNewGatewayEventMapper(t *testing.T) { em := NewGatewayEventMapper(WithLogger(log.NewLogger())) t.Run("not gateway related event", func(subT *testing.T) { - requests := em.MapToPolicy(&gatewayapiv1.HTTPRoute{}, &utils.PolicyKindStub{}) + requests := em.MapToPolicy(&gatewayapiv1.HTTPRoute{}, &kuadrant.PolicyKindStub{}) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) t.Run("gateway related event - no requests", func(subT *testing.T) { - requests := em.MapToPolicy(&gatewayapiv1.Gateway{}, &utils.PolicyKindStub{}) + requests := em.MapToPolicy(&gatewayapiv1.Gateway{}, &kuadrant.PolicyKindStub{}) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) t.Run("gateway related event - requests", func(subT *testing.T) { gateway := &gatewayapiv1.Gateway{} gateway.SetAnnotations(map[string]string{"kuadrant.io/testpolicies": `[{"Namespace":"app-ns","Name":"policy-1"},{"Namespace":"app-ns","Name":"policy-2"}]`}) - requests := em.MapToPolicy(gateway, &utils.PolicyKindStub{}) + requests := em.MapToPolicy(gateway, &kuadrant.PolicyKindStub{}) expected := []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: "app-ns", Name: "policy-1"}}, {NamespacedName: types.NamespacedName{Namespace: "app-ns", Name: "policy-2"}}} assert.DeepEqual(subT, expected, requests) }) diff --git a/pkg/library/mappers/httproute.go b/pkg/library/mappers/httproute.go index c3718e6ed..721ae9c51 100644 --- a/pkg/library/mappers/httproute.go +++ b/pkg/library/mappers/httproute.go @@ -7,7 +7,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func NewHTTPRouteEventMapper(o ...MapperOption) EventMapper { @@ -20,7 +20,7 @@ type httpRouteEventMapper struct { opts MapperOptions } -func (m *httpRouteEventMapper) MapToPolicy(obj client.Object, policyKind utils.Referrer) []reconcile.Request { +func (m *httpRouteEventMapper) MapToPolicy(obj client.Object, policyKind kuadrant.Referrer) []reconcile.Request { logger := m.opts.Logger.WithValues("httproute", client.ObjectKeyFromObject(obj)) httpRoute, ok := obj.(*gatewayapiv1.HTTPRoute) @@ -31,7 +31,7 @@ func (m *httpRouteEventMapper) MapToPolicy(obj client.Object, policyKind utils.R requests := make([]reconcile.Request, 0) - for _, policyKey := range utils.BackReferencesFromObject(httpRoute, policyKind) { + for _, policyKey := range kuadrant.BackReferencesFromObject(httpRoute, policyKind) { logger.V(1).Info("kuadrant policy possibly affected by the httproute related event found", policyKind.Kind(), policyKey) requests = append(requests, reconcile.Request{NamespacedName: policyKey}) } diff --git a/pkg/library/mappers/httproute_test.go b/pkg/library/mappers/httproute_test.go index d949b685c..ea043d1a7 100644 --- a/pkg/library/mappers/httproute_test.go +++ b/pkg/library/mappers/httproute_test.go @@ -8,7 +8,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/log" ) @@ -16,19 +16,19 @@ func TestNewHTTPRouteEventMapper(t *testing.T) { em := NewHTTPRouteEventMapper(WithLogger(log.NewLogger())) t.Run("not http route related event", func(subT *testing.T) { - requests := em.MapToPolicy(&gatewayapiv1.Gateway{}, &utils.PolicyKindStub{}) + requests := em.MapToPolicy(&gatewayapiv1.Gateway{}, &kuadrant.PolicyKindStub{}) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) t.Run("http route related event - no requests", func(subT *testing.T) { - requests := em.MapToPolicy(&gatewayapiv1.HTTPRoute{}, &utils.PolicyKindStub{}) + requests := em.MapToPolicy(&gatewayapiv1.HTTPRoute{}, &kuadrant.PolicyKindStub{}) assert.DeepEqual(subT, []reconcile.Request{}, requests) }) t.Run("http related event - requests", func(subT *testing.T) { httpRoute := &gatewayapiv1.HTTPRoute{} httpRoute.SetAnnotations(map[string]string{"kuadrant.io/testpolicies": `[{"Namespace":"app-ns","Name":"policy-1"},{"Namespace":"app-ns","Name":"policy-2"}]`}) - requests := em.MapToPolicy(httpRoute, &utils.PolicyKindStub{}) + requests := em.MapToPolicy(httpRoute, &kuadrant.PolicyKindStub{}) expected := []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: "app-ns", Name: "policy-1"}}, {NamespacedName: types.NamespacedName{Namespace: "app-ns", Name: "policy-2"}}} assert.DeepEqual(subT, expected, requests) }) diff --git a/pkg/library/reconcilers/gateway_diffs.go b/pkg/library/reconcilers/gateway_diffs.go index 9e0c5b608..05ee74ee6 100644 --- a/pkg/library/reconcilers/gateway_diffs.go +++ b/pkg/library/reconcilers/gateway_diffs.go @@ -9,13 +9,13 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) type GatewayDiffs struct { - GatewaysMissingPolicyRef []utils.GatewayWrapper - GatewaysWithValidPolicyRef []utils.GatewayWrapper - GatewaysWithInvalidPolicyRef []utils.GatewayWrapper + GatewaysMissingPolicyRef []kuadrant.GatewayWrapper + GatewaysWithValidPolicyRef []kuadrant.GatewayWrapper + GatewaysWithInvalidPolicyRef []kuadrant.GatewayWrapper } // ComputeGatewayDiffs computes all the differences to reconcile regarding the gateways whose behaviors should/should not be extended by the policy. @@ -39,7 +39,7 @@ func ComputeGatewayDiffs(ctx context.Context, k8sClient client.Reader, policy, t return nil, err } - policyKind, ok := policy.(utils.Referrer) + policyKind, ok := policy.(kuadrant.Referrer) if !ok { return nil, fmt.Errorf("policy %s is not a referrer", policy.GetObjectKind().GroupVersionKind()) } @@ -60,11 +60,11 @@ func ComputeGatewayDiffs(ctx context.Context, k8sClient client.Reader, policy, t } // gatewaysMissingPolicyRef returns gateways referenced by the policy but that miss the reference to it the annotations -func gatewaysMissingPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client.ObjectKey, policyGwKeys []client.ObjectKey, policyKind utils.Referrer) []utils.GatewayWrapper { - gateways := make([]utils.GatewayWrapper, 0) +func gatewaysMissingPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client.ObjectKey, policyGwKeys []client.ObjectKey, policyKind kuadrant.Referrer) []kuadrant.GatewayWrapper { + gateways := make([]kuadrant.GatewayWrapper, 0) for i := range gwList.Items { gateway := gwList.Items[i] - gw := utils.GatewayWrapper{Gateway: &gateway, Referrer: policyKind} + gw := kuadrant.GatewayWrapper{Gateway: &gateway, Referrer: policyKind} if slices.Contains(policyGwKeys, client.ObjectKeyFromObject(&gateway)) && !gw.ContainsPolicy(policyKey) { gateways = append(gateways, gw) } @@ -73,11 +73,11 @@ func gatewaysMissingPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client } // gatewaysWithValidPolicyRef returns gateways referenced by the policy that also have the reference in the annotations -func gatewaysWithValidPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client.ObjectKey, policyGwKeys []client.ObjectKey, policyKind utils.Referrer) []utils.GatewayWrapper { - gateways := make([]utils.GatewayWrapper, 0) +func gatewaysWithValidPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client.ObjectKey, policyGwKeys []client.ObjectKey, policyKind kuadrant.Referrer) []kuadrant.GatewayWrapper { + gateways := make([]kuadrant.GatewayWrapper, 0) for i := range gwList.Items { gateway := gwList.Items[i] - gw := utils.GatewayWrapper{Gateway: &gateway, Referrer: policyKind} + gw := kuadrant.GatewayWrapper{Gateway: &gateway, Referrer: policyKind} if slices.Contains(policyGwKeys, client.ObjectKeyFromObject(&gateway)) && gw.ContainsPolicy(policyKey) { gateways = append(gateways, gw) } @@ -86,11 +86,11 @@ func gatewaysWithValidPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey clie } // gatewaysWithInvalidPolicyRef returns gateways not referenced by the policy that still have the reference in the annotations -func gatewaysWithInvalidPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client.ObjectKey, policyGwKeys []client.ObjectKey, policyKind utils.Referrer) []utils.GatewayWrapper { - gateways := make([]utils.GatewayWrapper, 0) +func gatewaysWithInvalidPolicyRef(gwList *gatewayapiv1.GatewayList, policyKey client.ObjectKey, policyGwKeys []client.ObjectKey, policyKind kuadrant.Referrer) []kuadrant.GatewayWrapper { + gateways := make([]kuadrant.GatewayWrapper, 0) for i := range gwList.Items { gateway := gwList.Items[i] - gw := utils.GatewayWrapper{Gateway: &gateway, Referrer: policyKind} + gw := kuadrant.GatewayWrapper{Gateway: &gateway, Referrer: policyKind} if !slices.Contains(policyGwKeys, client.ObjectKeyFromObject(&gateway)) && gw.ContainsPolicy(policyKey) { gateways = append(gateways, gw) } diff --git a/pkg/library/reconcilers/gateway_diffs_test.go b/pkg/library/reconcilers/gateway_diffs_test.go index a04f63605..942415d7d 100644 --- a/pkg/library/reconcilers/gateway_diffs_test.go +++ b/pkg/library/reconcilers/gateway_diffs_test.go @@ -10,6 +10,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -40,8 +41,8 @@ func TestGatewaysMissingPolicyRef(t *testing.T) { } var gws []string - policyKind := &utils.PolicyKindStub{} - gwName := func(gw utils.GatewayWrapper) string { return gw.Gateway.Name } + policyKind := &kuadrant.PolicyKindStub{} + gwName := func(gw kuadrant.GatewayWrapper) string { return gw.Gateway.Name } gws = utils.Map(gatewaysMissingPolicyRef(gwList, client.ObjectKey{Namespace: "app-ns", Name: "policy-1"}, []client.ObjectKey{ {Namespace: "gw-ns", Name: "gw-2"}, @@ -115,8 +116,8 @@ func TestGatewaysWithValidPolicyRef(t *testing.T) { } var gws []string - policyKind := &utils.PolicyKindStub{} - gwName := func(gw utils.GatewayWrapper) string { return gw.Gateway.Name } + policyKind := &kuadrant.PolicyKindStub{} + gwName := func(gw kuadrant.GatewayWrapper) string { return gw.Gateway.Name } gws = utils.Map(gatewaysWithValidPolicyRef(gwList, client.ObjectKey{Namespace: "app-ns", Name: "policy-1"}, []client.ObjectKey{ {Namespace: "gw-ns", Name: "gw-2"}, @@ -190,8 +191,8 @@ func TestGatewaysWithInvalidPolicyRef(t *testing.T) { } var gws []string - policyKind := &utils.PolicyKindStub{} - gwName := func(gw utils.GatewayWrapper) string { return gw.Gateway.Name } + policyKind := &kuadrant.PolicyKindStub{} + gwName := func(gw kuadrant.GatewayWrapper) string { return gw.Gateway.Name } gws = utils.Map(gatewaysWithInvalidPolicyRef(gwList, client.ObjectKey{Namespace: "app-ns", Name: "policy-1"}, []client.ObjectKey{ {Namespace: "gw-ns", Name: "gw-2"}, diff --git a/pkg/library/reconcilers/target_ref_reconciler.go b/pkg/library/reconcilers/target_ref_reconciler.go index 3e5852946..e09283b4f 100644 --- a/pkg/library/reconcilers/target_ref_reconciler.go +++ b/pkg/library/reconcilers/target_ref_reconciler.go @@ -26,6 +26,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" "github.com/kuadrant/kuadrant-operator/pkg/library/utils" ) @@ -92,7 +93,7 @@ func (r *TargetRefReconciler) TargetedGatewayKeys(_ context.Context, targetNetwo } // ReconcileTargetBackReference adds policy key in annotations of the target object -func (r *TargetRefReconciler) ReconcileTargetBackReference(ctx context.Context, p utils.KuadrantPolicy, targetNetworkObject client.Object, annotationName string) error { +func (r *TargetRefReconciler) ReconcileTargetBackReference(ctx context.Context, p kuadrant.Policy, targetNetworkObject client.Object, annotationName string) error { logger, _ := logr.FromContext(ctx) policyKey := client.ObjectKeyFromObject(p) @@ -104,7 +105,7 @@ func (r *TargetRefReconciler) ReconcileTargetBackReference(ctx context.Context, if val, ok := objAnnotations[annotationName]; ok { if val != policyKey.String() { - return utils.NewErrConflict(p.Kind(), val, fmt.Errorf("the %s target %s is already referenced by policy %s", targetNetworkObjectKind, targetNetworkObjectKey, val)) + return kuadrant.NewErrConflict(p.Kind(), val, fmt.Errorf("the %s target %s is already referenced by policy %s", targetNetworkObjectKind, targetNetworkObjectKey, val)) } } else { objAnnotations[annotationName] = policyKey.String() @@ -146,7 +147,7 @@ func (r *TargetRefReconciler) DeleteTargetBackReference(ctx context.Context, tar // this list of policy refs; nevertheless, the actual order of returned policy refs depends on the order the policy refs // appear in the annotations of the gateways. // Only gateways with status programmed are considered. -func (r *TargetRefReconciler) GetAllGatewayPolicyRefs(ctx context.Context, policyRefsConfig utils.Referrer) ([]client.ObjectKey, error) { +func (r *TargetRefReconciler) GetAllGatewayPolicyRefs(ctx context.Context, policyRefsConfig kuadrant.Referrer) ([]client.ObjectKey, error) { var uniquePolicyRefs map[string]struct{} var policyRefs []client.ObjectKey @@ -156,14 +157,14 @@ func (r *TargetRefReconciler) GetAllGatewayPolicyRefs(ctx context.Context, polic } // sort the gateways by creation timestamp to mitigate the risk of non-idenpotent reconciliations - var gateways utils.GatewayWrapperList + var gateways kuadrant.GatewayWrapperList for i := range gwList.Items { gateway := gwList.Items[i] // skip gateways that are not managed by kuadrant or that are not ready - if !utils.IsKuadrantManaged(&gateway) || meta.IsStatusConditionFalse(gateway.Status.Conditions, string(gatewayapiv1.GatewayConditionProgrammed)) { + if !kuadrant.IsKuadrantManaged(&gateway) || meta.IsStatusConditionFalse(gateway.Status.Conditions, string(gatewayapiv1.GatewayConditionProgrammed)) { continue } - gateways = append(gateways, utils.GatewayWrapper{Gateway: &gateway, Referrer: policyRefsConfig}) + gateways = append(gateways, kuadrant.GatewayWrapper{Gateway: &gateway, Referrer: policyRefsConfig}) } sort.Sort(gateways) diff --git a/pkg/library/reconcilers/target_ref_reconciler_test.go b/pkg/library/reconcilers/target_ref_reconciler_test.go index 595b075c4..04a0d6d37 100644 --- a/pkg/library/reconcilers/target_ref_reconciler_test.go +++ b/pkg/library/reconcilers/target_ref_reconciler_test.go @@ -14,7 +14,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" gatewayapiv1 "sigs.k8s.io/gateway-api/apis/v1" - "github.com/kuadrant/kuadrant-operator/pkg/library/utils" + "github.com/kuadrant/kuadrant-operator/pkg/library/kuadrant" ) func TestReconcileTargetBackReference(t *testing.T) { @@ -36,7 +36,7 @@ func TestReconcileTargetBackReference(t *testing.T) { t.Fatal(err) } - policy := &utils.FakePolicy{ + policy := &kuadrant.FakePolicy{ Object: &metav1.PartialObjectMetadata{ ObjectMeta: metav1.ObjectMeta{ Name: "my-policy",