From c6a803525c856f1367326e2bc2db240e5fa34b67 Mon Sep 17 00:00:00 2001 From: David Cheung Date: Thu, 22 Aug 2024 22:33:41 +0000 Subject: [PATCH] Migrate all providers to the new interface. * Providers now should implement ResourcesToIRConverter interface and IRToGatewayAPIConverter interface. --- pkg/i2gw/ingress2gateway.go | 72 +-- pkg/i2gw/intermediate/provider_apisix.go | 12 + .../intermediate/provider_ingressnginx.go | 12 + pkg/i2gw/intermediate/provider_istio.go | 12 + pkg/i2gw/intermediate/provider_kong.go | 12 + pkg/i2gw/intermediate/provider_openapi3.go | 12 + pkg/i2gw/provider.go | 24 +- pkg/i2gw/providers/apisix/apisix.go | 24 +- pkg/i2gw/providers/apisix/converter.go | 21 +- pkg/i2gw/providers/apisix/http_to_https.go | 6 +- .../providers/apisix/http_to_https_test.go | 18 +- pkg/i2gw/providers/apisix/resource_reader.go | 2 +- pkg/i2gw/providers/common/converter.go | 38 +- pkg/i2gw/providers/common/converter_test.go | 395 ++++++------ .../providers/common/gateway_converter.go | 2 +- .../common/gateway_converter_test.go | 192 ++++++ pkg/i2gw/providers/gce/gce.go | 17 +- pkg/i2gw/providers/gce/ir_converter.go | 6 +- pkg/i2gw/providers/gce/ir_converter_test.go | 584 ------------------ pkg/i2gw/providers/ingressnginx/canary.go | 8 +- pkg/i2gw/providers/ingressnginx/converter.go | 23 +- .../providers/ingressnginx/converter_test.go | 483 ++++++++------- .../providers/ingressnginx/ingressnginx.go | 25 +- pkg/i2gw/providers/istio/converter.go | 40 +- pkg/i2gw/providers/istio/converter_test.go | 48 +- .../istio/e2e_file_converter_test.go | 8 +- pkg/i2gw/providers/istio/istio.go | 24 +- pkg/i2gw/providers/kong/converter.go | 34 +- pkg/i2gw/providers/kong/converter_test.go | 479 +++++++------- pkg/i2gw/providers/kong/crds/tcpingress.go | 16 +- .../providers/kong/crds/tcpingress_test.go | 38 +- pkg/i2gw/providers/kong/header_matching.go | 8 +- .../providers/kong/header_matching_test.go | 2 +- pkg/i2gw/providers/kong/kong.go | 18 +- pkg/i2gw/providers/kong/method_matching.go | 8 +- .../providers/kong/method_matching_test.go | 2 +- pkg/i2gw/providers/kong/plugins.go | 8 +- pkg/i2gw/providers/openapi3/converter.go | 45 +- pkg/i2gw/providers/openapi3/converter_test.go | 41 +- pkg/i2gw/providers/openapi3/openapi.go | 20 +- 40 files changed, 1254 insertions(+), 1585 deletions(-) create mode 100644 pkg/i2gw/providers/common/gateway_converter_test.go diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 418da193..5833eacb 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -19,18 +19,13 @@ package i2gw import ( "context" "fmt" - "maps" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/config" - gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" - gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" - gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) func ToGatewayAPIResources(ctx context.Context, namespace string, inputFile string, providers []string, providerSpecificFlags map[string]map[string]string) ([]GatewayResources, map[string]string, error) { @@ -73,7 +68,9 @@ func ToGatewayAPIResources(ctx context.Context, namespace string, inputFile stri errs field.ErrorList ) for _, provider := range providerByName { - providerGatewayResources, conversionErrs := provider.ToGatewayAPI() + ir, conversionErrs := provider.ToIR() + errs = append(errs, conversionErrs...) + providerGatewayResources, conversionErrs := provider.ToGatewayResources(ir) errs = append(errs, conversionErrs...) gatewayResources = append(gatewayResources, providerGatewayResources) } @@ -138,69 +135,6 @@ func GetSupportedProviders() []string { return supportedProviders } -// MergeGatewayResources accept multiple GatewayResources and create a unique Resource struct -// built as follows: -// - GatewayClasses, *Routes, and ReferenceGrants are grouped into the same maps -// - Gateways may have the same NamespaceName even if they come from different -// ingresses, as they have a their GatewayClass' name as name. For this reason, -// if there are mutiple gateways named the same, their listeners are merged into -// a unique Gateway. -// -// This behavior is likely to change after https://github.com/kubernetes-sigs/gateway-api/pull/1863 takes place. -func MergeGatewayResources(gatewayResources ...GatewayResources) (GatewayResources, field.ErrorList) { - mergedGatewayResources := GatewayResources{ - Gateways: make(map[types.NamespacedName]gatewayv1.Gateway), - GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), - HTTPRoutes: make(map[types.NamespacedName]gatewayv1.HTTPRoute), - TLSRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TLSRoute), - TCPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute), - UDPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.UDPRoute), - ReferenceGrants: make(map[types.NamespacedName]gatewayv1beta1.ReferenceGrant), - } - var errs field.ErrorList - mergedGatewayResources.Gateways, errs = mergeGateways(gatewayResources) - if len(errs) > 0 { - return GatewayResources{}, errs - } - for _, gr := range gatewayResources { - maps.Copy(mergedGatewayResources.GatewayClasses, gr.GatewayClasses) - maps.Copy(mergedGatewayResources.HTTPRoutes, gr.HTTPRoutes) - maps.Copy(mergedGatewayResources.TLSRoutes, gr.TLSRoutes) - maps.Copy(mergedGatewayResources.TCPRoutes, gr.TCPRoutes) - maps.Copy(mergedGatewayResources.UDPRoutes, gr.UDPRoutes) - maps.Copy(mergedGatewayResources.ReferenceGrants, gr.ReferenceGrants) - } - return mergedGatewayResources, errs -} - -func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName]gatewayv1.Gateway, field.ErrorList) { - newGateways := map[types.NamespacedName]gatewayv1.Gateway{} - errs := field.ErrorList{} - - for _, gr := range gatewaResources { - for _, g := range gr.Gateways { - nn := types.NamespacedName{Namespace: g.Namespace, Name: g.Name} - if existingGateway, ok := newGateways[nn]; ok { - g.Spec.Listeners = append(g.Spec.Listeners, existingGateway.Spec.Listeners...) - g.Spec.Addresses = append(g.Spec.Addresses, existingGateway.Spec.Addresses...) - } - newGateways[nn] = g - // 64 is the maximum number of listeners a Gateway can have - if len(g.Spec.Listeners) > 64 { - fieldPath := field.NewPath(fmt.Sprintf("%s/%s", nn.Namespace, nn.Name)).Child("spec").Child("listeners") - errs = append(errs, field.Invalid(fieldPath, g, "error while merging gateway listeners: a gateway cannot have more than 64 listeners")) - } - // 16 is the maximum number of addresses a Gateway can have - if len(g.Spec.Addresses) > 16 { - fieldPath := field.NewPath(fmt.Sprintf("%s/%s", nn.Namespace, nn.Name)).Child("spec").Child("addresses") - errs = append(errs, field.Invalid(fieldPath, g, "error while merging gateway listeners: a gateway cannot have more than 16 addresses")) - } - } - } - - return newGateways, errs -} - func CastToUnstructured(obj runtime.Object) (*unstructured.Unstructured, error) { // Convert the Kubernetes object to unstructured.Unstructured unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) diff --git a/pkg/i2gw/intermediate/provider_apisix.go b/pkg/i2gw/intermediate/provider_apisix.go index f7166db6..86957315 100644 --- a/pkg/i2gw/intermediate/provider_apisix.go +++ b/pkg/i2gw/intermediate/provider_apisix.go @@ -19,3 +19,15 @@ package intermediate type ApisixGatewayIR struct{} type ApisixHTTPRouteIR struct{} type ApisixServiceIR struct{} + +func MergeApisixGatewayIR(current, existing *ApisixGatewayIR) *ApisixGatewayIR { + var mergedGatewayIR *ApisixGatewayIR + // Populate the value of each fields once ApisixGatewayIR is not empty. + if existing != nil { + mergedGatewayIR = existing + } + if current != nil { + mergedGatewayIR = current + } + return mergedGatewayIR +} diff --git a/pkg/i2gw/intermediate/provider_ingressnginx.go b/pkg/i2gw/intermediate/provider_ingressnginx.go index 4ac1207f..7618db90 100644 --- a/pkg/i2gw/intermediate/provider_ingressnginx.go +++ b/pkg/i2gw/intermediate/provider_ingressnginx.go @@ -19,3 +19,15 @@ package intermediate type IngressNginxGatewayIR struct{} type IngressNginxHTTPRouteIR struct{} type IngressNginxServiceIR struct{} + +func MergeIngressNginxGatewayIR(current, existing *IngressNginxGatewayIR) *IngressNginxGatewayIR { + var mergedGatewayIR *IngressNginxGatewayIR + // Populate the value of each fields once IngressNginxGatewayIR is not empty. + if existing != nil { + mergedGatewayIR = existing + } + if current != nil { + mergedGatewayIR = current + } + return mergedGatewayIR +} diff --git a/pkg/i2gw/intermediate/provider_istio.go b/pkg/i2gw/intermediate/provider_istio.go index 50078ec1..540424d0 100644 --- a/pkg/i2gw/intermediate/provider_istio.go +++ b/pkg/i2gw/intermediate/provider_istio.go @@ -19,3 +19,15 @@ package intermediate type IstioGatewayIR struct{} type IstioHTTPRouteIR struct{} type IstioServiceIR struct{} + +func MergeIstioGatewayIR(current, existing *IstioGatewayIR) *IstioGatewayIR { + var mergedGatewayIR *IstioGatewayIR + // Populate the value of each fields once IstioGatewayIR is not empty. + if existing != nil { + mergedGatewayIR = existing + } + if current != nil { + mergedGatewayIR = current + } + return mergedGatewayIR +} diff --git a/pkg/i2gw/intermediate/provider_kong.go b/pkg/i2gw/intermediate/provider_kong.go index 10fbd62b..83e80cdd 100644 --- a/pkg/i2gw/intermediate/provider_kong.go +++ b/pkg/i2gw/intermediate/provider_kong.go @@ -19,3 +19,15 @@ package intermediate type KongGatewayIR struct{} type KongHTTPRouteIR struct{} type KongServiceIR struct{} + +func MergeKongGatewayIR(current, existing *KongGatewayIR) *KongGatewayIR { + var mergedGatewayIR *KongGatewayIR + // Populate the value of each fields once KongGatewayIR is not empty. + if existing != nil { + mergedGatewayIR = existing + } + if current != nil { + mergedGatewayIR = current + } + return mergedGatewayIR +} diff --git a/pkg/i2gw/intermediate/provider_openapi3.go b/pkg/i2gw/intermediate/provider_openapi3.go index 9657a122..8db3a3f5 100644 --- a/pkg/i2gw/intermediate/provider_openapi3.go +++ b/pkg/i2gw/intermediate/provider_openapi3.go @@ -19,3 +19,15 @@ package intermediate type Openapi3GatewayIR struct{} type Openapi3HTTPRouteIR struct{} type Openapi3ServiceIR struct{} + +func MergeOpenapi3GatewayIR(current, existing *Openapi3GatewayIR) *Openapi3GatewayIR { + var mergedGatewayIR *Openapi3GatewayIR + // Populate the value of each fields once Openapi3GatewayIR is not empty. + if existing != nil { + mergedGatewayIR = existing + } + if current != nil { + mergedGatewayIR = current + } + return mergedGatewayIR +} diff --git a/pkg/i2gw/provider.go b/pkg/i2gw/provider.go index c6cd0d5f..a3846f63 100644 --- a/pkg/i2gw/provider.go +++ b/pkg/i2gw/provider.go @@ -20,6 +20,7 @@ import ( "context" "sync" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" @@ -55,7 +56,8 @@ type ProviderConf struct { // be used. type Provider interface { CustomResourceReader - ResourceConverter + ResourcesToIRConverter + IRToGatewayAPIConverter } type CustomResourceReader interface { @@ -69,13 +71,19 @@ type CustomResourceReader interface { ReadResourcesFromFile(ctx context.Context, filename string) error } -// The ResourceConverter interface specifies all the implemented Gateway API resource -// conversion functions. -type ResourceConverter interface { +// The ResourcesToIRConverter interface specifies conversion functions from Ingress +// and extensions into IR. +type ResourcesToIRConverter interface { + // ToIR converts stored API entities associated with the Provider into IR. + ToIR() (intermediate.IR, field.ErrorList) +} - // ToGatewayAPIResources converts stored API entities associated - // with the Provider into GatewayResources. - ToGatewayAPI() (GatewayResources, field.ErrorList) +// The IRToGatewayAPIConverter interface specifies conversion functions from IR +// into Gateway and Gateway extensions. +type IRToGatewayAPIConverter interface { + // ToGatewayResources converts stored IR with the Provider into + // Gateway API resources and extensions + ToGatewayResources(intermediate.IR) (GatewayResources, field.ErrorList) } // ImplementationSpecificHTTPPathTypeMatchConverter is an option to customize the ingress implementationSpecific @@ -110,7 +118,7 @@ type GatewayResources struct { // // Different FeatureParsers will run in undetermined order. The function must // modify / create only the required fields of the gateway resources and nothing else. -type FeatureParser func([]networkingv1.Ingress, *GatewayResources) field.ErrorList +type FeatureParser func([]networkingv1.Ingress, *intermediate.IR) field.ErrorList var providerSpecificFlagDefinitions = providerSpecificFlags{ flags: make(map[ProviderName]map[string]ProviderSpecificFlag), diff --git a/pkg/i2gw/providers/apisix/apisix.go b/pkg/i2gw/providers/apisix/apisix.go index 585424c0..f3bd8a8b 100644 --- a/pkg/i2gw/providers/apisix/apisix.go +++ b/pkg/i2gw/providers/apisix/apisix.go @@ -21,6 +21,8 @@ import ( "fmt" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -34,24 +36,28 @@ func init() { // Provider implements the i2gw.Provider interface. type Provider struct { - storage *storage - resourceReader *resourceReader - converter *converter + storage *storage + resourceReader *resourceReader + resourcesToIRConverter *resourcesToIRConverter } // NewProvider constructs and returns the apisix implementation of i2gw.Provider. func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { return &Provider{ - storage: newResourcesStorage(), - resourceReader: newResourceReader(conf), - converter: newConverter(), + storage: newResourcesStorage(), + resourceReader: newResourceReader(conf), + resourcesToIRConverter: newResourcesToIRConverter(), } } -// ToGatewayAPI converts stored Apisix API entities to i2gw.GatewayResources +// ToIR converts stored Apisix API entities to intermediate.IR // including the apisix specific features. -func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - return p.converter.convert(p.storage) +func (p *Provider) ToIR() (intermediate.IR, field.ErrorList) { + return p.resourcesToIRConverter.convertToIR(p.storage) +} + +func (p *Provider) ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + return common.ToGatewayResources(ir) } func (p *Provider) ReadResourcesFromCluster(ctx context.Context) error { diff --git a/pkg/i2gw/providers/apisix/converter.go b/pkg/i2gw/providers/apisix/converter.go index a39171a2..c8244c34 100644 --- a/pkg/i2gw/providers/apisix/converter.go +++ b/pkg/i2gw/providers/apisix/converter.go @@ -18,20 +18,21 @@ package apisix import ( "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/util/validation/field" ) -// converter implements the ToGatewayAPI function of i2gw.ResourceConverter interface. -type converter struct { +// resourcesToIRConverter implements the ToIR function of i2gw.ResourcesToIRConverter interface. +type resourcesToIRConverter struct { featureParsers []i2gw.FeatureParser implementationSpecificOptions i2gw.ProviderImplementationSpecificOptions } -// newConverter returns an apisix converter instance. -func newConverter() *converter { - return &converter{ +// newResourcesToIRConverter returns an apisix resourcesToIRConverter instance. +func newResourcesToIRConverter() *resourcesToIRConverter { + return &resourcesToIRConverter{ featureParsers: []i2gw.FeatureParser{ httpToHTTPSFeature, }, @@ -41,24 +42,24 @@ func newConverter() *converter { } } -func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.ErrorList) { +func (c *resourcesToIRConverter) convertToIR(storage *storage) (intermediate.IR, field.ErrorList) { ingressList := []networkingv1.Ingress{} for _, ing := range storage.Ingresses { ingressList = append(ingressList, *ing) } // Convert plain ingress resources to gateway resources, ignoring all // provider-specific features. - gatewayResources, errs := common.ToGateway(ingressList, c.implementationSpecificOptions) + ir, errs := common.ToIR(ingressList, c.implementationSpecificOptions) if len(errs) > 0 { - return i2gw.GatewayResources{}, errs + return intermediate.IR{}, errs } for _, parseFeatureFunc := range c.featureParsers { // Apply the feature parsing function to the gateway resources, one by one. - parseErrs := parseFeatureFunc(ingressList, &gatewayResources) + parseErrs := parseFeatureFunc(ingressList, &ir) // Append the parsing errors to the error list. errs = append(errs, parseErrs...) } - return gatewayResources, errs + return ir, errs } diff --git a/pkg/i2gw/providers/apisix/http_to_https.go b/pkg/i2gw/providers/apisix/http_to_https.go index 0068d3aa..aa632cb0 100644 --- a/pkg/i2gw/providers/apisix/http_to_https.go +++ b/pkg/i2gw/providers/apisix/http_to_https.go @@ -19,7 +19,7 @@ package apisix import ( "fmt" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" @@ -29,7 +29,7 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -func httpToHTTPSFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw.GatewayResources) field.ErrorList { +func httpToHTTPSFeature(ingresses []networkingv1.Ingress, ir *intermediate.IR) field.ErrorList { var errs field.ErrorList httpToHTTPSAnnotation := apisixAnnotation("http-to-https") ruleGroups := common.GetRuleGroups(ingresses) @@ -40,7 +40,7 @@ func httpToHTTPSFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw continue } key := types.NamespacedName{Namespace: rule.Ingress.Namespace, Name: common.RouteName(rg.Name, rg.Host)} - httpRoute, ok := gatewayResources.HTTPRoutes[key] + httpRoute, ok := ir.HTTPRoutes[key] if !ok { errs = append(errs, field.NotFound(field.NewPath("HTTPRoute"), key)) } diff --git a/pkg/i2gw/providers/apisix/http_to_https_test.go b/pkg/i2gw/providers/apisix/http_to_https_test.go index 6304f302..8c3562ef 100644 --- a/pkg/i2gw/providers/apisix/http_to_https_test.go +++ b/pkg/i2gw/providers/apisix/http_to_https_test.go @@ -20,7 +20,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -258,13 +258,15 @@ func Test_httpToHttpsFeature(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { ingresses := []networkingv1.Ingress{tc.ingress} - gatewayResources := &i2gw.GatewayResources{ - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Name: tc.expectedHTTPRoute.Name, Namespace: tc.expectedHTTPRoute.Namespace}: *tc.initialHTTPRoute, + ir := &intermediate.IR{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ + {Name: tc.expectedHTTPRoute.Name, Namespace: tc.expectedHTTPRoute.Namespace}: { + HTTPRoute: *tc.initialHTTPRoute, + }, }, } - errs := httpToHTTPSFeature(ingresses, gatewayResources) + errs := httpToHTTPSFeature(ingresses, ir) if len(errs) != len(tc.expectedError) { t.Errorf("expected %d errors, got %d", len(tc.expectedError), len(errs)) @@ -272,13 +274,13 @@ func Test_httpToHttpsFeature(t *testing.T) { key := types.NamespacedName{Namespace: tc.ingress.Namespace, Name: common.RouteName(tc.ingress.Name, tc.ingress.Spec.Rules[0].Host)} - actualHTTPRoute, ok := gatewayResources.HTTPRoutes[key] + actualHTTPRouteContext, ok := ir.HTTPRoutes[key] if !ok { t.Errorf("HTTPRoute not found: %v", key) } - if diff := cmp.Diff(*tc.expectedHTTPRoute, actualHTTPRoute); diff != "" { - t.Errorf("Unexpected HTTPRoute resource found, \n want: %+v\n got: %+v\n diff (-want +got):\n%s", *tc.expectedHTTPRoute, actualHTTPRoute, diff) + if diff := cmp.Diff(*tc.expectedHTTPRoute, actualHTTPRouteContext.HTTPRoute); diff != "" { + t.Errorf("Unexpected HTTPRoute resource found, \n want: %+v\n got: %+v\n diff (-want +got):\n%s", *tc.expectedHTTPRoute, actualHTTPRouteContext.HTTPRoute, diff) } }) } diff --git a/pkg/i2gw/providers/apisix/resource_reader.go b/pkg/i2gw/providers/apisix/resource_reader.go index 7e774304..bd34eda3 100644 --- a/pkg/i2gw/providers/apisix/resource_reader.go +++ b/pkg/i2gw/providers/apisix/resource_reader.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" ) -// converter implements the i2gw.CustomResourceReader interface. +// resourceReader implements the i2gw.CustomResourceReader interface. type resourceReader struct { conf *i2gw.ProviderConf } diff --git a/pkg/i2gw/providers/common/converter.go b/pkg/i2gw/providers/common/converter.go index 9546327b..aff489e1 100644 --- a/pkg/i2gw/providers/common/converter.go +++ b/pkg/i2gw/providers/common/converter.go @@ -32,43 +32,7 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -// ToGateway converts the received ingresses to i2gw.GatewayResources, -// without taking into consideration any provider specific logic. -func ToGateway(ingresses []networkingv1.Ingress, options i2gw.ProviderImplementationSpecificOptions) (i2gw.GatewayResources, field.ErrorList) { - aggregator := ingressAggregator{ruleGroups: map[ruleGroupKey]*ingressRuleGroup{}} - - var errs field.ErrorList - for _, ingress := range ingresses { - aggregator.addIngress(ingress) - } - if len(errs) > 0 { - return i2gw.GatewayResources{}, errs - } - - routes, gateways, errs := aggregator.toHTTPRoutesAndGateways(options) - if len(errs) > 0 { - return i2gw.GatewayResources{}, errs - } - - routeByKey := make(map[types.NamespacedName]gatewayv1.HTTPRoute) - for _, route := range routes { - key := types.NamespacedName{Namespace: route.Namespace, Name: route.Name} - routeByKey[key] = route - } - - gatewayByKey := make(map[types.NamespacedName]gatewayv1.Gateway) - for _, gateway := range gateways { - key := types.NamespacedName{Namespace: gateway.Namespace, Name: gateway.Name} - gatewayByKey[key] = gateway - } - - return i2gw.GatewayResources{ - Gateways: gatewayByKey, - HTTPRoutes: routeByKey, - }, nil -} - -// ToIR converts the received ingresses to i2gw.IR without taking into +// ToIR converts the received ingresses to intermediate.IR without taking into // consideration any provider specific logic. func ToIR(ingresses []networkingv1.Ingress, options i2gw.ProviderImplementationSpecificOptions) (intermediate.IR, field.ErrorList) { aggregator := ingressAggregator{ruleGroups: map[ruleGroupKey]*ingressRuleGroup{}} diff --git a/pkg/i2gw/providers/common/converter_test.go b/pkg/i2gw/providers/common/converter_test.go index 74c6b351..95501b2c 100644 --- a/pkg/i2gw/providers/common/converter_test.go +++ b/pkg/i2gw/providers/common/converter_test.go @@ -22,6 +22,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" @@ -31,23 +32,23 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -func Test_ingresses2GatewaysAndHttpRoutes(t *testing.T) { +func Test_ToIR(t *testing.T) { iPrefix := networkingv1.PathTypePrefix iExact := networkingv1.PathTypeExact gPathPrefix := gatewayv1.PathMatchPathPrefix gExact := gatewayv1.PathMatchExact testCases := []struct { - name string - ingresses []networkingv1.Ingress - expectedGatewayResources i2gw.GatewayResources - expectedErrors field.ErrorList + name string + ingresses []networkingv1.Ingress + expectedIR intermediate.IR + expectedErrors field.ErrorList }{ { - name: "empty", - ingresses: []networkingv1.Ingress{}, - expectedGatewayResources: i2gw.GatewayResources{}, - expectedErrors: field.ErrorList{}, + name: "empty", + ingresses: []networkingv1.Ingress{}, + expectedIR: intermediate.IR{}, + expectedErrors: field.ErrorList{}, }, { name: "simple ingress", @@ -76,47 +77,51 @@ func Test_ingresses2GatewaysAndHttpRoutes(t *testing.T) { IngressClassName: PtrTo("simple"), }, }}, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "test", Name: "simple"}: { - ObjectMeta: metav1.ObjectMeta{Name: "simple", Namespace: "test"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "simple", - Listeners: []gatewayv1.Listener{{ - Name: "example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: PtrTo(gatewayv1.Hostname("example.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "simple", Namespace: "test"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "simple", + Listeners: []gatewayv1.Listener{{ + Name: "example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "test", Name: "simple-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "simple-example-com", Namespace: "test"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "simple", - }}, - }, - Hostnames: []gatewayv1.Hostname{"example.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: PtrTo("/foo"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{{ - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "example", - Port: PtrTo(gatewayv1.PortNumber(3000)), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "simple-example-com", Namespace: "test"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "simple", + }}, + }, + Hostnames: []gatewayv1.Hostname{"example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: PtrTo("/foo"), }, - }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "example", + Port: PtrTo(gatewayv1.PortNumber(3000)), + }, + }, + }}, }}, - }}, + }, }, }, }, @@ -154,57 +159,61 @@ func Test_ingresses2GatewaysAndHttpRoutes(t *testing.T) { IngressClassName: PtrTo("with-tls"), }, }}, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "test", Name: "with-tls"}: { - ObjectMeta: metav1.ObjectMeta{Name: "with-tls", Namespace: "test"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "with-tls", - Listeners: []gatewayv1.Listener{{ - Name: "example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: PtrTo(gatewayv1.Hostname("example.com")), - }, { - Name: "example-com-https", - Port: 443, - Protocol: gatewayv1.HTTPSProtocolType, - Hostname: PtrTo(gatewayv1.Hostname("example.com")), - TLS: &gatewayv1.GatewayTLSConfig{ - CertificateRefs: []gatewayv1.SecretObjectReference{{ - Name: "example-cert", - }}, - }, - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "with-tls", Namespace: "test"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "with-tls", + Listeners: []gatewayv1.Listener{{ + Name: "example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.com")), + }, { + Name: "example-com-https", + Port: 443, + Protocol: gatewayv1.HTTPSProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.com")), + TLS: &gatewayv1.GatewayTLSConfig{ + CertificateRefs: []gatewayv1.SecretObjectReference{{ + Name: "example-cert", + }}, + }, + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "test", Name: "with-tls-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "with-tls-example-com", Namespace: "test"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "with-tls", - }}, - }, - Hostnames: []gatewayv1.Hostname{"example.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: PtrTo("/foo"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{{ - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "example", - Port: PtrTo(gatewayv1.PortNumber(3000)), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "with-tls-example-com", Namespace: "test"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "with-tls", + }}, + }, + Hostnames: []gatewayv1.Hostname{"example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: PtrTo("/foo"), }, - }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "example", + Port: PtrTo(gatewayv1.PortNumber(3000)), + }, + }, + }}, }}, - }}, + }, }, }, }, @@ -245,67 +254,73 @@ func Test_ingresses2GatewaysAndHttpRoutes(t *testing.T) { }, }, }}, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "different", Name: "example-proxy"}: { - ObjectMeta: metav1.ObjectMeta{Name: "example-proxy", Namespace: "different"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "example-proxy", - Listeners: []gatewayv1.Listener{{ - Name: "example-net-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: PtrTo(gatewayv1.Hostname("example.net")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "example-proxy", Namespace: "different"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "example-proxy", + Listeners: []gatewayv1.Listener{{ + Name: "example-net-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.net")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "different", Name: "net-example-net"}: { - ObjectMeta: metav1.ObjectMeta{Name: "net-example-net", Namespace: "different"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "example-proxy", - }}, - }, - Hostnames: []gatewayv1.Hostname{"example.net"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gExact, - Value: PtrTo("/bar"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{{ - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "custom", - Group: PtrTo(gatewayv1.Group("vendor.example.com")), - Kind: PtrTo(gatewayv1.Kind("StorageBucket")), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "net-example-net", Namespace: "different"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "example-proxy", + }}, + }, + Hostnames: []gatewayv1.Hostname{"example.net"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gExact, + Value: PtrTo("/bar"), }, - }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "custom", + Group: PtrTo(gatewayv1.Group("vendor.example.com")), + Kind: PtrTo(gatewayv1.Kind("StorageBucket")), + }, + }, + }}, }}, - }}, + }, }, }, {Namespace: "different", Name: "net-default-backend"}: { - ObjectMeta: metav1.ObjectMeta{Name: "net-default-backend", Namespace: "different"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "example-proxy", - }}, - }, - Rules: []gatewayv1.HTTPRouteRule{{ - BackendRefs: []gatewayv1.HTTPBackendRef{{ - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "default", - Port: PtrTo(gatewayv1.PortNumber(8080)), - }, + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "net-default-backend", Namespace: "different"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "example-proxy", }}, - }}, + }, + Rules: []gatewayv1.HTTPRouteRule{{ + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "default", + Port: PtrTo(gatewayv1.PortNumber(8080)), + }, + }}, + }}, + }, }, }, }, @@ -364,47 +379,51 @@ func Test_ingresses2GatewaysAndHttpRoutes(t *testing.T) { }}, }, }}, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "test", Name: "example-proxy"}: { - ObjectMeta: metav1.ObjectMeta{Name: "example-proxy", Namespace: "test"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "example-proxy", - Listeners: []gatewayv1.Listener{{ - Name: "example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: PtrTo(gatewayv1.Hostname("example.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "example-proxy", Namespace: "test"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "example-proxy", + Listeners: []gatewayv1.Listener{{ + Name: "example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "test", Name: "duplicate-a-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "duplicate-a-example-com", Namespace: "test"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "example-proxy", - }}, - }, - Hostnames: []gatewayv1.Hostname{"example.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: PtrTo("/foo"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{{ - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "example", - Port: PtrTo(gatewayv1.PortNumber(3000)), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "duplicate-a-example-com", Namespace: "test"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "example-proxy", + }}, + }, + Hostnames: []gatewayv1.Hostname{"example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: PtrTo("/foo"), }, - }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "example", + Port: PtrTo(gatewayv1.PortNumber(3000)), + }, + }, + }}, }}, - }}, + }, }, }, }, @@ -416,32 +435,32 @@ func Test_ingresses2GatewaysAndHttpRoutes(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - gatewayResources, errs := ToGateway(tc.ingresses, i2gw.ProviderImplementationSpecificOptions{}) + ir, errs := ToIR(tc.ingresses, i2gw.ProviderImplementationSpecificOptions{}) - if len(gatewayResources.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { + if len(ir.HTTPRoutes) != len(tc.expectedIR.HTTPRoutes) { t.Errorf("Expected %d HTTPRoutes, got %d: %+v", - len(tc.expectedGatewayResources.HTTPRoutes), len(gatewayResources.HTTPRoutes), gatewayResources.HTTPRoutes) + len(tc.expectedIR.HTTPRoutes), len(ir.HTTPRoutes), ir.HTTPRoutes) } else { - for i, got := range gatewayResources.HTTPRoutes { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.HTTPRoutes[key] - want.SetGroupVersionKind(HTTPRouteGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + for i, gotHTTPRouteContext := range ir.HTTPRoutes { + key := types.NamespacedName{Namespace: gotHTTPRouteContext.HTTPRoute.Namespace, Name: gotHTTPRouteContext.HTTPRoute.Name} + wantHTTPRouteContext := tc.expectedIR.HTTPRoutes[key] + wantHTTPRouteContext.HTTPRoute.SetGroupVersionKind(HTTPRouteGVK) + if !apiequality.Semantic.DeepEqual(gotHTTPRouteContext.HTTPRoute, wantHTTPRouteContext.HTTPRoute) { + t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, wantHTTPRouteContext.HTTPRoute, gotHTTPRouteContext.HTTPRoute, cmp.Diff(wantHTTPRouteContext.HTTPRoute, gotHTTPRouteContext.HTTPRoute)) } } } - if len(gatewayResources.Gateways) != len(tc.expectedGatewayResources.Gateways) { + if len(ir.Gateways) != len(tc.expectedIR.Gateways) { t.Errorf("Expected %d Gateways, got %d: %+v", - len(tc.expectedGatewayResources.Gateways), len(gatewayResources.Gateways), gatewayResources.Gateways) + len(tc.expectedIR.Gateways), len(ir.Gateways), ir.Gateways) } else { - for i, got := range gatewayResources.Gateways { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.Gateways[key] - want.SetGroupVersionKind(GatewayGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + for i, gotGatewayContext := range ir.Gateways { + key := types.NamespacedName{Namespace: gotGatewayContext.Gateway.Namespace, Name: gotGatewayContext.Gateway.Name} + wantGatewayContext := tc.expectedIR.Gateways[key] + wantGatewayContext.Gateway.SetGroupVersionKind(GatewayGVK) + if !apiequality.Semantic.DeepEqual(gotGatewayContext.Gateway, wantGatewayContext.Gateway) { + t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, wantGatewayContext.Gateway, gotGatewayContext.Gateway, cmp.Diff(wantGatewayContext.Gateway, gotGatewayContext.Gateway)) } } } diff --git a/pkg/i2gw/providers/common/gateway_converter.go b/pkg/i2gw/providers/common/gateway_converter.go index 4926c258..066c983b 100644 --- a/pkg/i2gw/providers/common/gateway_converter.go +++ b/pkg/i2gw/providers/common/gateway_converter.go @@ -24,7 +24,7 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -// ToGatewayResources converts the received i2gw.IR to i2gw.GatewayResource +// ToGatewayResources converts the received intermediate.IR to i2gw.GatewayResource // without taking into consideration any provider specific logic. func ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { gatewayResources := i2gw.GatewayResources{ diff --git a/pkg/i2gw/providers/common/gateway_converter_test.go b/pkg/i2gw/providers/common/gateway_converter_test.go new file mode 100644 index 00000000..d8a1e350 --- /dev/null +++ b/pkg/i2gw/providers/common/gateway_converter_test.go @@ -0,0 +1,192 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package common + +import ( + "errors" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + apiequality "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/validation/field" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" +) + +func Test_ToGatewayResources(t *testing.T) { + gPathPrefix := gatewayv1.PathMatchPathPrefix + + testCases := []struct { + desc string + ir intermediate.IR + expectedGatewayResources i2gw.GatewayResources + expectedErrors field.ErrorList + }{ + { + desc: "empty", + ir: intermediate.IR{}, + expectedGatewayResources: i2gw.GatewayResources{}, + expectedErrors: field.ErrorList{}, + }, + { + desc: "no additional extensions", + ir: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: "test", Name: "simple"}: { + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "simple", Namespace: "test"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "simple", + Listeners: []gatewayv1.Listener{{ + Name: "example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.com")), + }}, + }, + }, + }, + }, + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ + {Namespace: "test", Name: "simple-example-com"}: { + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "simple-example-com", Namespace: "test"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "simple", + }}, + }, + Hostnames: []gatewayv1.Hostname{"example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: PtrTo("/foo"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "example", + Port: PtrTo(gatewayv1.PortNumber(3000)), + }, + }, + }}, + }}, + }, + }, + }, + }, + }, + expectedGatewayResources: i2gw.GatewayResources{ + Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + {Namespace: "test", Name: "simple"}: { + ObjectMeta: metav1.ObjectMeta{Name: "simple", Namespace: "test"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "simple", + Listeners: []gatewayv1.Listener{{ + Name: "example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: PtrTo(gatewayv1.Hostname("example.com")), + }}, + }, + }, + }, + HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + {Namespace: "test", Name: "simple-example-com"}: { + ObjectMeta: metav1.ObjectMeta{Name: "simple-example-com", Namespace: "test"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "simple", + }}, + }, + Hostnames: []gatewayv1.Hostname{"example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: PtrTo("/foo"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{{ + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "example", + Port: PtrTo(gatewayv1.PortNumber(3000)), + }, + }, + }}, + }}, + }, + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + gatewayResouces, errs := ToGatewayResources(tc.ir) + + if len(errs) != len(tc.expectedErrors) { + t.Errorf("Expected %d errors, got %d: %+v", len(tc.expectedErrors), len(errs), errs) + } else { + for i, e := range errs { + if errors.Is(e, tc.expectedErrors[i]) { + t.Errorf("Unexpected error message at %d index. Got %s, want: %s", i, e, tc.expectedErrors[i]) + } + } + } + + if len(gatewayResouces.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { + t.Errorf("Expected %d HTTPRoutes, got %d: %+v", + len(tc.expectedGatewayResources.HTTPRoutes), len(gatewayResouces.HTTPRoutes), gatewayResouces.HTTPRoutes) + } else { + for i, got := range gatewayResouces.HTTPRoutes { + got.SetGroupVersionKind(HTTPRouteGVK) + key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} + want := tc.expectedGatewayResources.HTTPRoutes[key] + want.SetGroupVersionKind(HTTPRouteGVK) + if !apiequality.Semantic.DeepEqual(got, want) { + t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + } + } + } + + if len(gatewayResouces.Gateways) != len(tc.expectedGatewayResources.Gateways) { + t.Errorf("Expected %d Gateways, got %d: %+v", + len(tc.expectedGatewayResources.Gateways), len(gatewayResouces.Gateways), gatewayResouces.Gateways) + } else { + for i, got := range gatewayResouces.Gateways { + got.SetGroupVersionKind(GatewayGVK) + key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} + want := tc.expectedGatewayResources.Gateways[key] + want.SetGroupVersionKind(GatewayGVK) + if !apiequality.Semantic.DeepEqual(got, want) { + t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + } + } + } + }) + } +} diff --git a/pkg/i2gw/providers/gce/gce.go b/pkg/i2gw/providers/gce/gce.go index 7740824a..35e7ca50 100644 --- a/pkg/i2gw/providers/gce/gce.go +++ b/pkg/i2gw/providers/gce/gce.go @@ -21,6 +21,7 @@ import ( "fmt" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "k8s.io/apimachinery/pkg/util/validation/field" backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" @@ -51,7 +52,7 @@ func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { return &Provider{ storage: newResourcesStorage(), reader: newResourceReader(conf), - irConverter: newResourceToIRConverter(conf), + irConverter: newResourcesToIRConverter(conf), gatewayConverter: newIRToGatewayResourcesConverter(), } } @@ -75,12 +76,12 @@ func (p *Provider) ReadResourcesFromFile(_ context.Context, filename string) err return nil } -// ToGatewayAPI converts stored Ingress GCE API entities to -// i2gw.GatewayResources including the ingress-gce specific features. -func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - ir, err := p.irConverter.convertToIR(p.storage) - if err != nil { - return i2gw.GatewayResources{}, err - } +// ToIR converts stored Ingress GCE API entities to intermediate.IR including the +// ingress-gce specific features. +func (p *Provider) ToIR() (intermediate.IR, field.ErrorList) { + return p.irConverter.convertToIR(p.storage) +} + +func (p *Provider) ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { return p.gatewayConverter.irToGateway(ir) } diff --git a/pkg/i2gw/providers/gce/ir_converter.go b/pkg/i2gw/providers/gce/ir_converter.go index 83e7c51b..9780a8c3 100644 --- a/pkg/i2gw/providers/gce/ir_converter.go +++ b/pkg/i2gw/providers/gce/ir_converter.go @@ -33,7 +33,7 @@ const ( serviceKey contextKey = iota ) -// converter implements the ToGatewayAPI function of i2gw.ResourceConverter interface. +// resourcesToIRConverter implements the ToIR function of i2gw.ResourcesToIRConverter interface. type resourcesToIRConverter struct { conf *i2gw.ProviderConf @@ -41,8 +41,8 @@ type resourcesToIRConverter struct { ctx context.Context } -// newConverter returns an ingress-gce resourcesToIRConverter instance. -func newResourceToIRConverter(conf *i2gw.ProviderConf) resourcesToIRConverter { +// newResourcesToIRConverter returns an ingress-gce resourcesToIRConverter instance. +func newResourcesToIRConverter(conf *i2gw.ProviderConf) resourcesToIRConverter { return resourcesToIRConverter{ conf: conf, implementationSpecificOptions: i2gw.ProviderImplementationSpecificOptions{ diff --git a/pkg/i2gw/providers/gce/ir_converter_test.go b/pkg/i2gw/providers/gce/ir_converter_test.go index d4e88a0f..f094991b 100644 --- a/pkg/i2gw/providers/gce/ir_converter_test.go +++ b/pkg/i2gw/providers/gce/ir_converter_test.go @@ -36,590 +36,6 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -func Test_ToGateway(t *testing.T) { - testNamespace := "default" - testHost := "test.mydomain.com" - testBackendServiceName := "test" - iPrefix := networkingv1.PathTypePrefix - implSpecificPathType := networkingv1.PathTypeImplementationSpecific - - gPathPrefix := gatewayv1.PathMatchPathPrefix - gExact := gatewayv1.PathMatchExact - - extIngClassIngressName := "gce-ingress-class" - intIngClassIngressName := "gce-internal-ingress-class" - noIngClassIngressName := "no-ingress-class" - - testCases := []struct { - name string - ingresses map[types.NamespacedName]*networkingv1.Ingress - expectedGatewayResources i2gw.GatewayResources - expectedErrors field.ErrorList - }{ - { - name: "gce ingress class", - ingresses: map[types.NamespacedName]*networkingv1.Ingress{ - {Namespace: testNamespace, Name: extIngClassIngressName}: { - ObjectMeta: metav1.ObjectMeta{ - Name: extIngClassIngressName, - Namespace: testNamespace, - Annotations: map[string]string{networkingv1beta1.AnnotationIngressClass: gceIngressClass}, - }, - Spec: networkingv1.IngressSpec{ - Rules: []networkingv1.IngressRule{{ - Host: testHost, - IngressRuleValue: networkingv1.IngressRuleValue{ - HTTP: &networkingv1.HTTPIngressRuleValue{ - Paths: []networkingv1.HTTPIngressPath{{ - Path: "/", - PathType: &iPrefix, - Backend: networkingv1.IngressBackend{ - Service: &networkingv1.IngressServiceBackend{ - Name: testBackendServiceName, - Port: networkingv1.ServiceBackendPort{ - Number: 80, - }, - }, - }, - }}, - }, - }, - }}, - }, - }, - }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ - {Namespace: testNamespace, Name: gceIngressClass}: { - ObjectMeta: metav1.ObjectMeta{Name: gceIngressClass, Namespace: testNamespace}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: gceL7GlobalExternalManagedGatewayClass, - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname(testHost)), - }}, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { - ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName), Namespace: testNamespace}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: gceIngressClass, - }}, - }, - Hostnames: []gatewayv1.Hostname{gatewayv1.Hostname(testHost)}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: gatewayv1.ObjectName(testBackendServiceName), - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expectedErrors: field.ErrorList{}, - }, - { - name: "gce-internal ingress class", - ingresses: map[types.NamespacedName]*networkingv1.Ingress{ - {Namespace: testNamespace, Name: intIngClassIngressName}: { - ObjectMeta: metav1.ObjectMeta{ - Name: intIngClassIngressName, - Namespace: testNamespace, - Annotations: map[string]string{networkingv1beta1.AnnotationIngressClass: gceL7ILBIngressClass}, - }, - Spec: networkingv1.IngressSpec{ - Rules: []networkingv1.IngressRule{{ - Host: testHost, - IngressRuleValue: networkingv1.IngressRuleValue{ - HTTP: &networkingv1.HTTPIngressRuleValue{ - Paths: []networkingv1.HTTPIngressPath{{ - Path: "/", - PathType: &iPrefix, - Backend: networkingv1.IngressBackend{ - Service: &networkingv1.IngressServiceBackend{ - Name: testBackendServiceName, - Port: networkingv1.ServiceBackendPort{ - Number: 80, - }, - }, - }, - }}, - }, - }, - }}, - }, - }, - }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ - {Namespace: testNamespace, Name: gceL7ILBIngressClass}: { - ObjectMeta: metav1.ObjectMeta{Name: gceL7ILBIngressClass, Namespace: testNamespace}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: gceL7RegionalInternalGatewayClass, - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname(testHost)), - }}, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: testNamespace, Name: "gce-internal-ingress-class-test-mydomain-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "gce-internal-ingress-class-test-mydomain-com", Namespace: testNamespace}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: gceL7ILBIngressClass, - }}, - }, - Hostnames: []gatewayv1.Hostname{gatewayv1.Hostname(testHost)}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: gatewayv1.ObjectName(testBackendServiceName), - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expectedErrors: field.ErrorList{}, - }, - { - name: "empty ingress class, default to gce ingress class", - ingresses: map[types.NamespacedName]*networkingv1.Ingress{ - {Namespace: testNamespace, Name: noIngClassIngressName}: { - ObjectMeta: metav1.ObjectMeta{ - Name: noIngClassIngressName, - Namespace: testNamespace, - }, - Spec: networkingv1.IngressSpec{ - Rules: []networkingv1.IngressRule{{ - Host: testHost, - IngressRuleValue: networkingv1.IngressRuleValue{ - HTTP: &networkingv1.HTTPIngressRuleValue{ - Paths: []networkingv1.HTTPIngressPath{{ - Path: "/", - PathType: &iPrefix, - Backend: networkingv1.IngressBackend{ - Service: &networkingv1.IngressServiceBackend{ - Name: testBackendServiceName, - Port: networkingv1.ServiceBackendPort{ - Number: 80, - }, - }, - }, - }}, - }, - }, - }}, - }, - }, - }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ - {Namespace: testNamespace, Name: gceIngressClass}: { - ObjectMeta: metav1.ObjectMeta{Name: gceIngressClass, Namespace: testNamespace}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: gceL7GlobalExternalManagedGatewayClass, - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname(testHost)), - }}, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", noIngClassIngressName)}: { - ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-test-mydomain-com", noIngClassIngressName), Namespace: testNamespace}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: gceIngressClass, - }}, - }, - Hostnames: []gatewayv1.Hostname{gatewayv1.Hostname(testHost)}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: gatewayv1.ObjectName(testBackendServiceName), - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expectedErrors: field.ErrorList{}, - }, - { - name: "gce implementation-specific with /*, map to / Prefix", - ingresses: map[types.NamespacedName]*networkingv1.Ingress{ - {Namespace: testNamespace, Name: extIngClassIngressName}: { - ObjectMeta: metav1.ObjectMeta{ - Name: extIngClassIngressName, - Namespace: testNamespace, - Annotations: map[string]string{networkingv1beta1.AnnotationIngressClass: gceIngressClass}, - }, - Spec: networkingv1.IngressSpec{ - Rules: []networkingv1.IngressRule{{ - Host: testHost, - IngressRuleValue: networkingv1.IngressRuleValue{ - HTTP: &networkingv1.HTTPIngressRuleValue{ - Paths: []networkingv1.HTTPIngressPath{{ - Path: "/*", - PathType: &implSpecificPathType, - Backend: networkingv1.IngressBackend{ - Service: &networkingv1.IngressServiceBackend{ - Name: testBackendServiceName, - Port: networkingv1.ServiceBackendPort{ - Number: 80, - }, - }, - }, - }}, - }, - }, - }}, - }, - }, - }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ - {Namespace: testNamespace, Name: gceIngressClass}: { - ObjectMeta: metav1.ObjectMeta{Name: gceIngressClass, Namespace: testNamespace}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: gceL7GlobalExternalManagedGatewayClass, - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname(testHost)), - }}, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { - ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName), Namespace: testNamespace}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: gceIngressClass, - }}, - }, - Hostnames: []gatewayv1.Hostname{gatewayv1.Hostname(testHost)}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: gatewayv1.ObjectName(testBackendServiceName), - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expectedErrors: field.ErrorList{}, - }, - { - name: "gce implementation-specific with /foo/*, converted to /foo", - ingresses: map[types.NamespacedName]*networkingv1.Ingress{ - {Namespace: testNamespace, Name: extIngClassIngressName}: { - ObjectMeta: metav1.ObjectMeta{ - Name: extIngClassIngressName, - Namespace: testNamespace, - Annotations: map[string]string{networkingv1beta1.AnnotationIngressClass: gceIngressClass}, - }, - Spec: networkingv1.IngressSpec{ - Rules: []networkingv1.IngressRule{{ - Host: testHost, - IngressRuleValue: networkingv1.IngressRuleValue{ - HTTP: &networkingv1.HTTPIngressRuleValue{ - Paths: []networkingv1.HTTPIngressPath{{ - Path: "/foo/*", - PathType: &implSpecificPathType, - Backend: networkingv1.IngressBackend{ - Service: &networkingv1.IngressServiceBackend{ - Name: testBackendServiceName, - Port: networkingv1.ServiceBackendPort{ - Number: 80, - }, - }, - }, - }}, - }, - }, - }}, - }, - }, - }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ - {Namespace: testNamespace, Name: gceIngressClass}: { - ObjectMeta: metav1.ObjectMeta{Name: gceIngressClass, Namespace: testNamespace}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: gceL7GlobalExternalManagedGatewayClass, - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname(testHost)), - }}, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { - ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName), Namespace: testNamespace}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: gceIngressClass, - }}, - }, - Hostnames: []gatewayv1.Hostname{gatewayv1.Hostname(testHost)}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/foo"), - }, - }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: gatewayv1.ObjectName(testBackendServiceName), - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expectedErrors: nil, - }, - { - name: "gce implementation-specific without wildcard path, map to Prefix", - ingresses: map[types.NamespacedName]*networkingv1.Ingress{ - {Namespace: testNamespace, Name: extIngClassIngressName}: { - ObjectMeta: metav1.ObjectMeta{ - Name: extIngClassIngressName, - Namespace: testNamespace, - Annotations: map[string]string{networkingv1beta1.AnnotationIngressClass: gceIngressClass}, - }, - Spec: networkingv1.IngressSpec{ - Rules: []networkingv1.IngressRule{{ - Host: testHost, - IngressRuleValue: networkingv1.IngressRuleValue{ - HTTP: &networkingv1.HTTPIngressRuleValue{ - Paths: []networkingv1.HTTPIngressPath{{ - Path: "/foo", - PathType: &implSpecificPathType, - Backend: networkingv1.IngressBackend{ - Service: &networkingv1.IngressServiceBackend{ - Name: testBackendServiceName, - Port: networkingv1.ServiceBackendPort{ - Number: 80, - }, - }, - }, - }}, - }, - }, - }}, - }, - }, - }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ - {Namespace: testNamespace, Name: gceIngressClass}: { - ObjectMeta: metav1.ObjectMeta{Name: gceIngressClass, Namespace: testNamespace}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: gceL7GlobalExternalManagedGatewayClass, - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname(testHost)), - }}, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { - ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName), Namespace: testNamespace}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: gceIngressClass, - }}, - }, - Hostnames: []gatewayv1.Hostname{gatewayv1.Hostname(testHost)}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gExact, - Value: ptrTo("/foo"), - }, - }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: gatewayv1.ObjectName(testBackendServiceName), - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expectedErrors: field.ErrorList{}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - - provider := NewProvider(&i2gw.ProviderConf{}) - gceProvider := provider.(*Provider) - gceProvider.storage = newResourcesStorage() - gceProvider.storage.Ingresses = tc.ingresses - - // TODO(#113) we pass an empty i2gw.InputResources temporarily until we change ToGatewayAPI function on the interface - gatewayResources, errs := provider.ToGatewayAPI() - - if len(errs) != len(tc.expectedErrors) { - t.Errorf("Expected %d errors, got %d: %+v", len(tc.expectedErrors), len(errs), errs) - } else { - for i, e := range errs { - if errors.Is(e, tc.expectedErrors[i]) { - t.Errorf("Unexpected error message at %d index. Got %s, want: %s", i, e, tc.expectedErrors[i]) - } - } - } - - if len(gatewayResources.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { - t.Errorf("Expected %d HTTPRoutes, got %d: %+v", - len(tc.expectedGatewayResources.HTTPRoutes), len(gatewayResources.HTTPRoutes), gatewayResources.HTTPRoutes) - } else { - for i, got := range gatewayResources.HTTPRoutes { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.HTTPRoutes[key] - want.SetGroupVersionKind(common.HTTPRouteGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) - } - } - } - - if len(gatewayResources.Gateways) != len(tc.expectedGatewayResources.Gateways) { - t.Errorf("Expected %d Gateways, got %d: %+v", - len(tc.expectedGatewayResources.Gateways), len(gatewayResources.Gateways), gatewayResources.Gateways) - } else { - for i, got := range gatewayResources.Gateways { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.Gateways[key] - want.SetGroupVersionKind(common.GatewayGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) - } - } - } - - }) - } -} - func Test_convertToIR(t *testing.T) { testNamespace := "default" testHost := "test.mydomain.com" diff --git a/pkg/i2gw/providers/ingressnginx/canary.go b/pkg/i2gw/providers/ingressnginx/canary.go index 002814e9..1d737e4a 100644 --- a/pkg/i2gw/providers/ingressnginx/canary.go +++ b/pkg/i2gw/providers/ingressnginx/canary.go @@ -20,7 +20,7 @@ import ( "fmt" "strconv" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" @@ -30,7 +30,7 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -func canaryFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw.GatewayResources) field.ErrorList { +func canaryFeature(ingresses []networkingv1.Ingress, ir *intermediate.IR) field.ErrorList { ruleGroups := common.GetRuleGroups(ingresses) for _, rg := range ruleGroups { @@ -59,14 +59,14 @@ func canaryFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw.Gate errs = append(errs, calculationErrs...) key := types.NamespacedName{Namespace: path.ingress.Namespace, Name: common.RouteName(rg.Name, rg.Host)} - httpRoute, ok := gatewayResources.HTTPRoutes[key] + httpRouteContext, ok := ir.HTTPRoutes[key] if !ok { // If there wasn't an HTTPRoute for this Ingress, we can skip it as something is wrong. // All the available errors will be returned at the end. continue } - patchHTTPRouteWithBackendRefs(&httpRoute, backendRefs) + patchHTTPRouteWithBackendRefs(&httpRouteContext.HTTPRoute, backendRefs) } if len(errs) > 0 { return errs diff --git a/pkg/i2gw/providers/ingressnginx/converter.go b/pkg/i2gw/providers/ingressnginx/converter.go index 5521f8b4..22725f89 100644 --- a/pkg/i2gw/providers/ingressnginx/converter.go +++ b/pkg/i2gw/providers/ingressnginx/converter.go @@ -18,42 +18,43 @@ package ingressnginx import ( "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" "k8s.io/apimachinery/pkg/util/validation/field" ) -// converter implements the ToGatewayAPI function of i2gw.ResourceConverter interface. -type converter struct { +// resourcesToIRConverter implements the ToIR function of i2gw.ResourcesToIRConverter interface. +type resourcesToIRConverter struct { featureParsers []i2gw.FeatureParser } -// newConverter returns an ingress-nginx converter instance. -func newConverter() *converter { - return &converter{ +// newResourcesToIRConverter returns an ingress-nginx resourcesToIRConverter instance. +func newResourcesToIRConverter() *resourcesToIRConverter { + return &resourcesToIRConverter{ featureParsers: []i2gw.FeatureParser{ canaryFeature, }, } } -func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.ErrorList) { +func (c *resourcesToIRConverter) convert(storage *storage) (intermediate.IR, field.ErrorList) { - // TODO(liorliberman) temporary until we decide to change ToGateway and featureParsers to get a map of [types.NamespacedName]*networkingv1.Ingress instead of a list + // TODO(liorliberman) temporary until we decide to change ToIR and featureParsers to get a map of [types.NamespacedName]*networkingv1.Ingress instead of a list ingressList := storage.Ingresses.List() // Convert plain ingress resources to gateway resources, ignoring all // provider-specific features. - gatewayResources, errs := common.ToGateway(ingressList, i2gw.ProviderImplementationSpecificOptions{}) + ir, errs := common.ToIR(ingressList, i2gw.ProviderImplementationSpecificOptions{}) if len(errs) > 0 { - return i2gw.GatewayResources{}, errs + return intermediate.IR{}, errs } for _, parseFeatureFunc := range c.featureParsers { // Apply the feature parsing function to the gateway resources, one by one. - parseErrs := parseFeatureFunc(ingressList, &gatewayResources) + parseErrs := parseFeatureFunc(ingressList, &ir) // Append the parsing errors to the error list. errs = append(errs, parseErrs...) } - return gatewayResources, errs + return ir, errs } diff --git a/pkg/i2gw/providers/ingressnginx/converter_test.go b/pkg/i2gw/providers/ingressnginx/converter_test.go index 6cf5643b..0c4d7fab 100644 --- a/pkg/i2gw/providers/ingressnginx/converter_test.go +++ b/pkg/i2gw/providers/ingressnginx/converter_test.go @@ -22,6 +22,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" @@ -33,7 +34,7 @@ import ( gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -func Test_ToGateway(t *testing.T) { +func Test_ToIR(t *testing.T) { iPrefix := networkingv1.PathTypePrefix //iExact := networkingv1.PathTypeExact isPathType := networkingv1.PathTypeImplementationSpecific @@ -41,10 +42,10 @@ func Test_ToGateway(t *testing.T) { //gExact := gatewayv1.PathMatchExact testCases := []struct { - name string - ingresses OrderedIngressMap - expectedGatewayResources i2gw.GatewayResources - expectedErrors field.ErrorList + name string + ingresses OrderedIngressMap + expectedIR intermediate.IR + expectedErrors field.ErrorList }{ { name: "canary deployment", @@ -108,61 +109,65 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "ingress-nginx"}: { - ObjectMeta: metav1.ObjectMeta{Name: "ingress-nginx", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "ingress-nginx", - Listeners: []gatewayv1.Listener{{ - Name: "echo-prod-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("echo.prod.mydomain.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "ingress-nginx", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "ingress-nginx", + Listeners: []gatewayv1.Listener{{ + Name: "echo-prod-mydomain-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("echo.prod.mydomain.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "default", Name: "production-echo-prod-mydomain-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "production-echo-prod-mydomain-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "ingress-nginx", - }}, - }, - Hostnames: []gatewayv1.Hostname{"echo.prod.mydomain.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "production", - Group: ptrTo(gatewayv1.Group("vendor.example.com")), - Kind: ptrTo(gatewayv1.Kind("StorageBucket")), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "production-echo-prod-mydomain-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "ingress-nginx", + }}, + }, + Hostnames: []gatewayv1.Hostname{"echo.prod.mydomain.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "production", + Group: ptrTo(gatewayv1.Group("vendor.example.com")), + Kind: ptrTo(gatewayv1.Kind("StorageBucket")), + }, + Weight: ptrTo(int32(80)), }, - Weight: ptrTo(int32(80)), }, - }, - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "canary", - Group: ptrTo(gatewayv1.Group("vendor.example.com")), - Kind: ptrTo(gatewayv1.Kind("StorageBucket")), + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "canary", + Group: ptrTo(gatewayv1.Group("vendor.example.com")), + Kind: ptrTo(gatewayv1.Kind("StorageBucket")), + }, + Weight: ptrTo(int32(20)), }, - Weight: ptrTo(int32(20)), }, }, - }, - }}, + }}, + }, }, }, }, @@ -204,7 +209,7 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{}, + expectedIR: intermediate.IR{}, expectedErrors: field.ErrorList{ { Type: field.ErrorTypeInvalid, @@ -284,92 +289,65 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "nginx"}: { - ObjectMeta: metav1.ObjectMeta{Name: "nginx", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "nginx", - Listeners: []gatewayv1.Listener{ - { - Name: "bar-example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("bar.example.com")), - }, - { - Name: "bar-example-com-https", - Port: 443, - Protocol: gatewayv1.HTTPSProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("bar.example.com")), - TLS: &gatewayv1.GatewayTLSConfig{ - CertificateRefs: []gatewayv1.SecretObjectReference{ - {Name: "example-com"}, - }, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "nginx", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "nginx", + Listeners: []gatewayv1.Listener{ + { + Name: "bar-example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("bar.example.com")), }, - }, - { - Name: "foo-example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("foo.example.com")), - }, - { - Name: "foo-example-com-https", - Port: 443, - Protocol: gatewayv1.HTTPSProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("foo.example.com")), - TLS: &gatewayv1.GatewayTLSConfig{ - CertificateRefs: []gatewayv1.SecretObjectReference{ - {Name: "example-com"}, + { + Name: "bar-example-com-https", + Port: 443, + Protocol: gatewayv1.HTTPSProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("bar.example.com")), + TLS: &gatewayv1.GatewayTLSConfig{ + CertificateRefs: []gatewayv1.SecretObjectReference{ + {Name: "example-com"}, + }, }, }, - }, - }, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: "default", Name: "example-ingress-bar-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-bar-example-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "nginx", - }}, - }, - Hostnames: []gatewayv1.Hostname{"bar.example.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), + { + Name: "foo-example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("foo.example.com")), }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{ { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "bar-app", - Port: ptrTo(gatewayv1.PortNumber(80)), + Name: "foo-example-com-https", + Port: 443, + Protocol: gatewayv1.HTTPSProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("foo.example.com")), + TLS: &gatewayv1.GatewayTLSConfig{ + CertificateRefs: []gatewayv1.SecretObjectReference{ + {Name: "example-com"}, }, }, }, }, - }}, + }, }, }, - {Namespace: "default", Name: "example-ingress-foo-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-foo-example-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "nginx", - }}, - }, - Hostnames: []gatewayv1.Hostname{"foo.example.com"}, - Rules: []gatewayv1.HTTPRouteRule{ - { + }, + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ + {Namespace: "default", Name: "example-ingress-bar-example-com"}: { + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-bar-example-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "nginx", + }}, + }, + Hostnames: []gatewayv1.Hostname{"bar.example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ Matches: []gatewayv1.HTTPRouteMatch{{ Path: &gatewayv1.HTTPPathMatch{ Type: &gPathPrefix, @@ -380,26 +358,59 @@ func Test_ToGateway(t *testing.T) { { BackendRef: gatewayv1.BackendRef{ BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "foo-app", + Name: "bar-app", Port: ptrTo(gatewayv1.PortNumber(80)), }, }, }, }, + }}, + }, + }, + }, + {Namespace: "default", Name: "example-ingress-foo-example-com"}: { + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-foo-example-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "nginx", + }}, }, - { - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/orders"), + Hostnames: []gatewayv1.Hostname{"foo.example.com"}, + Rules: []gatewayv1.HTTPRouteRule{ + { + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "foo-app", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, + }, }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "foo-orders-app", - Port: ptrTo(gatewayv1.PortNumber(80)), + }, + { + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/orders"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "foo-orders-app", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, }, }, }, @@ -512,80 +523,43 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "nginx"}: { - ObjectMeta: metav1.ObjectMeta{Name: "nginx", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "nginx", - Listeners: []gatewayv1.Listener{ - { - Name: "bar-example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("bar.example.com")), - }, - { - Name: "foo-example-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("foo.example.com")), - }, - }, - }, - }, - }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ - {Namespace: "default", Name: "example-ingress-bar-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-bar-example-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "nginx", - }}, - }, - Hostnames: []gatewayv1.Hostname{"bar.example.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{ + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "nginx", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "nginx", + Listeners: []gatewayv1.Listener{ { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "bar-app", - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - Weight: ptrTo[int32](70), - }, + Name: "bar-example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("bar.example.com")), }, { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "bar-app-canary", - Port: ptrTo(gatewayv1.PortNumber(80)), - }, - Weight: ptrTo[int32](30), - }, + Name: "foo-example-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("foo.example.com")), }, }, - }}, + }, }, }, - {Namespace: "default", Name: "example-ingress-foo-example-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-foo-example-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "nginx", - }}, - }, - Hostnames: []gatewayv1.Hostname{"foo.example.com"}, - Rules: []gatewayv1.HTTPRouteRule{ - { + }, + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ + {Namespace: "default", Name: "example-ingress-bar-example-com"}: { + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-bar-example-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "nginx", + }}, + }, + Hostnames: []gatewayv1.Hostname{"bar.example.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ Matches: []gatewayv1.HTTPRouteMatch{{ Path: &gatewayv1.HTTPPathMatch{ Type: &gPathPrefix, @@ -596,27 +570,70 @@ func Test_ToGateway(t *testing.T) { { BackendRef: gatewayv1.BackendRef{ BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "foo-app", + Name: "bar-app", Port: ptrTo(gatewayv1.PortNumber(80)), }, + Weight: ptrTo[int32](70), }, }, - }, - }, - { - Matches: []gatewayv1.HTTPRouteMatch{{ - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/orders"), - }, - }}, - BackendRefs: []gatewayv1.HTTPBackendRef{ { BackendRef: gatewayv1.BackendRef{ BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "foo-orders-app", + Name: "bar-app-canary", Port: ptrTo(gatewayv1.PortNumber(80)), }, + Weight: ptrTo[int32](30), + }, + }, + }, + }}, + }, + }, + }, + {Namespace: "default", Name: "example-ingress-foo-example-com"}: { + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "example-ingress-foo-example-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "nginx", + }}, + }, + Hostnames: []gatewayv1.Hostname{"foo.example.com"}, + Rules: []gatewayv1.HTTPRouteRule{ + { + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "foo-app", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, + }, + }, + }, + { + Matches: []gatewayv1.HTTPRouteMatch{{ + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/orders"), + }, + }}, + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "foo-orders-app", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, }, }, }, @@ -638,7 +655,7 @@ func Test_ToGateway(t *testing.T) { nginxProvider := provider.(*Provider) nginxProvider.storage.Ingresses = tc.ingresses - gatewayResources, errs := provider.ToGatewayAPI() + ir, errs := provider.ToIR() if len(errs) != len(tc.expectedErrors) { t.Errorf("Expected %d errors, got %d: %+v", len(tc.expectedErrors), len(errs), errs) @@ -650,30 +667,30 @@ func Test_ToGateway(t *testing.T) { } } - if len(gatewayResources.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { + if len(ir.HTTPRoutes) != len(tc.expectedIR.HTTPRoutes) { t.Errorf("Expected %d HTTPRoutes, got %d: %+v", - len(tc.expectedGatewayResources.HTTPRoutes), len(gatewayResources.HTTPRoutes), gatewayResources.HTTPRoutes) + len(tc.expectedIR.HTTPRoutes), len(ir.HTTPRoutes), ir.HTTPRoutes) } else { - for i, got := range gatewayResources.HTTPRoutes { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.HTTPRoutes[key] - want.SetGroupVersionKind(common.HTTPRouteGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + for i, gotHTTPRouteContext := range ir.HTTPRoutes { + key := types.NamespacedName{Namespace: gotHTTPRouteContext.HTTPRoute.Namespace, Name: gotHTTPRouteContext.HTTPRoute.Name} + wantHTTPRouteContext := tc.expectedIR.HTTPRoutes[key] + wantHTTPRouteContext.HTTPRoute.SetGroupVersionKind(common.HTTPRouteGVK) + if !apiequality.Semantic.DeepEqual(gotHTTPRouteContext.HTTPRoute, wantHTTPRouteContext.HTTPRoute) { + t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, wantHTTPRouteContext.HTTPRoute, gotHTTPRouteContext.HTTPRoute, cmp.Diff(wantHTTPRouteContext.HTTPRoute, gotHTTPRouteContext.HTTPRoute)) } } } - if len(gatewayResources.Gateways) != len(tc.expectedGatewayResources.Gateways) { + if len(ir.Gateways) != len(tc.expectedIR.Gateways) { t.Errorf("Expected %d Gateways, got %d: %+v", - len(tc.expectedGatewayResources.Gateways), len(gatewayResources.Gateways), gatewayResources.Gateways) + len(tc.expectedIR.Gateways), len(ir.Gateways), ir.Gateways) } else { - for i, got := range gatewayResources.Gateways { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.Gateways[key] - want.SetGroupVersionKind(common.GatewayGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + for i, gotGatewayContext := range ir.Gateways { + key := types.NamespacedName{Namespace: gotGatewayContext.Gateway.Namespace, Name: gotGatewayContext.Gateway.Name} + wantGatewayContext := tc.expectedIR.Gateways[key] + wantGatewayContext.Gateway.SetGroupVersionKind(common.GatewayGVK) + if !apiequality.Semantic.DeepEqual(gotGatewayContext.Gateway, wantGatewayContext.Gateway) { + t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, wantGatewayContext.Gateway, gotGatewayContext.Gateway, cmp.Diff(wantGatewayContext.Gateway, gotGatewayContext.Gateway)) } } } diff --git a/pkg/i2gw/providers/ingressnginx/ingressnginx.go b/pkg/i2gw/providers/ingressnginx/ingressnginx.go index 8e0a33b7..71dad46a 100644 --- a/pkg/i2gw/providers/ingressnginx/ingressnginx.go +++ b/pkg/i2gw/providers/ingressnginx/ingressnginx.go @@ -21,6 +21,8 @@ import ( "fmt" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -34,24 +36,29 @@ func init() { // Provider implements the i2gw.Provider interface. type Provider struct { - storage *storage - resourceReader *resourceReader - converter *converter + storage *storage + resourceReader *resourceReader + resourcesToIRConverter *resourcesToIRConverter } // NewProvider constructs and returns the ingress-nginx implementation of i2gw.Provider. func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { return &Provider{ - storage: newResourcesStorage(), - resourceReader: newResourceReader(conf), - converter: newConverter(), + storage: newResourcesStorage(), + resourceReader: newResourceReader(conf), + resourcesToIRConverter: newResourcesToIRConverter(), } } -// ToGatewayAPI converts stored Ingress-Nginx API entities to i2gw.GatewayResources +// ToIR converts stored Ingress-Nginx API entities to intermediate.IR // including the ingress-nginx specific features. -func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - return p.converter.convert(p.storage) +func (p *Provider) ToIR() (intermediate.IR, field.ErrorList) { + return p.resourcesToIRConverter.convert(p.storage) +} + +func (p *Provider) ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + return common.ToGatewayResources(ir) + } func (p *Provider) ReadResourcesFromCluster(ctx context.Context) error { diff --git a/pkg/i2gw/providers/istio/converter.go b/pkg/i2gw/providers/istio/converter.go index b729a235..2e36de0f 100644 --- a/pkg/i2gw/providers/istio/converter.go +++ b/pkg/i2gw/providers/istio/converter.go @@ -23,7 +23,7 @@ import ( "regexp" "strings" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" istiov1beta1 "istio.io/api/networking/v1beta1" @@ -44,25 +44,25 @@ const ( virtualServiceKey contextKey = iota ) -type converter struct { +type resourcesToIRConverter struct { // gw -> namespace -> hosts; stores hosts allowed by each Gateway gwAllowedHosts map[types.NamespacedName]map[string]sets.Set[string] ctx context.Context } -func newConverter() converter { - return converter{ +func newResourcesToIRConverter() resourcesToIRConverter { + return resourcesToIRConverter{ gwAllowedHosts: make(map[types.NamespacedName]map[string]sets.Set[string]), ctx: context.Background(), } } -func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.ErrorList) { +func (c *resourcesToIRConverter) convertToIR(storage *storage) (intermediate.IR, field.ErrorList) { var errList field.ErrorList - gatewayResources := i2gw.GatewayResources{ - Gateways: make(map[types.NamespacedName]gatewayv1.Gateway), - HTTPRoutes: make(map[types.NamespacedName]gatewayv1.HTTPRoute), + gatewayResources := intermediate.IR{ + Gateways: make(map[types.NamespacedName]intermediate.GatewayContext), + HTTPRoutes: make(map[types.NamespacedName]intermediate.HTTPRouteContext), TLSRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TLSRoute), TCPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute), ReferenceGrants: make(map[types.NamespacedName]gatewayv1beta1.ReferenceGrant), @@ -80,7 +80,7 @@ func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.Erro gatewayResources.Gateways[types.NamespacedName{ Namespace: gw.Namespace, Name: gw.Name, - }] = *gw + }] = intermediate.GatewayContext{Gateway: *gw} } for _, vs := range storage.VirtualServices { @@ -104,7 +104,7 @@ func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.Erro gatewayResources.HTTPRoutes[types.NamespacedName{ Namespace: httpRoute.Namespace, Name: httpRoute.Name, - }] = *httpRoute + }] = intermediate.HTTPRouteContext{HTTPRoute: *httpRoute} } } @@ -132,10 +132,10 @@ func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.Erro } } - return gatewayResources, nil + return gatewayResources, errList } -func (c *converter) convertGateway(gw *istioclientv1beta1.Gateway, fieldPath *field.Path) (*gatewayv1.Gateway, field.ErrorList) { +func (c *resourcesToIRConverter) convertGateway(gw *istioclientv1beta1.Gateway, fieldPath *field.Path) (*gatewayv1.Gateway, field.ErrorList) { var errList field.ErrorList apiVersion, kind := common.GatewayGVK.ToAPIVersionAndKind() gwPath := fieldPath.Child("Gateway").Key(gw.Name) @@ -353,7 +353,7 @@ func convertHostnames(ctx context.Context, hosts []string, fieldPath *field.Path return resHostnames } -func (c *converter) convertVsHTTPRoutes(virtualService metav1.ObjectMeta, istioHTTPRoutes []*istiov1beta1.HTTPRoute, istioHTTPHosts []string, fieldPath *field.Path) ([]*gatewayv1.HTTPRoute, field.ErrorList) { +func (c *resourcesToIRConverter) convertVsHTTPRoutes(virtualService metav1.ObjectMeta, istioHTTPRoutes []*istiov1beta1.HTTPRoute, istioHTTPHosts []string, fieldPath *field.Path) ([]*gatewayv1.HTTPRoute, field.ErrorList) { var errList field.ErrorList var resHTTPRoutes []*gatewayv1.HTTPRoute @@ -719,7 +719,7 @@ type createHTTPRouteParams struct { timeouts *gatewayv1.HTTPRouteTimeouts } -func (c *converter) createHTTPRoute(params createHTTPRouteParams) *gatewayv1.HTTPRoute { +func (c *resourcesToIRConverter) createHTTPRoute(params createHTTPRouteParams) *gatewayv1.HTTPRoute { apiVersion, kind := common.HTTPRouteGVK.ToAPIVersionAndKind() return &gatewayv1.HTTPRoute{ @@ -754,7 +754,7 @@ func (c *converter) createHTTPRoute(params createHTTPRouteParams) *gatewayv1.HTT // And generates max 2 HTTPRoutes (one with prefix matches and ReplacePrefixMatch filter and the other if non-prefix matches and ReplaceFullPath filter). // If any of the match group is empty, the corresponding HTTPRoute won't be generated. // If all URI matches are empty, there would be HTTPRoute with HTTPRouteFilterURLRewrite of ReplaceFullPath type. -func (c *converter) createHTTPRoutesWithRewrite(params createHTTPRouteParams, rewrite *istiov1beta1.HTTPRewrite, fieldPath *field.Path) []*gatewayv1.HTTPRoute { +func (c *resourcesToIRConverter) createHTTPRoutesWithRewrite(params createHTTPRouteParams, rewrite *istiov1beta1.HTTPRewrite, fieldPath *field.Path) []*gatewayv1.HTTPRoute { vs := c.ctx.Value(virtualServiceKey).(*istioclientv1beta1.VirtualService) if rewrite == nil { return nil @@ -825,7 +825,7 @@ func (c *converter) createHTTPRoutesWithRewrite(params createHTTPRouteParams, re return resHTTPRoutes } -func (c *converter) convertVsTLSRoutes(virtualService metav1.ObjectMeta, istioTLSRoutes []*istiov1beta1.TLSRoute, fieldPath *field.Path) []*gatewayv1alpha2.TLSRoute { +func (c *resourcesToIRConverter) convertVsTLSRoutes(virtualService metav1.ObjectMeta, istioTLSRoutes []*istiov1beta1.TLSRoute, fieldPath *field.Path) []*gatewayv1alpha2.TLSRoute { var resTLSRoutes []*gatewayv1alpha2.TLSRoute vs := c.ctx.Value(virtualServiceKey).(*istioclientv1beta1.VirtualService) @@ -907,7 +907,7 @@ func (c *converter) convertVsTLSRoutes(virtualService metav1.ObjectMeta, istioTL return resTLSRoutes } -func (c *converter) convertVsTCPRoutes(virtualService metav1.ObjectMeta, istioTCPRoutes []*istiov1beta1.TCPRoute, fieldPath *field.Path) []*gatewayv1alpha2.TCPRoute { +func (c *resourcesToIRConverter) convertVsTCPRoutes(virtualService metav1.ObjectMeta, istioTCPRoutes []*istiov1beta1.TCPRoute, fieldPath *field.Path) []*gatewayv1alpha2.TCPRoute { var resTCPRoutes []*gatewayv1alpha2.TCPRoute vs := c.ctx.Value(virtualServiceKey).(*istioclientv1beta1.VirtualService) @@ -986,7 +986,7 @@ func (c *converter) convertVsTCPRoutes(virtualService metav1.ObjectMeta, istioTC return resTCPRoutes } -func (c *converter) isVirtualServiceAllowedForGateway(gateway types.NamespacedName, vs *istioclientv1beta1.VirtualService, fieldPath *field.Path) bool { +func (c *resourcesToIRConverter) isVirtualServiceAllowedForGateway(gateway types.NamespacedName, vs *istioclientv1beta1.VirtualService, fieldPath *field.Path) bool { // by default, if ExportTo is empty it allowes export of the VirtualService to all namespaces vsAllowedNamespaces := sets.New("*") if len(vs.Spec.GetExportTo()) > 0 { @@ -1034,7 +1034,7 @@ func (c *converter) isVirtualServiceAllowedForGateway(gateway types.NamespacedNa // Generate parentRefs and optionally ReferenceGrants for the given VirtualService and all required Gateways // We consider fields: vs.Spec.Gateways; gateway.Server[i].Hosts -func (c *converter) generateReferences(vs *istioclientv1beta1.VirtualService, fieldPath *field.Path) ([]gatewayv1.ParentReference, []*gatewayv1beta1.ReferenceGrant) { +func (c *resourcesToIRConverter) generateReferences(vs *istioclientv1beta1.VirtualService, fieldPath *field.Path) ([]gatewayv1.ParentReference, []*gatewayv1beta1.ReferenceGrant) { var ( parentRefs []gatewayv1.ParentReference referenceGrants []*gatewayv1beta1.ReferenceGrant @@ -1097,7 +1097,7 @@ type generateReferenceGrantsParams struct { forHTTPRoute, forTLSRoute, forTCPRoute bool } -func (c *converter) generateReferenceGrant(params generateReferenceGrantsParams) *gatewayv1beta1.ReferenceGrant { +func (c *resourcesToIRConverter) generateReferenceGrant(params generateReferenceGrantsParams) *gatewayv1beta1.ReferenceGrant { var fromGrants []gatewayv1beta1.ReferenceGrantFrom if params.forHTTPRoute { diff --git a/pkg/i2gw/providers/istio/converter_test.go b/pkg/i2gw/providers/istio/converter_test.go index 55505e4f..764a34cb 100644 --- a/pkg/i2gw/providers/istio/converter_test.go +++ b/pkg/i2gw/providers/istio/converter_test.go @@ -37,7 +37,7 @@ import ( gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) -func Test_converter_convertGateway(t *testing.T) { +func Test_resourcesToIRConverter_convertGateway(t *testing.T) { type args struct { gw *istioclientv1beta1.Gateway } @@ -326,14 +326,14 @@ func Test_converter_convertGateway(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := newConverter() + c := newResourcesToIRConverter() got, errList := c.convertGateway(tt.args.gw, field.NewPath("")) if tt.wantError && len(errList) == 0 { - t.Errorf("converter.convertGateway().errList = %+v, wantError %+v", errList, tt.wantError) + t.Errorf("resourcesToIRConverter.convertGateway().errList = %+v, wantError %+v", errList, tt.wantError) } if !apiequality.Semantic.DeepEqual(got, tt.wantGateway) { - t.Errorf("converter.convertGateway().gateway = %+v, want %+v, diff (-want +got): %s", got, tt.wantGateway, cmp.Diff(tt.wantGateway, got)) + t.Errorf("resourcesToIRConverter.convertGateway().gateway = %+v, want %+v, diff (-want +got): %s", got, tt.wantGateway, cmp.Diff(tt.wantGateway, got)) } if got := c.gwAllowedHosts; !apiequality.Semantic.DeepEqual(got, tt.wantAllowedHosts) { @@ -343,7 +343,7 @@ func Test_converter_convertGateway(t *testing.T) { } } -func Test_converter_convertVsHTTPRoutes(t *testing.T) { +func Test_resourcesToIRConverter_convertVsHTTPRoutes(t *testing.T) { type args struct { virtualService *istioclientv1beta1.VirtualService istioHTTPRoutes []*istiov1beta1.HTTPRoute @@ -1378,20 +1378,20 @@ func Test_converter_convertVsHTTPRoutes(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := &converter{ctx: context.Background()} + c := &resourcesToIRConverter{ctx: context.Background()} c.ctx = context.WithValue(c.ctx, virtualServiceKey, tt.args.virtualService) httpRoutes, errList := c.convertVsHTTPRoutes(tt.args.virtualService.ObjectMeta, tt.args.istioHTTPRoutes, tt.args.allowedHostnames, field.NewPath("")) if tt.wantError && len(errList) == 0 { - t.Errorf("converter.convertVsHTTPRoutes().errList = %+v, wantError %+v", errList, tt.wantError) + t.Errorf("resourcesToIRConverter.convertVsHTTPRoutes().errList = %+v, wantError %+v", errList, tt.wantError) } if !apiequality.Semantic.DeepEqual(httpRoutes, tt.want) { - t.Errorf("converter.convertVsHTTPRoutes().httpRoutes = %v, want %v, diff (-want +got): %s", httpRoutes, tt.want, cmp.Diff(tt.want, httpRoutes)) + t.Errorf("resourcesToIRConverter.convertVsHTTPRoutes().httpRoutes = %v, want %v, diff (-want +got): %s", httpRoutes, tt.want, cmp.Diff(tt.want, httpRoutes)) } }) } } -func Test_converter_convertVsTLSRoutes(t *testing.T) { +func Test_resourcesToIRConverter_convertVsTLSRoutes(t *testing.T) { type args struct { virtualService *istioclientv1beta1.VirtualService istioTLSRoutes []*istiov1beta1.TLSRoute @@ -1507,16 +1507,16 @@ func Test_converter_convertVsTLSRoutes(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := &converter{ctx: context.Background()} + c := &resourcesToIRConverter{ctx: context.Background()} c.ctx = context.WithValue(c.ctx, virtualServiceKey, tt.args.virtualService) if got := c.convertVsTLSRoutes(tt.args.virtualService.ObjectMeta, tt.args.istioTLSRoutes, field.NewPath("")); !apiequality.Semantic.DeepEqual(got, tt.want) { - t.Errorf("converter.convertVsTLSRoutes() = %+v, want %+v, diff (-want +got): %s", got, tt.want, cmp.Diff(tt.want, got)) + t.Errorf("resourcesToIRConverter.convertVsTLSRoutes() = %+v, want %+v, diff (-want +got): %s", got, tt.want, cmp.Diff(tt.want, got)) } }) } } -func Test_converter_convertVsTCPRoutes(t *testing.T) { +func Test_resourcesToIRConverter_convertVsTCPRoutes(t *testing.T) { type args struct { virtualService *istioclientv1beta1.VirtualService istioTCPRoutes []*istiov1beta1.TCPRoute @@ -1619,10 +1619,10 @@ func Test_converter_convertVsTCPRoutes(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := &converter{ctx: context.Background()} + c := &resourcesToIRConverter{ctx: context.Background()} c.ctx = context.WithValue(c.ctx, virtualServiceKey, tt.args.virtualService) if got := c.convertVsTCPRoutes(tt.args.virtualService.ObjectMeta, tt.args.istioTCPRoutes, field.NewPath("")); !apiequality.Semantic.DeepEqual(got, tt.want) { - t.Errorf("converter.convertVsTCPRoutes() = %+v, want %+v, diff (-want +got): %s", got, tt.want, cmp.Diff(tt.want, got)) + t.Errorf("resourcesToIRConverter.convertVsTCPRoutes() = %+v, want %+v, diff (-want +got): %s", got, tt.want, cmp.Diff(tt.want, got)) } }) } @@ -1702,7 +1702,7 @@ func TestNameMatches(t *testing.T) { } } -func Test_converter_generateReferenceGrants(t *testing.T) { +func Test_resourcesToIRConverter_generateReferenceGrants(t *testing.T) { type args struct { params generateReferenceGrantsParams } @@ -1765,15 +1765,15 @@ func Test_converter_generateReferenceGrants(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := &converter{} + c := &resourcesToIRConverter{} if got := c.generateReferenceGrant(tt.args.params); !apiequality.Semantic.DeepEqual(got, tt.want) { - t.Errorf("converter.generateReferenceGrant() = %+v, want %+v, diff (-want +got): %s", got, tt.want, cmp.Diff(tt.want, got)) + t.Errorf("resourcesToIRConverter.generateReferenceGrant() = %+v, want %+v, diff (-want +got): %s", got, tt.want, cmp.Diff(tt.want, got)) } }) } } -func Test_converter_isGatewayAllowedForVirtualService(t *testing.T) { +func Test_resourcesToIRConverter_isGatewayAllowedForVirtualService(t *testing.T) { type fields struct { gwAllowedHosts map[types.NamespacedName]map[string]sets.Set[string] } @@ -1947,17 +1947,17 @@ func Test_converter_isGatewayAllowedForVirtualService(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := &converter{ + c := &resourcesToIRConverter{ gwAllowedHosts: tt.fields.gwAllowedHosts, } if got := c.isVirtualServiceAllowedForGateway(tt.args.gateway, tt.args.vs, field.NewPath("")); got != tt.want { - t.Errorf("converter.isVirtualServiceAllowedForGateway() = %v, want %v", got, tt.want) + t.Errorf("resourcesToIRConverter.isVirtualServiceAllowedForGateway() = %v, want %v", got, tt.want) } }) } } -func Test_converter_generateReferences(t *testing.T) { +func Test_resourcesToIRConverter_generateReferences(t *testing.T) { type fields struct { gwAllowedHosts map[types.NamespacedName]map[string]sets.Set[string] } @@ -2084,15 +2084,15 @@ func Test_converter_generateReferences(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := &converter{ + c := &resourcesToIRConverter{ gwAllowedHosts: tt.fields.gwAllowedHosts, } gotParentReferences, gotReferenceGrants := c.generateReferences(tt.args.vs, field.NewPath("")) if !apiequality.Semantic.DeepEqual(gotParentReferences, tt.wantParentReferences) { - t.Errorf("converter.generateReferences() gotParentReferences = %v, want %v, diff (-want +got): %s", gotParentReferences, tt.wantParentReferences, cmp.Diff(tt.wantParentReferences, gotParentReferences)) + t.Errorf("resourcesToIRConverter.generateReferences() gotParentReferences = %v, want %v, diff (-want +got): %s", gotParentReferences, tt.wantParentReferences, cmp.Diff(tt.wantParentReferences, gotParentReferences)) } if !apiequality.Semantic.DeepEqual(gotReferenceGrants, tt.wantReferenceGrants) { - t.Errorf("converter.generateReferences() gotReferenceGrants = %v, want %v, diff (-want +got): %s", gotReferenceGrants, tt.wantReferenceGrants, cmp.Diff(tt.wantReferenceGrants, gotReferenceGrants)) + t.Errorf("resourcesToIRConverter.generateReferences() gotReferenceGrants = %v, want %v, diff (-want +got): %s", gotReferenceGrants, tt.wantReferenceGrants, cmp.Diff(tt.wantReferenceGrants, gotReferenceGrants)) } }) } diff --git a/pkg/i2gw/providers/istio/e2e_file_converter_test.go b/pkg/i2gw/providers/istio/e2e_file_converter_test.go index c9b35b18..63f49145 100644 --- a/pkg/i2gw/providers/istio/e2e_file_converter_test.go +++ b/pkg/i2gw/providers/istio/e2e_file_converter_test.go @@ -56,9 +56,13 @@ func TestFileConversion(t *testing.T) { t.Fatalf("Failed to read input from file %v: %v", d.Name(), err.Error()) } - gotGatewayResources, errList := istioProvider.ToGatewayAPI() + ir, errList := istioProvider.ToIR() if len(errList) > 0 { - t.Fatalf("unexpected errors during input conversion for file %v: %v", d.Name(), errList.ToAggregate().Error()) + t.Fatalf("unexpected errors during input conversion to ir for file %v: %v", d.Name(), errList.ToAggregate().Error()) + } + gotGatewayResources, errList := istioProvider.ToGatewayResources(ir) + if len(errList) > 0 { + t.Fatalf("unexpected errors during ir conversion to Gateway for file %v: %v", d.Name(), errList.ToAggregate().Error()) } outputFile := filepath.Join(fixturesDir, "output", d.Name()) diff --git a/pkg/i2gw/providers/istio/istio.go b/pkg/i2gw/providers/istio/istio.go index 97aa55b3..71bccac9 100644 --- a/pkg/i2gw/providers/istio/istio.go +++ b/pkg/i2gw/providers/istio/istio.go @@ -21,6 +21,8 @@ import ( "fmt" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -32,24 +34,28 @@ func init() { } type Provider struct { - storage *storage - reader reader - converter converter + storage *storage + reader reader + resourcesToIRConverter resourcesToIRConverter } // NewProvider returns the istio implementation of i2gw.Provider. func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { return &Provider{ - storage: newResourcesStorage(), - reader: newResourceReader(conf), - converter: newConverter(), + storage: newResourcesStorage(), + reader: newResourceReader(conf), + resourcesToIRConverter: newResourcesToIRConverter(), } } -// ToGatewayAPI converts stored Istio API entities to i2gw.GatewayResources +// ToIR converts stored Istio API entities to intermediate.IR // K8S Ingress resources are not needed, only Istio-based are converted -func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - return p.converter.convert(p.storage) +func (p *Provider) ToIR() (intermediate.IR, field.ErrorList) { + return p.resourcesToIRConverter.convertToIR(p.storage) +} + +func (p *Provider) ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + return common.ToGatewayResources(ir) } func (p *Provider) ReadResourcesFromCluster(ctx context.Context) error { diff --git a/pkg/i2gw/providers/kong/converter.go b/pkg/i2gw/providers/kong/converter.go index d4d320b4..ae4deb0a 100644 --- a/pkg/i2gw/providers/kong/converter.go +++ b/pkg/i2gw/providers/kong/converter.go @@ -21,19 +21,20 @@ import ( "k8s.io/apimachinery/pkg/util/validation/field" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/kong/crds" ) -// converter implements the ToGatewayAPI function of i2gw.ResourceConverter interface. -type converter struct { +// resourcesToIRConverter implements the ToIR function of i2gw.ResourcesToIRConverter interface. +type resourcesToIRConverter struct { featureParsers []i2gw.FeatureParser implementationSpecificOptions i2gw.ProviderImplementationSpecificOptions } -// newConverter returns an kong converter instance. -func newConverter() *converter { - return &converter{ +// newResourcesToIRConverter returns an kong converter instance. +func newResourcesToIRConverter() *resourcesToIRConverter { + return &resourcesToIRConverter{ featureParsers: []i2gw.FeatureParser{ headerMatchingFeature, methodMatchingFeature, @@ -45,22 +46,20 @@ func newConverter() *converter { } } -func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.ErrorList) { +func (c *resourcesToIRConverter) convert(storage *storage) (intermediate.IR, field.ErrorList) { ingressList := []networkingv1.Ingress{} for _, ingress := range storage.Ingresses { ingressList = append(ingressList, *ingress) } - errorList := field.ErrorList{} - // Convert plain ingress resources to gateway resources, ignoring all // provider-specific features. - gatewayResources, errs := common.ToGateway(ingressList, c.implementationSpecificOptions) - if len(errs) > 0 { - errorList = append(errorList, errs...) + ir, errorList := common.ToIR(ingressList, c.implementationSpecificOptions) + if len(errorList) > 0 { + return intermediate.IR{}, errorList } - tcpGatewayResources, notificationsAggregator, errs := crds.TCPIngressToGatewayAPI(storage.TCPIngresses) + tcpGatewayIR, notificationsAggregator, errs := crds.TCPIngressToGatewayIR(storage.TCPIngresses) if len(errs) > 0 { errorList = append(errorList, errs...) } @@ -68,20 +67,21 @@ func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.Erro dispatchNotification(notificationsAggregator) if len(errorList) > 0 { - return i2gw.GatewayResources{}, errorList + return intermediate.IR{}, errorList } - gatewayResources, errs = i2gw.MergeGatewayResources(gatewayResources, tcpGatewayResources) + ir, errs = intermediate.MergeIRs(ir, tcpGatewayIR) + if len(errs) > 0 { - return i2gw.GatewayResources{}, errs + return intermediate.IR{}, errs } for _, parseFeatureFunc := range c.featureParsers { // Apply the feature parsing function to the gateway resources, one by one. - errs = parseFeatureFunc(ingressList, &gatewayResources) + errs = parseFeatureFunc(ingressList, &ir) // Append the parsing errors to the error list. errorList = append(errorList, errs...) } - return gatewayResources, errorList + return ir, errorList } diff --git a/pkg/i2gw/providers/kong/converter_test.go b/pkg/i2gw/providers/kong/converter_test.go index aa84fefc..830ac468 100644 --- a/pkg/i2gw/providers/kong/converter_test.go +++ b/pkg/i2gw/providers/kong/converter_test.go @@ -22,6 +22,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" @@ -38,10 +39,10 @@ func Test_ToGateway(t *testing.T) { gPathRegex := gatewayv1.PathMatchRegularExpression testCases := []struct { - name string - ingresses map[types.NamespacedName]*networkingv1.Ingress - expectedGatewayResources i2gw.GatewayResources - expectedErrors field.ErrorList + name string + ingresses map[types.NamespacedName]*networkingv1.Ingress + expectedIR intermediate.IR + expectedErrors field.ErrorList }{ { name: "header matching, method matching, plugin, single ingress rule", @@ -80,81 +81,85 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "ingress-kong"}: { - ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "ingress-kong", - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "ingress-kong", + Listeners: []gatewayv1.Listener{{ + Name: "test-mydomain-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "default", Name: "multiple-matching-single-rule-test-mydomain-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "multiple-matching-single-rule-test-mydomain-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "ingress-kong", - }}, - }, - Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, - Rules: []gatewayv1.HTTPRouteRule{{ - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - Headers: []gatewayv1.HTTPHeaderMatch{ - { - Name: "key1", - Value: "val1", + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "multiple-matching-single-rule-test-mydomain-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "ingress-kong", + }}, + }, + Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, + Rules: []gatewayv1.HTTPRouteRule{{ + Matches: []gatewayv1.HTTPRouteMatch{ + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/"), }, + Headers: []gatewayv1.HTTPHeaderMatch{ + { + Name: "key1", + Value: "val1", + }, + }, + Method: ptrTo(gatewayv1.HTTPMethodGet), }, - Method: ptrTo(gatewayv1.HTTPMethodGet), - }, - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/"), - }, - Headers: []gatewayv1.HTTPHeaderMatch{ - { - Name: "key1", - Value: "val1", + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/"), + }, + Headers: []gatewayv1.HTTPHeaderMatch{ + { + Name: "key1", + Value: "val1", + }, }, + Method: ptrTo(gatewayv1.HTTPMethodPost), }, - Method: ptrTo(gatewayv1.HTTPMethodPost), }, - }, - Filters: []gatewayv1.HTTPRouteFilter{ - { - Type: gatewayv1.HTTPRouteFilterExtensionRef, - ExtensionRef: &gatewayv1.LocalObjectReference{ - Group: gatewayv1.Group(kongResourcesGroup), - Kind: gatewayv1.Kind(kongPluginKind), - Name: gatewayv1.ObjectName("plugin1"), + Filters: []gatewayv1.HTTPRouteFilter{ + { + Type: gatewayv1.HTTPRouteFilterExtensionRef, + ExtensionRef: &gatewayv1.LocalObjectReference{ + Group: gatewayv1.Group(kongResourcesGroup), + Kind: gatewayv1.Kind(kongPluginKind), + Name: gatewayv1.ObjectName("plugin1"), + }, }, }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "test", - Port: ptrTo(gatewayv1.PortNumber(80)), + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "test", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, }, }, }, - }, - }}, + }}, + }, }, }, }, @@ -211,107 +216,111 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "ingress-kong"}: { - ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "ingress-kong", - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "ingress-kong", + Listeners: []gatewayv1.Listener{{ + Name: "test-mydomain-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "default", Name: "multiple-matching-multiple-rules-test-mydomain-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "multiple-matching-multiple-rules-test-mydomain-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "ingress-kong", - }}, - }, - Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/first"), - }, - Headers: []gatewayv1.HTTPHeaderMatch{ - { - Name: "key1", - Value: "val1", + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "multiple-matching-multiple-rules-test-mydomain-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "ingress-kong", + }}, + }, + Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, + Rules: []gatewayv1.HTTPRouteRule{ + { + Matches: []gatewayv1.HTTPRouteMatch{ + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/first"), }, + Headers: []gatewayv1.HTTPHeaderMatch{ + { + Name: "key1", + Value: "val1", + }, + }, + Method: ptrTo(gatewayv1.HTTPMethodGet), }, - Method: ptrTo(gatewayv1.HTTPMethodGet), - }, - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/first"), - }, - Headers: []gatewayv1.HTTPHeaderMatch{ - { - Name: "key1", - Value: "val1", + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/first"), + }, + Headers: []gatewayv1.HTTPHeaderMatch{ + { + Name: "key1", + Value: "val1", + }, }, + Method: ptrTo(gatewayv1.HTTPMethodPost), }, - Method: ptrTo(gatewayv1.HTTPMethodPost), }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "test-first", - Port: ptrTo(gatewayv1.PortNumber(80)), + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "test-first", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, }, }, }, }, - }, - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/second"), - }, - Headers: []gatewayv1.HTTPHeaderMatch{ - { - Name: "key1", - Value: "val1", + { + Matches: []gatewayv1.HTTPRouteMatch{ + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/second"), }, + Headers: []gatewayv1.HTTPHeaderMatch{ + { + Name: "key1", + Value: "val1", + }, + }, + Method: ptrTo(gatewayv1.HTTPMethodGet), }, - Method: ptrTo(gatewayv1.HTTPMethodGet), - }, - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/second"), - }, - Headers: []gatewayv1.HTTPHeaderMatch{ - { - Name: "key1", - Value: "val1", + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/second"), + }, + Headers: []gatewayv1.HTTPHeaderMatch{ + { + Name: "key1", + Value: "val1", + }, }, + Method: ptrTo(gatewayv1.HTTPMethodPost), }, - Method: ptrTo(gatewayv1.HTTPMethodPost), }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "test-second", - Port: ptrTo(gatewayv1.PortNumber(80)), + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "test-second", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, }, }, }, @@ -356,47 +365,51 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "ingress-kong"}: { - ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "ingress-kong", - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "ingress-kong", + Listeners: []gatewayv1.Listener{{ + Name: "test-mydomain-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "default", Name: "implementation-specific-regex-test-mydomain-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "implementation-specific-regex-test-mydomain-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "ingress-kong", - }}, - }, - Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathRegex, - Value: ptrTo("/echo/**/test"), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "implementation-specific-regex-test-mydomain-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "ingress-kong", + }}, + }, + Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, + Rules: []gatewayv1.HTTPRouteRule{ + { + Matches: []gatewayv1.HTTPRouteMatch{ + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathRegex, + Value: ptrTo("/echo/**/test"), + }, }, }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "test", - Port: ptrTo(gatewayv1.PortNumber(80)), + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "test", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, }, }, }, @@ -441,47 +454,51 @@ func Test_ToGateway(t *testing.T) { }, }, }, - expectedGatewayResources: i2gw.GatewayResources{ - Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ {Namespace: "default", Name: "ingress-kong"}: { - ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, - Spec: gatewayv1.GatewaySpec{ - GatewayClassName: "ingress-kong", - Listeners: []gatewayv1.Listener{{ - Name: "test-mydomain-com-http", - Port: 80, - Protocol: gatewayv1.HTTPProtocolType, - Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), - }}, + Gateway: gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: "ingress-kong", Namespace: "default"}, + Spec: gatewayv1.GatewaySpec{ + GatewayClassName: "ingress-kong", + Listeners: []gatewayv1.Listener{{ + Name: "test-mydomain-com-http", + Port: 80, + Protocol: gatewayv1.HTTPProtocolType, + Hostname: ptrTo(gatewayv1.Hostname("test.mydomain.com")), + }}, + }, }, }, }, - HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ {Namespace: "default", Name: "implementation-specific-no-regex-test-mydomain-com"}: { - ObjectMeta: metav1.ObjectMeta{Name: "implementation-specific-no-regex-test-mydomain-com", Namespace: "default"}, - Spec: gatewayv1.HTTPRouteSpec{ - CommonRouteSpec: gatewayv1.CommonRouteSpec{ - ParentRefs: []gatewayv1.ParentReference{{ - Name: "ingress-kong", - }}, - }, - Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, - Rules: []gatewayv1.HTTPRouteRule{ - { - Matches: []gatewayv1.HTTPRouteMatch{ - { - Path: &gatewayv1.HTTPPathMatch{ - Type: &gPathPrefix, - Value: ptrTo("/echo"), + HTTPRoute: gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: "implementation-specific-no-regex-test-mydomain-com", Namespace: "default"}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: "ingress-kong", + }}, + }, + Hostnames: []gatewayv1.Hostname{"test.mydomain.com"}, + Rules: []gatewayv1.HTTPRouteRule{ + { + Matches: []gatewayv1.HTTPRouteMatch{ + { + Path: &gatewayv1.HTTPPathMatch{ + Type: &gPathPrefix, + Value: ptrTo("/echo"), + }, }, }, - }, - BackendRefs: []gatewayv1.HTTPBackendRef{ - { - BackendRef: gatewayv1.BackendRef{ - BackendObjectReference: gatewayv1.BackendObjectReference{ - Name: "test", - Port: ptrTo(gatewayv1.PortNumber(80)), + BackendRefs: []gatewayv1.HTTPBackendRef{ + { + BackendRef: gatewayv1.BackendRef{ + BackendObjectReference: gatewayv1.BackendObjectReference{ + Name: "test", + Port: ptrTo(gatewayv1.PortNumber(80)), + }, }, }, }, @@ -504,32 +521,32 @@ func Test_ToGateway(t *testing.T) { kongProvider.storage = newResourceStorage() kongProvider.storage.Ingresses = tc.ingresses - gatewayResources, errs := provider.ToGatewayAPI() + ir, errs := provider.ToIR() - if len(gatewayResources.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { + if len(ir.HTTPRoutes) != len(tc.expectedIR.HTTPRoutes) { t.Errorf("Expected %d HTTPRoutes, got %d: %+v", - len(tc.expectedGatewayResources.HTTPRoutes), len(gatewayResources.HTTPRoutes), gatewayResources.HTTPRoutes) + len(tc.expectedIR.HTTPRoutes), len(ir.HTTPRoutes), ir.HTTPRoutes) } else { - for i, got := range gatewayResources.HTTPRoutes { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.HTTPRoutes[key] - want.SetGroupVersionKind(common.HTTPRouteGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + for i, gotHTTPRouteContext := range ir.HTTPRoutes { + key := types.NamespacedName{Namespace: gotHTTPRouteContext.HTTPRoute.Namespace, Name: gotHTTPRouteContext.HTTPRoute.Name} + wantHTTPRouteContext := tc.expectedIR.HTTPRoutes[key] + wantHTTPRouteContext.HTTPRoute.SetGroupVersionKind(common.HTTPRouteGVK) + if !apiequality.Semantic.DeepEqual(gotHTTPRouteContext.HTTPRoute, wantHTTPRouteContext.HTTPRoute) { + t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, wantHTTPRouteContext.HTTPRoute, gotHTTPRouteContext.HTTPRoute, cmp.Diff(wantHTTPRouteContext.HTTPRoute, gotHTTPRouteContext.HTTPRoute)) } } } - if len(gatewayResources.Gateways) != len(tc.expectedGatewayResources.Gateways) { + if len(ir.Gateways) != len(tc.expectedIR.Gateways) { t.Errorf("Expected %d Gateways, got %d: %+v", - len(tc.expectedGatewayResources.Gateways), len(gatewayResources.Gateways), gatewayResources.Gateways) + len(tc.expectedIR.Gateways), len(ir.Gateways), ir.Gateways) } else { - for i, got := range gatewayResources.Gateways { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} - want := tc.expectedGatewayResources.Gateways[key] - want.SetGroupVersionKind(common.GatewayGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + for i, gotGatewayContext := range ir.Gateways { + key := types.NamespacedName{Namespace: gotGatewayContext.Gateway.Namespace, Name: gotGatewayContext.Gateway.Name} + wantGatewayContext := tc.expectedIR.Gateways[key] + wantGatewayContext.Gateway.SetGroupVersionKind(common.GatewayGVK) + if !apiequality.Semantic.DeepEqual(gotGatewayContext.Gateway, wantGatewayContext.Gateway) { + t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, wantGatewayContext.Gateway, gotGatewayContext.Gateway, cmp.Diff(wantGatewayContext.Gateway, gotGatewayContext.Gateway)) } } } diff --git a/pkg/i2gw/providers/kong/crds/tcpingress.go b/pkg/i2gw/providers/kong/crds/tcpingress.go index c01b6a4a..fa017c4e 100644 --- a/pkg/i2gw/providers/kong/crds/tcpingress.go +++ b/pkg/i2gw/providers/kong/crds/tcpingress.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1beta1 "k8s.io/api/networking/v1beta1" @@ -34,8 +34,8 @@ import ( kongv1beta1 "github.com/kong/kubernetes-ingress-controller/v2/pkg/apis/configuration/v1beta1" ) -// TCPIngressToGatewayAPI converts the received TCPingresses to i2gw.GatewayResources, -func TCPIngressToGatewayAPI(ingresses []kongv1beta1.TCPIngress) (i2gw.GatewayResources, []notifications.Notification, field.ErrorList) { +// TCPIngressToGatewayIR converts the received TCPingresses to intermediate.IR, +func TCPIngressToGatewayIR(ingresses []kongv1beta1.TCPIngress) (intermediate.IR, []notifications.Notification, field.ErrorList) { aggregator := tcpIngressAggregator{ruleGroups: map[ruleGroupKey]*tcpIngressRuleGroup{}} var notificationsAggregator []notifications.Notification @@ -44,12 +44,12 @@ func TCPIngressToGatewayAPI(ingresses []kongv1beta1.TCPIngress) (i2gw.GatewayRes aggregator.addIngress(ingress, ¬ificationsAggregator) } if len(errs) > 0 { - return i2gw.GatewayResources{}, notificationsAggregator, errs + return intermediate.IR{}, notificationsAggregator, errs } tcpRoutes, tlsRoutes, gateways, errs := aggregator.toRoutesAndGateways() if len(errs) > 0 { - return i2gw.GatewayResources{}, notificationsAggregator, errs + return intermediate.IR{}, notificationsAggregator, errs } tcpRouteByKey := make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute) @@ -64,13 +64,13 @@ func TCPIngressToGatewayAPI(ingresses []kongv1beta1.TCPIngress) (i2gw.GatewayRes tlsRouteByKey[key] = route } - gatewayByKey := make(map[types.NamespacedName]gatewayv1.Gateway) + gatewayByKey := make(map[types.NamespacedName]intermediate.GatewayContext) for _, gateway := range gateways { key := types.NamespacedName{Namespace: gateway.Namespace, Name: gateway.Name} - gatewayByKey[key] = gateway + gatewayByKey[key] = intermediate.GatewayContext{Gateway: gateway} } - return i2gw.GatewayResources{ + return intermediate.IR{ Gateways: gatewayByKey, TCPRoutes: tcpRouteByKey, TLSRoutes: tlsRouteByKey, diff --git a/pkg/i2gw/providers/kong/crds/tcpingress_test.go b/pkg/i2gw/providers/kong/crds/tcpingress_test.go index 7ba51c87..e0c9bd5b 100644 --- a/pkg/i2gw/providers/kong/crds/tcpingress_test.go +++ b/pkg/i2gw/providers/kong/crds/tcpingress_test.go @@ -204,41 +204,41 @@ func TestTCPIngressToGatewayAPI(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - gatewayResources, _, errs := TCPIngressToGatewayAPI(tc.tcpIngresses) + ir, _, errs := TCPIngressToGatewayIR(tc.tcpIngresses) - if len(gatewayResources.Gateways) != len(tc.expectedGatewayResources.Gateways) { + if len(ir.Gateways) != len(tc.expectedGatewayResources.Gateways) { t.Errorf("Expected %d Gateways, got %d: %+v", - len(tc.expectedGatewayResources.Gateways), len(gatewayResources.Gateways), gatewayResources.Gateways) + len(tc.expectedGatewayResources.Gateways), len(ir.Gateways), ir.Gateways) } else { - for i, got := range gatewayResources.Gateways { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} + for i, gotGatewayContext := range ir.Gateways { + key := types.NamespacedName{Namespace: gotGatewayContext.Gateway.Namespace, Name: gotGatewayContext.Gateway.Name} want := tc.expectedGatewayResources.Gateways[key] want.SetGroupVersionKind(common.GatewayGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + if !apiequality.Semantic.DeepEqual(gotGatewayContext.Gateway, want) { + t.Errorf("Expected Gateway %s to be %+v\n Got: %+v\n Diff: %s", i, want, gotGatewayContext.Gateway, cmp.Diff(want, gotGatewayContext.Gateway)) } } } - if len(gatewayResources.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { + if len(ir.HTTPRoutes) != len(tc.expectedGatewayResources.HTTPRoutes) { t.Errorf("Expected %d HTTPRoutes, got %d: %+v", - len(tc.expectedGatewayResources.HTTPRoutes), len(gatewayResources.HTTPRoutes), gatewayResources.HTTPRoutes) + len(tc.expectedGatewayResources.HTTPRoutes), len(ir.HTTPRoutes), ir.HTTPRoutes) } else { - for i, got := range gatewayResources.HTTPRoutes { - key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} + for i, gotHTTPRouteContext := range ir.HTTPRoutes { + key := types.NamespacedName{Namespace: gotHTTPRouteContext.HTTPRoute.Namespace, Name: gotHTTPRouteContext.HTTPRoute.Name} want := tc.expectedGatewayResources.HTTPRoutes[key] want.SetGroupVersionKind(common.HTTPRouteGVK) - if !apiequality.Semantic.DeepEqual(got, want) { - t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, got, cmp.Diff(want, got)) + if !apiequality.Semantic.DeepEqual(gotHTTPRouteContext.HTTPRoute, want) { + t.Errorf("Expected HTTPRoute %s to be %+v\n Got: %+v\n Diff: %s", i, want, gotHTTPRouteContext.HTTPRoute, cmp.Diff(want, gotHTTPRouteContext.HTTPRoute)) } } } - if len(gatewayResources.TCPRoutes) != len(tc.expectedGatewayResources.TCPRoutes) { + if len(ir.TCPRoutes) != len(tc.expectedGatewayResources.TCPRoutes) { t.Errorf("Expected %d TCPRoutes, got %d: %+v", - len(tc.expectedGatewayResources.TCPRoutes), len(gatewayResources.TCPRoutes), gatewayResources.TCPRoutes) + len(tc.expectedGatewayResources.TCPRoutes), len(ir.TCPRoutes), ir.TCPRoutes) } else { - for i, got := range gatewayResources.TCPRoutes { + for i, got := range ir.TCPRoutes { key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} want := tc.expectedGatewayResources.TCPRoutes[key] want.SetGroupVersionKind(common.TCPRouteGVK) @@ -248,11 +248,11 @@ func TestTCPIngressToGatewayAPI(t *testing.T) { } } - if len(gatewayResources.TLSRoutes) != len(tc.expectedGatewayResources.TLSRoutes) { + if len(ir.TLSRoutes) != len(tc.expectedGatewayResources.TLSRoutes) { t.Errorf("Expected %d TLSRoutes, got %d: %+v", - len(tc.expectedGatewayResources.TLSRoutes), len(gatewayResources.TLSRoutes), gatewayResources.TLSRoutes) + len(tc.expectedGatewayResources.TLSRoutes), len(ir.TLSRoutes), ir.TLSRoutes) } else { - for i, got := range gatewayResources.TLSRoutes { + for i, got := range ir.TLSRoutes { key := types.NamespacedName{Namespace: got.Namespace, Name: got.Name} want := tc.expectedGatewayResources.TLSRoutes[key] want.SetGroupVersionKind(common.TLSRouteGVK) diff --git a/pkg/i2gw/providers/kong/header_matching.go b/pkg/i2gw/providers/kong/header_matching.go index 7930975c..3726a0f7 100644 --- a/pkg/i2gw/providers/kong/header_matching.go +++ b/pkg/i2gw/providers/kong/header_matching.go @@ -20,7 +20,7 @@ import ( "fmt" "strings" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" @@ -38,18 +38,18 @@ import ( // // All the values defined for each annotation name, and separated by comma, MUST be ORed. // All the annotation names MUST be ANDed, with the respective values. -func headerMatchingFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw.GatewayResources) field.ErrorList { +func headerMatchingFeature(ingresses []networkingv1.Ingress, ir *intermediate.IR) field.ErrorList { ruleGroups := common.GetRuleGroups(ingresses) for _, rg := range ruleGroups { for _, rule := range rg.Rules { headerskeys, headersValues := parseHeadersAnnotations(rule.Ingress.Annotations) key := types.NamespacedName{Namespace: rule.Ingress.Namespace, Name: common.RouteName(rg.Name, rg.Host)} - httpRoute, ok := gatewayResources.HTTPRoutes[key] + httpRouteContext, ok := ir.HTTPRoutes[key] if !ok { return field.ErrorList{field.InternalError(nil, fmt.Errorf("HTTPRoute does not exist - this should never happen"))} } - patchHTTPRouteHeaderMatching(&httpRoute, headerskeys, headersValues) + patchHTTPRouteHeaderMatching(&httpRouteContext.HTTPRoute, headerskeys, headersValues) } } diff --git a/pkg/i2gw/providers/kong/header_matching_test.go b/pkg/i2gw/providers/kong/header_matching_test.go index e7f1d415..b5136467 100644 --- a/pkg/i2gw/providers/kong/header_matching_test.go +++ b/pkg/i2gw/providers/kong/header_matching_test.go @@ -242,7 +242,7 @@ func TestHeaderMatchingFeature(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - gatewayResources, errs := common.ToGateway(tc.ingresses, i2gw.ProviderImplementationSpecificOptions{ + gatewayResources, errs := common.ToIR(tc.ingresses, i2gw.ProviderImplementationSpecificOptions{ ToImplementationSpecificHTTPPathTypeMatch: implementationSpecificHTTPPathTypeMatch, }) if len(errs) != 0 { diff --git a/pkg/i2gw/providers/kong/kong.go b/pkg/i2gw/providers/kong/kong.go index b606a34c..df84a6c4 100644 --- a/pkg/i2gw/providers/kong/kong.go +++ b/pkg/i2gw/providers/kong/kong.go @@ -22,6 +22,8 @@ import ( "k8s.io/apimachinery/pkg/util/validation/field" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" ) // The Name of the provider. @@ -36,21 +38,25 @@ func init() { type Provider struct { *storage *resourceReader - *converter + *resourcesToIRConverter } // NewProvider constructs and returns the kong implementation of i2gw.Provider. func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { return &Provider{ - resourceReader: newResourceReader(conf), - converter: newConverter(), + resourceReader: newResourceReader(conf), + resourcesToIRConverter: newResourcesToIRConverter(), } } -// ToGatewayAPI converts stored Kong API entities to i2gw.GatewayResources +// ToIR converts stored Kong API entities to intermediate.IR // including the kong specific features. -func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - return p.converter.convert(p.storage) +func (p *Provider) ToIR() (intermediate.IR, field.ErrorList) { + return p.resourcesToIRConverter.convert(p.storage) +} + +func (p *Provider) ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + return common.ToGatewayResources(ir) } func (p *Provider) ReadResourcesFromCluster(ctx context.Context) error { diff --git a/pkg/i2gw/providers/kong/method_matching.go b/pkg/i2gw/providers/kong/method_matching.go index 5a3193a5..04ef0717 100644 --- a/pkg/i2gw/providers/kong/method_matching.go +++ b/pkg/i2gw/providers/kong/method_matching.go @@ -21,7 +21,7 @@ import ( "fmt" "strings" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" @@ -37,12 +37,12 @@ import ( // konghq.com/methods: "GET,POST" // // All the values defined and separated by comma, MUST be ORed. -func methodMatchingFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw.GatewayResources) field.ErrorList { +func methodMatchingFeature(ingresses []networkingv1.Ingress, ir *intermediate.IR) field.ErrorList { ruleGroups := common.GetRuleGroups(ingresses) for _, rg := range ruleGroups { for _, rule := range rg.Rules { key := types.NamespacedName{Namespace: rule.Ingress.Namespace, Name: common.RouteName(rg.Name, rg.Host)} - httpRoute, ok := gatewayResources.HTTPRoutes[key] + httpRouteContext, ok := ir.HTTPRoutes[key] if !ok { return field.ErrorList{field.InternalError(nil, fmt.Errorf("HTTPRoute does not exist - this should never happen"))} } @@ -50,7 +50,7 @@ func methodMatchingFeature(ingresses []networkingv1.Ingress, gatewayResources *i if len(errs) != 0 { return errs } - patchHTTPRouteMethodMatching(&httpRoute, methods) + patchHTTPRouteMethodMatching(&httpRouteContext.HTTPRoute, methods) } } return nil diff --git a/pkg/i2gw/providers/kong/method_matching_test.go b/pkg/i2gw/providers/kong/method_matching_test.go index 4bb72bad..3fb5129c 100644 --- a/pkg/i2gw/providers/kong/method_matching_test.go +++ b/pkg/i2gw/providers/kong/method_matching_test.go @@ -183,7 +183,7 @@ func TestMethodMatchingFeature(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - gatewayResources, errs := common.ToGateway(tc.ingresses, i2gw.ProviderImplementationSpecificOptions{ + gatewayResources, errs := common.ToIR(tc.ingresses, i2gw.ProviderImplementationSpecificOptions{ ToImplementationSpecificHTTPPathTypeMatch: implementationSpecificHTTPPathTypeMatch, }) if len(errs) != 0 { diff --git a/pkg/i2gw/providers/kong/plugins.go b/pkg/i2gw/providers/kong/plugins.go index 9df98a2d..230a535e 100644 --- a/pkg/i2gw/providers/kong/plugins.go +++ b/pkg/i2gw/providers/kong/plugins.go @@ -21,7 +21,7 @@ import ( "fmt" "strings" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" networkingv1 "k8s.io/api/networking/v1" @@ -36,17 +36,17 @@ import ( // a comma-separated list. // // Example: konghq.com/plugins: "plugin1,plugin2" -func pluginsFeature(ingresses []networkingv1.Ingress, gatewayResources *i2gw.GatewayResources) field.ErrorList { +func pluginsFeature(ingresses []networkingv1.Ingress, ir *intermediate.IR) field.ErrorList { ruleGroups := common.GetRuleGroups(ingresses) for _, rg := range ruleGroups { for _, rule := range rg.Rules { key := types.NamespacedName{Namespace: rule.Ingress.Namespace, Name: common.RouteName(rg.Name, rg.Host)} - httpRoute, ok := gatewayResources.HTTPRoutes[key] + httpRouteContext, ok := ir.HTTPRoutes[key] if !ok { return field.ErrorList{field.InternalError(nil, errors.New("HTTPRoute does not exist - this should never happen"))} } filters := parsePluginsAnnotation(rule.Ingress.Annotations) - patchHTTPRoutePlugins(&httpRoute, filters) + patchHTTPRoutePlugins(&httpRouteContext.HTTPRoute, filters) } } return nil diff --git a/pkg/i2gw/providers/openapi3/converter.go b/pkg/i2gw/providers/openapi3/converter.go index 1b559c44..af701314 100644 --- a/pkg/i2gw/providers/openapi3/converter.go +++ b/pkg/i2gw/providers/openapi3/converter.go @@ -35,6 +35,7 @@ import ( gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" ) @@ -58,13 +59,13 @@ const ( // 4: path var uriRegexp = regexp.MustCompile(`^((https?)://([^/]+))?(/.*)?$`) -type Converter interface { - Convert(Storage) (i2gw.GatewayResources, field.ErrorList) +type ResourcesToIRConverter interface { + Convert(Storage) (intermediate.IR, field.ErrorList) } -// NewConverter returns a converter of OpenAPI Specifications 3.x from a storage into Gateway API resources. -func NewConverter(conf *i2gw.ProviderConf) Converter { - converter := &converter{ +// NewResourcesToIRConverter returns a resourcesToIRConverter of OpenAPI Specifications 3.x from a storage into Gateway API resources. +func NewResourcesToIRConverter(conf *i2gw.ProviderConf) ResourcesToIRConverter { + converter := &resourcesToIRConverter{ namespace: conf.Namespace, tlsSecretRef: types.NamespacedName{}, backendRef: toBackendRef(""), @@ -84,19 +85,19 @@ type backendRef struct { port *gatewayv1.PortNumber } -type converter struct { +type resourcesToIRConverter struct { namespace string gatewayClassName string tlsSecretRef types.NamespacedName backendRef backendRef } -var _ Converter = &converter{} +var _ ResourcesToIRConverter = &resourcesToIRConverter{} -func (c *converter) Convert(storage Storage) (i2gw.GatewayResources, field.ErrorList) { - gatewayResources := i2gw.GatewayResources{ - Gateways: make(map[types.NamespacedName]gatewayv1.Gateway), - HTTPRoutes: make(map[types.NamespacedName]gatewayv1.HTTPRoute), +func (c *resourcesToIRConverter) Convert(storage Storage) (intermediate.IR, field.ErrorList) { + ir := intermediate.IR{ + Gateways: make(map[types.NamespacedName]intermediate.GatewayContext), + HTTPRoutes: make(map[types.NamespacedName]intermediate.HTTPRouteContext), ReferenceGrants: make(map[types.NamespacedName]gatewayv1beta1.ReferenceGrant), } @@ -119,26 +120,26 @@ func (c *converter) Convert(storage Storage) (i2gw.GatewayResources, field.Error // convert the spec to Gateway API resources httpRoutes, gateways := c.toHTTPRoutesAndGateways(spec, resourcesNamePrefix, errors) for _, httpRoute := range httpRoutes { - gatewayResources.HTTPRoutes[types.NamespacedName{Name: httpRoute.GetName(), Namespace: httpRoute.GetNamespace()}] = httpRoute + ir.HTTPRoutes[types.NamespacedName{Name: httpRoute.GetName(), Namespace: httpRoute.GetNamespace()}] = intermediate.HTTPRouteContext{HTTPRoute: httpRoute} } // build reference grants for the resources if referenceGrant := c.buildHTTPRouteBackendReferenceGrant(); referenceGrant != nil { - gatewayResources.ReferenceGrants[types.NamespacedName{Name: referenceGrant.GetName(), Namespace: referenceGrant.GetNamespace()}] = *referenceGrant + ir.ReferenceGrants[types.NamespacedName{Name: referenceGrant.GetName(), Namespace: referenceGrant.GetNamespace()}] = *referenceGrant } for _, gateway := range gateways { - gatewayResources.Gateways[types.NamespacedName{Name: gateway.GetName(), Namespace: gateway.GetNamespace()}] = gateway + ir.Gateways[types.NamespacedName{Name: gateway.GetName(), Namespace: gateway.GetNamespace()}] = intermediate.GatewayContext{Gateway: gateway} if referenceGrant := c.buildGatewayTLSSecretReferenceGrant(gateway); referenceGrant != nil { - gatewayResources.ReferenceGrants[types.NamespacedName{Name: referenceGrant.GetName(), Namespace: referenceGrant.GetNamespace()}] = *referenceGrant + ir.ReferenceGrants[types.NamespacedName{Name: referenceGrant.GetName(), Namespace: referenceGrant.GetNamespace()}] = *referenceGrant } } } - return gatewayResources, errors + return ir, errors } // toHTTPRoutesAndGateways converts an OpenAPI Specification 3.x to Gateway API HTTPRoutes and Gateways. -func (c *converter) toHTTPRoutesAndGateways(spec *openapi3.T, resourcesNamePrefix string, errors field.ErrorList) ([]gatewayv1.HTTPRoute, []gatewayv1.Gateway) { +func (c *resourcesToIRConverter) toHTTPRoutesAndGateways(spec *openapi3.T, resourcesNamePrefix string, errors field.ErrorList) ([]gatewayv1.HTTPRoute, []gatewayv1.Gateway) { var matchers []httpRouteMatcher servers := spec.Servers @@ -271,7 +272,7 @@ func (c *converter) toHTTPRoutesAndGateways(spec *openapi3.T, resourcesNamePrefi // The listener name is derived from the protocol and hostname. // The listener port is assumed 80 for http protocol and 443 for https. // If the protocol is https, the listener TLS configuration is set from the general TLS secret reference. -func (c *converter) toListener(protocolAndHostname string, _ int) gatewayv1.Listener { +func (c *resourcesToIRConverter) toListener(protocolAndHostname string, _ int) gatewayv1.Listener { name, protocol, hostname := toListenerName(protocolAndHostname) listener := gatewayv1.Listener{ @@ -328,7 +329,7 @@ func toListenerName(protocolAndHostname string) (listenerName gatewayv1.SectionN // toHTTPRoute builds a Gateway API HTTPRoute object with a given name, for a given gateway parent, set of hostnames, // and HTTP route matchers out of which HTTPRouteMatches are built for the rules. // All HTTPRouteRules in the HTTPRoute are built with the same set of backendRefs, provided as argument. -func (c *converter) toHTTPRoute(name, gatewayName string, listenerName gatewayv1.SectionName, hostnames []string, matchers httpRouteRuleMatchers, backendRefs []gatewayv1.HTTPBackendRef) gatewayv1.HTTPRoute { +func (c *resourcesToIRConverter) toHTTPRoute(name, gatewayName string, listenerName gatewayv1.SectionName, hostnames []string, matchers httpRouteRuleMatchers, backendRefs []gatewayv1.HTTPBackendRef) gatewayv1.HTTPRoute { parentRef := gatewayv1.ParentReference{Name: gatewayv1.ObjectName(gatewayName)} if listenerName != "" { parentRef.SectionName = common.PtrTo(listenerName) @@ -359,13 +360,13 @@ func (c *converter) toHTTPRoute(name, gatewayName string, listenerName gatewayv1 // buildHTTPRouteBackendReferenceGrant builds a Gateway API ReferenceGrant object for the general backend reference // to be used in all HTTPRoute rules. -func (c *converter) buildHTTPRouteBackendReferenceGrant() *gatewayv1beta1.ReferenceGrant { +func (c *resourcesToIRConverter) buildHTTPRouteBackendReferenceGrant() *gatewayv1beta1.ReferenceGrant { return c.buildReferenceGrant(common.HTTPRouteGVK, gatewayv1.Kind("Service"), c.backendRef.NamespacedName) } // buildGatewayTLSSecretReferenceGrant builds a Gateway API ReferenceGrant object for the general TLS secret // reference to be used in all https gateway listeners. -func (c *converter) buildGatewayTLSSecretReferenceGrant(gateway gatewayv1.Gateway) *gatewayv1beta1.ReferenceGrant { +func (c *resourcesToIRConverter) buildGatewayTLSSecretReferenceGrant(gateway gatewayv1.Gateway) *gatewayv1beta1.ReferenceGrant { if slices.IndexFunc(gateway.Spec.Listeners, func(listener gatewayv1.Listener) bool { return listener.TLS != nil }) == -1 { return nil } @@ -374,7 +375,7 @@ func (c *converter) buildGatewayTLSSecretReferenceGrant(gateway gatewayv1.Gatewa // buildReferenceGrant builds a Gateway API ReferenceGrant object for a given source and destination resource. // The name of the reference grant is derived from the source resource namespace and the destination resource kind and name. -func (c *converter) buildReferenceGrant(fromGVK schema.GroupVersionKind, toKind gatewayv1.Kind, toRef types.NamespacedName) *gatewayv1beta1.ReferenceGrant { +func (c *resourcesToIRConverter) buildReferenceGrant(fromGVK schema.GroupVersionKind, toKind gatewayv1.Kind, toRef types.NamespacedName) *gatewayv1beta1.ReferenceGrant { if c.namespace == "" || toRef.Namespace == "" { return nil } diff --git a/pkg/i2gw/providers/openapi3/converter_test.go b/pkg/i2gw/providers/openapi3/converter_test.go index d994b8f7..52870ea6 100644 --- a/pkg/i2gw/providers/openapi3/converter_test.go +++ b/pkg/i2gw/providers/openapi3/converter_test.go @@ -36,6 +36,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" ) @@ -115,42 +116,42 @@ func TestFileConvertion(t *testing.T) { t.Fatalf("missing expected error during reading test file %v: %v", d.Name(), expectedReadFileError.Error()) } - gotGatewayResources, errList := provider.ToGatewayAPI() + gotIR, errList := provider.ToIR() if len(errList) > 0 { - t.Fatalf("unexpected errors during input conversion for file %v: %v", d.Name(), errList.ToAggregate().Error()) + t.Fatalf("unexpected errors during input conversion to ir for file %v: %v", d.Name(), errList.ToAggregate().Error()) } outputFile := filepath.Join(fixturesDir, "output", d.Name()) - wantGatewayResources, err := readGatewayResourcesFromFile(t, outputFile) + wantIR, err := readGatewayResourcesFromFile(t, outputFile) if err != nil { - t.Fatalf("failed to read wantGatewayResources from file %v: %v", outputFile, err.Error()) + t.Fatalf("failed to read wantIR from file %v: %v", outputFile, err.Error()) } - if !apiequality.Semantic.DeepEqual(gotGatewayResources.Gateways, wantGatewayResources.Gateways) { - t.Errorf("Gateways diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantGatewayResources.Gateways, gotGatewayResources.Gateways)) + if !apiequality.Semantic.DeepEqual(gotIR.Gateways, wantIR.Gateways) { + t.Errorf("Gateways diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantIR.Gateways, gotIR.Gateways)) } - if !apiequality.Semantic.DeepEqual(gotGatewayResources.HTTPRoutes, wantGatewayResources.HTTPRoutes) { - t.Errorf("HTTPRoutes diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantGatewayResources.HTTPRoutes, gotGatewayResources.HTTPRoutes)) + if !apiequality.Semantic.DeepEqual(gotIR.HTTPRoutes, wantIR.HTTPRoutes) { + t.Errorf("HTTPRoutes diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantIR.HTTPRoutes, gotIR.HTTPRoutes)) } - if !apiequality.Semantic.DeepEqual(gotGatewayResources.TLSRoutes, wantGatewayResources.TLSRoutes) { - t.Errorf("TLSRoutes diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantGatewayResources.TLSRoutes, gotGatewayResources.TLSRoutes)) + if !apiequality.Semantic.DeepEqual(gotIR.TLSRoutes, wantIR.TLSRoutes) { + t.Errorf("TLSRoutes diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantIR.TLSRoutes, gotIR.TLSRoutes)) } - if !apiequality.Semantic.DeepEqual(gotGatewayResources.TCPRoutes, wantGatewayResources.TCPRoutes) { - t.Errorf("TCPRoutes diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantGatewayResources.TCPRoutes, gotGatewayResources.TCPRoutes)) + if !apiequality.Semantic.DeepEqual(gotIR.TCPRoutes, wantIR.TCPRoutes) { + t.Errorf("TCPRoutes diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantIR.TCPRoutes, gotIR.TCPRoutes)) } - if !apiequality.Semantic.DeepEqual(gotGatewayResources.ReferenceGrants, wantGatewayResources.ReferenceGrants) { - t.Errorf("ReferenceGrants diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantGatewayResources.ReferenceGrants, gotGatewayResources.ReferenceGrants)) + if !apiequality.Semantic.DeepEqual(gotIR.ReferenceGrants, wantIR.ReferenceGrants) { + t.Errorf("ReferenceGrants diff for file %v (-want +got): %s", d.Name(), cmp.Diff(wantIR.ReferenceGrants, gotIR.ReferenceGrants)) } return nil }) } -func readGatewayResourcesFromFile(t *testing.T, filename string) (*i2gw.GatewayResources, error) { +func readGatewayResourcesFromFile(t *testing.T, filename string) (*intermediate.IR, error) { t.Helper() stream, err := os.ReadFile(filename) @@ -163,9 +164,9 @@ func readGatewayResourcesFromFile(t *testing.T, filename string) (*i2gw.GatewayR return nil, fmt.Errorf("failed to extract objects: %w", err) } - res := i2gw.GatewayResources{ - Gateways: make(map[types.NamespacedName]gatewayv1.Gateway), - HTTPRoutes: make(map[types.NamespacedName]gatewayv1.HTTPRoute), + res := intermediate.IR{ + Gateways: make(map[types.NamespacedName]intermediate.GatewayContext), + HTTPRoutes: make(map[types.NamespacedName]intermediate.HTTPRouteContext), TLSRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TLSRoute), TCPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute), ReferenceGrants: make(map[types.NamespacedName]gatewayv1beta1.ReferenceGrant), @@ -181,7 +182,7 @@ func readGatewayResourcesFromFile(t *testing.T, filename string) (*i2gw.GatewayR res.Gateways[types.NamespacedName{ Namespace: gw.Namespace, Name: gw.Name, - }] = gw + }] = intermediate.GatewayContext{Gateway: gw} case "HTTPRoute": var httpRoute gatewayv1.HTTPRoute if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.UnstructuredContent(), &httpRoute); err != nil { @@ -191,7 +192,7 @@ func readGatewayResourcesFromFile(t *testing.T, filename string) (*i2gw.GatewayR res.HTTPRoutes[types.NamespacedName{ Namespace: httpRoute.Namespace, Name: httpRoute.Name, - }] = httpRoute + }] = intermediate.HTTPRouteContext{HTTPRoute: httpRoute} case "TLSRoute": var tlsRoute gatewayv1alpha2.TLSRoute if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.UnstructuredContent(), &tlsRoute); err != nil { diff --git a/pkg/i2gw/providers/openapi3/openapi.go b/pkg/i2gw/providers/openapi3/openapi.go index a016c028..7870ffaa 100644 --- a/pkg/i2gw/providers/openapi3/openapi.go +++ b/pkg/i2gw/providers/openapi3/openapi.go @@ -24,6 +24,8 @@ import ( "k8s.io/apimachinery/pkg/util/validation/field" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" ) const ( @@ -55,8 +57,8 @@ func init() { } type Provider struct { - storage Storage - converter Converter + storage Storage + resourcesToIRConverter ResourcesToIRConverter } var _ i2gw.Provider = &Provider{} @@ -64,8 +66,8 @@ var _ i2gw.Provider = &Provider{} // NewProvider returns an implementation of i2gw.Provider that converts OpenAPI specs to Gateway API resources. func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { return &Provider{ - storage: NewResourceStorage(), - converter: NewConverter(conf), + storage: NewResourceStorage(), + resourcesToIRConverter: NewResourcesToIRConverter(conf), } } @@ -89,9 +91,13 @@ func (p *Provider) ReadResourcesFromFile(ctx context.Context, filename string) e return nil } -// ToGatewayAPI converts stored OpenAPI specs to Gateway API resources. -func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - return p.converter.Convert(p.storage) +// ToIR converts stored OpenAPI specs to IR. +func (p *Provider) ToIR() (intermediate.IR, field.ErrorList) { + return p.resourcesToIRConverter.Convert(p.storage) +} + +func (p *Provider) ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + return common.ToGatewayResources(ir) } func readSpecFromFile(ctx context.Context, filename string) (*openapi3.T, error) {