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 9 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...)
}
100 changes: 100 additions & 0 deletions conformance/tests/mesh/grpcroute-weight.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
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"

"google.golang.org/grpc/codes"

pb "sigs.k8s.io/gateway-api/conformance/echo-basic/grpcechoserver"
"sigs.k8s.io/gateway-api/conformance/utils/echo"
"sigs.k8s.io/gateway-api/conformance/utils/grpc"
"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) {
// Connect to mesh app to get the service address
client := echo.ConnectToApp(t, s, echo.MeshAppEchoV1)

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-mesh",
}

// Assert request succeeds before doing our distribution check
grpcClient := &grpc.DefaultClient{}
defer grpcClient.Close()
resp, err := grpcClient.SendRPC(t, client.Address+":9000", expected, s.TimeoutConfig.MaxTimeToConsistency)
if err != nil {
t.Skipf("gRPC mesh test requires gRPC support on mesh services: %v", err)
}
if resp.Code != codes.OK {
t.Skipf("gRPC mesh test requires working gRPC endpoints: got %v", resp.Code)
}

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

sender := weight.NewFunctionBasedSender(func() (string, error) {
uniqueExpected := expected
if err := grpc.AddEntropy(&uniqueExpected); err != nil {
return "", fmt.Errorf("error adding entropy: %w", err)
}

grpcClient := &grpc.DefaultClient{}
defer grpcClient.Close()
resp, err := grpcClient.SendRPC(t, client.Address+":9000", uniqueExpected, s.TimeoutConfig.MaxTimeToConsistency)
if err != nil {
return "", fmt.Errorf("failed to send gRPC mesh 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/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: 9000
rules:
- backendRefs:
- name: echo-v1
port: 9000
weight: 70
- name: echo-v2
port: 9000
weight: 30
Loading