diff --git a/internal/cmd/egctl/config.go b/internal/cmd/egctl/config.go index eb3dd5b8d12..bdba859ed9c 100644 --- a/internal/cmd/egctl/config.go +++ b/internal/cmd/egctl/config.go @@ -331,7 +331,7 @@ func portForwarder(nn types.NamespacedName) (kube.PortForwarder, error) { return nil, fmt.Errorf("pod %s is not running", nn) } - fw, err := kube.NewLocalPortForwarder(c, nn, 0, int(adminPort)) + fw, err := kube.NewLocalPortForwarder(c, nn, 0, adminPort) if err != nil { return nil, err } diff --git a/internal/cmd/egctl/translate.go b/internal/cmd/egctl/translate.go index cc697c17ac1..6aa4706802d 100644 --- a/internal/cmd/egctl/translate.go +++ b/internal/cmd/egctl/translate.go @@ -21,7 +21,7 @@ import ( adminv3 "github.com/envoyproxy/go-control-plane/envoy/admin/v3" bootstrapv3 "github.com/envoyproxy/go-control-plane/envoy/config/bootstrap/v3" - resource "github.com/envoyproxy/go-control-plane/pkg/resource/v3" + resourcev3 "github.com/envoyproxy/go-control-plane/pkg/resource/v3" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -289,7 +289,7 @@ func constructConfigDump(tCtx *xds_types.ResourceVersionTable) (*adminv3.ConfigD } // construct clusters config - clusters := tCtx.XdsResources[resource.ClusterType] + clusters := tCtx.XdsResources[resourcev3.ClusterType] for _, cluster := range clusters { c, err := anypb.New(cluster) if err != nil { @@ -307,7 +307,7 @@ func constructConfigDump(tCtx *xds_types.ResourceVersionTable) (*adminv3.ConfigD } // construct listeners config - listeners := tCtx.XdsResources[resource.ListenerType] + listeners := tCtx.XdsResources[resourcev3.ListenerType] for _, listener := range listeners { l, err := anypb.New(listener) if err != nil { @@ -327,7 +327,7 @@ func constructConfigDump(tCtx *xds_types.ResourceVersionTable) (*adminv3.ConfigD } // construct routes config - routes := tCtx.XdsResources[resource.RouteType] + routes := tCtx.XdsResources[resourcev3.RouteType] for _, route := range routes { r, err := anypb.New(route) if err != nil { diff --git a/internal/envoygateway/config/decoder_test.go b/internal/envoygateway/config/decoder_test.go index d71748ec61e..d934a78431b 100644 --- a/internal/envoygateway/config/decoder_test.go +++ b/internal/envoygateway/config/decoder_test.go @@ -153,7 +153,7 @@ func TestDecode(t *testing.T) { require.NoError(t, err) require.Equal(t, tc.out, eg) } else { - require.Equal(t, (!reflect.DeepEqual(tc.out, eg) || err != nil), true) + require.Equal(t, !reflect.DeepEqual(tc.out, eg) || err != nil, true) } }) } diff --git a/internal/gatewayapi/contexts.go b/internal/gatewayapi/contexts.go index 8cc06c6313c..1a0f19f085d 100644 --- a/internal/gatewayapi/contexts.go +++ b/internal/gatewayapi/contexts.go @@ -165,18 +165,18 @@ type RouteContext interface { // GetRouteStatus returns the RouteStatus object associated with the Route. GetRouteStatus() *v1beta1.RouteStatus - // TODO: [v1alpha2-v1beta1] This should not be required once all Route - // objects being implemented are of type v1beta1. // GetParentReferences returns the ParentReference of the Route object. + // objects being implemented are of type v1beta1. + // TODO: [v1alpha2-v1beta1] This should not be required once all Route GetParentReferences() []v1beta1.ParentReference // GetRouteParentContext returns RouteParentContext by using the Route // objects' ParentReference. GetRouteParentContext(forParentRef v1beta1.ParentReference) *RouteParentContext - // TODO: [v1alpha2-v1beta1] This should not be required once all Route - // objects being implemented are of type v1beta1. // GetHostnames returns the hosts targeted by the Route object. + // objects being implemented are of type v1beta1. + // TODO: [v1alpha2-v1beta1] This should not be required once all Route GetHostnames() []string } diff --git a/internal/gatewayapi/listener.go b/internal/gatewayapi/listener.go index 7952d6c14c7..76d6ba30d70 100644 --- a/internal/gatewayapi/listener.go +++ b/internal/gatewayapi/listener.go @@ -21,7 +21,6 @@ type ListenersTranslator interface { } func (t *Translator) ProcessListeners(gateways []*GatewayContext, xdsIR XdsIRMap, infraIR InfraIRMap, resources *Resources) { - t.validateConflictedLayer7Listeners(gateways) t.validateConflictedLayer4Listeners(gateways, v1beta1.TCPProtocolType) t.validateConflictedLayer4Listeners(gateways, v1beta1.UDPProtocolType) diff --git a/internal/gatewayapi/sort.go b/internal/gatewayapi/sort.go index 6a7d1cc2a24..0fed937d42c 100644 --- a/internal/gatewayapi/sort.go +++ b/internal/gatewayapi/sort.go @@ -48,8 +48,8 @@ func (x XdsIRRoutes) Less(i, j int) bool { // defined in the Gateway API spec. // https://gateway-api.sigs.k8s.io/references/spec/#gateway.networking.k8s.io/v1beta1.HTTPRouteRule func sortXdsIRMap(xdsIR XdsIRMap) { - for _, ir := range xdsIR { - for _, http := range ir.HTTP { + for _, irItem := range xdsIR { + for _, http := range irItem.HTTP { // descending order sort.Sort(sort.Reverse(XdsIRRoutes(http.Routes))) } diff --git a/internal/gatewayapi/validate.go b/internal/gatewayapi/validate.go index ee2bd32ffe7..b76fc26ccb8 100644 --- a/internal/gatewayapi/validate.go +++ b/internal/gatewayapi/validate.go @@ -275,7 +275,7 @@ func (t *Translator) validateTLSConfiguration(listener *ListenerContext, resourc if certificateRef.Namespace != nil && string(*certificateRef.Namespace) != "" && string(*certificateRef.Namespace) != listener.gateway.Namespace { if !t.validateCrossNamespaceRef( crossNamespaceFrom{ - group: string(v1beta1.GroupName), + group: v1beta1.GroupName, kind: KindGateway, namespace: listener.gateway.Namespace, }, diff --git a/internal/globalratelimit/runner/runner.go b/internal/globalratelimit/runner/runner.go index 053dd31fb0f..0dd36f802f9 100644 --- a/internal/globalratelimit/runner/runner.go +++ b/internal/globalratelimit/runner/runner.go @@ -78,9 +78,9 @@ func (r *Runner) translate(xdsIRs []*ir.Xds) (*ir.RateLimitInfra, error) { for _, xdsIR := range xdsIRs { for _, listener := range xdsIR.HTTP { - config := translator.BuildRateLimitServiceConfig(listener) - if config != nil { - str, err := translator.GetRateLimitServiceConfigStr(config) + cfg := translator.BuildRateLimitServiceConfig(listener) + if cfg != nil { + str, err := translator.GetRateLimitServiceConfigStr(cfg) if err != nil { return nil, fmt.Errorf("failed to get rate limit config string: %w", err) } diff --git a/internal/infrastructure/kubernetes/infra.go b/internal/infrastructure/kubernetes/infra.go index 7c2a4ab28c0..0037319f9bd 100644 --- a/internal/infrastructure/kubernetes/infra.go +++ b/internal/infrastructure/kubernetes/infra.go @@ -6,9 +6,12 @@ package kubernetes import ( + "fmt" + "sigs.k8s.io/controller-runtime/pkg/client" "github.com/envoyproxy/gateway/internal/envoygateway/config" + "github.com/envoyproxy/gateway/internal/provider/utils" ) // Infra manages the creation and deletion of Kubernetes infrastructure @@ -27,3 +30,9 @@ func NewInfra(cli client.Client, cfg *config.Server) *Infra { Namespace: cfg.Namespace, } } + +// expectedResourceHashedName returns hashed resource name. +func expectedResourceHashedName(name string) string { + hashedName := utils.GetHashedName(name) + return fmt.Sprintf("%s-%s", config.EnvoyPrefix, hashedName) +} diff --git a/internal/infrastructure/kubernetes/proxy_configmap.go b/internal/infrastructure/kubernetes/proxy_configmap.go index 8adfa5113ed..f61835ed1e8 100644 --- a/internal/infrastructure/kubernetes/proxy_configmap.go +++ b/internal/infrastructure/kubernetes/proxy_configmap.go @@ -12,10 +12,8 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/envoyproxy/gateway/internal/envoygateway/config" "github.com/envoyproxy/gateway/internal/gatewayapi" "github.com/envoyproxy/gateway/internal/ir" - "github.com/envoyproxy/gateway/internal/provider/utils" ) // expectedProxyConfigMap returns the expected ConfigMap based on the provided infra. @@ -29,7 +27,7 @@ func (i *Infra) expectedProxyConfigMap(infra *ir.Infra) (*corev1.ConfigMap, erro return &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyConfigMapName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), Labels: labels, }, Data: map[string]string{ @@ -55,14 +53,9 @@ func (i *Infra) deleteProxyConfigMap(ctx context.Context, infra *ir.Infra) error cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyConfigMapName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), }, } return i.deleteConfigMap(ctx, cm) } - -func expectedProxyConfigMapName(proxyName string) string { - cMapName := utils.GetHashedName(proxyName) - return fmt.Sprintf("%s-%s", config.EnvoyPrefix, cMapName) -} diff --git a/internal/infrastructure/kubernetes/proxy_deployment.go b/internal/infrastructure/kubernetes/proxy_deployment.go index 40b71b7676e..1fa9c7e98a7 100644 --- a/internal/infrastructure/kubernetes/proxy_deployment.go +++ b/internal/infrastructure/kubernetes/proxy_deployment.go @@ -15,10 +15,8 @@ import ( "k8s.io/utils/pointer" egcfgv1a1 "github.com/envoyproxy/gateway/api/config/v1alpha1" - "github.com/envoyproxy/gateway/internal/envoygateway/config" "github.com/envoyproxy/gateway/internal/gatewayapi" "github.com/envoyproxy/gateway/internal/ir" - "github.com/envoyproxy/gateway/internal/provider/utils" "github.com/envoyproxy/gateway/internal/xds/bootstrap" ) @@ -35,11 +33,6 @@ const ( envoyHTTPSPort = int32(8443) ) -func expectedProxyDeploymentName(proxyName string) string { - deploymentName := utils.GetHashedName(proxyName) - return fmt.Sprintf("%s-%s", config.EnvoyPrefix, deploymentName) -} - // expectedProxyDeployment returns the expected Deployment based on the provided infra. func (i *Infra) expectedProxyDeployment(infra *ir.Infra) (*appsv1.Deployment, error) { containers, err := expectedProxyContainers(infra) @@ -68,7 +61,7 @@ func (i *Infra) expectedProxyDeployment(infra *ir.Infra) (*appsv1.Deployment, er }, ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyDeploymentName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), Labels: labels, }, Spec: appsv1.DeploymentSpec{ @@ -80,7 +73,7 @@ func (i *Infra) expectedProxyDeployment(infra *ir.Infra) (*appsv1.Deployment, er }, Spec: corev1.PodSpec{ Containers: containers, - ServiceAccountName: expectedProxyServiceAccountName(infra.Proxy.Name), + ServiceAccountName: expectedResourceHashedName(infra.Proxy.Name), AutomountServiceAccountToken: pointer.Bool(false), TerminationGracePeriodSeconds: pointer.Int64(int64(300)), DNSPolicy: corev1.DNSClusterFirst, @@ -100,7 +93,7 @@ func (i *Infra) expectedProxyDeployment(infra *ir.Infra) (*appsv1.Deployment, er VolumeSource: corev1.VolumeSource{ ConfigMap: &corev1.ConfigMapVolumeSource{ LocalObjectReference: corev1.LocalObjectReference{ - Name: expectedProxyConfigMapName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), }, Items: []corev1.KeyToPath{ { @@ -214,7 +207,7 @@ func (i *Infra) deleteProxyDeployment(ctx context.Context, infra *ir.Infra) erro deploy := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyDeploymentName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), }, } diff --git a/internal/infrastructure/kubernetes/proxy_deployment_test.go b/internal/infrastructure/kubernetes/proxy_deployment_test.go index 5e0c08b2d5a..a7dfbe210f6 100644 --- a/internal/infrastructure/kubernetes/proxy_deployment_test.go +++ b/internal/infrastructure/kubernetes/proxy_deployment_test.go @@ -121,7 +121,7 @@ func TestExpectedProxyDeployment(t *testing.T) { require.NoError(t, err) // Check the deployment name is as expected. - assert.Equal(t, deploy.Name, expectedProxyDeploymentName(infra.Proxy.Name)) + assert.Equal(t, deploy.Name, expectedResourceHashedName(infra.Proxy.Name)) // Check container details, i.e. env vars, labels, etc. for the deployment are as expected. container := checkContainer(t, deploy, envoyContainerName, true) @@ -226,7 +226,7 @@ func TestCreateOrUpdateProxyDeployment(t *testing.T) { actual := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: kube.Namespace, - Name: expectedProxyDeploymentName(tc.in.Proxy.Name), + Name: expectedResourceHashedName(tc.in.Proxy.Name), }, } require.NoError(t, kube.Client.Get(context.Background(), client.ObjectKeyFromObject(actual), actual)) diff --git a/internal/infrastructure/kubernetes/proxy_infra_test.go b/internal/infrastructure/kubernetes/proxy_infra_test.go index 5b8743e6b05..d37ac084c03 100644 --- a/internal/infrastructure/kubernetes/proxy_infra_test.go +++ b/internal/infrastructure/kubernetes/proxy_infra_test.go @@ -76,7 +76,7 @@ func TestCreateProxyInfra(t *testing.T) { sa := &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Namespace: kube.Namespace, - Name: expectedProxyServiceAccountName(tc.in.Proxy.Name), + Name: expectedResourceHashedName(tc.in.Proxy.Name), }, } require.NoError(t, kube.Client.Get(context.Background(), client.ObjectKeyFromObject(sa), sa)) @@ -84,7 +84,7 @@ func TestCreateProxyInfra(t *testing.T) { cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: kube.Namespace, - Name: expectedProxyConfigMapName(tc.in.Proxy.Name), + Name: expectedResourceHashedName(tc.in.Proxy.Name), }, } require.NoError(t, kube.Client.Get(context.Background(), client.ObjectKeyFromObject(cm), cm)) @@ -92,7 +92,7 @@ func TestCreateProxyInfra(t *testing.T) { deploy := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Namespace: kube.Namespace, - Name: expectedProxyDeploymentName(tc.in.Proxy.Name), + Name: expectedResourceHashedName(tc.in.Proxy.Name), }, } require.NoError(t, kube.Client.Get(context.Background(), client.ObjectKeyFromObject(deploy), deploy)) @@ -100,7 +100,7 @@ func TestCreateProxyInfra(t *testing.T) { svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Namespace: kube.Namespace, - Name: expectedProxyServiceName(tc.in.Proxy.Name), + Name: expectedResourceHashedName(tc.in.Proxy.Name), }, } require.NoError(t, kube.Client.Get(context.Background(), client.ObjectKeyFromObject(svc), svc)) diff --git a/internal/infrastructure/kubernetes/proxy_service.go b/internal/infrastructure/kubernetes/proxy_service.go index f5f808475ce..a5ab6952ef0 100644 --- a/internal/infrastructure/kubernetes/proxy_service.go +++ b/internal/infrastructure/kubernetes/proxy_service.go @@ -13,18 +13,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" - "github.com/envoyproxy/gateway/internal/envoygateway/config" "github.com/envoyproxy/gateway/internal/gatewayapi" "github.com/envoyproxy/gateway/internal/ir" - "github.com/envoyproxy/gateway/internal/provider/utils" ) -func expectedProxyServiceName(proxyName string) string { - svcName := utils.GetHashedName(proxyName) - return fmt.Sprintf("%s-%s", config.EnvoyPrefix, svcName) -} - -// expectedproxyService returns the expected Service based on the provided infra. +// expectedProxyService returns the expected Service based on the provided infra. func (i *Infra) expectedProxyService(infra *ir.Infra) (*corev1.Service, error) { var ports []corev1.ServicePort for _, listener := range infra.Proxy.Listeners { @@ -53,7 +46,7 @@ func (i *Infra) expectedProxyService(infra *ir.Infra) (*corev1.Service, error) { svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyServiceName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), Labels: labels, }, Spec: corev1.ServiceSpec{ @@ -69,7 +62,7 @@ func (i *Infra) expectedProxyService(infra *ir.Infra) (*corev1.Service, error) { return svc, nil } -// createOrUpdateproxyService creates a Service in the kube api server based on the provided infra, +// createOrUpdateProxyService creates a Service in the kube api server based on the provided infra, // if it doesn't exist or updates it if it does. func (i *Infra) createOrUpdateProxyService(ctx context.Context, infra *ir.Infra) error { svc, err := i.expectedProxyService(infra) @@ -84,7 +77,7 @@ func (i *Infra) deleteProxyService(ctx context.Context, infra *ir.Infra) error { svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyServiceName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), }, } diff --git a/internal/infrastructure/kubernetes/proxy_service_test.go b/internal/infrastructure/kubernetes/proxy_service_test.go index 004d77cce3c..240cc30e1b8 100644 --- a/internal/infrastructure/kubernetes/proxy_service_test.go +++ b/internal/infrastructure/kubernetes/proxy_service_test.go @@ -92,7 +92,7 @@ func TestDesiredProxyService(t *testing.T) { require.NoError(t, err) // Check the service name is as expected. - assert.Equal(t, svc.Name, expectedProxyDeploymentName(infra.Proxy.Name)) + assert.Equal(t, svc.Name, expectedResourceHashedName(infra.Proxy.Name)) checkServiceHasPort(t, svc, 80) checkServiceHasPort(t, svc, 443) diff --git a/internal/infrastructure/kubernetes/proxy_serviceaccount.go b/internal/infrastructure/kubernetes/proxy_serviceaccount.go index a59b63b19c3..925be5564a9 100644 --- a/internal/infrastructure/kubernetes/proxy_serviceaccount.go +++ b/internal/infrastructure/kubernetes/proxy_serviceaccount.go @@ -12,17 +12,10 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/envoyproxy/gateway/internal/envoygateway/config" "github.com/envoyproxy/gateway/internal/gatewayapi" "github.com/envoyproxy/gateway/internal/ir" - "github.com/envoyproxy/gateway/internal/provider/utils" ) -func expectedProxyServiceAccountName(proxyName string) string { - svcActName := utils.GetHashedName(proxyName) - return fmt.Sprintf("%s-%s", config.EnvoyPrefix, svcActName) -} - // expectedProxyServiceAccount returns the expected proxy serviceAccount. func (i *Infra) expectedProxyServiceAccount(infra *ir.Infra) (*corev1.ServiceAccount, error) { // Set the labels based on the owning gateway name. @@ -38,7 +31,7 @@ func (i *Infra) expectedProxyServiceAccount(infra *ir.Infra) (*corev1.ServiceAcc }, ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyServiceAccountName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), Labels: labels, }, }, nil @@ -60,7 +53,7 @@ func (i *Infra) deleteProxyServiceAccount(ctx context.Context, infra *ir.Infra) sa := &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Namespace: i.Namespace, - Name: expectedProxyServiceAccountName(infra.Proxy.Name), + Name: expectedResourceHashedName(infra.Proxy.Name), }, } diff --git a/internal/infrastructure/kubernetes/proxy_serviceaccount_test.go b/internal/infrastructure/kubernetes/proxy_serviceaccount_test.go index 6cec635a347..eae2333275b 100644 --- a/internal/infrastructure/kubernetes/proxy_serviceaccount_test.go +++ b/internal/infrastructure/kubernetes/proxy_serviceaccount_test.go @@ -44,7 +44,7 @@ func TestExpectedProxyServiceAccount(t *testing.T) { require.NoError(t, err) // Check the serviceaccount name is as expected. - assert.Equal(t, sa.Name, expectedProxyServiceAccountName(infra.Proxy.Name)) + assert.Equal(t, sa.Name, expectedResourceHashedName(infra.Proxy.Name)) wantLabels := envoyAppLabel() wantLabels[gatewayapi.OwningGatewayNamespaceLabel] = "default" @@ -199,7 +199,7 @@ func TestCreateOrUpdateProxyServiceAccount(t *testing.T) { actual := &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Namespace: kube.Namespace, - Name: expectedProxyServiceAccountName(tc.in.Proxy.Name), + Name: expectedResourceHashedName(tc.in.Proxy.Name), }, } require.NoError(t, kube.Client.Get(context.Background(), client.ObjectKeyFromObject(actual), actual)) diff --git a/internal/ir/xds.go b/internal/ir/xds.go index 39adf9fe37b..59dcedd5d31 100644 --- a/internal/ir/xds.go +++ b/internal/ir/xds.go @@ -20,7 +20,7 @@ var ( ErrListenerAddressInvalid = errors.New("field Address must be a valid IP address") ErrListenerPortInvalid = errors.New("field Port specified is invalid") ErrHTTPListenerHostnamesEmpty = errors.New("field Hostnames must be specified with at least a single hostname entry") - ErrTCPListenesSNIsEmpty = errors.New("field SNIs must be specified with at least a single server name entry") + ErrTCPListenerSNIsEmpty = errors.New("field SNIs must be specified with at least a single server name entry") ErrTLSServerCertEmpty = errors.New("field ServerCertificate must be specified") ErrTLSPrivateKey = errors.New("field PrivateKey must be specified") ErrHTTPRouteNameEmpty = errors.New("field Name must be specified") @@ -181,7 +181,7 @@ func (t TLSListenerConfig) Validate() error { return errs } -// DestinationWeights stores the weights of valid and invalid backends for the route so that 500 error responses can be returned in the same proportions +// BackendWeights stores the weights of valid and invalid backends for the route so that 500 error responses can be returned in the same proportions type BackendWeights struct { Valid uint32 Invalid uint32 @@ -401,7 +401,7 @@ func NewRouteDest(host string, port uint32, weight uint32) *RouteDestination { } } -// Add header configures a header to be added to a request or response. +// AddHeader configures a header to be added to a request or response. // +k8s:deepcopy-gen=true type AddHeader struct { Name string @@ -419,7 +419,7 @@ func (h AddHeader) Validate() error { return errs } -// Direct response holds the details for returning a body and status code for a route. +// DirectResponse holds the details for returning a body and status code for a route. // +k8s:deepcopy-gen=true type DirectResponse struct { // Body configures the body of the direct response. Currently only a string response @@ -439,7 +439,7 @@ func (r DirectResponse) Validate() error { return errs } -// Re holds the details for how to rewrite a request +// URLRewrite holds the details for how to rewrite a request // +k8s:deepcopy-gen=true type URLRewrite struct { // Path contains config for rewriting the path of the request. @@ -629,7 +629,7 @@ type TLSInspectorConfig struct { func (t TLSInspectorConfig) Validate() error { var errs error if len(t.SNIs) == 0 { - errs = multierror.Append(errs, ErrTCPListenesSNIsEmpty) + errs = multierror.Append(errs, ErrTCPListenerSNIsEmpty) } return errs } diff --git a/internal/ir/xds_test.go b/internal/ir/xds_test.go index 38e9790fa16..0c9f92661f7 100644 --- a/internal/ir/xds_test.go +++ b/internal/ir/xds_test.go @@ -596,7 +596,7 @@ func TestValidateTCPListener(t *testing.T) { { name: "tls passthrough empty SNIs", input: invalidSNITCPListenerTLSPassthrough, - want: []error{ErrTCPListenesSNIsEmpty}, + want: []error{ErrTCPListenerSNIsEmpty}, }, } for _, test := range tests { diff --git a/internal/provider/kubernetes/controller.go b/internal/provider/kubernetes/controller.go index 1069d80494e..7bdb15c27c3 100644 --- a/internal/provider/kubernetes/controller.go +++ b/internal/provider/kubernetes/controller.go @@ -220,7 +220,7 @@ func (r *gatewayAPIReconciler) Reconcile(ctx context.Context, request reconcile. } } - if err := r.gatewayClassUpdater(ctx, acceptedGC, true, string(gwapiv1b1.GatewayClassReasonAccepted), string(status.MsgValidGatewayClass)); err != nil { + if err := r.gatewayClassUpdater(ctx, acceptedGC, true, string(gwapiv1b1.GatewayClassReasonAccepted), status.MsgValidGatewayClass); err != nil { r.log.Error(err, "unable to update GatewayClass status") return reconcile.Result{}, err } @@ -269,10 +269,10 @@ func (r *gatewayAPIReconciler) gatewayClassUpdater(ctx context.Context, gc *gwap }) } else { // this branch makes testing easier by not going through the status.Updater. - copy := status.SetGatewayClassAccepted(gc.DeepCopy(), accepted, reason, msg) + duplicate := status.SetGatewayClassAccepted(gc.DeepCopy(), accepted, reason, msg) - if err := r.client.Status().Update(ctx, copy); err != nil && !kerrors.IsNotFound(err) { - return fmt.Errorf("error updating status of gatewayclass %s: %w", copy.Name, err) + if err := r.client.Status().Update(ctx, duplicate); err != nil && !kerrors.IsNotFound(err) { + return fmt.Errorf("error updating status of gatewayclass %s: %w", duplicate.Name, err) } } return nil @@ -341,8 +341,8 @@ func (r *gatewayAPIReconciler) findReferenceGrant(ctx context.Context, from, to for _, refGrant := range refGrantList.Items { if refGrant.Namespace == to.namespace { - for _, source := range refGrant.Spec.From { - if source.Kind == gwapiv1a2.Kind(from.kind) && string(source.Namespace) == from.namespace { + for _, src := range refGrant.Spec.From { + if src.Kind == gwapiv1a2.Kind(from.kind) && string(src.Namespace) == from.namespace { return &refGrant, nil } } diff --git a/internal/provider/utils/utils.go b/internal/provider/utils/utils.go index 353e3ae08d8..df5e7a2c9f9 100644 --- a/internal/provider/utils/utils.go +++ b/internal/provider/utils/utils.go @@ -22,12 +22,12 @@ func NamespacedName(obj client.Object) types.NamespacedName { } } -// Returns a partially hashed name for the string including up to 48 characters of the original name before the hash +// GetHashedName returns a partially hashed name for the string including up to 48 characters of the original name before the hash func GetHashedName(name string) string { h := sha256.New() // Using sha256 instead of sha1 due to Blocklisted import crypto/sha1: weak cryptographic primitive (gosec) - hsha := h.Sum([]byte(name)) - hashedName := strings.ToLower(fmt.Sprintf("%x", hsha)) + hSum := h.Sum([]byte(name)) + hashedName := strings.ToLower(fmt.Sprintf("%x", hSum)) if len(name) > 48 { return fmt.Sprintf("%s-%s", name[0:48], hashedName[0:8]) diff --git a/internal/status/gateway.go b/internal/status/gateway.go index 20dd392f9d0..b4546c1d8f5 100644 --- a/internal/status/gateway.go +++ b/internal/status/gateway.go @@ -13,38 +13,38 @@ import ( "github.com/envoyproxy/gateway/internal/gatewayapi" ) -// UpdateGatewayScheduledCondition updates the status condition for the provided Gateway based on the scheduled state. +// UpdateGatewayStatusScheduledCondition updates the status condition for the provided Gateway based on the scheduled state. func UpdateGatewayStatusScheduledCondition(gw *gwapiv1b1.Gateway, scheduled bool) *gwapiv1b1.Gateway { gw.Status.Conditions = MergeConditions(gw.Status.Conditions, computeGatewayScheduledCondition(gw, scheduled)) return gw } -// UpdateGatewayStatusAddrs updates the status addresses for the provided gateway +// UpdateGatewayStatusReadyCondition updates the status addresses for the provided gateway // based on the status IP/Hostname of svc and updates the Ready condition based on the // service and deployment state. func UpdateGatewayStatusReadyCondition(gw *gwapiv1b1.Gateway, svc *corev1.Service, deployment *appsv1.Deployment) { - var addrs, hostnames []string + var addresses, hostnames []string // Update the status addresses field. if svc != nil { for i := range svc.Status.LoadBalancer.Ingress { switch { case len(svc.Status.LoadBalancer.Ingress[i].IP) > 0: - addrs = append(addrs, svc.Status.LoadBalancer.Ingress[i].IP) + addresses = append(addresses, svc.Status.LoadBalancer.Ingress[i].IP) case len(svc.Status.LoadBalancer.Ingress[i].Hostname) > 0: // Remove when the following supports the hostname address type: // https://github.com/kubernetes-sigs/gateway-api/blob/v0.5.0/conformance/utils/kubernetes/helpers.go#L201-L207 if svc.Status.LoadBalancer.Ingress[i].Hostname == "localhost" { - addrs = append(addrs, "127.0.0.1") + addresses = append(addresses, "127.0.0.1") } hostnames = append(hostnames, svc.Status.LoadBalancer.Ingress[i].Hostname) } } var gwAddrs []gwapiv1b1.GatewayAddress - for i := range addrs { + for i := range addresses { addr := gwapiv1b1.GatewayAddress{ Type: gatewayapi.GatewayAddressTypePtr(gwapiv1b1.IPAddressType), - Value: addrs[i], + Value: addresses[i], } gwAddrs = append(gwAddrs, addr) } diff --git a/internal/xds/cache/logrwrapper.go b/internal/xds/cache/logrwrapper.go index a21324e4ba1..4be00cebc83 100644 --- a/internal/xds/cache/logrwrapper.go +++ b/internal/xds/cache/logrwrapper.go @@ -25,27 +25,22 @@ const LevelInfo int = 0 const LevelWarn int = -1 func (l LogrWrapper) Debugf(template string, args ...interface{}) { - l.logr.V(LevelDebug).Info(fmt.Sprintf(template, args...)) } func (l LogrWrapper) Infof(template string, args ...interface{}) { - l.logr.V(LevelInfo).Info(fmt.Sprintf(template, args...)) } func (l LogrWrapper) Warnf(template string, args ...interface{}) { - l.logr.V(LevelWarn).Info(fmt.Sprintf(template, args...)) } func (l LogrWrapper) Errorf(template string, args ...interface{}) { - l.logr.Error(fmt.Errorf(template, args...), "") } func NewLogrWrapper(log logr.Logger) *LogrWrapper { - return &LogrWrapper{ logr: log, } diff --git a/internal/xds/cache/snapshotcache.go b/internal/xds/cache/snapshotcache.go index 255bbc591eb..c68899ca97d 100644 --- a/internal/xds/cache/snapshotcache.go +++ b/internal/xds/cache/snapshotcache.go @@ -20,16 +20,16 @@ import ( "strconv" "sync" - envoy_config_core_v3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - envoy_service_discovery_v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" - envoy_cache_v3 "github.com/envoyproxy/go-control-plane/pkg/cache/v3" - envoy_server_v3 "github.com/envoyproxy/go-control-plane/pkg/server/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + discoveryv3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" + cachev3 "github.com/envoyproxy/go-control-plane/pkg/cache/v3" + serverv3 "github.com/envoyproxy/go-control-plane/pkg/server/v3" "github.com/go-logr/logr" "github.com/envoyproxy/gateway/internal/xds/types" ) -var Hash = envoy_cache_v3.IDHash{} +var Hash = cachev3.IDHash{} // SnapshotCacheWithCallbacks uses the go-control-plane SimpleCache to store snapshots of // Envoy resources, sliced by Node ID so that we can do incremental xDS properly. @@ -41,17 +41,17 @@ var Hash = envoy_cache_v3.IDHash{} // TODO(youngnick): Talk to the go-control-plane maintainers and see if we can upstream // this in a better way. type SnapshotCacheWithCallbacks interface { - envoy_cache_v3.SnapshotCache - envoy_server_v3.Callbacks + cachev3.SnapshotCache + serverv3.Callbacks GenerateNewSnapshot(string, types.XdsResources) error } -type snapshotMap map[string]*envoy_cache_v3.Snapshot +type snapshotMap map[string]*cachev3.Snapshot -type nodeInfoMap map[int64]*envoy_config_core_v3.Node +type nodeInfoMap map[int64]*corev3.Node -type snapshotcache struct { - envoy_cache_v3.SnapshotCache +type snapshotCache struct { + cachev3.SnapshotCache streamIDNodeInfo nodeInfoMap snapshotVersion int64 lastSnapshot snapshotMap @@ -61,7 +61,7 @@ type snapshotcache struct { // GenerateNewSnapshot takes a table of resources (the output from the IR->xDS // translator) and updates the snapshot version. -func (s *snapshotcache) GenerateNewSnapshot(irKey string, resources types.XdsResources) error { +func (s *snapshotCache) GenerateNewSnapshot(irKey string, resources types.XdsResources) error { s.mu.Lock() defer s.mu.Unlock() @@ -69,7 +69,7 @@ func (s *snapshotcache) GenerateNewSnapshot(irKey string, resources types.XdsRes version := s.newSnapshotVersion() // Create a snapshot with all xDS resources. - snapshot, err := envoy_cache_v3.NewSnapshot( + snapshot, err := cachev3.NewSnapshot( version, resources, ) @@ -93,7 +93,7 @@ func (s *snapshotcache) GenerateNewSnapshot(irKey string, resources types.XdsRes // newSnapshotVersion increments the current snapshotVersion // and returns as a string. -func (s *snapshotcache) newSnapshotVersion() string { +func (s *snapshotCache) newSnapshotVersion() string { // Reset the snapshotVersion if it ever hits max size. if s.snapshotVersion == math.MaxInt64 { @@ -111,8 +111,8 @@ func (s *snapshotcache) newSnapshotVersion() string { func NewSnapshotCache(ads bool, logger logr.Logger) SnapshotCacheWithCallbacks { // Set up the nasty wrapper hack. wrappedLogger := NewLogrWrapper(logger) - return &snapshotcache{ - SnapshotCache: envoy_cache_v3.NewSnapshotCache(ads, &Hash, wrappedLogger), + return &snapshotCache{ + SnapshotCache: cachev3.NewSnapshotCache(ads, &Hash, wrappedLogger), log: wrappedLogger, lastSnapshot: make(snapshotMap), streamIDNodeInfo: make(nodeInfoMap), @@ -121,7 +121,7 @@ func NewSnapshotCache(ads bool, logger logr.Logger) SnapshotCacheWithCallbacks { // getNodeIDs retrieves the node ids from the node info map whose // cluster field matches the ir key -func (s *snapshotcache) getNodeIDs(irKey string) []string { +func (s *snapshotCache) getNodeIDs(irKey string) []string { var nodeIDs []string for _, node := range s.streamIDNodeInfo { if node.Cluster == irKey { @@ -135,7 +135,7 @@ func (s *snapshotcache) getNodeIDs(irKey string) []string { // OnStreamOpen and the other OnStream* functions implement the callbacks for the // state-of-the-world stream types. -func (s *snapshotcache) OnStreamOpen(ctx context.Context, streamID int64, typeURL string) error { +func (s *snapshotCache) OnStreamOpen(ctx context.Context, streamID int64, typeURL string) error { s.mu.Lock() defer s.mu.Unlock() @@ -145,7 +145,7 @@ func (s *snapshotcache) OnStreamOpen(ctx context.Context, streamID int64, typeUR return nil } -func (s *snapshotcache) OnStreamClosed(streamID int64, node *envoy_config_core_v3.Node) { +func (s *snapshotCache) OnStreamClosed(streamID int64, node *corev3.Node) { // TODO: something with the node? s.mu.Lock() @@ -155,7 +155,7 @@ func (s *snapshotcache) OnStreamClosed(streamID int64, node *envoy_config_core_v } -func (s *snapshotcache) OnStreamRequest(streamID int64, req *envoy_service_discovery_v3.DiscoveryRequest) error { +func (s *snapshotCache) OnStreamRequest(streamID int64, req *discoveryv3.DiscoveryRequest) error { s.mu.Lock() // We could do this a little earlier than the defer, since the last half of this func is only logging @@ -217,7 +217,7 @@ func (s *snapshotcache) OnStreamRequest(streamID int64, req *envoy_service_disco return nil } -func (s *snapshotcache) OnStreamResponse(ctx context.Context, streamID int64, req *envoy_service_discovery_v3.DiscoveryRequest, resp *envoy_service_discovery_v3.DiscoveryResponse) { +func (s *snapshotCache) OnStreamResponse(ctx context.Context, streamID int64, req *discoveryv3.DiscoveryRequest, resp *discoveryv3.DiscoveryResponse) { // No mutex lock required here because no writing to the cache. node := s.streamIDNodeInfo[streamID] @@ -231,7 +231,7 @@ func (s *snapshotcache) OnStreamResponse(ctx context.Context, streamID int64, re // OnDeltaStreamOpen and the other OnDeltaStream*/OnStreamDelta* functions implement // the callbacks for the incremental xDS versions. // Yes, the different ordering in the name is part of the go-control-plane interface. -func (s *snapshotcache) OnDeltaStreamOpen(ctx context.Context, streamID int64, typeURL string) error { +func (s *snapshotCache) OnDeltaStreamOpen(ctx context.Context, streamID int64, typeURL string) error { s.mu.Lock() defer s.mu.Unlock() @@ -242,7 +242,7 @@ func (s *snapshotcache) OnDeltaStreamOpen(ctx context.Context, streamID int64, t return nil } -func (s *snapshotcache) OnDeltaStreamClosed(streamID int64, node *envoy_config_core_v3.Node) { +func (s *snapshotCache) OnDeltaStreamClosed(streamID int64, node *corev3.Node) { // TODO: something with the node? s.mu.Lock() @@ -252,7 +252,7 @@ func (s *snapshotcache) OnDeltaStreamClosed(streamID int64, node *envoy_config_c } -func (s *snapshotcache) OnStreamDeltaRequest(streamID int64, req *envoy_service_discovery_v3.DeltaDiscoveryRequest) error { +func (s *snapshotCache) OnStreamDeltaRequest(streamID int64, req *discoveryv3.DeltaDiscoveryRequest) error { s.mu.Lock() // We could do this a little earlier than with a defer, since the last half of this func is logging // but that seemed like a premature optimization. @@ -276,7 +276,7 @@ func (s *snapshotcache) OnStreamDeltaRequest(streamID int64, req *envoy_service_ nodeID := s.streamIDNodeInfo[streamID].Id cluster := s.streamIDNodeInfo[streamID].Cluster - // If no snapshot has been written into the snapshotcache yet, we can't do anything, so don't mess with + // If no snapshot has been written into the snapshotCache yet, we can't do anything, so don't mess with // this request. go-control-plane will respond with an empty response, then send an update when a // snapshot is generated. if s.lastSnapshot[cluster] == nil { @@ -315,7 +315,7 @@ func (s *snapshotcache) OnStreamDeltaRequest(streamID int64, req *envoy_service_ return nil } -func (s *snapshotcache) OnStreamDeltaResponse(streamID int64, req *envoy_service_discovery_v3.DeltaDiscoveryRequest, resp *envoy_service_discovery_v3.DeltaDiscoveryResponse) { +func (s *snapshotCache) OnStreamDeltaResponse(streamID int64, req *discoveryv3.DeltaDiscoveryRequest, resp *discoveryv3.DeltaDiscoveryResponse) { // No mutex lock required here because no writing to the cache. node := s.streamIDNodeInfo[streamID] if node == nil { @@ -325,9 +325,9 @@ func (s *snapshotcache) OnStreamDeltaResponse(streamID int64, req *envoy_service } } -func (s *snapshotcache) OnFetchRequest(ctx context.Context, req *envoy_service_discovery_v3.DiscoveryRequest) error { +func (s *snapshotCache) OnFetchRequest(ctx context.Context, req *discoveryv3.DiscoveryRequest) error { return nil } -func (s *snapshotcache) OnFetchResponse(req *envoy_service_discovery_v3.DiscoveryRequest, resp *envoy_service_discovery_v3.DiscoveryResponse) { +func (s *snapshotCache) OnFetchResponse(req *discoveryv3.DiscoveryRequest, resp *discoveryv3.DiscoveryResponse) { } diff --git a/internal/xds/server/runner/runner.go b/internal/xds/server/runner/runner.go index 378490f73c9..bdf4fb2fde0 100644 --- a/internal/xds/server/runner/runner.go +++ b/internal/xds/server/runner/runner.go @@ -15,14 +15,14 @@ import ( "os" "strconv" - controlplane_service_cluster_v3 "github.com/envoyproxy/go-control-plane/envoy/service/cluster/v3" - controlplane_service_discovery_v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" - controlplane_service_endpoint_v3 "github.com/envoyproxy/go-control-plane/envoy/service/endpoint/v3" - controlplane_service_listener_v3 "github.com/envoyproxy/go-control-plane/envoy/service/listener/v3" - controlplane_service_route_v3 "github.com/envoyproxy/go-control-plane/envoy/service/route/v3" - controlplane_service_runtime_v3 "github.com/envoyproxy/go-control-plane/envoy/service/runtime/v3" - controlplane_service_secret_v3 "github.com/envoyproxy/go-control-plane/envoy/service/secret/v3" - controlplane_server_v3 "github.com/envoyproxy/go-control-plane/pkg/server/v3" + clusterv3 "github.com/envoyproxy/go-control-plane/envoy/service/cluster/v3" + discoveryv3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" + endpointv3 "github.com/envoyproxy/go-control-plane/envoy/service/endpoint/v3" + listenerv3 "github.com/envoyproxy/go-control-plane/envoy/service/listener/v3" + routev3 "github.com/envoyproxy/go-control-plane/envoy/service/route/v3" + runtimev3 "github.com/envoyproxy/go-control-plane/envoy/service/runtime/v3" + secretv3 "github.com/envoyproxy/go-control-plane/envoy/service/secret/v3" + serverv3 "github.com/envoyproxy/go-control-plane/pkg/server/v3" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -78,7 +78,7 @@ func (r *Runner) Start(ctx context.Context) error { r.grpc = grpc.NewServer(grpc.Creds(credentials.NewTLS(cfg))) r.cache = cache.NewSnapshotCache(false, r.Logger) - registerServer(controlplane_server_v3.NewServer(ctx, r.cache, r.cache), r.grpc) + registerServer(serverv3.NewServer(ctx, r.cache, r.cache), r.grpc) // Start and listen xDS gRPC Server. go r.serveXdsServer(ctx) @@ -111,15 +111,15 @@ func (r *Runner) serveXdsServer(ctx context.Context) { // registerServer registers the given xDS protocol Server with the gRPC // runtime. -func registerServer(srv controlplane_server_v3.Server, g *grpc.Server) { +func registerServer(srv serverv3.Server, g *grpc.Server) { // register services - controlplane_service_discovery_v3.RegisterAggregatedDiscoveryServiceServer(g, srv) - controlplane_service_secret_v3.RegisterSecretDiscoveryServiceServer(g, srv) - controlplane_service_cluster_v3.RegisterClusterDiscoveryServiceServer(g, srv) - controlplane_service_endpoint_v3.RegisterEndpointDiscoveryServiceServer(g, srv) - controlplane_service_listener_v3.RegisterListenerDiscoveryServiceServer(g, srv) - controlplane_service_route_v3.RegisterRouteDiscoveryServiceServer(g, srv) - controlplane_service_runtime_v3.RegisterRuntimeDiscoveryServiceServer(g, srv) + discoveryv3.RegisterAggregatedDiscoveryServiceServer(g, srv) + secretv3.RegisterSecretDiscoveryServiceServer(g, srv) + clusterv3.RegisterClusterDiscoveryServiceServer(g, srv) + endpointv3.RegisterEndpointDiscoveryServiceServer(g, srv) + listenerv3.RegisterListenerDiscoveryServiceServer(g, srv) + routev3.RegisterRouteDiscoveryServiceServer(g, srv) + runtimev3.RegisterRuntimeDiscoveryServiceServer(g, srv) } func (r *Runner) subscribeAndTranslate(ctx context.Context) { diff --git a/internal/xds/translator/authentication.go b/internal/xds/translator/authentication.go index 8c13ae82885..66c20a72239 100644 --- a/internal/xds/translator/authentication.go +++ b/internal/xds/translator/authentication.go @@ -13,12 +13,12 @@ import ( "strconv" "strings" - core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" - jwtext "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/jwt_authn/v3" - hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" - tls "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" + jwtauthnv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/jwt_authn/v3" + hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" + tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" "github.com/envoyproxy/go-control-plane/pkg/resource/v3" "github.com/envoyproxy/go-control-plane/pkg/wellknown" "google.golang.org/protobuf/types/known/anypb" @@ -36,13 +36,13 @@ const ( // patchHCMWithJwtAuthnFilter builds and appends the Jwt Filter to the HTTP // Connection Manager if applicable, and it does not already exist. -func patchHCMWithJwtAuthnFilter(mgr *hcm.HttpConnectionManager, irListener *ir.HTTPListener) error { +func patchHCMWithJwtAuthnFilter(mgr *hcmv3.HttpConnectionManager, irListener *ir.HTTPListener) error { if mgr == nil { - return errors.New("hcm is nil") + return errors.New("hcmv3 is nil") } if irListener == nil { - return errors.New("ir listener is nil") + return errors.New("ir listenerv3 is nil") } if !listenerContainsJwtAuthn(irListener) { @@ -62,13 +62,13 @@ func patchHCMWithJwtAuthnFilter(mgr *hcm.HttpConnectionManager, irListener *ir.H } // Ensure the authn filter is the first and the terminal filter is the last in the chain. - mgr.HttpFilters = append([]*hcm.HttpFilter{jwtFilter}, mgr.HttpFilters...) + mgr.HttpFilters = append([]*hcmv3.HttpFilter{jwtFilter}, mgr.HttpFilters...) return nil } -// buildHCMJwtFilter returns a JWT authn HTTP filter from the provided IR listener. -func buildHCMJwtFilter(irListener *ir.HTTPListener) (*hcm.HttpFilter, error) { +// buildHCMJwtFilter returns a JWT authn HTTP filter from the provided IR listenerv3. +func buildHCMJwtFilter(irListener *ir.HTTPListener) (*hcmv3.HttpFilter, error) { jwtAuthnProto, err := buildJwtAuthn(irListener) if err != nil { return nil, err @@ -83,22 +83,22 @@ func buildHCMJwtFilter(irListener *ir.HTTPListener) (*hcm.HttpFilter, error) { return nil, err } - return &hcm.HttpFilter{ + return &hcmv3.HttpFilter{ Name: jwtAuthenFilter, - ConfigType: &hcm.HttpFilter_TypedConfig{ + ConfigType: &hcmv3.HttpFilter_TypedConfig{ TypedConfig: jwtAuthnAny, }, }, nil } // buildJwtAuthn returns a JwtAuthentication based on the provided IR HTTPListener. -func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, error) { - jwtProviders := make(map[string]*jwtext.JwtProvider) - reqMap := make(map[string]*jwtext.JwtRequirement) +func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtauthnv3.JwtAuthentication, error) { + jwtProviders := make(map[string]*jwtauthnv3.JwtProvider) + reqMap := make(map[string]*jwtauthnv3.JwtRequirement) for _, route := range irListener.Routes { if route != nil && routeContainsJwtAuthn(route) { - var reqs []*jwtext.JwtRequirement + var reqs []*jwtauthnv3.JwtRequirement for i := range route.RequestAuthentication.JWT.Providers { irProvider := route.RequestAuthentication.JWT.Providers[i] // Create the cluster for the remote jwks, if it doesn't exist. @@ -107,11 +107,11 @@ func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, erro return nil, err } - remote := &jwtext.JwtProvider_RemoteJwks{ - RemoteJwks: &jwtext.RemoteJwks{ - HttpUri: &core.HttpUri{ + remote := &jwtauthnv3.JwtProvider_RemoteJwks{ + RemoteJwks: &jwtauthnv3.RemoteJwks{ + HttpUri: &corev3.HttpUri{ Uri: irProvider.RemoteJWKS.URI, - HttpUpstreamType: &core.HttpUri_Cluster{ + HttpUpstreamType: &corev3.HttpUri_Cluster{ Cluster: jwksCluster.name, }, Timeout: &durationpb.Duration{Seconds: 5}, @@ -120,7 +120,7 @@ func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, erro }, } - jwtProvider := &jwtext.JwtProvider{ + jwtProvider := &jwtauthnv3.JwtProvider{ Issuer: irProvider.Issuer, Audiences: irProvider.Audiences, JwksSourceSpecifier: remote, @@ -129,8 +129,8 @@ func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, erro providerKey := fmt.Sprintf("%s-%s", route.Name, irProvider.Name) jwtProviders[providerKey] = jwtProvider - reqs = append(reqs, &jwtext.JwtRequirement{ - RequiresType: &jwtext.JwtRequirement_ProviderName{ + reqs = append(reqs, &jwtauthnv3.JwtRequirement{ + RequiresType: &jwtauthnv3.JwtRequirement_ProviderName{ ProviderName: providerKey, }, }) @@ -138,9 +138,9 @@ func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, erro if len(reqs) == 1 { reqMap[route.Name] = reqs[0] } else { - orListReqs := &jwtext.JwtRequirement{ - RequiresType: &jwtext.JwtRequirement_RequiresAny{ - RequiresAny: &jwtext.JwtRequirementOrList{ + orListReqs := &jwtauthnv3.JwtRequirement{ + RequiresType: &jwtauthnv3.JwtRequirement_RequiresAny{ + RequiresAny: &jwtauthnv3.JwtRequirementOrList{ Requirements: reqs, }, }, @@ -150,7 +150,7 @@ func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, erro } } - return &jwtext.JwtAuthentication{ + return &jwtauthnv3.JwtAuthentication{ RequirementMap: reqMap, Providers: jwtProviders, }, nil @@ -158,13 +158,13 @@ func buildJwtAuthn(irListener *ir.HTTPListener) (*jwtext.JwtAuthentication, erro // buildXdsUpstreamTLSSocket returns an xDS TransportSocket that uses envoyTrustBundle // as the CA to authenticate server certificates. -func buildXdsUpstreamTLSSocket() (*core.TransportSocket, error) { - tlsCtxProto := &tls.UpstreamTlsContext{ - CommonTlsContext: &tls.CommonTlsContext{ - ValidationContextType: &tls.CommonTlsContext_ValidationContext{ - ValidationContext: &tls.CertificateValidationContext{ - TrustedCa: &core.DataSource{ - Specifier: &core.DataSource_Filename{ +func buildXdsUpstreamTLSSocket() (*corev3.TransportSocket, error) { + tlsCtxProto := &tlsv3.UpstreamTlsContext{ + CommonTlsContext: &tlsv3.CommonTlsContext{ + ValidationContextType: &tlsv3.CommonTlsContext_ValidationContext{ + ValidationContext: &tlsv3.CertificateValidationContext{ + TrustedCa: &corev3.DataSource{ + Specifier: &corev3.DataSource_Filename{ Filename: envoyTrustBundle, }, }, @@ -178,9 +178,9 @@ func buildXdsUpstreamTLSSocket() (*core.TransportSocket, error) { return nil, err } - return &core.TransportSocket{ + return &corev3.TransportSocket{ Name: wellknown.TransportSocketTls, - ConfigType: &core.TransportSocket_TypedConfig{ + ConfigType: &corev3.TransportSocket_TypedConfig{ TypedConfig: tlsCtxAny, }, }, nil @@ -189,7 +189,7 @@ func buildXdsUpstreamTLSSocket() (*core.TransportSocket, error) { // patchRouteWithJwtConfig patches the provided route with a JWT PerRouteConfig, if the // route doesn't contain it. The listener is used to create the PerRouteConfig JWT // requirement. -func patchRouteWithJwtConfig(route *routev3.Route, irRoute *ir.HTTPRoute, listener *listener.Listener) error { //nolint:unparam +func patchRouteWithJwtConfig(route *routev3.Route, irRoute *ir.HTTPRoute, listener *listenerv3.Listener) error { //nolint:unparam if route == nil { return errors.New("xds route is nil") } @@ -197,7 +197,7 @@ func patchRouteWithJwtConfig(route *routev3.Route, irRoute *ir.HTTPRoute, listen return errors.New("ir route is nil") } if listener == nil { - return errors.New("listener is nil") + return errors.New("listenerv3 is nil") } filterCfg := route.GetTypedPerFilterConfig() @@ -227,7 +227,7 @@ func patchRouteWithJwtConfig(route *routev3.Route, irRoute *ir.HTTPRoute, listen } // buildJwtPerRouteConfig returns a JWT PerRouteConfig based on the provided IR route and HCM. -func buildJwtPerRouteConfig(irRoute *ir.HTTPRoute, listener *listener.Listener) (*jwtext.PerRouteConfig, error) { +func buildJwtPerRouteConfig(irRoute *ir.HTTPRoute, listener *listenerv3.Listener) (*jwtauthnv3.PerRouteConfig, error) { if irRoute == nil { return nil, errors.New("ir route is nil") } @@ -235,18 +235,18 @@ func buildJwtPerRouteConfig(irRoute *ir.HTTPRoute, listener *listener.Listener) return nil, errors.New("ir route does not contain jwt authn") } if listener == nil { - return nil, errors.New("listener is nil") + return nil, errors.New("listenerv3 is nil") } filterCh := listener.GetDefaultFilterChain() if filterCh == nil { - return nil, fmt.Errorf("listener %s does not contain the default filterchain", listener.Name) + return nil, fmt.Errorf("listenerv3 %s does not contain the default filterchain", listener.Name) } for _, filter := range filterCh.Filters { if filter.Name == wellknown.HTTPConnectionManager { // Unmarshal the filter to a jwt authn config and validate it. - hcmProto := new(hcm.HttpConnectionManager) + hcmProto := new(hcmv3.HttpConnectionManager) hcmAny := filter.GetTypedConfig() if err := hcmAny.UnmarshalTo(hcmProto); err != nil { return nil, err @@ -260,7 +260,7 @@ func buildJwtPerRouteConfig(irRoute *ir.HTTPRoute, listener *listener.Listener) return nil, err } - return &jwtext.PerRouteConfig{ + return &jwtauthnv3.PerRouteConfig{ RequirementSpecifier: req, }, nil } @@ -271,15 +271,15 @@ func buildJwtPerRouteConfig(irRoute *ir.HTTPRoute, listener *listener.Listener) // getJwtRequirement iterates through the provided filters, returning a JWT requirement // name if one exists. -func getJwtRequirement(filters []*hcm.HttpFilter, name string) (*jwtext.PerRouteConfig_RequirementName, error) { +func getJwtRequirement(filters []*hcmv3.HttpFilter, name string) (*jwtauthnv3.PerRouteConfig_RequirementName, error) { if len(filters) == 0 { - return nil, errors.New("no hcm http filters") + return nil, errors.New("no hcmv3 http filters") } for _, filter := range filters { if filter.Name == jwtAuthenFilter { // Unmarshal the filter to a jwt authn config and validate it. - jwtAuthnProto := new(jwtext.JwtAuthentication) + jwtAuthnProto := new(jwtauthnv3.JwtAuthentication) jwtAuthnAny := filter.GetTypedConfig() if err := jwtAuthnAny.UnmarshalTo(jwtAuthnProto); err != nil { return nil, err @@ -289,7 +289,7 @@ func getJwtRequirement(filters []*hcm.HttpFilter, name string) (*jwtext.PerRoute } // Return the requirement name if it's found. if _, found := jwtAuthnProto.RequirementMap[name]; found { - return &jwtext.PerRouteConfig_RequirementName{RequirementName: name}, nil + return &jwtauthnv3.PerRouteConfig_RequirementName{RequirementName: name}, nil } return nil, fmt.Errorf("failed to find jwt requirement %s", name) } diff --git a/internal/xds/translator/cluster.go b/internal/xds/translator/cluster.go index 3120c80e44b..6f547f0e7bc 100644 --- a/internal/xds/translator/cluster.go +++ b/internal/xds/translator/cluster.go @@ -9,8 +9,8 @@ import ( "time" clusterv3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" - core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + endpointv3 "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3" httpv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/upstreams/http/v3" "google.golang.org/protobuf/types/known/anypb" "google.golang.org/protobuf/types/known/durationpb" @@ -20,9 +20,9 @@ import ( ) func buildXdsCluster(routeName string, destinations []*ir.RouteDestination, isHTTP2 bool, isStatic bool) *clusterv3.Cluster { - localities := make([]*endpoint.LocalityLbEndpoints, 0, 1) - locality := &endpoint.LocalityLbEndpoints{ - Locality: &core.Locality{}, + localities := make([]*endpointv3.LocalityLbEndpoints, 0, 1) + locality := &endpointv3.LocalityLbEndpoints{ + Locality: &corev3.Locality{}, LbEndpoints: buildXdsEndpoints(destinations), Priority: 0, // Each locality gets the same weight 1. There is a single locality @@ -35,7 +35,7 @@ func buildXdsCluster(routeName string, destinations []*ir.RouteDestination, isHT Name: clusterName, ConnectTimeout: durationpb.New(10 * time.Second), LbPolicy: clusterv3.Cluster_ROUND_ROBIN, - LoadAssignment: &endpoint.ClusterLoadAssignment{ClusterName: clusterName, Endpoints: localities}, + LoadAssignment: &endpointv3.ClusterLoadAssignment{ClusterName: clusterName, Endpoints: localities}, DnsLookupFamily: clusterv3.Cluster_V4_ONLY, CommonLbConfig: &clusterv3.Cluster_CommonLbConfig{ LocalityConfigSpecifier: &clusterv3.Cluster_CommonLbConfig_LocalityWeightedLbConfig_{ @@ -58,18 +58,18 @@ func buildXdsCluster(routeName string, destinations []*ir.RouteDestination, isHT return cluster } -func buildXdsEndpoints(destinations []*ir.RouteDestination) []*endpoint.LbEndpoint { - endpoints := make([]*endpoint.LbEndpoint, 0, len(destinations)) +func buildXdsEndpoints(destinations []*ir.RouteDestination) []*endpointv3.LbEndpoint { + endpoints := make([]*endpointv3.LbEndpoint, 0, len(destinations)) for _, destination := range destinations { - lbEndpoint := &endpoint.LbEndpoint{ - HostIdentifier: &endpoint.LbEndpoint_Endpoint{ - Endpoint: &endpoint.Endpoint{ - Address: &core.Address{ - Address: &core.Address_SocketAddress{ - SocketAddress: &core.SocketAddress{ - Protocol: core.SocketAddress_TCP, + lbEndpoint := &endpointv3.LbEndpoint{ + HostIdentifier: &endpointv3.LbEndpoint_Endpoint{ + Endpoint: &endpointv3.Endpoint{ + Address: &corev3.Address{ + Address: &corev3.Address_SocketAddress{ + SocketAddress: &corev3.SocketAddress{ + Protocol: corev3.SocketAddress_TCP, Address: destination.Host, - PortSpecifier: &core.SocketAddress_PortValue{ + PortSpecifier: &corev3.SocketAddress_PortValue{ PortValue: destination.Port, }, }, diff --git a/internal/xds/translator/listener.go b/internal/xds/translator/listener.go index ec44d1f4ade..1f4a1a171d5 100644 --- a/internal/xds/translator/listener.go +++ b/internal/xds/translator/listener.go @@ -10,16 +10,16 @@ import ( xdscore "github.com/cncf/xds/go/xds/core/v3" matcher "github.com/cncf/xds/go/xds/type/matcher/v3" - accesslog "github.com/envoyproxy/go-control-plane/envoy/config/accesslog/v3" - core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" - grpc_web "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/grpc_web/v3" - router "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/router/v3" - tls_inspector "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/listener/tls_inspector/v3" - hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" - tcp "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/tcp_proxy/v3" - udp "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/udp/udp_proxy/v3" - tls "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" + accesslogv3 "github.com/envoyproxy/go-control-plane/envoy/config/accesslog/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" + grpc_webv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/grpc_web/v3" + routerv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/router/v3" + tls_inspectorv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/listener/tls_inspector/v3" + hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" + tcpv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/tcp_proxy/v3" + udpv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/udp/udp_proxy/v3" + tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" "github.com/envoyproxy/go-control-plane/pkg/resource/v3" "github.com/envoyproxy/go-control-plane/pkg/wellknown" "github.com/golang/protobuf/ptypes/wrappers" @@ -28,23 +28,23 @@ import ( "github.com/envoyproxy/gateway/internal/ir" ) -func buildXdsTCPListener(name, address string, port uint32) *listener.Listener { +func buildXdsTCPListener(name, address string, port uint32) *listenerv3.Listener { accesslogAny, _ := anypb.New(stdoutFileAccessLog) - return &listener.Listener{ + return &listenerv3.Listener{ Name: name, - AccessLog: []*accesslog.AccessLog{ + AccessLog: []*accesslogv3.AccessLog{ { Name: wellknown.FileAccessLog, - ConfigType: &accesslog.AccessLog_TypedConfig{TypedConfig: accesslogAny}, + ConfigType: &accesslogv3.AccessLog_TypedConfig{TypedConfig: accesslogAny}, Filter: listenerAccessLogFilter, }, }, - Address: &core.Address{ - Address: &core.Address_SocketAddress{ - SocketAddress: &core.SocketAddress{ - Protocol: core.SocketAddress_TCP, + Address: &corev3.Address{ + Address: &corev3.Address_SocketAddress{ + SocketAddress: &corev3.SocketAddress{ + Protocol: corev3.SocketAddress_TCP, Address: address, - PortSpecifier: &core.SocketAddress_PortValue{ + PortSpecifier: &corev3.SocketAddress_PortValue{ PortValue: port, }, }, @@ -53,8 +53,8 @@ func buildXdsTCPListener(name, address string, port uint32) *listener.Listener { } } -func (t *Translator) addXdsHTTPFilterChain(xdsListener *listener.Listener, irListener *ir.HTTPListener) error { - routerAny, err := anypb.New(&router.Router{}) +func (t *Translator) addXdsHTTPFilterChain(xdsListener *listenerv3.Listener, irListener *ir.HTTPListener) error { + routerAny, err := anypb.New(&routerv3.Router{}) if err != nil { return err } @@ -71,17 +71,17 @@ func (t *Translator) addXdsHTTPFilterChain(xdsListener *listener.Listener, irLis } else { statPrefix = "http" } - mgr := &hcm.HttpConnectionManager{ - AccessLog: []*accesslog.AccessLog{ + mgr := &hcmv3.HttpConnectionManager{ + AccessLog: []*accesslogv3.AccessLog{ { Name: wellknown.FileAccessLog, - ConfigType: &accesslog.AccessLog_TypedConfig{TypedConfig: accesslogAny}, + ConfigType: &accesslogv3.AccessLog_TypedConfig{TypedConfig: accesslogAny}, }, }, - CodecType: hcm.HttpConnectionManager_AUTO, + CodecType: hcmv3.HttpConnectionManager_AUTO, StatPrefix: statPrefix, - RouteSpecifier: &hcm.HttpConnectionManager_Rds{ - Rds: &hcm.Rds{ + RouteSpecifier: &hcmv3.HttpConnectionManager_Rds{ + Rds: &hcmv3.Rds{ ConfigSource: makeConfigSource(), // Configure route name to be found via RDS. RouteConfigName: irListener.Name, @@ -89,33 +89,33 @@ func (t *Translator) addXdsHTTPFilterChain(xdsListener *listener.Listener, irLis }, // https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers#x-forwarded-for UseRemoteAddress: &wrappers.BoolValue{Value: true}, - // Use only router. - HttpFilters: []*hcm.HttpFilter{{ + // Use only routerv3. + HttpFilters: []*hcmv3.HttpFilter{{ Name: wellknown.Router, - ConfigType: &hcm.HttpFilter_TypedConfig{TypedConfig: routerAny}, + ConfigType: &hcmv3.HttpFilter_TypedConfig{TypedConfig: routerAny}, }}, } if irListener.IsHTTP2 { // Set codec to HTTP2 - mgr.CodecType = hcm.HttpConnectionManager_HTTP2 + mgr.CodecType = hcmv3.HttpConnectionManager_HTTP2 // Enable grpc-web filter for HTTP2 - grpcWebAny, err := anypb.New(&grpc_web.GrpcWeb{}) + grpcWebAny, err := anypb.New(&grpc_webv3.GrpcWeb{}) if err != nil { return err } - grpcWebFilter := &hcm.HttpFilter{ + grpcWebFilter := &hcmv3.HttpFilter{ Name: wellknown.GRPCWeb, - ConfigType: &hcm.HttpFilter_TypedConfig{TypedConfig: grpcWebAny}, + ConfigType: &hcmv3.HttpFilter_TypedConfig{TypedConfig: grpcWebAny}, } - // Ensure router is the last filter - mgr.HttpFilters = append([]*hcm.HttpFilter{grpcWebFilter}, mgr.HttpFilters...) + // Ensure routerv3 is the last filter + mgr.HttpFilters = append([]*hcmv3.HttpFilter{grpcWebFilter}, mgr.HttpFilters...) } else { // Allow websocket upgrades for HTTP 1.1 // Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism - mgr.UpgradeConfigs = []*hcm.HttpConnectionManager_UpgradeConfig{ + mgr.UpgradeConfigs = []*hcmv3.HttpConnectionManager_UpgradeConfig{ { UpgradeType: "websocket", }, @@ -136,10 +136,10 @@ func (t *Translator) addXdsHTTPFilterChain(xdsListener *listener.Listener, irLis return err } - filterChain := &listener.FilterChain{ - Filters: []*listener.Filter{{ + filterChain := &listenerv3.FilterChain{ + Filters: []*listenerv3.Filter{{ Name: wellknown.HTTPConnectionManager, - ConfigType: &listener.Filter_TypedConfig{ + ConfigType: &listenerv3.Filter_TypedConfig{ TypedConfig: mgrAny, }, }}, @@ -168,10 +168,10 @@ func (t *Translator) addXdsHTTPFilterChain(xdsListener *listener.Listener, irLis return nil } -func addServerNamesMatch(xdsListener *listener.Listener, filterChain *listener.FilterChain, hostnames []string) error { +func addServerNamesMatch(xdsListener *listenerv3.Listener, filterChain *listenerv3.FilterChain, hostnames []string) error { // Dont add a filter chain match if the hostname is a wildcard character. if len(hostnames) > 0 && hostnames[0] != "*" { - filterChain.FilterChainMatch = &listener.FilterChainMatch{ + filterChain.FilterChainMatch = &listenerv3.FilterChainMatch{ ServerNames: hostnames, } @@ -186,14 +186,14 @@ func addServerNamesMatch(xdsListener *listener.Listener, filterChain *listener.F // findXdsHTTPRouteConfigName finds the name of the route config associated with the // http connection manager within the default filter chain and returns an empty string if // not found. -func findXdsHTTPRouteConfigName(xdsListener *listener.Listener) string { +func findXdsHTTPRouteConfigName(xdsListener *listenerv3.Listener) string { if xdsListener == nil || xdsListener.DefaultFilterChain == nil || xdsListener.DefaultFilterChain.Filters == nil { return "" } for _, filter := range xdsListener.DefaultFilterChain.Filters { if filter.Name == wellknown.HTTPConnectionManager { - m := new(hcm.HttpConnectionManager) + m := new(hcmv3.HttpConnectionManager) if err := filter.GetTypedConfig().UnmarshalTo(m); err != nil { return "" } @@ -207,7 +207,7 @@ func findXdsHTTPRouteConfigName(xdsListener *listener.Listener) string { return "" } -func addXdsTCPFilterChain(xdsListener *listener.Listener, irListener *ir.TCPListener, clusterName string) error { +func addXdsTCPFilterChain(xdsListener *listenerv3.Listener, irListener *ir.TCPListener, clusterName string) error { if irListener == nil { return errors.New("tcp listener is nil") } @@ -222,15 +222,15 @@ func addXdsTCPFilterChain(xdsListener *listener.Listener, irListener *ir.TCPList return err } - mgr := &tcp.TcpProxy{ - AccessLog: []*accesslog.AccessLog{ + mgr := &tcpv3.TcpProxy{ + AccessLog: []*accesslogv3.AccessLog{ { Name: wellknown.FileAccessLog, - ConfigType: &accesslog.AccessLog_TypedConfig{TypedConfig: accesslogAny}, + ConfigType: &accesslogv3.AccessLog_TypedConfig{TypedConfig: accesslogAny}, }, }, StatPrefix: statPrefix, - ClusterSpecifier: &tcp.TcpProxy_Cluster{ + ClusterSpecifier: &tcpv3.TcpProxy_Cluster{ Cluster: clusterName, }, } @@ -239,10 +239,10 @@ func addXdsTCPFilterChain(xdsListener *listener.Listener, irListener *ir.TCPList return err } - filterChain := &listener.FilterChain{ - Filters: []*listener.Filter{{ + filterChain := &listenerv3.FilterChain{ + Filters: []*listenerv3.Filter{{ Name: wellknown.TCPProxy, - ConfigType: &listener.Filter_TypedConfig{ + ConfigType: &listenerv3.Filter_TypedConfig{ TypedConfig: mgrAny, }, }}, @@ -260,7 +260,7 @@ func addXdsTCPFilterChain(xdsListener *listener.Listener, irListener *ir.TCPList } // addXdsTLSInspectorFilter adds a Tls Inspector filter if it does not yet exist. -func addXdsTLSInspectorFilter(xdsListener *listener.Listener) error { +func addXdsTLSInspectorFilter(xdsListener *listenerv3.Listener) error { // Return early if it exists for _, filter := range xdsListener.ListenerFilters { if filter.Name == wellknown.TlsInspector { @@ -268,15 +268,15 @@ func addXdsTLSInspectorFilter(xdsListener *listener.Listener) error { } } - tlsInspector := &tls_inspector.TlsInspector{} + tlsInspector := &tls_inspectorv3.TlsInspector{} tlsInspectorAny, err := anypb.New(tlsInspector) if err != nil { return err } - filter := &listener.ListenerFilter{ + filter := &listenerv3.ListenerFilter{ Name: wellknown.TlsInspector, - ConfigType: &listener.ListenerFilter_TypedConfig{ + ConfigType: &listenerv3.ListenerFilter_TypedConfig{ TypedConfig: tlsInspectorAny, }, } @@ -286,11 +286,11 @@ func addXdsTLSInspectorFilter(xdsListener *listener.Listener) error { return nil } -func buildXdsDownstreamTLSSocket(listenerName string) (*core.TransportSocket, error) { - tlsCtx := &tls.DownstreamTlsContext{ - CommonTlsContext: &tls.CommonTlsContext{ - TlsCertificateSdsSecretConfigs: []*tls.SdsSecretConfig{{ - // Generate key name for this listener. The actual key will be +func buildXdsDownstreamTLSSocket(listenerName string) (*corev3.TransportSocket, error) { + tlsCtx := &tlsv3.DownstreamTlsContext{ + CommonTlsContext: &tlsv3.CommonTlsContext{ + TlsCertificateSdsSecretConfigs: []*tlsv3.SdsSecretConfig{{ + // Generate key name for this listenerv3. The actual key will be // delivered to Envoy via SDS. Name: listenerName, SdsConfig: makeConfigSource(), @@ -303,40 +303,40 @@ func buildXdsDownstreamTLSSocket(listenerName string) (*core.TransportSocket, er return nil, err } - return &core.TransportSocket{ + return &corev3.TransportSocket{ Name: wellknown.TransportSocketTls, - ConfigType: &core.TransportSocket_TypedConfig{ + ConfigType: &corev3.TransportSocket_TypedConfig{ TypedConfig: tlsCtxAny, }, }, nil } func buildXdsDownstreamTLSSecret(listenerName string, - tlsConfig *ir.TLSListenerConfig) *tls.Secret { - // Build the tls secret - return &tls.Secret{ + tlsConfig *ir.TLSListenerConfig) *tlsv3.Secret { + // Build the tlsv3 secret + return &tlsv3.Secret{ Name: listenerName, - Type: &tls.Secret_TlsCertificate{ - TlsCertificate: &tls.TlsCertificate{ - CertificateChain: &core.DataSource{ - Specifier: &core.DataSource_InlineBytes{InlineBytes: tlsConfig.ServerCertificate}, + Type: &tlsv3.Secret_TlsCertificate{ + TlsCertificate: &tlsv3.TlsCertificate{ + CertificateChain: &corev3.DataSource{ + Specifier: &corev3.DataSource_InlineBytes{InlineBytes: tlsConfig.ServerCertificate}, }, - PrivateKey: &core.DataSource{ - Specifier: &core.DataSource_InlineBytes{InlineBytes: tlsConfig.PrivateKey}, + PrivateKey: &corev3.DataSource{ + Specifier: &corev3.DataSource_InlineBytes{InlineBytes: tlsConfig.PrivateKey}, }, }, }, } } -func buildXdsUDPListener(clusterName string, udpListener *ir.UDPListener) (*listener.Listener, error) { +func buildXdsUDPListener(clusterName string, udpListener *ir.UDPListener) (*listenerv3.Listener, error) { if udpListener == nil { - return nil, errors.New("udp listener is nil") + return nil, errors.New("udpv3 listenerv3 is nil") } statPrefix := "service" - route := &udp.Route{ + route := &udpv3.Route{ Cluster: clusterName, } routeAny, err := anypb.New(route) @@ -344,15 +344,15 @@ func buildXdsUDPListener(clusterName string, udpListener *ir.UDPListener) (*list return nil, err } accesslogAny, _ := anypb.New(stdoutFileAccessLog) - udpProxy := &udp.UdpProxyConfig{ + udpProxy := &udpv3.UdpProxyConfig{ StatPrefix: statPrefix, - AccessLog: []*accesslog.AccessLog{ + AccessLog: []*accesslogv3.AccessLog{ { Name: wellknown.FileAccessLog, - ConfigType: &accesslog.AccessLog_TypedConfig{TypedConfig: accesslogAny}, + ConfigType: &accesslogv3.AccessLog_TypedConfig{TypedConfig: accesslogAny}, }, }, - RouteSpecifier: &udp.UdpProxyConfig_Matcher{ + RouteSpecifier: &udpv3.UdpProxyConfig_Matcher{ Matcher: &matcher.Matcher{ OnNoMatch: &matcher.Matcher_OnMatch{ OnMatch: &matcher.Matcher_OnMatch_Action{ @@ -370,28 +370,28 @@ func buildXdsUDPListener(clusterName string, udpListener *ir.UDPListener) (*list return nil, err } - xdsListener := &listener.Listener{ + xdsListener := &listenerv3.Listener{ Name: udpListener.Name, - AccessLog: []*accesslog.AccessLog{ + AccessLog: []*accesslogv3.AccessLog{ { Name: wellknown.FileAccessLog, - ConfigType: &accesslog.AccessLog_TypedConfig{TypedConfig: accesslogAny}, + ConfigType: &accesslogv3.AccessLog_TypedConfig{TypedConfig: accesslogAny}, }, }, - Address: &core.Address{ - Address: &core.Address_SocketAddress{ - SocketAddress: &core.SocketAddress{ - Protocol: core.SocketAddress_UDP, + Address: &corev3.Address{ + Address: &corev3.Address_SocketAddress{ + SocketAddress: &corev3.SocketAddress{ + Protocol: corev3.SocketAddress_UDP, Address: udpListener.Address, - PortSpecifier: &core.SocketAddress_PortValue{ + PortSpecifier: &corev3.SocketAddress_PortValue{ PortValue: udpListener.Port, }, }, }, }, - ListenerFilters: []*listener.ListenerFilter{{ + ListenerFilters: []*listenerv3.ListenerFilter{{ Name: "envoy.filters.udp_listener.udp_proxy", - ConfigType: &listener.ListenerFilter_TypedConfig{ + ConfigType: &listenerv3.ListenerFilter_TypedConfig{ TypedConfig: udpProxyAny, }, }}, @@ -401,17 +401,17 @@ func buildXdsUDPListener(clusterName string, udpListener *ir.UDPListener) (*list } // Point to xds cluster. -func makeConfigSource() *core.ConfigSource { - source := &core.ConfigSource{} +func makeConfigSource() *corev3.ConfigSource { + source := &corev3.ConfigSource{} source.ResourceApiVersion = resource.DefaultAPIVersion - source.ConfigSourceSpecifier = &core.ConfigSource_ApiConfigSource{ - ApiConfigSource: &core.ApiConfigSource{ + source.ConfigSourceSpecifier = &corev3.ConfigSource_ApiConfigSource{ + ApiConfigSource: &corev3.ApiConfigSource{ TransportApiVersion: resource.DefaultAPIVersion, - ApiType: core.ApiConfigSource_DELTA_GRPC, + ApiType: corev3.ApiConfigSource_DELTA_GRPC, SetNodeOnFirstMessageOnly: true, - GrpcServices: []*core.GrpcService{{ - TargetSpecifier: &core.GrpcService_EnvoyGrpc_{ - EnvoyGrpc: &core.GrpcService_EnvoyGrpc{ClusterName: "xds_cluster"}, + GrpcServices: []*corev3.GrpcService{{ + TargetSpecifier: &corev3.GrpcService_EnvoyGrpc_{ + EnvoyGrpc: &corev3.GrpcService_EnvoyGrpc{ClusterName: "xds_cluster"}, }, }}, }, diff --git a/internal/xds/translator/ratelimit.go b/internal/xds/translator/ratelimit.go index 7a6b2cf4375..5c466c834ff 100644 --- a/internal/xds/translator/ratelimit.go +++ b/internal/xds/translator/ratelimit.go @@ -10,12 +10,12 @@ import ( "net/url" "strconv" - cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" - core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - ratelimit "github.com/envoyproxy/go-control-plane/envoy/config/ratelimit/v3" + clusterv3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + ratelimitv3 "github.com/envoyproxy/go-control-plane/envoy/config/ratelimit/v3" routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" - ratelimitfilter "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ratelimit/v3" - hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" + ratelimitfilterv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ratelimit/v3" + hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" "github.com/envoyproxy/go-control-plane/pkg/wellknown" ratelimitserviceconfig "github.com/envoyproxy/ratelimit/src/config" "google.golang.org/protobuf/types/known/anypb" @@ -27,7 +27,7 @@ import ( // patchHCMWithRateLimit builds and appends the Rate Limit Filter to the HTTP connection manager // if applicable and it does not already exist. -func (t *Translator) patchHCMWithRateLimit(mgr *hcm.HttpConnectionManager, irListener *ir.HTTPListener) { +func (t *Translator) patchHCMWithRateLimit(mgr *hcmv3.HttpConnectionManager, irListener *ir.HTTPListener) { // Return early if rate limits dont exist if !t.isRateLimitPresent(irListener) { return @@ -42,7 +42,7 @@ func (t *Translator) patchHCMWithRateLimit(mgr *hcm.HttpConnectionManager, irLis rateLimitFilter := buildRateLimitFilter(irListener) // Make sure the router filter is the terminal filter in the chain. - mgr.HttpFilters = append([]*hcm.HttpFilter{rateLimitFilter}, mgr.HttpFilters...) + mgr.HttpFilters = append([]*hcmv3.HttpFilter{rateLimitFilter}, mgr.HttpFilters...) } // isRateLimitPresent returns true if rate limit config exists for the listener. @@ -60,18 +60,18 @@ func (t *Translator) isRateLimitPresent(irListener *ir.HTTPListener) bool { return false } -func buildRateLimitFilter(irListener *ir.HTTPListener) *hcm.HttpFilter { - rateLimitFilterProto := &ratelimitfilter.RateLimit{ +func buildRateLimitFilter(irListener *ir.HTTPListener) *hcmv3.HttpFilter { + rateLimitFilterProto := &ratelimitfilterv3.RateLimit{ Domain: getRateLimitDomain(irListener), - RateLimitService: &ratelimit.RateLimitServiceConfig{ - GrpcService: &core.GrpcService{ - TargetSpecifier: &core.GrpcService_EnvoyGrpc_{ - EnvoyGrpc: &core.GrpcService_EnvoyGrpc{ + RateLimitService: &ratelimitv3.RateLimitServiceConfig{ + GrpcService: &corev3.GrpcService{ + TargetSpecifier: &corev3.GrpcService_EnvoyGrpc_{ + EnvoyGrpc: &corev3.GrpcService_EnvoyGrpc{ ClusterName: getRateLimitServiceClusterName(), }, }, }, - TransportApiVersion: core.ApiVersion_V3, + TransportApiVersion: corev3.ApiVersion_V3, }, } @@ -80,9 +80,9 @@ func buildRateLimitFilter(irListener *ir.HTTPListener) *hcm.HttpFilter { return nil } - rateLimitFilter := &hcm.HttpFilter{ + rateLimitFilter := &hcmv3.HttpFilter{ Name: wellknown.HTTPRateLimit, - ConfigType: &hcm.HttpFilter_TypedConfig{ + ConfigType: &hcmv3.HttpFilter_TypedConfig{ TypedConfig: rateLimitFilterAny, }, } @@ -234,7 +234,7 @@ func buildRateLimitServiceDescriptors(descriptorPrefix string, global *ir.Global } - // Add the ratelimit values to the last descriptor + // Add the ratelimitv3 values to the last descriptor if mIdx == len(rule.HeaderMatches)-1 { rateLimit := ratelimitserviceconfig.YamlRateLimit{ RequestsPerUnit: uint32(rule.Limit.Requests), @@ -258,7 +258,7 @@ func buildRateLimitServiceDescriptors(descriptorPrefix string, global *ir.Global return yamlDescs } -func (t *Translator) buildRateLimitServiceCluster(irListener *ir.HTTPListener) *cluster.Cluster { +func (t *Translator) buildRateLimitServiceCluster(irListener *ir.HTTPListener) *clusterv3.Cluster { // Return early if rate limits dont exist. if !t.isRateLimitPresent(irListener) { return nil diff --git a/internal/xds/translator/route.go b/internal/xds/translator/route.go index 24d1582d55c..ae47ff506b6 100644 --- a/internal/xds/translator/route.go +++ b/internal/xds/translator/route.go @@ -8,16 +8,16 @@ package translator import ( "fmt" - core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" - matcher "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3" + matcherv3 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3" "google.golang.org/protobuf/types/known/wrapperspb" "github.com/envoyproxy/gateway/internal/ir" ) -func buildXdsRoute(httpRoute *ir.HTTPRoute, listener *listener.Listener) *routev3.Route { +func buildXdsRoute(httpRoute *ir.HTTPRoute, listener *listenerv3.Listener) *routev3.Route { router := &routev3.Route{ Match: buildXdsRouteMatch(httpRoute.PathMatch, httpRoute.HeaderMatches, httpRoute.QueryParamMatches), } @@ -107,8 +107,8 @@ func buildXdsRouteMatch(pathMatch *ir.StringMatch, headerMatches []*ir.StringMat } } else if pathMatch.SafeRegex != nil { outMatch.PathSpecifier = &routev3.RouteMatch_SafeRegex{ - SafeRegex: &matcher.RegexMatcher{ - EngineType: &matcher.RegexMatcher_GoogleRe2{}, + SafeRegex: &matcherv3.RegexMatcher{ + EngineType: &matcherv3.RegexMatcher_GoogleRe2{}, Regex: *pathMatch.SafeRegex, }, } @@ -143,35 +143,35 @@ func buildXdsRouteMatch(pathMatch *ir.StringMatch, headerMatches []*ir.StringMat return outMatch } -func buildXdsStringMatcher(irMatch *ir.StringMatch) *matcher.StringMatcher { - stringMatcher := new(matcher.StringMatcher) +func buildXdsStringMatcher(irMatch *ir.StringMatch) *matcherv3.StringMatcher { + stringMatcher := new(matcherv3.StringMatcher) //nolint:gocritic if irMatch.Exact != nil { - stringMatcher = &matcher.StringMatcher{ - MatchPattern: &matcher.StringMatcher_Exact{ + stringMatcher = &matcherv3.StringMatcher{ + MatchPattern: &matcherv3.StringMatcher_Exact{ Exact: *irMatch.Exact, }, } } else if irMatch.Prefix != nil { - stringMatcher = &matcher.StringMatcher{ - MatchPattern: &matcher.StringMatcher_Prefix{ + stringMatcher = &matcherv3.StringMatcher{ + MatchPattern: &matcherv3.StringMatcher_Prefix{ Prefix: *irMatch.Prefix, }, } } else if irMatch.Suffix != nil { - stringMatcher = &matcher.StringMatcher{ - MatchPattern: &matcher.StringMatcher_Suffix{ + stringMatcher = &matcherv3.StringMatcher{ + MatchPattern: &matcherv3.StringMatcher_Suffix{ Suffix: *irMatch.Suffix, }, } } else if irMatch.SafeRegex != nil { - stringMatcher = &matcher.StringMatcher{ - MatchPattern: &matcher.StringMatcher_SafeRegex{ - SafeRegex: &matcher.RegexMatcher{ + stringMatcher = &matcherv3.StringMatcher{ + MatchPattern: &matcherv3.StringMatcher_SafeRegex{ + SafeRegex: &matcherv3.RegexMatcher{ Regex: *irMatch.SafeRegex, - EngineType: &matcher.RegexMatcher_GoogleRe2{ - GoogleRe2: &matcher.RegexMatcher_GoogleRE2{}, + EngineType: &matcherv3.RegexMatcher_GoogleRe2{ + GoogleRe2: &matcherv3.RegexMatcher_GoogleRE2{}, }, }, }, @@ -254,8 +254,8 @@ func buildXdsURLRewriteAction(routeName string, urlRewrite *ir.URLRewrite) *rout if urlRewrite.Path != nil { if urlRewrite.Path.FullReplace != nil { - routeAction.RegexRewrite = &matcher.RegexMatchAndSubstitute{ - Pattern: &matcher.RegexMatcher{ + routeAction.RegexRewrite = &matcherv3.RegexMatchAndSubstitute{ + Pattern: &matcherv3.RegexMatcher{ Regex: "/.+", }, Substitution: *urlRewrite.Path.FullReplace, @@ -280,8 +280,8 @@ func buildXdsDirectResponseAction(res *ir.DirectResponse) *routev3.DirectRespons routeAction := &routev3.DirectResponseAction{Status: res.StatusCode} if res.Body != nil { - routeAction.Body = &core.DataSource{ - Specifier: &core.DataSource_InlineString{ + routeAction.Body = &corev3.DataSource{ + Specifier: &corev3.DataSource_InlineString{ InlineString: *res.Body, }, } @@ -302,12 +302,12 @@ func buildXdsRequestMirrorPolicies(routeName string, mirrors []*ir.RouteDestinat return mirrorPolicies } -func buildXdsAddedHeaders(headersToAdd []ir.AddHeader) []*core.HeaderValueOption { - headerValueOptions := make([]*core.HeaderValueOption, len(headersToAdd)) +func buildXdsAddedHeaders(headersToAdd []ir.AddHeader) []*corev3.HeaderValueOption { + headerValueOptions := make([]*corev3.HeaderValueOption, len(headersToAdd)) for i, header := range headersToAdd { - headerValueOptions[i] = &core.HeaderValueOption{ - Header: &core.HeaderValue{ + headerValueOptions[i] = &corev3.HeaderValueOption{ + Header: &corev3.HeaderValue{ Key: header.Name, Value: header.Value, }, diff --git a/internal/xds/translator/translator.go b/internal/xds/translator/translator.go index 053b80e55f1..76505cab236 100644 --- a/internal/xds/translator/translator.go +++ b/internal/xds/translator/translator.go @@ -9,11 +9,11 @@ import ( "errors" "fmt" - cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" - core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" - listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" - route "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" - resource "github.com/envoyproxy/go-control-plane/pkg/resource/v3" + clusterv3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" + routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" + resourcev3 "github.com/envoyproxy/go-control-plane/pkg/resource/v3" "github.com/tetratelabs/multierror" "github.com/envoyproxy/gateway/internal/ir" @@ -59,13 +59,13 @@ func (t *Translator) Translate(ir *ir.Xds) (*types.ResourceVersionTable, error) func (t *Translator) processHTTPListenerXdsTranslation(tCtx *types.ResourceVersionTable, httpListeners []*ir.HTTPListener) error { for _, httpListener := range httpListeners { addFilterChain := true - var xdsRouteCfg *route.RouteConfiguration + var xdsRouteCfg *routev3.RouteConfiguration // Search for an existing listener, if it does not exist, create one. - xdsListener := findXdsListener(tCtx, httpListener.Address, httpListener.Port, core.SocketAddress_TCP) + xdsListener := findXdsListener(tCtx, httpListener.Address, httpListener.Port, corev3.SocketAddress_TCP) if xdsListener == nil { xdsListener = buildXdsTCPListener(httpListener.Name, httpListener.Address, httpListener.Port) - tCtx.AddXdsResource(resource.ListenerType, xdsListener) + tCtx.AddXdsResource(resourcev3.ListenerType, xdsListener) } else if httpListener.TLS == nil { // Find the route config associated with this listener that // maps to the default filter chain for http traffic @@ -90,21 +90,21 @@ func (t *Translator) processHTTPListenerXdsTranslation(tCtx *types.ResourceVersi // Create a route config if we have not found one yet if xdsRouteCfg == nil { - xdsRouteCfg = &route.RouteConfiguration{ + xdsRouteCfg = &routev3.RouteConfiguration{ Name: httpListener.Name, } - tCtx.AddXdsResource(resource.RouteType, xdsRouteCfg) + tCtx.AddXdsResource(resourcev3.RouteType, xdsRouteCfg) } // 1:1 between IR TLSListenerConfig and xDS Secret if httpListener.TLS != nil { secret := buildXdsDownstreamTLSSecret(httpListener.Name, httpListener.TLS) - tCtx.AddXdsResource(resource.SecretType, secret) + tCtx.AddXdsResource(resourcev3.SecretType, secret) } // Allocate virtual host for this httpListener. // 1:1 between IR HTTPListener and xDS VirtualHost - vHost := &route.VirtualHost{ + vHost := &routev3.VirtualHost{ Name: httpListener.Name, Domains: httpListener.Hostnames, } @@ -120,14 +120,14 @@ func (t *Translator) processHTTPListenerXdsTranslation(tCtx *types.ResourceVersi } xdsCluster := buildXdsCluster(httpRoute.Name, httpRoute.Destinations, httpListener.IsHTTP2, true /* isStatic */) - tCtx.AddXdsResource(resource.ClusterType, xdsCluster) + tCtx.AddXdsResource(resourcev3.ClusterType, xdsCluster) // If the httpRoute has a list of mirrors create clusters for them unless they already have one for i, mirror := range httpRoute.Mirrors { mirrorClusterName := fmt.Sprintf("%s-mirror-%d", httpRoute.Name, i) if cluster := findXdsCluster(tCtx, mirrorClusterName); cluster == nil { mirrorCluster := buildXdsCluster(mirrorClusterName, []*ir.RouteDestination{mirror}, httpListener.IsHTTP2, true /* isStatic */) - tCtx.AddXdsResource(resource.ClusterType, mirrorCluster) + tCtx.AddXdsResource(resourcev3.ClusterType, mirrorCluster) } } @@ -144,7 +144,7 @@ func (t *Translator) processHTTPListenerXdsTranslation(tCtx *types.ResourceVersi rlCluster := t.buildRateLimitServiceCluster(httpListener) // Add cluster if rlCluster != nil { - tCtx.AddXdsResource(resource.ClusterType, rlCluster) + tCtx.AddXdsResource(resourcev3.ClusterType, rlCluster) } } @@ -160,13 +160,13 @@ func processTCPListenerXdsTranslation(tCtx *types.ResourceVersionTable, tcpListe for _, tcpListener := range tcpListeners { // 1:1 between IR TCPListener and xDS Cluster xdsCluster := buildXdsCluster(tcpListener.Name, tcpListener.Destinations, false /*isHTTP2 */, true /* isStatic */) - tCtx.AddXdsResource(resource.ClusterType, xdsCluster) + tCtx.AddXdsResource(resourcev3.ClusterType, xdsCluster) // Search for an existing listener, if it does not exist, create one. - xdsListener := findXdsListener(tCtx, tcpListener.Address, tcpListener.Port, core.SocketAddress_TCP) + xdsListener := findXdsListener(tCtx, tcpListener.Address, tcpListener.Port, corev3.SocketAddress_TCP) if xdsListener == nil { xdsListener = buildXdsTCPListener(tcpListener.Name, tcpListener.Address, tcpListener.Port) - tCtx.AddXdsResource(resource.ListenerType, xdsListener) + tCtx.AddXdsResource(resourcev3.ListenerType, xdsListener) } if err := addXdsTCPFilterChain(xdsListener, tcpListener, xdsCluster.Name); err != nil { @@ -180,7 +180,7 @@ func processUDPListenerXdsTranslation(tCtx *types.ResourceVersionTable, udpListe for _, udpListener := range udpListeners { // 1:1 between IR UDPListener and xDS Cluster xdsCluster := buildXdsCluster(udpListener.Name, udpListener.Destinations, false /*isHTTP2 */, true /*isStatic */) - tCtx.AddXdsResource(resource.ClusterType, xdsCluster) + tCtx.AddXdsResource(resourcev3.ClusterType, xdsCluster) // There won't be multiple UDP listeners on the same port since it's already been checked at the gateway api // translator @@ -188,7 +188,7 @@ func processUDPListenerXdsTranslation(tCtx *types.ResourceVersionTable, udpListe if err != nil { return multierror.Append(err, errors.New("error building xds cluster")) } - tCtx.AddXdsResource(resource.ListenerType, xdsListener) + tCtx.AddXdsResource(resourcev3.ListenerType, xdsListener) } return nil @@ -196,13 +196,13 @@ func processUDPListenerXdsTranslation(tCtx *types.ResourceVersionTable, udpListe // findXdsListener finds a xds listener with the same address, port and protocol, and returns nil if there is no match. func findXdsListener(tCtx *types.ResourceVersionTable, address string, port uint32, - protocol core.SocketAddress_Protocol) *listener.Listener { - if tCtx == nil || tCtx.XdsResources == nil || tCtx.XdsResources[resource.ListenerType] == nil { + protocol corev3.SocketAddress_Protocol) *listenerv3.Listener { + if tCtx == nil || tCtx.XdsResources == nil || tCtx.XdsResources[resourcev3.ListenerType] == nil { return nil } - for _, r := range tCtx.XdsResources[resource.ListenerType] { - listener := r.(*listener.Listener) + for _, r := range tCtx.XdsResources[resourcev3.ListenerType] { + listener := r.(*listenerv3.Listener) addr := listener.GetAddress() if addr.GetSocketAddress().GetPortValue() == port && addr.GetSocketAddress().Address == address && addr. GetSocketAddress().Protocol == protocol { @@ -214,13 +214,13 @@ func findXdsListener(tCtx *types.ResourceVersionTable, address string, port uint } // findXdsCluster finds a xds cluster with the same name, and returns nil if there is no match. -func findXdsCluster(tCtx *types.ResourceVersionTable, name string) *cluster.Cluster { - if tCtx == nil || tCtx.XdsResources == nil || tCtx.XdsResources[resource.ClusterType] == nil { +func findXdsCluster(tCtx *types.ResourceVersionTable, name string) *clusterv3.Cluster { + if tCtx == nil || tCtx.XdsResources == nil || tCtx.XdsResources[resourcev3.ClusterType] == nil { return nil } - for _, r := range tCtx.XdsResources[resource.ClusterType] { - cluster := r.(*cluster.Cluster) + for _, r := range tCtx.XdsResources[resourcev3.ClusterType] { + cluster := r.(*clusterv3.Cluster) if cluster.Name == name { return cluster } @@ -230,13 +230,13 @@ func findXdsCluster(tCtx *types.ResourceVersionTable, name string) *cluster.Clus } // findXdsRouteConfig finds an xds route with the name and returns nil if there is no match. -func findXdsRouteConfig(tCtx *types.ResourceVersionTable, name string) *route.RouteConfiguration { - if tCtx == nil || tCtx.XdsResources == nil || tCtx.XdsResources[resource.RouteType] == nil { +func findXdsRouteConfig(tCtx *types.ResourceVersionTable, name string) *routev3.RouteConfiguration { + if tCtx == nil || tCtx.XdsResources == nil || tCtx.XdsResources[resourcev3.RouteType] == nil { return nil } - for _, r := range tCtx.XdsResources[resource.RouteType] { - route := r.(*route.RouteConfiguration) + for _, r := range tCtx.XdsResources[resourcev3.RouteType] { + route := r.(*routev3.RouteConfiguration) if route.Name == name { return route } diff --git a/internal/xds/translator/translator_test.go b/internal/xds/translator/translator_test.go index f205ccf7cb4..60e78f8c180 100644 --- a/internal/xds/translator/translator_test.go +++ b/internal/xds/translator/translator_test.go @@ -11,7 +11,7 @@ import ( "testing" "github.com/envoyproxy/go-control-plane/pkg/cache/types" - resource "github.com/envoyproxy/go-control-plane/pkg/resource/v3" + resourcev3 "github.com/envoyproxy/go-control-plane/pkg/resource/v3" ratelimitserviceconfig "github.com/envoyproxy/ratelimit/src/config" "github.com/stretchr/testify/require" "sigs.k8s.io/yaml" @@ -132,14 +132,14 @@ func TestTranslateXds(t *testing.T) { } tCtx, err := tr.Translate(ir) require.NoError(t, err) - listeners := tCtx.XdsResources[resource.ListenerType] - routes := tCtx.XdsResources[resource.RouteType] - clusters := tCtx.XdsResources[resource.ClusterType] + listeners := tCtx.XdsResources[resourcev3.ListenerType] + routes := tCtx.XdsResources[resourcev3.RouteType] + clusters := tCtx.XdsResources[resourcev3.ClusterType] require.Equal(t, requireTestDataOutFile(t, "xds-ir", tc.name+".listeners.yaml"), requireResourcesToYAMLString(t, listeners)) require.Equal(t, requireTestDataOutFile(t, "xds-ir", tc.name+".routes.yaml"), requireResourcesToYAMLString(t, routes)) require.Equal(t, requireTestDataOutFile(t, "xds-ir", tc.name+".clusters.yaml"), requireResourcesToYAMLString(t, clusters)) if tc.requireSecrets { - secrets := tCtx.XdsResources[resource.SecretType] + secrets := tCtx.XdsResources[resourcev3.SecretType] require.Equal(t, requireTestDataOutFile(t, "xds-ir", tc.name+".secrets.yaml"), requireResourcesToYAMLString(t, secrets)) } }) diff --git a/internal/xds/types/resourceversiontable.go b/internal/xds/types/resourceversiontable.go index ebf323ab8f1..59aeef583b7 100644 --- a/internal/xds/types/resourceversiontable.go +++ b/internal/xds/types/resourceversiontable.go @@ -7,12 +7,12 @@ package types import ( "github.com/envoyproxy/go-control-plane/pkg/cache/types" - resource "github.com/envoyproxy/go-control-plane/pkg/resource/v3" + resourcev3 "github.com/envoyproxy/go-control-plane/pkg/resource/v3" "google.golang.org/protobuf/proto" ) // XdsResources represents all the xds resources -type XdsResources = map[resource.Type][]types.Resource +type XdsResources = map[resourcev3.Type][]types.Resource // ResourceVersionTable holds all the translated xds resources type ResourceVersionTable struct { @@ -63,7 +63,7 @@ func (t *ResourceVersionTable) GetXdsResources() XdsResources { return t.XdsResources } -func (t *ResourceVersionTable) AddXdsResource(rType resource.Type, xdsResource types.Resource) { +func (t *ResourceVersionTable) AddXdsResource(rType resourcev3.Type, xdsResource types.Resource) { if t.XdsResources == nil { t.XdsResources = make(XdsResources) } diff --git a/internal/xds/types/resourceversiontable_test.go b/internal/xds/types/resourceversiontable_test.go index 2cb17be407f..8dfdaaada39 100644 --- a/internal/xds/types/resourceversiontable_test.go +++ b/internal/xds/types/resourceversiontable_test.go @@ -11,7 +11,7 @@ import ( listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" "github.com/envoyproxy/go-control-plane/pkg/cache/types" - resource "github.com/envoyproxy/go-control-plane/pkg/resource/v3" + resourcev3 "github.com/envoyproxy/go-control-plane/pkg/resource/v3" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/require" "google.golang.org/protobuf/testing/protocmp" @@ -41,12 +41,12 @@ func TestDeepCopy(t *testing.T) { name: "listener", in: &ResourceVersionTable{ XdsResources: XdsResources{ - resource.ListenerType: []types.Resource{testListener}, + resourcev3.ListenerType: []types.Resource{testListener}, }, }, out: &ResourceVersionTable{ XdsResources: XdsResources{ - resource.ListenerType: []types.Resource{testListener}, + resourcev3.ListenerType: []types.Resource{testListener}, }, }, }, @@ -54,14 +54,14 @@ func TestDeepCopy(t *testing.T) { name: "kitchen-sink", in: &ResourceVersionTable{ XdsResources: XdsResources{ - resource.ListenerType: []types.Resource{testListener}, - resource.SecretType: []types.Resource{testSecret}, + resourcev3.ListenerType: []types.Resource{testListener}, + resourcev3.SecretType: []types.Resource{testSecret}, }, }, out: &ResourceVersionTable{ XdsResources: XdsResources{ - resource.ListenerType: []types.Resource{testListener}, - resource.SecretType: []types.Resource{testSecret}, + resourcev3.ListenerType: []types.Resource{testListener}, + resourcev3.SecretType: []types.Resource{testSecret}, }, }, },