Skip to content

Add GRPCRoute weighted backendRefs test #3962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions conformance/tests/grpcroute-weight.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package tests

import (
"fmt"
"testing"

"google.golang.org/grpc/codes"
"k8s.io/apimachinery/pkg/types"

v1 "sigs.k8s.io/gateway-api/apis/v1"
pb "sigs.k8s.io/gateway-api/conformance/echo-basic/grpcechoserver"
"sigs.k8s.io/gateway-api/conformance/utils/grpc"
"sigs.k8s.io/gateway-api/conformance/utils/kubernetes"
"sigs.k8s.io/gateway-api/conformance/utils/suite"
"sigs.k8s.io/gateway-api/conformance/utils/weight"
"sigs.k8s.io/gateway-api/pkg/features"
)

func init() {
ConformanceTests = append(ConformanceTests, GRPCRouteWeight)
}

var GRPCRouteWeight = suite.ConformanceTest{
ShortName: "GRPCRouteWeight",
Description: "An GRPCRoute with weighted backends",
Manifests: []string{"tests/grpcroute-weight.yaml"},
Features: []features.FeatureName{
features.SupportGateway,
features.SupportGRPCRoute,
},
Test: func(t *testing.T, suite *suite.ConformanceTestSuite) {
var (
ns = "gateway-conformance-infra"
routeNN = types.NamespacedName{Name: "weighted-backends", Namespace: ns}
gwNN = types.NamespacedName{Name: "same-namespace", Namespace: ns}
gwAddr = kubernetes.GatewayAndRoutesMustBeAccepted(t, suite.Client, suite.TimeoutConfig, suite.ControllerName, kubernetes.NewGatewayRef(gwNN), &v1.GRPCRoute{}, true, routeNN)
)

t.Run("Requests should have a distribution that matches the weight", func(t *testing.T) {
expected := grpc.ExpectedResponse{
EchoRequest: &pb.EchoRequest{},
Response: grpc.Response{Code: codes.OK},
Namespace: "gateway-conformance-infra",
}

// Assert request succeeds before doing our distribution check
grpc.MakeRequestAndExpectEventuallyConsistentResponse(t, suite.GRPCClient, suite.TimeoutConfig, gwAddr, expected)

expectedWeights := map[string]float64{
"grpc-infra-backend-v1": 0.7,
"grpc-infra-backend-v2": 0.3,
"grpc-infra-backend-v3": 0.0,
}

sender := weight.NewFunctionBasedSender(func() (string, error) {
uniqueExpected := expected
if err := grpc.AddEntropy(&uniqueExpected); err != nil {
return "", fmt.Errorf("error adding entropy: %w", err)
}
client := &grpc.DefaultClient{}
defer client.Close()
resp, err := client.SendRPC(t, gwAddr, uniqueExpected, suite.TimeoutConfig.MaxTimeToConsistency)
if err != nil {
return "", fmt.Errorf("failed to send gRPC request: %w", err)
}
if resp.Code != codes.OK {
return "", fmt.Errorf("expected OK response, got %v", resp.Code)
}
return resp.Response.GetAssertions().GetContext().GetPod(), nil
})

for i := 0; i < 10; i++ {
if err := weight.TestWeightedDistribution(sender, expectedWeights); err != nil {
t.Logf("Traffic distribution test failed (%d/10): %s", i+1, err)
} else {
return
}
}
t.Fatal("Weighted distribution tests failed")
})
},
}
19 changes: 19 additions & 0 deletions conformance/tests/grpcroute-weight.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
apiVersion: gateway.networking.k8s.io/v1
kind: GRPCRoute
metadata:
name: weighted-backends
namespace: gateway-conformance-infra
spec:
parentRefs:
- name: same-namespace
rules:
- backendRefs:
- name: grpc-infra-backend-v1
port: 8080
weight: 70
- name: grpc-infra-backend-v2
port: 8080
weight: 30
- name: grpc-infra-backend-v3
port: 8080
weight: 0
114 changes: 24 additions & 90 deletions conformance/tests/httproute-weight.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,15 @@ limitations under the License.
package tests

import (
"cmp"
"errors"
"fmt"
"math"
"slices"
"strings"
"sync"
"testing"

"golang.org/x/sync/errgroup"
"k8s.io/apimachinery/pkg/types"

"sigs.k8s.io/gateway-api/conformance/utils/http"
"sigs.k8s.io/gateway-api/conformance/utils/kubernetes"
"sigs.k8s.io/gateway-api/conformance/utils/suite"
"sigs.k8s.io/gateway-api/conformance/utils/weight"
"sigs.k8s.io/gateway-api/pkg/features"
)

