From 8c5b7ba0f658aa7fec4dec31ce310b2388860b8b Mon Sep 17 00:00:00 2001 From: David Cheung Date: Wed, 21 Aug 2024 16:21:03 +0000 Subject: [PATCH 01/10] Create IR struct to hold specs for extension features. --- pkg/i2gw/ir/provider_apisix.go | 21 +++++++++ pkg/i2gw/ir/provider_gce.go | 21 +++++++++ pkg/i2gw/ir/provider_ingressnginx.go | 21 +++++++++ pkg/i2gw/ir/provider_istio.go | 21 +++++++++ pkg/i2gw/ir/provider_kong.go | 21 +++++++++ pkg/i2gw/ir/provider_openapi3.go | 21 +++++++++ pkg/i2gw/provider.go | 67 ++++++++++++++++++++++++++++ 7 files changed, 193 insertions(+) create mode 100644 pkg/i2gw/ir/provider_apisix.go create mode 100644 pkg/i2gw/ir/provider_gce.go create mode 100644 pkg/i2gw/ir/provider_ingressnginx.go create mode 100644 pkg/i2gw/ir/provider_istio.go create mode 100644 pkg/i2gw/ir/provider_kong.go create mode 100644 pkg/i2gw/ir/provider_openapi3.go diff --git a/pkg/i2gw/ir/provider_apisix.go b/pkg/i2gw/ir/provider_apisix.go new file mode 100644 index 00000000..20839b5b --- /dev/null +++ b/pkg/i2gw/ir/provider_apisix.go @@ -0,0 +1,21 @@ +/* +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 ir + +type ApisixGatewayIR struct{} +type ApisixHTTPRouteIR struct{} +type ApisixServiceIR struct{} diff --git a/pkg/i2gw/ir/provider_gce.go b/pkg/i2gw/ir/provider_gce.go new file mode 100644 index 00000000..2761a022 --- /dev/null +++ b/pkg/i2gw/ir/provider_gce.go @@ -0,0 +1,21 @@ +/* +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 ir + +type GceGatewayIR struct{} +type GceHTTPRouteIR struct{} +type GceServiceIR struct{} diff --git a/pkg/i2gw/ir/provider_ingressnginx.go b/pkg/i2gw/ir/provider_ingressnginx.go new file mode 100644 index 00000000..a896d1cf --- /dev/null +++ b/pkg/i2gw/ir/provider_ingressnginx.go @@ -0,0 +1,21 @@ +/* +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 ir + +type IngressNginxGatewayIR struct{} +type IngressNginxHTTPRouteIR struct{} +type IngressNginxServiceIR struct{} diff --git a/pkg/i2gw/ir/provider_istio.go b/pkg/i2gw/ir/provider_istio.go new file mode 100644 index 00000000..87c8a7df --- /dev/null +++ b/pkg/i2gw/ir/provider_istio.go @@ -0,0 +1,21 @@ +/* +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 ir + +type IstioGatewayIR struct{} +type IstioHTTPRouteIR struct{} +type IstioServiceIR struct{} diff --git a/pkg/i2gw/ir/provider_kong.go b/pkg/i2gw/ir/provider_kong.go new file mode 100644 index 00000000..5156d8b3 --- /dev/null +++ b/pkg/i2gw/ir/provider_kong.go @@ -0,0 +1,21 @@ +/* +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 ir + +type KongGatewayIR struct{} +type KongHTTPRouteIR struct{} +type KongServiceIR struct{} diff --git a/pkg/i2gw/ir/provider_openapi3.go b/pkg/i2gw/ir/provider_openapi3.go new file mode 100644 index 00000000..220ca9ed --- /dev/null +++ b/pkg/i2gw/ir/provider_openapi3.go @@ -0,0 +1,21 @@ +/* +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 ir + +type Openapi3GatewayIR struct{} +type Openapi3HTTPRouteIR struct{} +type Openapi3ServiceIR struct{} diff --git a/pkg/i2gw/provider.go b/pkg/i2gw/provider.go index c7141998..6c384b88 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/ir" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -101,6 +102,72 @@ type GatewayResources struct { ReferenceGrants map[types.NamespacedName]gatewayv1beta1.ReferenceGrant } +// IR holds specifications of Gateway Objects for supporting Ingress extensions, +// annotations, and proprietary API features not supported as Gateway core +// features. An IR field can be mapped to core Gateway-API fields, +// or provider-specific Gateway extensions. +type IR struct { + Gateways map[types.NamespacedName]GatewayContext + HTTPRoutes map[types.NamespacedName]HTTPRouteContext + Services map[types.NamespacedName]*ServiceIR + + GatewayClasses map[types.NamespacedName]gatewayv1.GatewayClass + TLSRoutes map[types.NamespacedName]gatewayv1alpha2.TLSRoute + TCPRoutes map[types.NamespacedName]gatewayv1alpha2.TCPRoute + UDPRoutes map[types.NamespacedName]gatewayv1alpha2.UDPRoute + + ReferenceGrants map[types.NamespacedName]gatewayv1beta1.ReferenceGrant +} + +// GatewayContext contains the Gateway-API Gateway object and GatewayIR, which +// has a dedicated field for each provider to specify their extension features +// on Gateways. +// The IR will contain necessary information to construct the Gateway +// extensions, but not the extensions themselves. +type GatewayContext struct { + gatewayv1.Gateway + GatewayIR +} + +type GatewayIR struct { + Apisix *ir.ApisixGatewayIR + Gce *ir.GceGatewayIR + IngressNginx *ir.IngressNginxGatewayIR + Istio *ir.IstioGatewayIR + Kong *ir.KongGatewayIR + Openapi3 *ir.Openapi3GatewayIR +} + +// HTTPRouteContext contains the Gateway-API HTTPRoute object and HTTPRouteIR, +// which has a dedicated field for each provider to specify their extension +// features on HTTPRoutes. +// The IR will contain necessary information to construct the HTTPRoute +// extensions, but not the extensions themselves. +type HTTPRouteContext struct { + gatewayv1.HTTPRoute + HTTPRouteIR +} + +type HTTPRouteIR struct { + Apisix *ir.ApisixHTTPRouteIR + Gce *ir.GceHTTPRouteIR + IngressNginx *ir.IngressNginxHTTPRouteIR + Istio *ir.IstioHTTPRouteIR + Kong *ir.KongHTTPRouteIR + Openapi3 *ir.Openapi3HTTPRouteIR +} + +// ServiceIR contains a dedicated field for each provider to specify their +// extension features on Service. +type ServiceIR struct { + Apisix *ir.ApisixServiceIR + Gce *ir.GceServiceIR + IngressNginx *ir.IngressNginxServiceIR + Istio *ir.IstioServiceIR + Kong *ir.KongServiceIR + Openapi3 *ir.Openapi3ServiceIR +} + // FeatureParser is a function that reads the Ingresses, and applies // the appropriate modifications to the GatewayResources. // From db033246488ac4489fe484046baf3c7f6ecb7ace Mon Sep 17 00:00:00 2001 From: David Cheung Date: Thu, 5 Sep 2024 08:59:00 +0000 Subject: [PATCH 02/10] Add merge functions for GceGatewayIR. --- pkg/i2gw/ingress2gateway.go | 72 +++++++++++++++++++++++++++++++++++++ pkg/i2gw/ir/provider_gce.go | 19 +++++++++- 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 643a66a9..12768a12 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -21,6 +21,7 @@ import ( "fmt" "maps" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/ir" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -198,3 +199,74 @@ func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName return newGateways, errs } + +// MergeIRs accepts multiple IRs and creatse a unique IR 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 MergeIRs(irs ...IR) (IR, field.ErrorList) { + mergedIRs := IR{ + Gateways: make(map[types.NamespacedName]GatewayContext), + GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), + HTTPRoutes: make(map[types.NamespacedName]HTTPRouteContext), + Services: make(map[types.NamespacedName]*ServiceIR), + 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 + mergedIRs.Gateways, errs = mergeGatewayContexts(irs) + if len(errs) > 0 { + return IR{}, errs + } + for _, gr := range irs { + maps.Copy(mergedIRs.GatewayClasses, gr.GatewayClasses) + maps.Copy(mergedIRs.HTTPRoutes, gr.HTTPRoutes) + maps.Copy(mergedIRs.TLSRoutes, gr.TLSRoutes) + maps.Copy(mergedIRs.TCPRoutes, gr.TCPRoutes) + maps.Copy(mergedIRs.UDPRoutes, gr.UDPRoutes) + maps.Copy(mergedIRs.ReferenceGrants, gr.ReferenceGrants) + } + return mergedIRs, errs +} + +func mergeGatewayContexts(irs []IR) (map[types.NamespacedName]GatewayContext, field.ErrorList) { + newGatewayContexts := make(map[types.NamespacedName]GatewayContext) + errs := field.ErrorList{} + + for _, ir := range irs { + for _, g := range ir.Gateways { + nn := types.NamespacedName{Namespace: g.Gateway.Namespace, Name: g.Gateway.Name} + if existingGatewayContext, ok := newGatewayContexts[nn]; ok { + g.Gateway.Spec.Listeners = append(g.Gateway.Spec.Listeners, existingGatewayContext.Gateway.Spec.Listeners...) + g.Gateway.Spec.Addresses = append(g.Gateway.Spec.Addresses, existingGatewayContext.Gateway.Spec.Addresses...) + g.GatewayIR = mergedGatewayIR(g.GatewayIR, existingGatewayContext.GatewayIR) + } + newGatewayContexts[nn] = GatewayContext{Gateway: g.Gateway} + // 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 newGatewayContexts, errs +} + +func mergedGatewayIR(current, existing GatewayIR) GatewayIR { + var mergedGatewayIR GatewayIR + // TODO: Add merge functions for other providers once their respective GatewayIRs exist. + mergedGatewayIR.Gce = ir.MergeGceGatewayIR(current.Gce, existing.Gce) + return mergedGatewayIR +} diff --git a/pkg/i2gw/ir/provider_gce.go b/pkg/i2gw/ir/provider_gce.go index 2761a022..3d99bf47 100644 --- a/pkg/i2gw/ir/provider_gce.go +++ b/pkg/i2gw/ir/provider_gce.go @@ -16,6 +16,23 @@ limitations under the License. package ir -type GceGatewayIR struct{} +type GceGatewayIR struct { + EnableHTTPSRedirect bool +} type GceHTTPRouteIR struct{} type GceServiceIR struct{} + +func MergeGceGatewayIR(current, existing *GceGatewayIR) *GceGatewayIR { + // If either GceGatewayIR is nil, return the other one as the merged result. + if current == nil { + return existing + } + if existing == nil { + return current + } + + // If both GceGatewayIRs are not nil, merge their fields. + var mergedGatewayIR GceGatewayIR + mergedGatewayIR.EnableHTTPSRedirect = current.EnableHTTPSRedirect || existing.EnableHTTPSRedirect + return &mergedGatewayIR +} From 280a9510c30fa3cf77259644a0c11561836b4b64 Mon Sep 17 00:00:00 2001 From: David Cheung Date: Fri, 6 Sep 2024 04:20:22 +0000 Subject: [PATCH 03/10] Move IR specific resources into package ir --- pkg/i2gw/ingress2gateway.go | 26 +++---- pkg/i2gw/ir/intermediate_representation.go | 90 ++++++++++++++++++++++ pkg/i2gw/provider.go | 67 ---------------- 3 files changed, 103 insertions(+), 80 deletions(-) create mode 100644 pkg/i2gw/ir/intermediate_representation.go diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 12768a12..c9a0c287 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -209,12 +209,12 @@ func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName // a unique Gateway. // // This behavior is likely to change after https://github.com/kubernetes-sigs/gateway-api/pull/1863 takes place. -func MergeIRs(irs ...IR) (IR, field.ErrorList) { - mergedIRs := IR{ - Gateways: make(map[types.NamespacedName]GatewayContext), +func MergeIRs(irs ...ir.IR) (ir.IR, field.ErrorList) { + mergedIRs := ir.IR{ + Gateways: make(map[types.NamespacedName]ir.GatewayContext), GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), - HTTPRoutes: make(map[types.NamespacedName]HTTPRouteContext), - Services: make(map[types.NamespacedName]*ServiceIR), + HTTPRoutes: make(map[types.NamespacedName]ir.HTTPRouteContext), + Services: make(map[types.NamespacedName]*ir.ServiceIR), TLSRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TLSRoute), TCPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute), UDPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.UDPRoute), @@ -223,7 +223,7 @@ func MergeIRs(irs ...IR) (IR, field.ErrorList) { var errs field.ErrorList mergedIRs.Gateways, errs = mergeGatewayContexts(irs) if len(errs) > 0 { - return IR{}, errs + return ir.IR{}, errs } for _, gr := range irs { maps.Copy(mergedIRs.GatewayClasses, gr.GatewayClasses) @@ -236,19 +236,19 @@ func MergeIRs(irs ...IR) (IR, field.ErrorList) { return mergedIRs, errs } -func mergeGatewayContexts(irs []IR) (map[types.NamespacedName]GatewayContext, field.ErrorList) { - newGatewayContexts := make(map[types.NamespacedName]GatewayContext) +func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayContext, field.ErrorList) { + newGatewayContexts := make(map[types.NamespacedName]ir.GatewayContext) errs := field.ErrorList{} - for _, ir := range irs { - for _, g := range ir.Gateways { + for _, currentIR := range irs { + for _, g := range currentIR.Gateways { nn := types.NamespacedName{Namespace: g.Gateway.Namespace, Name: g.Gateway.Name} if existingGatewayContext, ok := newGatewayContexts[nn]; ok { g.Gateway.Spec.Listeners = append(g.Gateway.Spec.Listeners, existingGatewayContext.Gateway.Spec.Listeners...) g.Gateway.Spec.Addresses = append(g.Gateway.Spec.Addresses, existingGatewayContext.Gateway.Spec.Addresses...) g.GatewayIR = mergedGatewayIR(g.GatewayIR, existingGatewayContext.GatewayIR) } - newGatewayContexts[nn] = GatewayContext{Gateway: g.Gateway} + newGatewayContexts[nn] = ir.GatewayContext{Gateway: g.Gateway} // 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") @@ -264,8 +264,8 @@ func mergeGatewayContexts(irs []IR) (map[types.NamespacedName]GatewayContext, fi return newGatewayContexts, errs } -func mergedGatewayIR(current, existing GatewayIR) GatewayIR { - var mergedGatewayIR GatewayIR +func mergedGatewayIR(current, existing ir.GatewayIR) ir.GatewayIR { + var mergedGatewayIR ir.GatewayIR // TODO: Add merge functions for other providers once their respective GatewayIRs exist. mergedGatewayIR.Gce = ir.MergeGceGatewayIR(current.Gce, existing.Gce) return mergedGatewayIR diff --git a/pkg/i2gw/ir/intermediate_representation.go b/pkg/i2gw/ir/intermediate_representation.go new file mode 100644 index 00000000..ffa1ffb6 --- /dev/null +++ b/pkg/i2gw/ir/intermediate_representation.go @@ -0,0 +1,90 @@ +/* +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 ir + +import ( + "k8s.io/apimachinery/pkg/types" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" +) + +// IR holds specifications of Gateway Objects for supporting Ingress extensions, +// annotations, and proprietary API features not supported as Gateway core +// features. An IR field can be mapped to core Gateway-API fields, +// or provider-specific Gateway extensions. +type IR struct { + Gateways map[types.NamespacedName]GatewayContext + HTTPRoutes map[types.NamespacedName]HTTPRouteContext + Services map[types.NamespacedName]*ServiceIR + + GatewayClasses map[types.NamespacedName]gatewayv1.GatewayClass + TLSRoutes map[types.NamespacedName]gatewayv1alpha2.TLSRoute + TCPRoutes map[types.NamespacedName]gatewayv1alpha2.TCPRoute + UDPRoutes map[types.NamespacedName]gatewayv1alpha2.UDPRoute + + ReferenceGrants map[types.NamespacedName]gatewayv1beta1.ReferenceGrant +} + +// GatewayContext contains the Gateway-API Gateway object and GatewayIR, which +// has a dedicated field for each provider to specify their extension features +// on Gateways. +// The IR will contain necessary information to construct the Gateway +// extensions, but not the extensions themselves. +type GatewayContext struct { + gatewayv1.Gateway + GatewayIR +} + +type GatewayIR struct { + Apisix *ApisixGatewayIR + Gce *GceGatewayIR + IngressNginx *IngressNginxGatewayIR + Istio *IstioGatewayIR + Kong *KongGatewayIR + Openapi3 *Openapi3GatewayIR +} + +// HTTPRouteContext contains the Gateway-API HTTPRoute object and HTTPRouteIR, +// which has a dedicated field for each provider to specify their extension +// features on HTTPRoutes. +// The IR will contain necessary information to construct the HTTPRoute +// extensions, but not the extensions themselves. +type HTTPRouteContext struct { + gatewayv1.HTTPRoute + HTTPRouteIR +} + +type HTTPRouteIR struct { + Apisix *ApisixHTTPRouteIR + Gce *GceHTTPRouteIR + IngressNginx *IngressNginxHTTPRouteIR + Istio *IstioHTTPRouteIR + Kong *KongHTTPRouteIR + Openapi3 *Openapi3HTTPRouteIR +} + +// ServiceIR contains a dedicated field for each provider to specify their +// extension features on Service. +type ServiceIR struct { + Apisix *ApisixServiceIR + Gce *GceServiceIR + IngressNginx *IngressNginxServiceIR + Istio *IstioServiceIR + Kong *KongServiceIR + Openapi3 *Openapi3ServiceIR +} diff --git a/pkg/i2gw/provider.go b/pkg/i2gw/provider.go index 6c384b88..c7141998 100644 --- a/pkg/i2gw/provider.go +++ b/pkg/i2gw/provider.go @@ -20,7 +20,6 @@ import ( "context" "sync" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/ir" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -102,72 +101,6 @@ type GatewayResources struct { ReferenceGrants map[types.NamespacedName]gatewayv1beta1.ReferenceGrant } -// IR holds specifications of Gateway Objects for supporting Ingress extensions, -// annotations, and proprietary API features not supported as Gateway core -// features. An IR field can be mapped to core Gateway-API fields, -// or provider-specific Gateway extensions. -type IR struct { - Gateways map[types.NamespacedName]GatewayContext - HTTPRoutes map[types.NamespacedName]HTTPRouteContext - Services map[types.NamespacedName]*ServiceIR - - GatewayClasses map[types.NamespacedName]gatewayv1.GatewayClass - TLSRoutes map[types.NamespacedName]gatewayv1alpha2.TLSRoute - TCPRoutes map[types.NamespacedName]gatewayv1alpha2.TCPRoute - UDPRoutes map[types.NamespacedName]gatewayv1alpha2.UDPRoute - - ReferenceGrants map[types.NamespacedName]gatewayv1beta1.ReferenceGrant -} - -// GatewayContext contains the Gateway-API Gateway object and GatewayIR, which -// has a dedicated field for each provider to specify their extension features -// on Gateways. -// The IR will contain necessary information to construct the Gateway -// extensions, but not the extensions themselves. -type GatewayContext struct { - gatewayv1.Gateway - GatewayIR -} - -type GatewayIR struct { - Apisix *ir.ApisixGatewayIR - Gce *ir.GceGatewayIR - IngressNginx *ir.IngressNginxGatewayIR - Istio *ir.IstioGatewayIR - Kong *ir.KongGatewayIR - Openapi3 *ir.Openapi3GatewayIR -} - -// HTTPRouteContext contains the Gateway-API HTTPRoute object and HTTPRouteIR, -// which has a dedicated field for each provider to specify their extension -// features on HTTPRoutes. -// The IR will contain necessary information to construct the HTTPRoute -// extensions, but not the extensions themselves. -type HTTPRouteContext struct { - gatewayv1.HTTPRoute - HTTPRouteIR -} - -type HTTPRouteIR struct { - Apisix *ir.ApisixHTTPRouteIR - Gce *ir.GceHTTPRouteIR - IngressNginx *ir.IngressNginxHTTPRouteIR - Istio *ir.IstioHTTPRouteIR - Kong *ir.KongHTTPRouteIR - Openapi3 *ir.Openapi3HTTPRouteIR -} - -// ServiceIR contains a dedicated field for each provider to specify their -// extension features on Service. -type ServiceIR struct { - Apisix *ir.ApisixServiceIR - Gce *ir.GceServiceIR - IngressNginx *ir.IngressNginxServiceIR - Istio *ir.IstioServiceIR - Kong *ir.KongServiceIR - Openapi3 *ir.Openapi3ServiceIR -} - // FeatureParser is a function that reads the Ingresses, and applies // the appropriate modifications to the GatewayResources. // From 18cebaca592965e05c5695134d1e8bd9e0d57de6 Mon Sep 17 00:00:00 2001 From: David Cheung Date: Fri, 6 Sep 2024 04:27:16 +0000 Subject: [PATCH 04/10] Rename GatewayIR, HTTPRouteIR, and ServiceIR to be more descriptive --- pkg/i2gw/ingress2gateway.go | 8 ++++---- pkg/i2gw/ir/intermediate_representation.go | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index c9a0c287..6e2dc395 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -214,7 +214,7 @@ func MergeIRs(irs ...ir.IR) (ir.IR, field.ErrorList) { Gateways: make(map[types.NamespacedName]ir.GatewayContext), GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), HTTPRoutes: make(map[types.NamespacedName]ir.HTTPRouteContext), - Services: make(map[types.NamespacedName]*ir.ServiceIR), + Services: make(map[types.NamespacedName]ir.ProviderSpecificServiceIR), TLSRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TLSRoute), TCPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute), UDPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.UDPRoute), @@ -246,7 +246,7 @@ func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayConte if existingGatewayContext, ok := newGatewayContexts[nn]; ok { g.Gateway.Spec.Listeners = append(g.Gateway.Spec.Listeners, existingGatewayContext.Gateway.Spec.Listeners...) g.Gateway.Spec.Addresses = append(g.Gateway.Spec.Addresses, existingGatewayContext.Gateway.Spec.Addresses...) - g.GatewayIR = mergedGatewayIR(g.GatewayIR, existingGatewayContext.GatewayIR) + g.ProviderSpecificIR = mergedGatewayIR(g.ProviderSpecificIR, existingGatewayContext.ProviderSpecificIR) } newGatewayContexts[nn] = ir.GatewayContext{Gateway: g.Gateway} // 64 is the maximum number of listeners a Gateway can have @@ -264,8 +264,8 @@ func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayConte return newGatewayContexts, errs } -func mergedGatewayIR(current, existing ir.GatewayIR) ir.GatewayIR { - var mergedGatewayIR ir.GatewayIR +func mergedGatewayIR(current, existing ir.ProviderSpecificGatewayIR) ir.ProviderSpecificGatewayIR { + var mergedGatewayIR ir.ProviderSpecificGatewayIR // TODO: Add merge functions for other providers once their respective GatewayIRs exist. mergedGatewayIR.Gce = ir.MergeGceGatewayIR(current.Gce, existing.Gce) return mergedGatewayIR diff --git a/pkg/i2gw/ir/intermediate_representation.go b/pkg/i2gw/ir/intermediate_representation.go index ffa1ffb6..be430ae9 100644 --- a/pkg/i2gw/ir/intermediate_representation.go +++ b/pkg/i2gw/ir/intermediate_representation.go @@ -30,7 +30,7 @@ import ( type IR struct { Gateways map[types.NamespacedName]GatewayContext HTTPRoutes map[types.NamespacedName]HTTPRouteContext - Services map[types.NamespacedName]*ServiceIR + Services map[types.NamespacedName]ProviderSpecificServiceIR GatewayClasses map[types.NamespacedName]gatewayv1.GatewayClass TLSRoutes map[types.NamespacedName]gatewayv1alpha2.TLSRoute @@ -47,10 +47,10 @@ type IR struct { // extensions, but not the extensions themselves. type GatewayContext struct { gatewayv1.Gateway - GatewayIR + ProviderSpecificIR ProviderSpecificGatewayIR } -type GatewayIR struct { +type ProviderSpecificGatewayIR struct { Apisix *ApisixGatewayIR Gce *GceGatewayIR IngressNginx *IngressNginxGatewayIR @@ -66,10 +66,10 @@ type GatewayIR struct { // extensions, but not the extensions themselves. type HTTPRouteContext struct { gatewayv1.HTTPRoute - HTTPRouteIR + ProviderSpecificIR ProviderSpecificHTTPRouteIR } -type HTTPRouteIR struct { +type ProviderSpecificHTTPRouteIR struct { Apisix *ApisixHTTPRouteIR Gce *GceHTTPRouteIR IngressNginx *IngressNginxHTTPRouteIR @@ -80,7 +80,7 @@ type HTTPRouteIR struct { // ServiceIR contains a dedicated field for each provider to specify their // extension features on Service. -type ServiceIR struct { +type ProviderSpecificServiceIR struct { Apisix *ApisixServiceIR Gce *GceServiceIR IngressNginx *IngressNginxServiceIR From f0e110da1ffd75f11b9bbc033e388c55124aa664 Mon Sep 17 00:00:00 2001 From: David Cheung Date: Fri, 6 Sep 2024 04:58:36 +0000 Subject: [PATCH 05/10] Add TODO and links to existing ingress2gateway issue. --- pkg/i2gw/ingress2gateway.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 6e2dc395..67752496 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -200,7 +200,7 @@ func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName return newGateways, errs } -// MergeIRs accepts multiple IRs and creatse a unique IR struct built +// MergeIRs accepts multiple IRs and creates a unique IR 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 @@ -225,9 +225,11 @@ func MergeIRs(irs ...ir.IR) (ir.IR, field.ErrorList) { if len(errs) > 0 { return ir.IR{}, errs } + // TODO(issue #189): Perform merge on HTTPRoute and Service like Gateway. for _, gr := range irs { maps.Copy(mergedIRs.GatewayClasses, gr.GatewayClasses) maps.Copy(mergedIRs.HTTPRoutes, gr.HTTPRoutes) + maps.Copy(mergedIRs.Services, gr.Services) maps.Copy(mergedIRs.TLSRoutes, gr.TLSRoutes) maps.Copy(mergedIRs.TCPRoutes, gr.TCPRoutes) maps.Copy(mergedIRs.UDPRoutes, gr.UDPRoutes) @@ -266,7 +268,8 @@ func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayConte func mergedGatewayIR(current, existing ir.ProviderSpecificGatewayIR) ir.ProviderSpecificGatewayIR { var mergedGatewayIR ir.ProviderSpecificGatewayIR - // TODO: Add merge functions for other providers once their respective GatewayIRs exist. + // TODO(issue #190): Find a different way to merge GatewayIR, instead of + // delegating them to each provider. mergedGatewayIR.Gce = ir.MergeGceGatewayIR(current.Gce, existing.Gce) return mergedGatewayIR } From 219c2f3a846aaa706114d7ec5255711969abf971 Mon Sep 17 00:00:00 2001 From: David Cheung Date: Fri, 6 Sep 2024 05:00:27 +0000 Subject: [PATCH 06/10] Rename package from ir to intermediate. * ir can be a commonly used name for local variable and function parameters, which could potential shadow the package ir. --- pkg/i2gw/ingress2gateway.go | 26 +++++++++---------- .../intermediate_representation.go | 0 .../{ir => intermediate}/provider_apisix.go | 0 pkg/i2gw/{ir => intermediate}/provider_gce.go | 0 .../provider_ingressnginx.go | 0 .../{ir => intermediate}/provider_istio.go | 0 .../{ir => intermediate}/provider_kong.go | 0 .../{ir => intermediate}/provider_openapi3.go | 0 8 files changed, 13 insertions(+), 13 deletions(-) rename pkg/i2gw/{ir => intermediate}/intermediate_representation.go (100%) rename pkg/i2gw/{ir => intermediate}/provider_apisix.go (100%) rename pkg/i2gw/{ir => intermediate}/provider_gce.go (100%) rename pkg/i2gw/{ir => intermediate}/provider_ingressnginx.go (100%) rename pkg/i2gw/{ir => intermediate}/provider_istio.go (100%) rename pkg/i2gw/{ir => intermediate}/provider_kong.go (100%) rename pkg/i2gw/{ir => intermediate}/provider_openapi3.go (100%) diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 67752496..2814fa5f 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -21,7 +21,7 @@ import ( "fmt" "maps" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/ir" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -209,12 +209,12 @@ func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName // a unique Gateway. // // This behavior is likely to change after https://github.com/kubernetes-sigs/gateway-api/pull/1863 takes place. -func MergeIRs(irs ...ir.IR) (ir.IR, field.ErrorList) { - mergedIRs := ir.IR{ - Gateways: make(map[types.NamespacedName]ir.GatewayContext), +func MergeIRs(irs ...intermediate.IR) (intermediate.IR, field.ErrorList) { + mergedIRs := intermediate.IR{ + Gateways: make(map[types.NamespacedName]intermediate.GatewayContext), GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), - HTTPRoutes: make(map[types.NamespacedName]ir.HTTPRouteContext), - Services: make(map[types.NamespacedName]ir.ProviderSpecificServiceIR), + HTTPRoutes: make(map[types.NamespacedName]intermediate.HTTPRouteContext), + Services: make(map[types.NamespacedName]intermediate.ProviderSpecificServiceIR), TLSRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TLSRoute), TCPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.TCPRoute), UDPRoutes: make(map[types.NamespacedName]gatewayv1alpha2.UDPRoute), @@ -223,7 +223,7 @@ func MergeIRs(irs ...ir.IR) (ir.IR, field.ErrorList) { var errs field.ErrorList mergedIRs.Gateways, errs = mergeGatewayContexts(irs) if len(errs) > 0 { - return ir.IR{}, errs + return intermediate.IR{}, errs } // TODO(issue #189): Perform merge on HTTPRoute and Service like Gateway. for _, gr := range irs { @@ -238,8 +238,8 @@ func MergeIRs(irs ...ir.IR) (ir.IR, field.ErrorList) { return mergedIRs, errs } -func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayContext, field.ErrorList) { - newGatewayContexts := make(map[types.NamespacedName]ir.GatewayContext) +func mergeGatewayContexts(irs []intermediate.IR) (map[types.NamespacedName]intermediate.GatewayContext, field.ErrorList) { + newGatewayContexts := make(map[types.NamespacedName]intermediate.GatewayContext) errs := field.ErrorList{} for _, currentIR := range irs { @@ -250,7 +250,7 @@ func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayConte g.Gateway.Spec.Addresses = append(g.Gateway.Spec.Addresses, existingGatewayContext.Gateway.Spec.Addresses...) g.ProviderSpecificIR = mergedGatewayIR(g.ProviderSpecificIR, existingGatewayContext.ProviderSpecificIR) } - newGatewayContexts[nn] = ir.GatewayContext{Gateway: g.Gateway} + newGatewayContexts[nn] = intermediate.GatewayContext{Gateway: g.Gateway} // 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") @@ -266,10 +266,10 @@ func mergeGatewayContexts(irs []ir.IR) (map[types.NamespacedName]ir.GatewayConte return newGatewayContexts, errs } -func mergedGatewayIR(current, existing ir.ProviderSpecificGatewayIR) ir.ProviderSpecificGatewayIR { - var mergedGatewayIR ir.ProviderSpecificGatewayIR +func mergedGatewayIR(current, existing intermediate.ProviderSpecificGatewayIR) intermediate.ProviderSpecificGatewayIR { + var mergedGatewayIR intermediate.ProviderSpecificGatewayIR // TODO(issue #190): Find a different way to merge GatewayIR, instead of // delegating them to each provider. - mergedGatewayIR.Gce = ir.MergeGceGatewayIR(current.Gce, existing.Gce) + mergedGatewayIR.Gce = intermediate.MergeGceGatewayIR(current.Gce, existing.Gce) return mergedGatewayIR } diff --git a/pkg/i2gw/ir/intermediate_representation.go b/pkg/i2gw/intermediate/intermediate_representation.go similarity index 100% rename from pkg/i2gw/ir/intermediate_representation.go rename to pkg/i2gw/intermediate/intermediate_representation.go diff --git a/pkg/i2gw/ir/provider_apisix.go b/pkg/i2gw/intermediate/provider_apisix.go similarity index 100% rename from pkg/i2gw/ir/provider_apisix.go rename to pkg/i2gw/intermediate/provider_apisix.go diff --git a/pkg/i2gw/ir/provider_gce.go b/pkg/i2gw/intermediate/provider_gce.go similarity index 100% rename from pkg/i2gw/ir/provider_gce.go rename to pkg/i2gw/intermediate/provider_gce.go diff --git a/pkg/i2gw/ir/provider_ingressnginx.go b/pkg/i2gw/intermediate/provider_ingressnginx.go similarity index 100% rename from pkg/i2gw/ir/provider_ingressnginx.go rename to pkg/i2gw/intermediate/provider_ingressnginx.go diff --git a/pkg/i2gw/ir/provider_istio.go b/pkg/i2gw/intermediate/provider_istio.go similarity index 100% rename from pkg/i2gw/ir/provider_istio.go rename to pkg/i2gw/intermediate/provider_istio.go diff --git a/pkg/i2gw/ir/provider_kong.go b/pkg/i2gw/intermediate/provider_kong.go similarity index 100% rename from pkg/i2gw/ir/provider_kong.go rename to pkg/i2gw/intermediate/provider_kong.go diff --git a/pkg/i2gw/ir/provider_openapi3.go b/pkg/i2gw/intermediate/provider_openapi3.go similarity index 100% rename from pkg/i2gw/ir/provider_openapi3.go rename to pkg/i2gw/intermediate/provider_openapi3.go From 538c9254567df579a6dcfdb4534e80fab4727c0a Mon Sep 17 00:00:00 2001 From: David Cheung Date: Fri, 6 Sep 2024 05:05:59 +0000 Subject: [PATCH 07/10] Move MergeIR into intermediate package. --- pkg/i2gw/ingress2gateway.go | 75 ------------- .../intermediate_representation.go | 2 +- pkg/i2gw/intermediate/provider_apisix.go | 2 +- pkg/i2gw/intermediate/provider_gce.go | 4 +- .../intermediate/provider_ingressnginx.go | 2 +- pkg/i2gw/intermediate/provider_istio.go | 2 +- pkg/i2gw/intermediate/provider_kong.go | 2 +- pkg/i2gw/intermediate/provider_openapi3.go | 2 +- pkg/i2gw/intermediate/utils.go | 102 ++++++++++++++++++ 9 files changed, 110 insertions(+), 83 deletions(-) create mode 100644 pkg/i2gw/intermediate/utils.go diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 2814fa5f..643a66a9 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -21,7 +21,6 @@ import ( "fmt" "maps" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -199,77 +198,3 @@ func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName return newGateways, errs } - -// MergeIRs accepts multiple IRs and creates a unique IR 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 MergeIRs(irs ...intermediate.IR) (intermediate.IR, field.ErrorList) { - mergedIRs := intermediate.IR{ - Gateways: make(map[types.NamespacedName]intermediate.GatewayContext), - GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), - HTTPRoutes: make(map[types.NamespacedName]intermediate.HTTPRouteContext), - Services: make(map[types.NamespacedName]intermediate.ProviderSpecificServiceIR), - 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 - mergedIRs.Gateways, errs = mergeGatewayContexts(irs) - if len(errs) > 0 { - return intermediate.IR{}, errs - } - // TODO(issue #189): Perform merge on HTTPRoute and Service like Gateway. - for _, gr := range irs { - maps.Copy(mergedIRs.GatewayClasses, gr.GatewayClasses) - maps.Copy(mergedIRs.HTTPRoutes, gr.HTTPRoutes) - maps.Copy(mergedIRs.Services, gr.Services) - maps.Copy(mergedIRs.TLSRoutes, gr.TLSRoutes) - maps.Copy(mergedIRs.TCPRoutes, gr.TCPRoutes) - maps.Copy(mergedIRs.UDPRoutes, gr.UDPRoutes) - maps.Copy(mergedIRs.ReferenceGrants, gr.ReferenceGrants) - } - return mergedIRs, errs -} - -func mergeGatewayContexts(irs []intermediate.IR) (map[types.NamespacedName]intermediate.GatewayContext, field.ErrorList) { - newGatewayContexts := make(map[types.NamespacedName]intermediate.GatewayContext) - errs := field.ErrorList{} - - for _, currentIR := range irs { - for _, g := range currentIR.Gateways { - nn := types.NamespacedName{Namespace: g.Gateway.Namespace, Name: g.Gateway.Name} - if existingGatewayContext, ok := newGatewayContexts[nn]; ok { - g.Gateway.Spec.Listeners = append(g.Gateway.Spec.Listeners, existingGatewayContext.Gateway.Spec.Listeners...) - g.Gateway.Spec.Addresses = append(g.Gateway.Spec.Addresses, existingGatewayContext.Gateway.Spec.Addresses...) - g.ProviderSpecificIR = mergedGatewayIR(g.ProviderSpecificIR, existingGatewayContext.ProviderSpecificIR) - } - newGatewayContexts[nn] = intermediate.GatewayContext{Gateway: g.Gateway} - // 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 newGatewayContexts, errs -} - -func mergedGatewayIR(current, existing intermediate.ProviderSpecificGatewayIR) intermediate.ProviderSpecificGatewayIR { - var mergedGatewayIR intermediate.ProviderSpecificGatewayIR - // TODO(issue #190): Find a different way to merge GatewayIR, instead of - // delegating them to each provider. - mergedGatewayIR.Gce = intermediate.MergeGceGatewayIR(current.Gce, existing.Gce) - return mergedGatewayIR -} diff --git a/pkg/i2gw/intermediate/intermediate_representation.go b/pkg/i2gw/intermediate/intermediate_representation.go index be430ae9..5fde45c5 100644 --- a/pkg/i2gw/intermediate/intermediate_representation.go +++ b/pkg/i2gw/intermediate/intermediate_representation.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate import ( "k8s.io/apimachinery/pkg/types" diff --git a/pkg/i2gw/intermediate/provider_apisix.go b/pkg/i2gw/intermediate/provider_apisix.go index 20839b5b..f7166db6 100644 --- a/pkg/i2gw/intermediate/provider_apisix.go +++ b/pkg/i2gw/intermediate/provider_apisix.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate type ApisixGatewayIR struct{} type ApisixHTTPRouteIR struct{} diff --git a/pkg/i2gw/intermediate/provider_gce.go b/pkg/i2gw/intermediate/provider_gce.go index 3d99bf47..fd82398f 100644 --- a/pkg/i2gw/intermediate/provider_gce.go +++ b/pkg/i2gw/intermediate/provider_gce.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate type GceGatewayIR struct { EnableHTTPSRedirect bool @@ -22,7 +22,7 @@ type GceGatewayIR struct { type GceHTTPRouteIR struct{} type GceServiceIR struct{} -func MergeGceGatewayIR(current, existing *GceGatewayIR) *GceGatewayIR { +func mergeGceGatewayIR(current, existing *GceGatewayIR) *GceGatewayIR { // If either GceGatewayIR is nil, return the other one as the merged result. if current == nil { return existing diff --git a/pkg/i2gw/intermediate/provider_ingressnginx.go b/pkg/i2gw/intermediate/provider_ingressnginx.go index a896d1cf..4ac1207f 100644 --- a/pkg/i2gw/intermediate/provider_ingressnginx.go +++ b/pkg/i2gw/intermediate/provider_ingressnginx.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate type IngressNginxGatewayIR struct{} type IngressNginxHTTPRouteIR struct{} diff --git a/pkg/i2gw/intermediate/provider_istio.go b/pkg/i2gw/intermediate/provider_istio.go index 87c8a7df..50078ec1 100644 --- a/pkg/i2gw/intermediate/provider_istio.go +++ b/pkg/i2gw/intermediate/provider_istio.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate type IstioGatewayIR struct{} type IstioHTTPRouteIR struct{} diff --git a/pkg/i2gw/intermediate/provider_kong.go b/pkg/i2gw/intermediate/provider_kong.go index 5156d8b3..10fbd62b 100644 --- a/pkg/i2gw/intermediate/provider_kong.go +++ b/pkg/i2gw/intermediate/provider_kong.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate type KongGatewayIR struct{} type KongHTTPRouteIR struct{} diff --git a/pkg/i2gw/intermediate/provider_openapi3.go b/pkg/i2gw/intermediate/provider_openapi3.go index 220ca9ed..9657a122 100644 --- a/pkg/i2gw/intermediate/provider_openapi3.go +++ b/pkg/i2gw/intermediate/provider_openapi3.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ir +package intermediate type Openapi3GatewayIR struct{} type Openapi3HTTPRouteIR struct{} diff --git a/pkg/i2gw/intermediate/utils.go b/pkg/i2gw/intermediate/utils.go new file mode 100644 index 00000000..bcd94e22 --- /dev/null +++ b/pkg/i2gw/intermediate/utils.go @@ -0,0 +1,102 @@ +/* +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 intermediate + +import ( + "fmt" + "maps" + + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/validation/field" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" +) + +// MergeIRs accepts multiple IRs and creates a unique IR 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 MergeIRs(irs ...IR) (IR, field.ErrorList) { + mergedIRs := IR{ + Gateways: make(map[types.NamespacedName]GatewayContext), + GatewayClasses: make(map[types.NamespacedName]gatewayv1.GatewayClass), + HTTPRoutes: make(map[types.NamespacedName]HTTPRouteContext), + Services: make(map[types.NamespacedName]ProviderSpecificServiceIR), + 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 + mergedIRs.Gateways, errs = mergeGatewayContexts(irs) + if len(errs) > 0 { + return IR{}, errs + } + // TODO(issue #189): Perform merge on HTTPRoute and Service like Gateway. + for _, gr := range irs { + maps.Copy(mergedIRs.GatewayClasses, gr.GatewayClasses) + maps.Copy(mergedIRs.HTTPRoutes, gr.HTTPRoutes) + maps.Copy(mergedIRs.Services, gr.Services) + maps.Copy(mergedIRs.TLSRoutes, gr.TLSRoutes) + maps.Copy(mergedIRs.TCPRoutes, gr.TCPRoutes) + maps.Copy(mergedIRs.UDPRoutes, gr.UDPRoutes) + maps.Copy(mergedIRs.ReferenceGrants, gr.ReferenceGrants) + } + return mergedIRs, errs +} + +func mergeGatewayContexts(irs []IR) (map[types.NamespacedName]GatewayContext, field.ErrorList) { + newGatewayContexts := make(map[types.NamespacedName]GatewayContext) + errs := field.ErrorList{} + + for _, currentIR := range irs { + for _, g := range currentIR.Gateways { + nn := types.NamespacedName{Namespace: g.Gateway.Namespace, Name: g.Gateway.Name} + if existingGatewayContext, ok := newGatewayContexts[nn]; ok { + g.Gateway.Spec.Listeners = append(g.Gateway.Spec.Listeners, existingGatewayContext.Gateway.Spec.Listeners...) + g.Gateway.Spec.Addresses = append(g.Gateway.Spec.Addresses, existingGatewayContext.Gateway.Spec.Addresses...) + g.ProviderSpecificIR = mergedGatewayIR(g.ProviderSpecificIR, existingGatewayContext.ProviderSpecificIR) + } + newGatewayContexts[nn] = GatewayContext{Gateway: g.Gateway} + // 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 newGatewayContexts, errs +} + +func mergedGatewayIR(current, existing ProviderSpecificGatewayIR) ProviderSpecificGatewayIR { + var mergedGatewayIR ProviderSpecificGatewayIR + // TODO(issue #190): Find a different way to merge GatewayIR, instead of + // delegating them to each provider. + mergedGatewayIR.Gce = mergeGceGatewayIR(current.Gce, existing.Gce) + return mergedGatewayIR +} From 76278257e9431ee79554a44bd50cbf03e9fb242a Mon Sep 17 00:00:00 2001 From: David Cheung Date: Tue, 18 Jun 2024 22:58:15 +0000 Subject: [PATCH 08/10] Add BackendConfig to resource_reader and bump golangci-lint version. * Add BackendConfig to resource_reader. * go.mod requires go 1.22.4, while golangci-lint 1.55.2 is built on go 1.21. This would cause an issue to load go package. "go.mod requires go >= 1.22.1 (running go 1.22.0; GOTOOLCHAIN=local)" * Thus, we need to update to the latest goclint-ci version. --- cmd/print.go | 2 +- cmd/root.go | 2 +- go.mod | 31 +++--- go.sum | 73 +++++++------ hack/verify-golint.sh | 2 +- pkg/i2gw/ingress2gateway_test.go | 4 +- pkg/i2gw/providers/gce/resource_reader.go | 118 +++++++++++++++++++++- pkg/i2gw/providers/gce/storage.go | 13 ++- 8 files changed, 188 insertions(+), 57 deletions(-) diff --git a/cmd/print.go b/cmd/print.go index a26ff0fc..a8cf3b04 100644 --- a/cmd/print.go +++ b/cmd/print.go @@ -245,7 +245,7 @@ func newPrintCommand() *cobra.Command { Use: "print", Short: "Prints Gateway API objects generated from ingress and provider-specific resources.", RunE: pr.PrintGatewayAPIObjects, - PreRunE: func(cmd *cobra.Command, args []string) error { + PreRunE: func(_ *cobra.Command, _ []string) error { openAPIExist := slices.Contains(pr.providers, "openapi3") if openAPIExist && len(pr.providers) != 1 { return fmt.Errorf("openapi3 must be the only provider when specified") diff --git a/cmd/root.go b/cmd/root.go index 594d02b6..67f8f0e3 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -29,7 +29,7 @@ func newRootCmd() *cobra.Command { rootCmd := &cobra.Command{ Use: "ingress2gateway", Short: "Convert Ingress manifests to Gateway API manifests", - PersistentPreRun: func(cmd *cobra.Command, args []string) { + PersistentPreRun: func(_ *cobra.Command, _ []string) { getKubeconfig() }, } diff --git a/go.mod b/go.mod index bfb87ede..945ca8f1 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/kubernetes-sigs/ingress2gateway -go 1.21 +go 1.22.0 require ( github.com/getkin/kin-openapi v0.124.0 @@ -11,19 +11,22 @@ require ( github.com/spf13/cobra v1.8.0 github.com/stretchr/testify v1.9.0 istio.io/api v1.20.0 - k8s.io/api v0.28.4 - k8s.io/apimachinery v0.28.4 - k8s.io/cli-runtime v0.28.4 - k8s.io/client-go v0.28.4 - k8s.io/utils v0.0.0-20231121161247-cf03d44ff3cf + k8s.io/api v0.30.0 + k8s.io/apimachinery v0.30.0 + k8s.io/cli-runtime v0.29.0 + k8s.io/client-go v0.30.0 + k8s.io/ingress-gce v1.30.0 + k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0 sigs.k8s.io/controller-runtime v0.16.3 sigs.k8s.io/gateway-api v1.0.0 ) require ( + github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/invopop/yaml v0.2.0 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect + github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/perimeterx/marshmallow v1.1.5 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect @@ -37,12 +40,12 @@ require ( github.com/evanphx/json-patch v5.7.0+incompatible // indirect github.com/evanphx/json-patch/v5 v5.7.0 // indirect github.com/go-errors/errors v1.5.1 // indirect - github.com/go-logr/logr v1.3.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect github.com/go-openapi/jsonpointer v0.20.2 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.22.8 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect + github.com/golang/protobuf v1.5.4 // indirect github.com/google/btree v1.1.2 // indirect github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 // indirect github.com/google/gofuzz v1.2.0 // indirect @@ -64,24 +67,24 @@ require ( github.com/spf13/pflag v1.0.5 // indirect github.com/xlab/treeprint v1.2.0 // indirect go.starlark.net v0.0.0-20231121155337-90ade8b19d09 // indirect - golang.org/x/net v0.18.0 // indirect + golang.org/x/net v0.23.0 // indirect golang.org/x/oauth2 v0.14.0 // indirect golang.org/x/sync v0.5.0 // indirect - golang.org/x/sys v0.17.0 // indirect - golang.org/x/term v0.17.0 // indirect + golang.org/x/sys v0.18.0 // indirect + golang.org/x/term v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.4.0 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f // indirect google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f // indirect - google.golang.org/protobuf v1.31.0 + google.golang.org/protobuf v1.33.0 gopkg.in/evanphx/json-patch.v5 v5.7.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect istio.io/client-go v1.19.0-alpha.1.0.20231130185426-9f1859c8ff42 - k8s.io/klog/v2 v2.110.1 - k8s.io/kube-openapi v0.0.0-20231113174909-778a5567bc1e // indirect + k8s.io/klog/v2 v2.120.1 + k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/kustomize/api v0.15.0 // indirect sigs.k8s.io/kustomize/kyaml v0.15.0 // indirect diff --git a/go.sum b/go.sum index e3e8496f..43222e77 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,13 @@ +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -20,8 +24,8 @@ github.com/getkin/kin-openapi v0.124.0 h1:VSFNMB9C9rTKBnQ/fpyDU8ytMTr4dWI9QovSKj github.com/getkin/kin-openapi v0.124.0/go.mod h1:wb1aSZA/iWmorQP9KTAS/phLj/t17B5jT7+fS8ed9NM= github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= -github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/zapr v1.2.4 h1:QHVo+6stLbfJmYGkQ7uGHUCu5hnAFAj6mDe6Ea0SeOo= github.com/go-logr/zapr v1.2.4/go.mod h1:FyHWQIzQORZ0QVE1BtVHv3cKtNLuXsbNLtpuhNapBOA= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= @@ -40,8 +44,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 h1:0VpGH+cDhbDtdcweoyCVsF3fhN8kejK6rFe/2FFX2nU= @@ -91,6 +95,8 @@ github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZ github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg= github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -105,10 +111,10 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= -github.com/onsi/ginkgo/v2 v2.11.0 h1:WgqUCUt/lT6yXoQ8Wef0fsNn5cAuMK7+KT9UFRz2tcU= -github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM= -github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= -github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= +github.com/onsi/ginkgo/v2 v2.15.0 h1:79HwNRBAZHOEwrczrgSOPy+eFTTlIGELKy5as+ClttY= +github.com/onsi/ginkgo/v2 v2.15.0/go.mod h1:HlxMHtYF57y6Dpf+mc5529KKmSq9h2FpCF+/ZkwUxKM= +github.com/onsi/gomega v1.31.0 h1:54UJxxj6cPInHS3a35wm6BK/F9nHYueZ1NVujHDrnXE= +github.com/onsi/gomega v1.31.0/go.mod h1:DW9aCi7U6Yi40wNVAvT6kzFnEVEI5n3DloYBiKiT6zk= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= @@ -179,8 +185,8 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= -golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/oauth2 v0.14.0 h1:P0Vrf/2538nmC0H+pEQ3MNFRRnVR7RlqyVw+bvm26z0= golang.org/x/oauth2 v0.14.0/go.mod h1:lAtNWgaWfL4cm7j2OV8TxGi9Qb7ECORx8DktCY74OwM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -194,14 +200,15 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U= -golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= @@ -215,8 +222,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= -golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= +golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ= +golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -231,8 +238,8 @@ google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f h1: google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f/go.mod h1:Uy9bTZJqmfrw2rIBxgGLnamc78euZULUBrLZ9XTITKI= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -251,22 +258,24 @@ istio.io/api v1.20.0 h1:heE1eQoMsuZlwWOf7Xm8TKqKLNKVs11G/zMe5QyR1u4= istio.io/api v1.20.0/go.mod h1:hm1PE/mGdIAsjCDkTIAplP53H7TjO5LUQCiVvF26SVg= istio.io/client-go v1.19.0-alpha.1.0.20231130185426-9f1859c8ff42 h1:YOTiFclrIEagVGbM2oHdD579+j6koeblvoOYGVMmzpE= istio.io/client-go v1.19.0-alpha.1.0.20231130185426-9f1859c8ff42/go.mod h1:yifta8BCYPNw5wFf42Jqt55cnGocIW0DxGlltwQUAaM= -k8s.io/api v0.28.4 h1:8ZBrLjwosLl/NYgv1P7EQLqoO8MGQApnbgH8tu3BMzY= -k8s.io/api v0.28.4/go.mod h1:axWTGrY88s/5YE+JSt4uUi6NMM+gur1en2REMR7IRj0= +k8s.io/api v0.30.0 h1:siWhRq7cNjy2iHssOB9SCGNCl2spiF1dO3dABqZ8niA= +k8s.io/api v0.30.0/go.mod h1:OPlaYhoHs8EQ1ql0R/TsUgaRPhpKNxIMrKQfWUp8QSE= k8s.io/apiextensions-apiserver v0.28.3 h1:Od7DEnhXHnHPZG+W9I97/fSQkVpVPQx2diy+2EtmY08= k8s.io/apiextensions-apiserver v0.28.3/go.mod h1:NE1XJZ4On0hS11aWWJUTNkmVB03j9LM7gJSisbRt8Lc= -k8s.io/apimachinery v0.28.4 h1:zOSJe1mc+GxuMnFzD4Z/U1wst50X28ZNsn5bhgIIao8= -k8s.io/apimachinery v0.28.4/go.mod h1:wI37ncBvfAoswfq626yPTe6Bz1c22L7uaJ8dho83mgg= -k8s.io/cli-runtime v0.28.4 h1:IW3aqSNFXiGDllJF4KVYM90YX4cXPGxuCxCVqCD8X+Q= -k8s.io/cli-runtime v0.28.4/go.mod h1:MLGRB7LWTIYyYR3d/DOgtUC8ihsAPA3P8K8FDNIqJ0k= -k8s.io/client-go v0.28.4 h1:Np5ocjlZcTrkyRJ3+T3PkXDpe4UpatQxj85+xjaD2wY= -k8s.io/client-go v0.28.4/go.mod h1:0VDZFpgoZfelyP5Wqu0/r/TRYcLYuJ2U1KEeoaPa1N4= -k8s.io/klog/v2 v2.110.1 h1:U/Af64HJf7FcwMcXyKm2RPM22WZzyR7OSpYj5tg3cL0= -k8s.io/klog/v2 v2.110.1/go.mod h1:YGtd1984u+GgbuZ7e08/yBuAfKLSO0+uR1Fhi6ExXjo= -k8s.io/kube-openapi v0.0.0-20231113174909-778a5567bc1e h1:snPmy96t93RredGRjKfMFt+gvxuVAncqSAyBveJtr4Q= -k8s.io/kube-openapi v0.0.0-20231113174909-778a5567bc1e/go.mod h1:AsvuZPBlUDVuCdzJ87iajxtXuR9oktsTctW/R9wwouA= -k8s.io/utils v0.0.0-20231121161247-cf03d44ff3cf h1:iTzha1p7Fi83476ypNSz8nV9iR9932jIIs26F7gNLsU= -k8s.io/utils v0.0.0-20231121161247-cf03d44ff3cf/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/apimachinery v0.30.0 h1:qxVPsyDM5XS96NIh9Oj6LavoVFYff/Pon9cZeDIkHHA= +k8s.io/apimachinery v0.30.0/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc= +k8s.io/cli-runtime v0.29.0 h1:q2kC3cex4rOBLfPOnMSzV2BIrrQlx97gxHJs21KxKS4= +k8s.io/cli-runtime v0.29.0/go.mod h1:VKudXp3X7wR45L+nER85YUzOQIru28HQpXr0mTdeCrk= +k8s.io/client-go v0.30.0 h1:sB1AGGlhY/o7KCyCEQ0bPWzYDL0pwOZO4vAtTSh/gJQ= +k8s.io/client-go v0.30.0/go.mod h1:g7li5O5256qe6TYdAMyX/otJqMhIiGgTapdLchhmOaY= +k8s.io/ingress-gce v1.30.0 h1:t3TChtmeLWJTX4sqBErvtJD1q+7836WRjM5g05q8xyE= +k8s.io/ingress-gce v1.30.0/go.mod h1:IodeDa6NxJL40x4HkNlATPHRF3zI4oA/X4CpSMPax1E= +k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw= +k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag= +k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98= +k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0 h1:jgGTlFYnhF1PM1Ax/lAlxUPE+KfCIXHaathvJg1C3ak= +k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/controller-runtime v0.16.3 h1:2TuvuokmfXvDUamSx1SuAOO3eTyye+47mJCigwG62c4= sigs.k8s.io/controller-runtime v0.16.3/go.mod h1:j7bialYoSn142nv9sCOJmQgDXQXxnroFU4VnX/brVJ0= sigs.k8s.io/gateway-api v1.0.0 h1:iPTStSv41+d9p0xFydll6d7f7MOBGuqXM6p2/zVYMAs= diff --git a/hack/verify-golint.sh b/hack/verify-golint.sh index 4507a540..e64b48d4 100755 --- a/hack/verify-golint.sh +++ b/hack/verify-golint.sh @@ -18,7 +18,7 @@ set -o errexit set -o nounset set -o pipefail -readonly VERSION="v1.55.2" +readonly VERSION="v1.59.1" readonly KUBE_ROOT=$(dirname "${BASH_SOURCE}")/.. cd "${KUBE_ROOT}" diff --git a/pkg/i2gw/ingress2gateway_test.go b/pkg/i2gw/ingress2gateway_test.go index 57308592..e65a1cf1 100644 --- a/pkg/i2gw/ingress2gateway_test.go +++ b/pkg/i2gw/ingress2gateway_test.go @@ -27,7 +27,7 @@ import ( func Test_constructProviders(t *testing.T) { supportProviders := []string{"ingress-nginx"} for _, provider := range supportProviders { - ProviderConstructorByName[ProviderName(provider)] = func(conf *ProviderConf) Provider { return nil } + ProviderConstructorByName[ProviderName(provider)] = func(_ *ProviderConf) Provider { return nil } } testCases := []struct { name string @@ -77,7 +77,7 @@ func Test_constructProviders(t *testing.T) { func Test_GetSupportedProviders(t *testing.T) { supportProviders := []string{"ingress-nginx"} for _, provider := range supportProviders { - ProviderConstructorByName[ProviderName(provider)] = func(conf *ProviderConf) Provider { return nil } + ProviderConstructorByName[ProviderName(provider)] = func(_ *ProviderConf) Provider { return nil } } t.Run("Test GetSupportedProviders", func(t *testing.T) { allProviders := GetSupportedProviders() diff --git a/pkg/i2gw/providers/gce/resource_reader.go b/pkg/i2gw/providers/gce/resource_reader.go index be749776..ec9f701c 100644 --- a/pkg/i2gw/providers/gce/resource_reader.go +++ b/pkg/i2gw/providers/gce/resource_reader.go @@ -17,11 +17,20 @@ limitations under the License. package gce import ( + "bytes" "context" + "fmt" + "os" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" + apiv1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" + backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" ) // GCE supports the following Ingress Class values: @@ -30,6 +39,10 @@ import ( // 3. "", which defaults to external Ingress var supportedGCEIngressClass = sets.New(gceIngressClass, gceL7ILBIngressClass, "") +const ( + IngressKind = "Ingress" +) + // reader implements the i2gw.CustomResourceReader interface. type reader struct { conf *i2gw.ProviderConf @@ -49,17 +62,112 @@ func (r *reader) readResourcesFromCluster(ctx context.Context) (*storage, error) if err != nil { return nil, err } - storage.Ingresses = (ingresses) + storage.Ingresses = ingresses + + services, err := r.readServicesFromCluster(ctx) + if err != nil { + return nil, err + } + storage.Services = services + + backendConfigs, err := r.readBackendConfigsFromCluster(ctx) + if err != nil { + return nil, err + } + storage.BackendConfigs = backendConfigs return storage, nil } func (r *reader) readResourcesFromFile(filename string) (*storage, error) { - storage := newResourcesStorage() + stream, err := os.ReadFile(filename) + if err != nil { + return nil, fmt.Errorf("failed to read file %v: %w", filename, err) + } - ingresses, err := common.ReadIngressesFromFile(filename, r.conf.Namespace, supportedGCEIngressClass) + unstructuredObjects, err := common.ExtractObjectsFromReader(bytes.NewReader(stream), r.conf.Namespace) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to extract objects: %w", err) } - storage.Ingresses = ingresses + + storage, err := r.readUnstructuredObjects(unstructuredObjects) + if err != nil { + return nil, fmt.Errorf("failed to read unstructured objects: %w", err) + } + return storage, nil } + +func (r *reader) readServicesFromCluster(ctx context.Context) (map[types.NamespacedName]*apiv1.Service, error) { + var serviceList apiv1.ServiceList + err := r.conf.Client.List(ctx, &serviceList) + if err != nil { + return nil, fmt.Errorf("failed to get services from the cluster: %w", err) + } + services := make(map[types.NamespacedName]*apiv1.Service) + for i, service := range serviceList.Items { + services[types.NamespacedName{Namespace: service.Namespace, Name: service.Name}] = &serviceList.Items[i] + } + return services, nil +} + +func (r *reader) readBackendConfigsFromCluster(ctx context.Context) (map[types.NamespacedName]*backendconfigv1.BackendConfig, error) { + var backendConfigList backendconfigv1.BackendConfigList + err := r.conf.Client.List(ctx, &backendConfigList) + if err != nil { + return nil, fmt.Errorf("failed to get backendConfigs from the cluster: %w", err) + } + backendConfigs := make(map[types.NamespacedName]*backendconfigv1.BackendConfig) + for i, backendConfig := range backendConfigList.Items { + backendConfigs[types.NamespacedName{Namespace: backendConfig.Namespace, Name: backendConfig.Name}] = &backendConfigList.Items[i] + } + return backendConfigs, nil +} + +func (r *reader) readUnstructuredObjects(objects []*unstructured.Unstructured) (*storage, error) { + res := newResourcesStorage() + + ingresses := make(map[types.NamespacedName]*networkingv1.Ingress) + services := make(map[types.NamespacedName]*apiv1.Service) + backendConfigs := make(map[types.NamespacedName]*backendconfigv1.BackendConfig) + + for _, f := range objects { + if f.GroupVersionKind().Empty() { + continue + } + + if f.GetKind() == "Ingress" { + var ingress networkingv1.Ingress + err := runtime.DefaultUnstructuredConverter. + FromUnstructured(f.UnstructuredContent(), &ingress) + if err != nil { + return nil, err + } + if !supportedGCEIngressClass.Has(common.GetIngressClass(ingress)) { + continue + } + ingresses[types.NamespacedName{Namespace: ingress.Namespace, Name: ingress.Name}] = &ingress + } + if f.GetAPIVersion() == "v1" && f.GetKind() == "Service" { + var service apiv1.Service + err := runtime.DefaultUnstructuredConverter. + FromUnstructured(f.UnstructuredContent(), &service) + if err != nil { + return nil, err + } + services[types.NamespacedName{Namespace: service.Namespace, Name: service.Name}] = &service + } + if f.GetAPIVersion() == "cloud.google.com/v1" && f.GetKind() == "BackendConfig" { + var backendConfig backendconfigv1.BackendConfig + err := runtime.DefaultUnstructuredConverter. + FromUnstructured(f.UnstructuredContent(), &backendConfig) + if err != nil { + return nil, err + } + backendConfigs[types.NamespacedName{Namespace: backendConfig.Namespace, Name: backendConfig.Name}] = &backendConfig + } + } + res.Ingresses = ingresses + res.Services = services + res.BackendConfigs = backendConfigs + return res, nil +} diff --git a/pkg/i2gw/providers/gce/storage.go b/pkg/i2gw/providers/gce/storage.go index 2e312c66..faf1a282 100644 --- a/pkg/i2gw/providers/gce/storage.go +++ b/pkg/i2gw/providers/gce/storage.go @@ -17,16 +17,27 @@ limitations under the License. package gce import ( + apiv1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/types" + backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" ) type storage struct { Ingresses map[types.NamespacedName]*networkingv1.Ingress + + // BackendConfig is a GKE Ingress extension, and it is associated to an GKE + // Ingress through specifying `cloud.google.com/backend-config` or + // `beta.cloud.google.com/backend-config` annotation on its Backend Services. + + Services map[types.NamespacedName]*apiv1.Service + BackendConfigs map[types.NamespacedName]*backendconfigv1.BackendConfig } func newResourcesStorage() *storage { return &storage{ - Ingresses: map[types.NamespacedName]*networkingv1.Ingress{}, + Ingresses: make(map[types.NamespacedName]*networkingv1.Ingress), + Services: make(map[types.NamespacedName]*apiv1.Service), + BackendConfigs: make(map[types.NamespacedName]*backendconfigv1.BackendConfig), } } From db2f8931582e575b337bfd9b041091b875a73d7a Mon Sep 17 00:00:00 2001 From: David Cheung Date: Fri, 6 Sep 2024 23:10:42 +0000 Subject: [PATCH 09/10] Add GCE session affinity translation --- cmd/print.go | 31 + go.mod | 39 +- go.sum | 149 +- pkg/i2gw/ingress2gateway.go | 12 + pkg/i2gw/intermediate/provider_gce.go | 8 +- pkg/i2gw/provider.go | 6 +- pkg/i2gw/providers/common/converter.go | 37 + .../providers/common/gateway_converter.go | 46 + pkg/i2gw/providers/gce/converter_test.go | 622 ------- pkg/i2gw/providers/gce/gateway_converter.go | 40 + .../providers/gce/gateway_converter_test.go | 291 ++++ pkg/i2gw/providers/gce/gce.go | 29 +- pkg/i2gw/providers/gce/gce_extensions.go | 198 +++ pkg/i2gw/providers/gce/gce_extensions_test.go | 239 +++ .../gce/{converter.go => ir_converter.go} | 44 +- pkg/i2gw/providers/gce/ir_converter_test.go | 1547 +++++++++++++++++ pkg/i2gw/providers/gce/storage.go | 6 +- pkg/i2gw/providers/gce/types.go | 10 + pkg/i2gw/providers/gce/utils.go | 8 +- 19 files changed, 2584 insertions(+), 778 deletions(-) create mode 100644 pkg/i2gw/providers/common/gateway_converter.go delete mode 100644 pkg/i2gw/providers/gce/converter_test.go create mode 100644 pkg/i2gw/providers/gce/gateway_converter.go create mode 100644 pkg/i2gw/providers/gce/gateway_converter_test.go create mode 100644 pkg/i2gw/providers/gce/gce_extensions.go create mode 100644 pkg/i2gw/providers/gce/gce_extensions_test.go rename pkg/i2gw/providers/gce/{converter.go => ir_converter.go} (65%) create mode 100644 pkg/i2gw/providers/gce/ir_converter_test.go diff --git a/cmd/print.go b/cmd/print.go index a8cf3b04..180c8dd5 100644 --- a/cmd/print.go +++ b/cmd/print.go @@ -25,6 +25,8 @@ import ( "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" "github.com/samber/lo" "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/serializer/json" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/cli-runtime/pkg/printers" "k8s.io/client-go/tools/clientcmd" @@ -179,6 +181,17 @@ func (pr *PrintRunner) outputResult(gatewayResources []i2gw.GatewayResources) { } } + for _, r := range gatewayResources { + resourceCount += len(r.GatewayExtensions) + for _, gatewayExtension := range r.GatewayExtensions { + gatewayExtension := gatewayExtension + fmt.Println("---") + if err := PrintUnstructuredAsYaml(&gatewayExtension); err != nil { + fmt.Printf("# Error printing %s gatewayExtension: %v\n", gatewayExtension.GetName(), err) + } + } + } + if resourceCount == 0 { msg := "No resources found" if pr.namespaceFilter != "" { @@ -310,3 +323,21 @@ func (pr *PrintRunner) getProviderSpecificFlags() map[string]map[string]string { } return providerSpecificFlags } + +func PrintUnstructuredAsYaml(obj *unstructured.Unstructured) error { + // Create a YAML serializer + serializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, nil, nil, + json.SerializerOptions{ + Yaml: true, + Pretty: true, // Optional: for better readability + Strict: true, + }) + + // Encode the unstructured object to YAML + err := serializer.Encode(obj, os.Stdout) + if err != nil { + return err + } + + return nil +} diff --git a/go.mod b/go.mod index 945ca8f1..7a6834e6 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/kubernetes-sigs/ingress2gateway go 1.22.0 require ( + github.com/GoogleCloudPlatform/gke-gateway-api v1.3.0 github.com/getkin/kin-openapi v0.124.0 github.com/google/go-cmp v0.6.0 github.com/kong/kubernetes-ingress-controller/v2 v2.12.3 @@ -11,39 +12,38 @@ require ( github.com/spf13/cobra v1.8.0 github.com/stretchr/testify v1.9.0 istio.io/api v1.20.0 - k8s.io/api v0.30.0 - k8s.io/apimachinery v0.30.0 + k8s.io/api v0.30.1 + k8s.io/apimachinery v0.30.1 k8s.io/cli-runtime v0.29.0 k8s.io/client-go v0.30.0 k8s.io/ingress-gce v1.30.0 k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0 - sigs.k8s.io/controller-runtime v0.16.3 - sigs.k8s.io/gateway-api v1.0.0 + sigs.k8s.io/controller-runtime v0.18.0 + sigs.k8s.io/gateway-api v1.1.0 ) require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/invopop/yaml v0.2.0 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect - github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect github.com/perimeterx/marshmallow v1.1.5 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/rivo/uniseg v0.2.0 // indirect - golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect + golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f // indirect ) require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/emicklei/go-restful/v3 v3.12.0 // indirect github.com/evanphx/json-patch v5.7.0+incompatible // indirect - github.com/evanphx/json-patch/v5 v5.7.0 // indirect + github.com/evanphx/json-patch/v5 v5.9.0 // indirect github.com/go-errors/errors v1.5.1 // indirect github.com/go-logr/logr v1.4.1 // indirect - github.com/go-openapi/jsonpointer v0.20.2 // indirect - github.com/go-openapi/jsonreference v0.20.2 // indirect - github.com/go-openapi/swag v0.22.8 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.21.0 // indirect + github.com/go-openapi/swag v0.23.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/btree v1.1.2 // indirect @@ -67,14 +67,13 @@ require ( github.com/spf13/pflag v1.0.5 // indirect github.com/xlab/treeprint v1.2.0 // indirect go.starlark.net v0.0.0-20231121155337-90ade8b19d09 // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/oauth2 v0.14.0 // indirect - golang.org/x/sync v0.5.0 // indirect - golang.org/x/sys v0.18.0 // indirect - golang.org/x/term v0.18.0 // indirect - golang.org/x/text v0.14.0 // indirect - golang.org/x/time v0.4.0 // indirect - google.golang.org/appengine v1.6.8 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/oauth2 v0.19.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/term v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + golang.org/x/time v0.5.0 // indirect google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f // indirect google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f // indirect google.golang.org/protobuf v1.33.0 @@ -84,7 +83,7 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect istio.io/client-go v1.19.0-alpha.1.0.20231130185426-9f1859c8ff42 k8s.io/klog/v2 v2.120.1 - k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect + k8s.io/kube-openapi v0.0.0-20240423202451-8948a665c108 // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/kustomize/api v0.15.0 // indirect sigs.k8s.io/kustomize/kyaml v0.15.0 // indirect diff --git a/go.sum b/go.sum index 43222e77..30922486 100644 --- a/go.sum +++ b/go.sum @@ -1,64 +1,54 @@ github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= -github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/GoogleCloudPlatform/gke-gateway-api v1.3.0 h1:4WjH6dFtnezCFiYlbmq0SBF2f8PIQD3rV99m5FRb/UM= +github.com/GoogleCloudPlatform/gke-gateway-api v1.3.0/go.mod h1:IFDp1XhE20jjqWG3o2ocYoz33nCH6HC4rJ6Hdag4y1M= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= -github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/emicklei/go-restful/v3 v3.12.0 h1:y2DdzBAURM29NFF94q6RaY4vjIH1rtwDapwQtU84iWk= +github.com/emicklei/go-restful/v3 v3.12.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/evanphx/json-patch v5.7.0+incompatible h1:vgGkfT/9f8zE6tvSCe74nfpAVDQ2tG6yudJd8LBksgI= github.com/evanphx/json-patch v5.7.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch/v5 v5.7.0 h1:nJqP7uwL84RJInrohHfW0Fx3awjbm8qZeFv0nW9SYGc= -github.com/evanphx/json-patch/v5 v5.7.0/go.mod h1:VNkHZ/282BpEyt/tObQO8s5CMPmYYq14uClGH4abBuQ= -github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= -github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/evanphx/json-patch/v5 v5.9.0 h1:kcBlZQbplgElYIlo/n1hJbls2z/1awpXxpRi0/FOJfg= +github.com/evanphx/json-patch/v5 v5.9.0/go.mod h1:VNkHZ/282BpEyt/tObQO8s5CMPmYYq14uClGH4abBuQ= github.com/getkin/kin-openapi v0.124.0 h1:VSFNMB9C9rTKBnQ/fpyDU8ytMTr4dWI9QovSKj9kz/M= github.com/getkin/kin-openapi v0.124.0/go.mod h1:wb1aSZA/iWmorQP9KTAS/phLj/t17B5jT7+fS8ed9NM= github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/zapr v1.2.4 h1:QHVo+6stLbfJmYGkQ7uGHUCu5hnAFAj6mDe6Ea0SeOo= -github.com/go-logr/zapr v1.2.4/go.mod h1:FyHWQIzQORZ0QVE1BtVHv3cKtNLuXsbNLtpuhNapBOA= -github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= -github.com/go-openapi/jsonpointer v0.20.2 h1:mQc3nmndL8ZBzStEo3JYF8wzmeWffDH4VbXz58sAx6Q= -github.com/go-openapi/jsonpointer v0.20.2/go.mod h1:bHen+N0u1KEO3YlmqOjTT9Adn1RfD91Ar825/PuiRVs= -github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= -github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= -github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= -github.com/go-openapi/swag v0.22.8 h1:/9RjDSQ0vbFR+NyjGMkFTsA1IA0fmhKSThmfGZjicbw= -github.com/go-openapi/swag v0.22.8/go.mod h1:6QT22icPLEqAM/z/TChgb4WAveCHF92+2gF0CNjHpPI= +github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= +github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= +github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM= github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 h1:0VpGH+cDhbDtdcweoyCVsF3fhN8kejK6rFe/2FFX2nU= github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49/go.mod h1:BkkQ4L1KS1xMt2aWSPStnn55ChGC0DPOn2FQYj+f25M= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20211214055906-6f57359322fd h1:1FjCyPC+syAzJ5/2S8fqdZK1R22vvA0J7JZKcuOIQ7Y= -github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -79,11 +69,8 @@ github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kong/kubernetes-ingress-controller/v2 v2.12.3 h1:HxQA6vp14rNMC4cIo81SMuNXD2vCUNMihPlQveTT9K4= github.com/kong/kubernetes-ingress-controller/v2 v2.12.3/go.mod h1:f2wIi3/yrwBYT+C/jtpB8tA+kEzewqLwOUGUwE5n+nk= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= @@ -93,8 +80,6 @@ github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJ github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg= -github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k= github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -111,10 +96,10 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= -github.com/onsi/ginkgo/v2 v2.15.0 h1:79HwNRBAZHOEwrczrgSOPy+eFTTlIGELKy5as+ClttY= -github.com/onsi/ginkgo/v2 v2.15.0/go.mod h1:HlxMHtYF57y6Dpf+mc5529KKmSq9h2FpCF+/ZkwUxKM= -github.com/onsi/gomega v1.31.0 h1:54UJxxj6cPInHS3a35wm6BK/F9nHYueZ1NVujHDrnXE= -github.com/onsi/gomega v1.31.0/go.mod h1:DW9aCi7U6Yi40wNVAvT6kzFnEVEI5n3DloYBiKiT6zk= +github.com/onsi/ginkgo/v2 v2.17.1 h1:V++EzdbhI4ZV4ev0UTIj0PzhzOcReJFyJaLjtSF55M8= +github.com/onsi/ginkgo/v2 v2.17.1/go.mod h1:llBI3WDLL9Z6taip6f33H76YcWtJv+7R3HigUjbIBOs= +github.com/onsi/gomega v1.32.0 h1:JRYU78fJ1LPxlckP6Txi/EYqJvjtMrDC04/MM5XRHPk= +github.com/onsi/gomega v1.32.0/go.mod h1:a4x4gW6Pz2yK1MAmvluYme5lvYTn61afQ2ETw/8n4Lg= github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s= github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= @@ -124,14 +109,6 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q= -github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY= -github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= -github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= -github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM= -github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY= -github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo= -github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= @@ -146,15 +123,10 @@ github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyh github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= @@ -163,7 +135,6 @@ github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.starlark.net v0.0.0-20231121155337-90ade8b19d09 h1:hzy3LFnSN8kuQK8h9tHl4ndF6UruMj47OqwqsS+/Ai4= go.starlark.net v0.0.0-20231121155337-90ade8b19d09/go.mod h1:LcLNIzVOMp4oV+uusnpk+VU+SzXaJakUuBjoCSWH5dM= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -173,71 +144,51 @@ go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= -golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY= +golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= -golang.org/x/oauth2 v0.14.0 h1:P0Vrf/2538nmC0H+pEQ3MNFRRnVR7RlqyVw+bvm26z0= -golang.org/x/oauth2 v0.14.0/go.mod h1:lAtNWgaWfL4cm7j2OV8TxGi9Qb7ECORx8DktCY74OwM= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/oauth2 v0.19.0 h1:9+E/EZBCbTLNrbN35fHv/a/d/mOBatymz1zbtQrXpIg= +golang.org/x/oauth2 v0.19.0/go.mod h1:vYi7skDa1x015PmRRYZ7+s1cWyPgrPiSYRe4rnsexc8= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= -golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= -golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= -golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/time v0.4.0 h1:Z81tqI5ddIoXDPvVQ7/7CC9TnLM7ubaFG2qXYd5BbYY= -golang.org/x/time v0.4.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ= -golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg= +golang.org/x/tools v0.21.0 h1:qc0xYgIbsSDt9EyWz05J5wfa7LOVW0YTLOXrqdLAWIw= +golang.org/x/tools v0.21.0/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= -gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= -google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= -google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f h1:Vn+VyHU5guc9KjB5KrjI2q0wCOWEOIh0OEsleqakHJg= google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f/go.mod h1:nWSwAFPb+qfNJXsoeO3Io7zf4tMSfN8EA8RlDA04GhY= google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f h1:2yNACc1O40tTnrsbk9Cv6oxiW8pxI/pXj0wRtdlYmgY= google.golang.org/genproto/googleapis/api v0.0.0-20231120223509-83a465c0220f/go.mod h1:Uy9bTZJqmfrw2rIBxgGLnamc78euZULUBrLZ9XTITKI= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -258,12 +209,12 @@ istio.io/api v1.20.0 h1:heE1eQoMsuZlwWOf7Xm8TKqKLNKVs11G/zMe5QyR1u4= istio.io/api v1.20.0/go.mod h1:hm1PE/mGdIAsjCDkTIAplP53H7TjO5LUQCiVvF26SVg= istio.io/client-go v1.19.0-alpha.1.0.20231130185426-9f1859c8ff42 h1:YOTiFclrIEagVGbM2oHdD579+j6koeblvoOYGVMmzpE= istio.io/client-go v1.19.0-alpha.1.0.20231130185426-9f1859c8ff42/go.mod h1:yifta8BCYPNw5wFf42Jqt55cnGocIW0DxGlltwQUAaM= -k8s.io/api v0.30.0 h1:siWhRq7cNjy2iHssOB9SCGNCl2spiF1dO3dABqZ8niA= -k8s.io/api v0.30.0/go.mod h1:OPlaYhoHs8EQ1ql0R/TsUgaRPhpKNxIMrKQfWUp8QSE= -k8s.io/apiextensions-apiserver v0.28.3 h1:Od7DEnhXHnHPZG+W9I97/fSQkVpVPQx2diy+2EtmY08= -k8s.io/apiextensions-apiserver v0.28.3/go.mod h1:NE1XJZ4On0hS11aWWJUTNkmVB03j9LM7gJSisbRt8Lc= -k8s.io/apimachinery v0.30.0 h1:qxVPsyDM5XS96NIh9Oj6LavoVFYff/Pon9cZeDIkHHA= -k8s.io/apimachinery v0.30.0/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc= +k8s.io/api v0.30.1 h1:kCm/6mADMdbAxmIh0LBjS54nQBE+U4KmbCfIkF5CpJY= +k8s.io/api v0.30.1/go.mod h1:ddbN2C0+0DIiPntan/bye3SW3PdwLa11/0yqwvuRrJM= +k8s.io/apiextensions-apiserver v0.30.0 h1:jcZFKMqnICJfRxTgnC4E+Hpcq8UEhT8B2lhBcQ+6uAs= +k8s.io/apiextensions-apiserver v0.30.0/go.mod h1:N9ogQFGcrbWqAY9p2mUAL5mGxsLqwgtUce127VtRX5Y= +k8s.io/apimachinery v0.30.1 h1:ZQStsEfo4n65yAdlGTfP/uSHMQSoYzU/oeEbkmF7P2U= +k8s.io/apimachinery v0.30.1/go.mod h1:iexa2somDaxdnj7bha06bhb43Zpa6eWH8N8dbqVjTUc= k8s.io/cli-runtime v0.29.0 h1:q2kC3cex4rOBLfPOnMSzV2BIrrQlx97gxHJs21KxKS4= k8s.io/cli-runtime v0.29.0/go.mod h1:VKudXp3X7wR45L+nER85YUzOQIru28HQpXr0mTdeCrk= k8s.io/client-go v0.30.0 h1:sB1AGGlhY/o7KCyCEQ0bPWzYDL0pwOZO4vAtTSh/gJQ= @@ -272,14 +223,14 @@ k8s.io/ingress-gce v1.30.0 h1:t3TChtmeLWJTX4sqBErvtJD1q+7836WRjM5g05q8xyE= k8s.io/ingress-gce v1.30.0/go.mod h1:IodeDa6NxJL40x4HkNlATPHRF3zI4oA/X4CpSMPax1E= k8s.io/klog/v2 v2.120.1 h1:QXU6cPEOIslTGvZaXvFWiP9VKyeet3sawzTOvdXb4Vw= k8s.io/klog/v2 v2.120.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= -k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 h1:BZqlfIlq5YbRMFko6/PM7FjZpUb45WallggurYhKGag= -k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98= +k8s.io/kube-openapi v0.0.0-20240423202451-8948a665c108 h1:Q8Z7VlGhcJgBHJHYugJ/K/7iB8a2eSxCyxdVjJp+lLY= +k8s.io/kube-openapi v0.0.0-20240423202451-8948a665c108/go.mod h1:yD4MZYeKMBwQKVht279WycxKyM84kkAx2DPrTXaeb98= k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0 h1:jgGTlFYnhF1PM1Ax/lAlxUPE+KfCIXHaathvJg1C3ak= k8s.io/utils v0.0.0-20240502163921-fe8a2dddb1d0/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -sigs.k8s.io/controller-runtime v0.16.3 h1:2TuvuokmfXvDUamSx1SuAOO3eTyye+47mJCigwG62c4= -sigs.k8s.io/controller-runtime v0.16.3/go.mod h1:j7bialYoSn142nv9sCOJmQgDXQXxnroFU4VnX/brVJ0= -sigs.k8s.io/gateway-api v1.0.0 h1:iPTStSv41+d9p0xFydll6d7f7MOBGuqXM6p2/zVYMAs= -sigs.k8s.io/gateway-api v1.0.0/go.mod h1:4cUgr0Lnp5FZ0Cdq8FdRwCvpiWws7LVhLHGIudLlf4c= +sigs.k8s.io/controller-runtime v0.18.0 h1:Z7jKuX784TQSUL1TIyeuF7j8KXZ4RtSX0YgtjKcSTME= +sigs.k8s.io/controller-runtime v0.18.0/go.mod h1:tuAt1+wbVsXIT8lPtk5RURxqAnq7xkpv2Mhttslg7Hw= +sigs.k8s.io/gateway-api v1.1.0 h1:DsLDXCi6jR+Xz8/xd0Z1PYl2Pn0TyaFMOPPZIj4inDM= +sigs.k8s.io/gateway-api v1.1.0/go.mod h1:ZH4lHrL2sDi0FHZ9jjneb8kKnGzFWyrTya35sWUTrRs= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/kustomize/api v0.15.0 h1:6Ca88kEOBVotHDw+y2IsIMYtg9Pvv7MKpW9JMyF/OH4= diff --git a/pkg/i2gw/ingress2gateway.go b/pkg/i2gw/ingress2gateway.go index 643a66a9..418da193 100644 --- a/pkg/i2gw/ingress2gateway.go +++ b/pkg/i2gw/ingress2gateway.go @@ -22,6 +22,8 @@ import ( "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" @@ -198,3 +200,13 @@ func mergeGateways(gatewaResources []GatewayResources) (map[types.NamespacedName return newGateways, errs } + +func CastToUnstructured(obj runtime.Object) (*unstructured.Unstructured, error) { + // Convert the Kubernetes object to unstructured.Unstructured + unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) + if err != nil { + return nil, err + } + + return &unstructured.Unstructured{Object: unstructuredObj}, nil +} diff --git a/pkg/i2gw/intermediate/provider_gce.go b/pkg/i2gw/intermediate/provider_gce.go index fd82398f..ebd9b512 100644 --- a/pkg/i2gw/intermediate/provider_gce.go +++ b/pkg/i2gw/intermediate/provider_gce.go @@ -20,7 +20,13 @@ type GceGatewayIR struct { EnableHTTPSRedirect bool } type GceHTTPRouteIR struct{} -type GceServiceIR struct{} +type GceServiceIR struct { + SessionAffinity *SessionAffinityConfig +} +type SessionAffinityConfig struct { + AffinityType string + CookieTTLSec *int64 +} func mergeGceGatewayIR(current, existing *GceGatewayIR) *GceGatewayIR { // If either GceGatewayIR is nil, return the other one as the merged result. diff --git a/pkg/i2gw/provider.go b/pkg/i2gw/provider.go index c7141998..c6cd0d5f 100644 --- a/pkg/i2gw/provider.go +++ b/pkg/i2gw/provider.go @@ -21,6 +21,7 @@ import ( "sync" networkingv1 "k8s.io/api/networking/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" "sigs.k8s.io/controller-runtime/pkg/client" @@ -88,7 +89,8 @@ type ProviderImplementationSpecificOptions struct { ToImplementationSpecificHTTPPathTypeMatch ImplementationSpecificHTTPPathTypeMatchConverter } -// GatewayResources contains all Gateway-API objects. +// GatewayResources contains all Gateway-API objects and provider Gateway +// extensions. type GatewayResources struct { Gateways map[types.NamespacedName]gatewayv1.Gateway GatewayClasses map[types.NamespacedName]gatewayv1.GatewayClass @@ -99,6 +101,8 @@ type GatewayResources struct { UDPRoutes map[types.NamespacedName]gatewayv1alpha2.UDPRoute ReferenceGrants map[types.NamespacedName]gatewayv1beta1.ReferenceGrant + + GatewayExtensions []unstructured.Unstructured } // FeatureParser is a function that reads the Ingresses, and applies diff --git a/pkg/i2gw/providers/common/converter.go b/pkg/i2gw/providers/common/converter.go index 5e9bee4b..9546327b 100644 --- a/pkg/i2gw/providers/common/converter.go +++ b/pkg/i2gw/providers/common/converter.go @@ -23,6 +23,7 @@ import ( "strings" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -67,6 +68,42 @@ func ToGateway(ingresses []networkingv1.Ingress, options i2gw.ProviderImplementa }, nil } +// ToIR converts the received ingresses to i2gw.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{}} + + var errs field.ErrorList + for _, ingress := range ingresses { + aggregator.addIngress(ingress) + } + if len(errs) > 0 { + return intermediate.IR{}, errs + } + + routes, gateways, errs := aggregator.toHTTPRoutesAndGateways(options) + if len(errs) > 0 { + return intermediate.IR{}, errs + } + + routeByKey := make(map[types.NamespacedName]intermediate.HTTPRouteContext) + for _, route := range routes { + key := types.NamespacedName{Namespace: route.Namespace, Name: route.Name} + routeByKey[key] = intermediate.HTTPRouteContext{HTTPRoute: route} + } + + gatewayByKey := make(map[types.NamespacedName]intermediate.GatewayContext) + for _, gateway := range gateways { + key := types.NamespacedName{Namespace: gateway.Namespace, Name: gateway.Name} + gatewayByKey[key] = intermediate.GatewayContext{Gateway: gateway} + } + + return intermediate.IR{ + Gateways: gatewayByKey, + HTTPRoutes: routeByKey, + }, nil +} + var ( GatewayGVK = schema.GroupVersionKind{ Group: "gateway.networking.k8s.io", diff --git a/pkg/i2gw/providers/common/gateway_converter.go b/pkg/i2gw/providers/common/gateway_converter.go new file mode 100644 index 00000000..4926c258 --- /dev/null +++ b/pkg/i2gw/providers/common/gateway_converter.go @@ -0,0 +1,46 @@ +/* +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 ( + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/validation/field" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" +) + +// ToGatewayResources converts the received i2gw.IR to i2gw.GatewayResource +// without taking into consideration any provider specific logic. +func ToGatewayResources(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + gatewayResources := i2gw.GatewayResources{ + Gateways: make(map[types.NamespacedName]gatewayv1.Gateway), + HTTPRoutes: make(map[types.NamespacedName]gatewayv1.HTTPRoute), + GatewayClasses: ir.GatewayClasses, + TLSRoutes: ir.TLSRoutes, + TCPRoutes: ir.TCPRoutes, + UDPRoutes: ir.UDPRoutes, + ReferenceGrants: ir.ReferenceGrants, + } + for key, gatewayContext := range ir.Gateways { + gatewayResources.Gateways[key] = gatewayContext.Gateway + } + for key, httpRouteContext := range ir.HTTPRoutes { + gatewayResources.HTTPRoutes[key] = httpRouteContext.HTTPRoute + } + return gatewayResources, nil +} diff --git a/pkg/i2gw/providers/gce/converter_test.go b/pkg/i2gw/providers/gce/converter_test.go deleted file mode 100644 index 9974f41b..00000000 --- a/pkg/i2gw/providers/gce/converter_test.go +++ /dev/null @@ -1,622 +0,0 @@ -/* -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 gce - -import ( - "errors" - "fmt" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" - "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/common" - networkingv1 "k8s.io/api/networking/v1" - networkingv1beta1 "k8s.io/api/networking/v1beta1" - 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_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 ptrTo[T any](a T) *T { - return &a -} diff --git a/pkg/i2gw/providers/gce/gateway_converter.go b/pkg/i2gw/providers/gce/gateway_converter.go new file mode 100644 index 00000000..1ab09951 --- /dev/null +++ b/pkg/i2gw/providers/gce/gateway_converter.go @@ -0,0 +1,40 @@ +/* +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 gce + +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" +) + +type irToGatewayResourcesConverter struct{} + +// newIRToGatewayResourcesConverter returns an gce irToGatewayResourcesConverter instance. +func newIRToGatewayResourcesConverter() irToGatewayResourcesConverter { + return irToGatewayResourcesConverter{} +} + +func (c *irToGatewayResourcesConverter) irToGateway(ir intermediate.IR) (i2gw.GatewayResources, field.ErrorList) { + gatewayResources, errs := common.ToGatewayResources(ir) + if len(errs) != 0 { + return i2gw.GatewayResources{}, errs + } + buildGceServiceExtensions(ir, &gatewayResources) + return gatewayResources, nil +} diff --git a/pkg/i2gw/providers/gce/gateway_converter_test.go b/pkg/i2gw/providers/gce/gateway_converter_test.go new file mode 100644 index 00000000..7b4de538 --- /dev/null +++ b/pkg/i2gw/providers/gce/gateway_converter_test.go @@ -0,0 +1,291 @@ +/* +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 gce + +import ( + "errors" + "testing" + + gkegatewayv1 "github.com/GoogleCloudPlatform/gke-gateway-api/apis/networking/v1" + "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" + apiequality "k8s.io/apimachinery/pkg/api/equality" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/validation/field" + + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + "sigs.k8s.io/gateway-api/apis/v1alpha2" +) + +func Test_irToGateway(t *testing.T) { + testNamespace := "default" + testHost := "test.mydomain.com" + testServiceName := "test-service" + testGatewayName := "test-gateway" + testHTTPRouteName := "test-http-route" + + gPathPrefix := gatewayv1.PathMatchPathPrefix + saTypeClientIP := "CLIENT_IP" + testCookieTTLSec := int64(10) + saTypeCookie := "GENERATED_COOKIE" + + testGateway := gatewayv1.Gateway{ + ObjectMeta: metav1.ObjectMeta{Name: testGatewayName, 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)), + }}, + }, + } + + testHTTPRoute := gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{Name: testHTTPRouteName, Namespace: testNamespace}, + Spec: gatewayv1.HTTPRouteSpec{ + CommonRouteSpec: gatewayv1.CommonRouteSpec{ + ParentRefs: []gatewayv1.ParentReference{{ + Name: gatewayv1.ObjectName(testGatewayName), + }}, + }, + 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(testServiceName), + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, + }, + }, + }, + }, + }, + } + + testSaBackendPolicyName := testServiceName + testSaGCPBackendPolicyCookie := gkegatewayv1.GCPBackendPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testSaBackendPolicyName, + }, + Spec: gkegatewayv1.GCPBackendPolicySpec{ + Default: &gkegatewayv1.GCPBackendPolicyConfig{ + SessionAffinity: &gkegatewayv1.SessionAffinityConfig{ + Type: ptrTo("GENERATED_COOKIE"), + CookieTTLSec: &testCookieTTLSec, + }, + }, + TargetRef: v1alpha2.NamespacedPolicyTargetReference{ + Group: "", + Kind: "Service", + Name: gatewayv1.ObjectName(testServiceName), + }, + }, + } + testSaGCPBackendPolicyCookie.SetGroupVersionKind(GCPBackendPolicyGVK) + testSaGCPBackendPolicyCookieUnstructured, err := i2gw.CastToUnstructured(&testSaGCPBackendPolicyCookie) + if err != nil { + t.Errorf("Failed to generate unstructured GCP Backend Policy with Cookie-based session affinity feature: %v", err) + } + + testSaGCPBackendPolicyClientIP := gkegatewayv1.GCPBackendPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testSaBackendPolicyName, + }, + Spec: gkegatewayv1.GCPBackendPolicySpec{ + Default: &gkegatewayv1.GCPBackendPolicyConfig{ + SessionAffinity: &gkegatewayv1.SessionAffinityConfig{ + Type: ptrTo("CLIENT_IP"), + }, + }, + TargetRef: v1alpha2.NamespacedPolicyTargetReference{ + Group: "", + Kind: "Service", + Name: gatewayv1.ObjectName(testServiceName), + }, + }, + } + testSaGCPBackendPolicyClientIP.SetGroupVersionKind(GCPBackendPolicyGVK) + testSaGCPBackendPolicyClientIPUnstructured, err := i2gw.CastToUnstructured(&testSaGCPBackendPolicyClientIP) + if err != nil { + t.Errorf("Failed to generate unstructured GCP Backend Policy with ClientIP-based session affinity feature: %v", err) + } + testCases := []struct { + name string + ir intermediate.IR + expectedGatewayResources i2gw.GatewayResources + expectedErrors field.ErrorList + }{ + { + name: "ingress with a Backend Config specifying CLIENT_IP type session affinity config", + ir: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: testGatewayName}: { + Gateway: testGateway, + }, + }, + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: testHTTPRouteName}: { + HTTPRoute: testHTTPRoute, + }, + }, + Services: map[types.NamespacedName]intermediate.ProviderSpecificServiceIR{ + {Namespace: testNamespace, Name: testServiceName}: { + Gce: &intermediate.GceServiceIR{ + SessionAffinity: &intermediate.SessionAffinityConfig{ + AffinityType: saTypeClientIP, + }, + }, + }, + }, + }, + expectedGatewayResources: i2gw.GatewayResources{ + Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + {Namespace: testNamespace, Name: testGatewayName}: testGateway, + }, + HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + {Namespace: testNamespace, Name: testHTTPRouteName}: testHTTPRoute, + }, + GatewayExtensions: []unstructured.Unstructured{ + *testSaGCPBackendPolicyClientIPUnstructured, + }, + }, + expectedErrors: field.ErrorList{}, + }, + { + name: "ingress with a Backend Config specifying GENERATED_COOKIE type session affinity config", + ir: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: testGatewayName}: { + Gateway: testGateway, + }, + }, + HTTPRoutes: map[types.NamespacedName]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: testHTTPRouteName}: { + HTTPRoute: testHTTPRoute, + }, + }, + Services: map[types.NamespacedName]intermediate.ProviderSpecificServiceIR{ + {Namespace: testNamespace, Name: testServiceName}: { + Gce: &intermediate.GceServiceIR{ + SessionAffinity: &intermediate.SessionAffinityConfig{ + AffinityType: saTypeCookie, + CookieTTLSec: &testCookieTTLSec, + }, + }, + }, + }, + }, + expectedGatewayResources: i2gw.GatewayResources{ + Gateways: map[types.NamespacedName]gatewayv1.Gateway{ + {Namespace: testNamespace, Name: testGatewayName}: testGateway, + }, + HTTPRoutes: map[types.NamespacedName]gatewayv1.HTTPRoute{ + {Namespace: testNamespace, Name: testHTTPRouteName}: testHTTPRoute, + }, + GatewayExtensions: []unstructured.Unstructured{ + *testSaGCPBackendPolicyCookieUnstructured, + }, + }, + expectedErrors: field.ErrorList{}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + + provider := NewProvider(&i2gw.ProviderConf{}) + gceProvider := provider.(*Provider) + gatewayResources, errs := gceProvider.gatewayConverter.irToGateway(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(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 { + got.SetGroupVersionKind(common.HTTPRouteGVK) + 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 { + got.SetGroupVersionKind(common.GatewayGVK) + 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)) + } + } + } + + if len(gatewayResources.GatewayExtensions) != len(tc.expectedGatewayResources.GatewayExtensions) { + t.Errorf("Expected %d GatewayExtensions, got %d: %+v", + len(tc.expectedGatewayResources.GatewayExtensions), len(gatewayResources.GatewayExtensions), gatewayResources.GatewayExtensions) + } else { + for _, got := range gatewayResources.GatewayExtensions { + for _, want := range tc.expectedGatewayResources.GatewayExtensions { + if got.GetNamespace() != want.GetNamespace() || got.GetName() != want.GetName() { + continue + } + if !apiequality.Semantic.DeepEqual(got, want) { + t.Errorf("Expected GatewayExtension %s/%s to be %+v\n Got: %+v\n Diff: %s", got.GetNamespace(), got.GetName(), want, got, cmp.Diff(want, got)) + } + } + } + } + }) + } +} diff --git a/pkg/i2gw/providers/gce/gce.go b/pkg/i2gw/providers/gce/gce.go index 602a0c5b..5c1dcd97 100644 --- a/pkg/i2gw/providers/gce/gce.go +++ b/pkg/i2gw/providers/gce/gce.go @@ -21,7 +21,9 @@ import ( "fmt" "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" "k8s.io/apimachinery/pkg/util/validation/field" + backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" ) const ProviderName = "gce" @@ -32,16 +34,25 @@ func init() { // Provider implements the i2gw.Provider interface. type Provider struct { - storage *storage - reader reader - converter converter + storage *storage + reader reader + irConverter resourcesToIRConverter + gatewayConverter irToGatewayResourcesConverter } func NewProvider(conf *i2gw.ProviderConf) i2gw.Provider { + // Add BackendConfig to Schema when reading in-cluster so these resources + // can be recognized. + if conf.Client != nil { + if err := backendconfigv1.AddToScheme(conf.Client.Scheme()); err != nil { + notify(notifications.ErrorNotification, "Failed to add v1 BackendConfig Scheme") + } + } return &Provider{ - storage: newResourcesStorage(), - reader: newResourceReader(conf), - converter: newConverter(conf), + storage: newResourcesStorage(), + reader: newResourceReader(conf), + irConverter: newResourceToIRConverter(conf), + gatewayConverter: newIRToGatewayResourcesConverter(), } } @@ -67,5 +78,9 @@ func (p *Provider) ReadResourcesFromFile(_ context.Context, filename string) err // ToGatewayAPI converts stored Ingress GCE API entities to // i2gw.GatewayResources including the ingress-gce specific features. func (p *Provider) ToGatewayAPI() (i2gw.GatewayResources, field.ErrorList) { - return p.converter.convert(p.storage) + ir, err := p.irConverter.convertToIR(p.storage) + if err != nil { + return i2gw.GatewayResources{}, err + } + return p.gatewayConverter.irToGateway(ir) } diff --git a/pkg/i2gw/providers/gce/gce_extensions.go b/pkg/i2gw/providers/gce/gce_extensions.go new file mode 100644 index 00000000..d566d575 --- /dev/null +++ b/pkg/i2gw/providers/gce/gce_extensions.go @@ -0,0 +1,198 @@ +/* +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 gce + +import ( + "context" + "encoding/json" + + gkegatewayv1 "github.com/GoogleCloudPlatform/gke-gateway-api/apis/networking/v1" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/intermediate" + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/notifications" + apiv1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" +) + +type serviceNames []types.NamespacedName + +func buildGceServiceIR(ctx context.Context, storage *storage, ir *intermediate.IR) { + if ir.Services == nil { + ir.Services = make(map[types.NamespacedName]intermediate.ProviderSpecificServiceIR) + } + + beConfigToSvcs := getBackendConfigMapping(ctx, storage) + for beConfigKey, beConfig := range storage.BackendConfigs { + if beConfig == nil { + continue + } + gceServiceIR := beConfigToGceServiceIR(beConfig) + services := beConfigToSvcs[beConfigKey] + for _, svcKey := range services { + serviceIR := ir.Services[svcKey] + serviceIR.Gce = &gceServiceIR + ir.Services[svcKey] = serviceIR + } + } +} + +func getBackendConfigMapping(ctx context.Context, storage *storage) map[types.NamespacedName]serviceNames { + beConfigToSvcs := make(map[types.NamespacedName]serviceNames) + + for _, service := range storage.Services { + svc := types.NamespacedName{Namespace: service.Namespace, Name: service.Name} + ctx = context.WithValue(ctx, serviceKey, service) + + // Read BackendConfig based on v1 BackendConfigKey. + beConfigName, exists := getBackendConfigName(ctx, service, backendConfigKey) + if exists { + beConfigKey := types.NamespacedName{Namespace: service.Namespace, Name: beConfigName} + beConfigToSvcs[beConfigKey] = append(beConfigToSvcs[beConfigKey], svc) + continue + } + + // Read BackendConfig based on v1beta1 BackendConfigKey. + beConfigName, exists = getBackendConfigName(ctx, service, betaBackendConfigKey) + if exists { + beConfigKey := types.NamespacedName{Namespace: service.Namespace, Name: beConfigName} + beConfigToSvcs[beConfigKey] = append(beConfigToSvcs[beConfigKey], svc) + continue + } + } + return beConfigToSvcs +} + +// Get names of the BackendConfig in the cluster based on the BackendConfig +// annotation on k8s Services. +func getBackendConfigName(ctx context.Context, service *apiv1.Service, backendConfigKey string) (string, bool) { + val, exists := getBackendConfigAnnotation(service, backendConfigKey) + if !exists { + return "", false + } + + return parseBackendConfigName(ctx, val) +} + +// Get the backend config annotation from the K8s service if it exists. +func getBackendConfigAnnotation(service *apiv1.Service, backendConfigKey string) (string, bool) { + val, ok := service.Annotations[backendConfigKey] + if ok { + return val, ok + } + return "", false +} + +type backendConfigs struct { + Default string `json:"default,omitempty"` + Ports map[string]string `json:"ports,omitempty"` +} + +// Parse the name of the BackendConfig based on the annotation. +// If different BackendConfigs are used on the same service, pick the one with +// the alphabetically smallest name. +func parseBackendConfigName(ctx context.Context, val string) (string, bool) { + service := ctx.Value(serviceKey).(*apiv1.Service) + + var configs backendConfigs + if err := json.Unmarshal([]byte(val), &configs); err != nil { + notify(notifications.ErrorNotification, "BackendConfig annotation is invalid json", service) + return "", false + } + + if configs.Default == "" && len(configs.Ports) == 0 { + notify(notifications.ErrorNotification, "No BackendConfig's found in annotation", service) + return "", false + } + + if len(configs.Ports) != 0 { + notify(notifications.ErrorNotification, "HealthCheckPolicy and GCPBackendPolicy can only be attached on the whole service, so having a dedicate policy for each port is not yet supported. Picking the first BackendConfig to translate to corresponding Gateway policy.", service) + // Return the BackendConfig associated with the alphabetically smallest port. + var backendConfigName string + var lowestPort string + for p, name := range configs.Ports { + if lowestPort == "" || p < lowestPort { + backendConfigName = name + lowestPort = p + } + } + return backendConfigName, true + } + return configs.Default, true +} + +func beConfigToGceServiceIR(beConfig *backendconfigv1.BackendConfig) intermediate.GceServiceIR { + var gceServiceIR intermediate.GceServiceIR + if beConfig.Spec.SessionAffinity != nil { + saConfig := intermediate.SessionAffinityConfig{ + AffinityType: beConfig.Spec.SessionAffinity.AffinityType, + CookieTTLSec: beConfig.Spec.SessionAffinity.AffinityCookieTtlSec, + } + gceServiceIR.SessionAffinity = &saConfig + } + + return gceServiceIR +} + +func buildGceServiceExtensions(ir intermediate.IR, gatewayResources *i2gw.GatewayResources) { + for svcKey, serviceIR := range ir.Services { + bePolicy := addBackendPolicyIfConfigured(svcKey, serviceIR) + if bePolicy == nil { + continue + } + obj, err := i2gw.CastToUnstructured(bePolicy) + if err != nil { + notify(notifications.ErrorNotification, "Failed to cast GCPBackendPolicy to unstructured", bePolicy) + continue + } + gatewayResources.GatewayExtensions = append(gatewayResources.GatewayExtensions, *obj) + } +} + +func addBackendPolicyIfConfigured(serviceNamespacedName types.NamespacedName, serviceIR intermediate.ProviderSpecificServiceIR) *gkegatewayv1.GCPBackendPolicy { + if serviceIR.Gce == nil || serviceIR.Gce.SessionAffinity == nil { + return nil + } + affinityType := serviceIR.Gce.SessionAffinity.AffinityType + backendPolicy := gkegatewayv1.GCPBackendPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: serviceNamespacedName.Namespace, + Name: serviceNamespacedName.Name, + }, + Spec: gkegatewayv1.GCPBackendPolicySpec{ + Default: &gkegatewayv1.GCPBackendPolicyConfig{ + SessionAffinity: &gkegatewayv1.SessionAffinityConfig{ + Type: &affinityType, + }, + }, + TargetRef: gatewayv1alpha2.NamespacedPolicyTargetReference{ + Group: "", + Kind: "Service", + Name: gatewayv1.ObjectName(serviceNamespacedName.Name), + }, + }, + } + if affinityType == "GENERATED_COOKIE" { + backendPolicy.Spec.Default.SessionAffinity.CookieTTLSec = serviceIR.Gce.SessionAffinity.CookieTTLSec + } + + backendPolicy.SetGroupVersionKind(GCPBackendPolicyGVK) + return &backendPolicy +} diff --git a/pkg/i2gw/providers/gce/gce_extensions_test.go b/pkg/i2gw/providers/gce/gce_extensions_test.go new file mode 100644 index 00000000..49ddb5cc --- /dev/null +++ b/pkg/i2gw/providers/gce/gce_extensions_test.go @@ -0,0 +1,239 @@ +/* +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 gce + +import ( + "context" + "reflect" + "testing" + + "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw" + apiv1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" +) + +func TestGetBackendConfigMapping(t *testing.T) { + t.Parallel() + testNamespace := "test-namespace" + + testServiceName := "test-service" + testBeConfigName1 := "backendconfig-1" + testBeConfigName2 := "backendconfig-2" + backendConfigs := map[types.NamespacedName]*backendconfigv1.BackendConfig{ + {Namespace: testNamespace, Name: testBeConfigName1}: {}, + {Namespace: testNamespace, Name: testBeConfigName2}: {}, + } + expectedServices := serviceNames{ + {Namespace: testNamespace, Name: testServiceName}, + } + + testCases := []struct { + desc string + services map[types.NamespacedName]*apiv1.Service + expectedServices serviceNames + }{ + { + desc: "Specify BackendConfig with cloud.google.com/backend-config annotation, using the same BackendConfig for all ports", + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + backendConfigKey: `{"default":"backendconfig-1"}`, + }, + }, + }, + }, + expectedServices: expectedServices, + }, + { + desc: "Specify BackendConfig with beta.cloud.google.com/backend-config annotation, using the same BackendConfig for all ports", + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + betaBackendConfigKey: `{"default":"backendconfig-1"}`, + }, + }, + }, + }, + expectedServices: expectedServices, + }, + { + desc: "Specify BackendConfig with both cloud.google.com/backend-config and beta.cloud.google.com/backend-config annotation, using the same BackendConfig for all ports, cloud.google.com/backend-config should have precedence over the beta one", + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + backendConfigKey: `{"default":"backendconfig-1"}`, + betaBackendConfigKey: `{"ports": {"port1": "backendconfig-1", "port2": "backendconfig-2"}}`, + }, + }, + }, + }, + expectedServices: expectedServices, + }, + { + desc: "Specify BackendConfig with cloud.google.com/backend-config annotation, using different BackendConfigs for each port, service will be associated with the BackendConfig for the alphabetically smallest port", + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + backendConfigKey: `{"ports": {"port1": "backendconfig-1", "port2": "backendconfig-2"}}`, + }, + }, + }, + }, + expectedServices: expectedServices, + }, + { + desc: "Specify BackendConfig with beta.cloud.google.com/backend-config annotation, using different BackendConfigs for each port, service will be associated with the BackendConfig for the alphabetically smallest port", + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + betaBackendConfigKey: `{"ports": {"port1": "backendconfig-1", "port2": "backendconfig-2"}}`, + }, + }, + }, + }, + expectedServices: expectedServices, + }, + { + desc: "Specify BackendConfig with both cloud.google.com/backend-config and beta.cloud.google.com/backend-config annotation, using different BackendConfigs for each port, service will be associated with the BackendConfig for the alphabetically smallest port, cloud.google.com/backend-config should have precedence over the beta one", + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + backendConfigKey: `{"ports": {"port1": "backendconfig-1", "port2": "backendconfig-2"}}`, + betaBackendConfigKey: `{"default":"backendconfig-1"}`, + }, + }, + }, + }, + expectedServices: expectedServices, + }, + } + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + provider := NewProvider(&i2gw.ProviderConf{}) + gceProvider := provider.(*Provider) + gceProvider.storage = newResourcesStorage() + gceProvider.storage.Services = tc.services + gceProvider.storage.BackendConfigs = backendConfigs + + beConfigToSvcs := getBackendConfigMapping(context.TODO(), gceProvider.storage) + backendConfigKey := types.NamespacedName{Namespace: testNamespace, Name: testBeConfigName1} + gotServiceList := beConfigToSvcs[backendConfigKey] + if len(gotServiceList) != len(tc.expectedServices) { + t.Errorf("Got BackendConfig mapped to %d services, expected %d", len(gotServiceList), len(tc.expectedServices)) + } + if !reflect.DeepEqual(gotServiceList, tc.expectedServices) { + t.Errorf("Got BackendConfig mapped to %v, expected %v", gotServiceList, tc.expectedServices) + } + }) + } +} + +func TestGetBackendConfigName(t *testing.T) { + t.Parallel() + + testNamespace := "test-namespace" + testServiceName := "test-service" + testBeConfigName := "backendconfig-1" + + testCases := []struct { + desc string + service *apiv1.Service + beConfigKey string + expectedName string + expectedExists bool + }{ + { + desc: "Service using cloud.google.com/backend-config, using default Config over all ports", + service: &apiv1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + backendConfigKey: `{"default":"backendconfig-1"}`, + }, + }, + }, + beConfigKey: backendConfigKey, + expectedName: testBeConfigName, + expectedExists: true, + }, + { + desc: "Service using beta.cloud.google.com/backend-config annotation, using default Config over all ports", + service: &apiv1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + betaBackendConfigKey: `{"default":"backendconfig-1"}`, + }, + }, + }, + beConfigKey: betaBackendConfigKey, + expectedName: testBeConfigName, + expectedExists: true, + }, + { + desc: "Service using cloud.google.com/backend-config, using Port Config, pick the BackendConfig with the alphabetically smallest port", + service: &apiv1.Service{ + ObjectMeta: metav1.ObjectMeta{ + Name: testServiceName, + Namespace: testNamespace, + Annotations: map[string]string{ + backendConfigKey: `{"ports": {"port1": "backendconfig-1", "port2": "backendconfig-2"}}`, + }, + }, + }, + beConfigKey: backendConfigKey, + expectedName: "backendconfig-1", + expectedExists: true, + }, + } + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + ctx := context.TODO() + ctx = context.WithValue(ctx, serviceKey, tc.service) + gotName, gotExists := getBackendConfigName(ctx, tc.service, tc.beConfigKey) + if gotExists != tc.expectedExists { + t.Errorf("getBackendConfigName() got exist = %v, expected %v", gotExists, tc.expectedExists) + } + if gotName != tc.expectedName { + t.Errorf("getBackendConfigName() got exist = %v, expected %v", gotName, tc.expectedName) + } + }) + } +} diff --git a/pkg/i2gw/providers/gce/converter.go b/pkg/i2gw/providers/gce/ir_converter.go similarity index 65% rename from pkg/i2gw/providers/gce/converter.go rename to pkg/i2gw/providers/gce/ir_converter.go index e5d183f7..83e7c51b 100644 --- a/pkg/i2gw/providers/gce/converter.go +++ b/pkg/i2gw/providers/gce/ir_converter.go @@ -17,33 +17,42 @@ limitations under the License. package gce import ( + "context" + "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" networkingv1beta1 "k8s.io/api/networking/v1beta1" "k8s.io/apimachinery/pkg/util/validation/field" ) +type contextKey int + +const ( + serviceKey contextKey = iota +) + // converter implements the ToGatewayAPI function of i2gw.ResourceConverter interface. -type converter struct { +type resourcesToIRConverter struct { conf *i2gw.ProviderConf - featureParsers []i2gw.FeatureParser implementationSpecificOptions i2gw.ProviderImplementationSpecificOptions + ctx context.Context } -// newConverter returns an ingress-gce converter instance. -func newConverter(conf *i2gw.ProviderConf) converter { - return converter{ - conf: conf, - featureParsers: []i2gw.FeatureParser{}, +// newConverter returns an ingress-gce resourcesToIRConverter instance. +func newResourceToIRConverter(conf *i2gw.ProviderConf) resourcesToIRConverter { + return resourcesToIRConverter{ + conf: conf, implementationSpecificOptions: i2gw.ProviderImplementationSpecificOptions{ ToImplementationSpecificHTTPPathTypeMatch: implementationSpecificHTTPPathTypeMatch, }, + ctx: context.Background(), } } -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 { if ing != nil && common.GetIngressClass(*ing) == "" { @@ -57,22 +66,15 @@ func (c *converter) convert(storage *storage) (i2gw.GatewayResources, field.Erro // 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 } - errs = setGCEGatewayClasses(ingressList, &gatewayResources) + errs = setGCEGatewayClasses(ingressList, ir.Gateways) 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) - // Append the parsing errors to the error list. - errs = append(errs, parseErrs...) - } - - return gatewayResources, errs + buildGceServiceIR(c.ctx, storage, &ir) + return ir, errs } diff --git a/pkg/i2gw/providers/gce/ir_converter_test.go b/pkg/i2gw/providers/gce/ir_converter_test.go new file mode 100644 index 00000000..d4e88a0f --- /dev/null +++ b/pkg/i2gw/providers/gce/ir_converter_test.go @@ -0,0 +1,1547 @@ +/* +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 gce + +import ( + "errors" + "fmt" + "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" + apiv1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + networkingv1beta1 "k8s.io/api/networking/v1beta1" + 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" + backendconfigv1 "k8s.io/ingress-gce/pkg/apis/backendconfig/v1" + 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" + testServiceName := "test-service" + testBackendConfigName := "test-backendconfig" + 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" + + saTypeClientIP := "CLIENT_IP" + testCookieTTLSec := int64(10) + saTypeCookie := "GENERATED_COOKIE" + + testCases := []struct { + name string + ingresses map[types.NamespacedName]*networkingv1.Ingress + services map[types.NamespacedName]*apiv1.Service + backendConfigs map[types.NamespacedName]*backendconfigv1.BackendConfig + expectedIR intermediate.IR + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceL7ILBIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: "gce-internal-ingress-class-test-mydomain-com"}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", noIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + expectedErrors: field.ErrorList{}, + }, + { + name: "ingress with a Backend Config specifying CLIENT_IP type session affinity config", + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + Annotations: map[string]string{ + backendConfigKey: `{"default":"test-backendconfig"}`, + }, + }, + }, + }, + backendConfigs: map[types.NamespacedName]*backendconfigv1.BackendConfig{ + {Namespace: testNamespace, Name: testBackendConfigName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testBackendConfigName, + }, + Spec: backendconfigv1.BackendConfigSpec{ + SessionAffinity: &backendconfigv1.SessionAffinityConfig{ + AffinityType: saTypeClientIP, + }, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + Services: map[types.NamespacedName]intermediate.ProviderSpecificServiceIR{ + {Namespace: testNamespace, Name: testServiceName}: { + Gce: &intermediate.GceServiceIR{ + SessionAffinity: &intermediate.SessionAffinityConfig{ + AffinityType: saTypeClientIP, + }, + }, + }, + }, + }, + expectedErrors: field.ErrorList{}, + }, + { + name: "ingress with a Backend Config specifying GENERATED_COOKIE type session affinity config", + 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: testServiceName, + Port: networkingv1.ServiceBackendPort{ + Number: 80, + }, + }, + }, + }}, + }, + }, + }}, + }, + }, + }, + services: map[types.NamespacedName]*apiv1.Service{ + {Namespace: testNamespace, Name: testServiceName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testServiceName, + Annotations: map[string]string{ + backendConfigKey: `{"default":"test-backendconfig"}`, + }, + }, + }, + }, + backendConfigs: map[types.NamespacedName]*backendconfigv1.BackendConfig{ + {Namespace: testNamespace, Name: testBackendConfigName}: { + ObjectMeta: metav1.ObjectMeta{ + Namespace: testNamespace, + Name: testBackendConfigName, + }, + Spec: backendconfigv1.BackendConfigSpec{ + SessionAffinity: &backendconfigv1.SessionAffinityConfig{ + AffinityType: saTypeCookie, + AffinityCookieTtlSec: &testCookieTTLSec, + }, + }, + }, + }, + expectedIR: intermediate.IR{ + Gateways: map[types.NamespacedName]intermediate.GatewayContext{ + {Namespace: testNamespace, Name: gceIngressClass}: { + Gateway: gatewayv1.Gateway{ + 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]intermediate.HTTPRouteContext{ + {Namespace: testNamespace, Name: fmt.Sprintf("%s-test-mydomain-com", extIngClassIngressName)}: { + HTTPRoute: gatewayv1.HTTPRoute{ + 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(testServiceName), + Port: ptrTo(gatewayv1.PortNumber(80)), + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + Services: map[types.NamespacedName]intermediate.ProviderSpecificServiceIR{ + {Namespace: testNamespace, Name: testServiceName}: { + Gce: &intermediate.GceServiceIR{ + SessionAffinity: &intermediate.SessionAffinityConfig{ + AffinityType: saTypeCookie, + CookieTTLSec: &testCookieTTLSec, + }, + }, + }, + }, + }, + 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 + gceProvider.storage.Services = tc.services + gceProvider.storage.BackendConfigs = tc.backendConfigs + + // TODO(#113) we pass an empty i2gw.InputResources temporarily until we change ToIR function on the interface + ir, errs := gceProvider.irConverter.convertToIR(gceProvider.storage) + + 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(ir.HTTPRoutes) != len(tc.expectedIR.HTTPRoutes) { + t.Errorf("Expected %d HTTPRoutes, got %d: %+v", + len(tc.expectedIR.HTTPRoutes), len(ir.HTTPRoutes), ir.HTTPRoutes) + } else { + 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(ir.Gateways) != len(tc.expectedIR.Gateways) { + t.Errorf("Expected %d Gateways, got %d: %+v", + len(tc.expectedIR.Gateways), len(ir.Gateways), ir.Gateways) + } else { + 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)) + } + } + } + + if len(ir.Services) != len(tc.expectedIR.Services) { + t.Errorf("Expected %d ServiceIR, got %d: %+v", + len(tc.expectedIR.Services), len(ir.Services), ir.Services) + } else { + for svcKey, gotServiceIR := range ir.Services { + key := types.NamespacedName{Namespace: svcKey.Namespace, Name: svcKey.Name} + wantServiceIR := tc.expectedIR.Services[key] + if !apiequality.Semantic.DeepEqual(gotServiceIR, wantServiceIR) { + t.Errorf("Expected ServiceIR %s to be %+v\n Got: %+v\n Diff: %s", svcKey, wantServiceIR, gotServiceIR, cmp.Diff(wantServiceIR, gotServiceIR)) + } + } + } + }) + } +} + +func ptrTo[T any](a T) *T { + return &a +} diff --git a/pkg/i2gw/providers/gce/storage.go b/pkg/i2gw/providers/gce/storage.go index faf1a282..71fac57a 100644 --- a/pkg/i2gw/providers/gce/storage.go +++ b/pkg/i2gw/providers/gce/storage.go @@ -25,12 +25,12 @@ import ( type storage struct { Ingresses map[types.NamespacedName]*networkingv1.Ingress + Services map[types.NamespacedName]*apiv1.Service // BackendConfig is a GKE Ingress extension, and it is associated to an GKE // Ingress through specifying `cloud.google.com/backend-config` or - // `beta.cloud.google.com/backend-config` annotation on its Backend Services. - - Services map[types.NamespacedName]*apiv1.Service + // `beta.cloud.google.com/backend-config` annotation on its Services. + // BackendConfig map is keyed by the namespaced name of the BackendConfig. BackendConfigs map[types.NamespacedName]*backendconfigv1.BackendConfig } diff --git a/pkg/i2gw/providers/gce/types.go b/pkg/i2gw/providers/gce/types.go index 08b00be8..974bb745 100644 --- a/pkg/i2gw/providers/gce/types.go +++ b/pkg/i2gw/providers/gce/types.go @@ -16,10 +16,20 @@ limitations under the License. package gce +import "k8s.io/apimachinery/pkg/runtime/schema" + const ( gceIngressClass = "gce" gceL7ILBIngressClass = "gce-internal" gceL7GlobalExternalManagedGatewayClass = "gke-l7-global-external-managed" gceL7RegionalInternalGatewayClass = "gke-l7-rilb" + backendConfigKey = "cloud.google.com/backend-config" + betaBackendConfigKey = "beta.cloud.google.com/backend-config" ) + +var GCPBackendPolicyGVK = schema.GroupVersionKind{ + Group: "networking.gke.io", + Version: "v1", + Kind: "GCPBackendPolicy", +} diff --git a/pkg/i2gw/providers/gce/utils.go b/pkg/i2gw/providers/gce/utils.go index ef431d53..513ed31f 100644 --- a/pkg/i2gw/providers/gce/utils.go +++ b/pkg/i2gw/providers/gce/utils.go @@ -19,7 +19,7 @@ package gce 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" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/types" @@ -28,7 +28,7 @@ import ( ) // setGCEGatewayClasses updates the list of Gateways to use GCE GatewayClass. -func setGCEGatewayClasses(ingresses []networkingv1.Ingress, gatewayResources *i2gw.GatewayResources) field.ErrorList { +func setGCEGatewayClasses(ingresses []networkingv1.Ingress, gatewayContexts map[types.NamespacedName]intermediate.GatewayContext) field.ErrorList { var errs field.ErrorList // Since we already validated ingress resources when reading, there are @@ -40,13 +40,13 @@ func setGCEGatewayClasses(ingresses []networkingv1.Ingress, gatewayResources *i2 // mapped to `gke-l7-global-external-managed`. for _, ingress := range ingresses { gwKey := types.NamespacedName{Namespace: ingress.Namespace, Name: common.GetIngressClass(ingress)} - existingGateway := gatewayResources.Gateways[gwKey] + existingGateway := gatewayContexts[gwKey].Gateway newGateway, err := setGCEGatewayClass(ingress, existingGateway) if err != nil { errs = append(errs, err) } - gatewayResources.Gateways[gwKey] = newGateway + gatewayContexts[gwKey] = intermediate.GatewayContext{Gateway: newGateway} } if len(errs) > 0 { return errs From 859f2c9ca8a01d1c1007ea02b7f30ec864059583 Mon Sep 17 00:00:00 2001 From: David Cheung Date: Thu, 22 Aug 2024 22:33:41 +0000 Subject: [PATCH 10/10] Migrate all providers to the new interface. * Providers now should implement ResourcesToIRConverter interface and IRToGatewayAPIConverter interface. --- pkg/i2gw/ingress2gateway.go | 72 +-- 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 +- 35 files changed, 1194 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/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 5c1dcd97..a355ce86 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) {