Expand Down Expand Up @@ -67,8 +61,30 @@ var HTTPRouteWeight = suite.ConformanceTest{
// Assert request succeeds before doing our distribution check
http.MakeRequestAndExpectEventuallyConsistentResponse(t, suite.RoundTripper, suite.TimeoutConfig, gwAddr, expected)

expectedWeights := map[string]float64{
"infra-backend-v1": 0.7,
"infra-backend-v2": 0.3,
"infra-backend-v3": 0.0,
}

sender := weight.NewFunctionBasedSender(func() (string, error) {
uniqueExpected := expected
if err := http.AddEntropy(&uniqueExpected); err != nil {
return "", fmt.Errorf("error adding entropy: %w", err)
}
req := http.MakeRequest(t, &uniqueExpected, gwAddr, "HTTP", "http")
cReq, cRes, err := suite.RoundTripper.CaptureRoundTrip(req)
if err != nil {
return "", fmt.Errorf("failed to roundtrip request: %w", err)
}
if err := http.CompareRoundTrip(t, &req, cReq, cRes, expected); err != nil {
return "", fmt.Errorf("response expectation failed for request: %w", err)
}
return cReq.Pod, nil
})

for i := 0; i < 10; i++ {
if err := testDistribution(t, suite, gwAddr, expected); err != nil {
if err := weight.TestWeightedDistribution(sender, expectedWeights); err != nil {
t.Logf("Traffic distribution test failed (%d/10): %s", i+1, err)
} else {
return
Expand All @@ -78,85 +94,3 @@ var HTTPRouteWeight = suite.ConformanceTest{
})
},
}

func testDistribution(t *testing.T, suite *suite.ConformanceTestSuite, gwAddr string, expected http.ExpectedResponse) error {
const (
concurrentRequests = 10
tolerancePercentage = 0.05
totalRequests = 500.0
)
var (
roundTripper = suite.RoundTripper

g errgroup.Group
seenMutex sync.Mutex
seen = make(map[string]float64, 3 /* number of backends */)
expectedWeights = map[string]float64{
"infra-backend-v1": 0.7,
"infra-backend-v2": 0.3,
"infra-backend-v3": 0.0,
}
)
g.SetLimit(concurrentRequests)
for i := 0.0; i < totalRequests; i++ {
g.Go(func() error {
uniqueExpected := expected
if err := http.AddEntropy(&uniqueExpected); err != nil {
return fmt.Errorf("error adding entropy: %w", err)
}
req := http.MakeRequest(t, &uniqueExpected, gwAddr, "HTTP", "http")
cReq, cRes, err := roundTripper.CaptureRoundTrip(req)
if err != nil {
return fmt.Errorf("failed to roundtrip request: %w", err)
}
if err := http.CompareRoundTrip(t, &req, cReq, cRes, expected); err != nil {
return fmt.Errorf("response expectation failed for request: %w", err)
}

seenMutex.Lock()
defer seenMutex.Unlock()

for expectedBackend := range expectedWeights {
if strings.HasPrefix(cReq.Pod, expectedBackend) {
seen[expectedBackend]++
return nil
}
}

return fmt.Errorf("request was handled by an unexpected pod %q", cReq.Pod)
})
}

if err := g.Wait(); err != nil {
return fmt.Errorf("error while sending requests: %w", err)
}

var errs []error
if len(seen) != 2 {
errs = append(errs, fmt.Errorf("expected only two backends to receive traffic"))
}

for wantBackend, wantPercent := range expectedWeights {
gotCount, ok := seen[wantBackend]

if !ok && wantPercent != 0.0 {
errs = append(errs, fmt.Errorf("expect traffic to hit backend %q - but none was received", wantBackend))
continue
}

gotPercent := gotCount / totalRequests

if math.Abs(gotPercent-wantPercent) > tolerancePercentage {
errs = append(errs, fmt.Errorf("backend %q weighted traffic of %v not within tolerance %v (+/-%f)",
wantBackend,
gotPercent,
wantPercent,
tolerancePercentage,
))
}
}
slices.SortFunc(errs, func(a, b error) int {
return cmp.Compare(a.Error(), b.Error())
})
return errors.Join(errs...)
}
83 changes: 83 additions & 0 deletions conformance/tests/mesh/grpcroute-weight.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
Copyright 2025 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package meshtests

import (
"fmt"
"testing"

"sigs.k8s.io/gateway-api/conformance/utils/echo"
"sigs.k8s.io/gateway-api/conformance/utils/http"
"sigs.k8s.io/gateway-api/conformance/utils/suite"
"sigs.k8s.io/gateway-api/conformance/utils/weight"
"sigs.k8s.io/gateway-api/pkg/features"
)

func init() {
MeshConformanceTests = append(MeshConformanceTests, MeshGRPCRouteWeight)
}

var MeshGRPCRouteWeight = suite.ConformanceTest{
ShortName: "MeshGRPCRouteWeight",
Description: "A GRPCRoute with weighted backends in mesh mode",
Manifests: []string{"tests/mesh/grpcroute-weight.yaml"},
Features: []features.FeatureName{
features.SupportMesh,
features.SupportGRPCRoute,
},
Test: func(t *testing.T, s *suite.ConformanceTestSuite) {
client := echo.ConnectToApp(t, s, echo.MeshAppEchoV1)

t.Run("Requests should have a distribution that matches the weight", func(t *testing.T) {
// Create a gRPC request using the mesh client framework
expected := http.ExpectedResponse{
Request: http.Request{Protocol: "grpc", Path: "", Host: "echo:7070"},
Response: http.Response{StatusCode: 200},
Namespace: "gateway-conformance-mesh",
}
Comment on lines +47 to +51
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like it is now doing http..? there is no sendGRPC stuff

Copy link
Author

@sarthyparty sarthyparty Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From my understand the way that the mesh http route weight test is working is by execing into the pod and running a command client http://echo:7070. Using the grpc package doesn't work, since I need to run the request from the pod I think?

I was able to configure this by just setting the protocol to grpc in the http Request structure. I think the correct way to do this is probably to refactor the echo client code to accept a structure that is independent of protocol.

Copy link
Author

@sarthyparty sarthyparty Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

req := m.rc.Post().
		Resource("pods").
		Name(m.Name).
		Namespace(m.Namespace).
		SubResource("exec").
		Param("container", container).
		VersionedParams(&v1.PodExecOptions{
			Container: container,
			Command:   args,
			Stdin:     false,
			Stdout:    true,
			Stderr:    true,
			TTY:       false,
		}, scheme.ParameterCodec)

This code here utils/echo/pod.go L168, with args being ['client', 'http://echo:7070'] for http. By setting the protocol to grpc it becomes ['client', 'grpc://echo:7070'] which makes a grpc request I believe

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I will refactor the echo pod function CaptureRequestResponseAndCompare to accept a structure that is protocol independent since it doesn't need to be http specific.

Copy link
Author

@sarthyparty sarthyparty Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually its a lot more code change than I thought to refactor that, what do you think

Copy link
Member

@LiorLieberman LiorLieberman Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is istio client code

/cc @howardjohn can you relate to this?


// Assert request succeeds before doing our distribution check
client.MakeRequestAndExpectEventuallyConsistentResponse(t, expected, s.TimeoutConfig)

expectedWeights := map[string]float64{
"echo-v1": 0.7,
"echo-v2": 0.3,
}

sender := weight.NewFunctionBasedSender(func() (string, error) {
uniqueExpected := expected
if err := http.AddEntropy(&uniqueExpected); err != nil {
return "", fmt.Errorf("error adding entropy: %w", err)
}
_, cRes, err := client.CaptureRequestResponseAndCompare(t, uniqueExpected)
if err != nil {
return "", fmt.Errorf("failed gRPC mesh request: %w", err)
}
return cRes.Hostname, nil
})

for i := 0; i < 10; i++ {
if err := weight.TestWeightedDistribution(sender, expectedWeights); err != nil {
t.Logf("Traffic distribution test failed (%d/10): %s", i+1, err)
} else {
return
}
}
t.Fatal("Weighted distribution tests failed")
})
},
}
19 changes: 19 additions & 0 deletions conformance/tests/mesh/grpcroute-weight.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
apiVersion: gateway.networking.k8s.io/v1
kind: GRPCRoute
metadata:
name: mesh-grpc-weighted-backends
namespace: gateway-conformance-mesh
spec:
parentRefs:
- group: ""
kind: Service
name: echo
port: 7070
rules:
- backendRefs:
- name: echo-v1
port: 7070
weight: 70
- name: echo-v2
port: 7070
weight: 30
Loading