Skip to content

Add TCPRoute and UDPRoute Support for L4 Load Balancing #3688

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 2 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
14 changes: 14 additions & 0 deletions internal/controller/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,18 @@ func registerControllers(
controller.WithK8sPredicate(k8spredicate.GenerationChangedPredicate{}),
},
},
{
objectType: &gatewayv1alpha2.TCPRoute{},
options: []controller.Option{
controller.WithK8sPredicate(k8spredicate.GenerationChangedPredicate{}),
},
},
{
objectType: &gatewayv1alpha2.UDPRoute{},
options: []controller.Option{
controller.WithK8sPredicate(k8spredicate.GenerationChangedPredicate{}),
},
},
}
controllerRegCfgs = append(controllerRegCfgs, gwExpFeatures...)
}
Expand Down Expand Up @@ -754,6 +766,8 @@ func prepareFirstEventBatchPreparerArgs(cfg config.Config) ([]client.Object, []c
&gatewayv1alpha3.BackendTLSPolicyList{},
&apiv1.ConfigMapList{},
&gatewayv1alpha2.TLSRouteList{},
&gatewayv1alpha2.TCPRouteList{},
&gatewayv1alpha2.UDPRouteList{},
)
}

Expand Down
6 changes: 6 additions & 0 deletions internal/controller/nginx/config/stream/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ type Server struct {
RewriteClientIP shared.RewriteClientIPSettings
SSLPreread bool
IsSocket bool
Protocol string
UDPConfig *UDPConfig
}

type UDPConfig struct {
ProxyTimeout string
}

// Upstream holds all configuration for a stream upstream.
Expand Down
52 changes: 50 additions & 2 deletions internal/controller/nginx/config/stream_servers.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,24 @@ func (g GeneratorImpl) executeStreamServers(conf dataplane.Configuration) []exec
}

func createStreamServers(conf dataplane.Configuration) []stream.Server {
if len(conf.TLSPassthroughServers) == 0 {
totalServers := len(conf.TLSPassthroughServers) + len(conf.TCPServers) + len(conf.UDPServers)
if totalServers == 0 {
return nil
}

streamServers := make([]stream.Server, 0, len(conf.TLSPassthroughServers)*2)
streamServers := make([]stream.Server, 0, totalServers*2)
portSet := make(map[int32]struct{})
upstreams := make(map[string]dataplane.Upstream)

for _, u := range conf.StreamUpstreams {
upstreams[u.Name] = u
}
for _, u := range conf.TCPUpstreams {
upstreams[u.Name] = u
}
for _, u := range conf.UDPUpstreams {
upstreams[u.Name] = u
}

for _, server := range conf.TLSPassthroughServers {
if u, ok := upstreams[server.UpstreamName]; ok && server.UpstreamName != "" {
Expand Down Expand Up @@ -76,6 +83,47 @@ func createStreamServers(conf dataplane.Configuration) []stream.Server {
}
streamServers = append(streamServers, streamServer)
}

// Process TCP servers
for i, server := range conf.TCPServers {
if _, inPortSet := portSet[server.Port]; inPortSet {
continue // Skip if port already in use
}

if u, ok := upstreams[server.UpstreamName]; ok && server.UpstreamName != "" && len(u.Endpoints) > 0 {
streamServer := stream.Server{
Listen: fmt.Sprint(server.Port),
StatusZone: fmt.Sprintf("tcp_%d", server.Port),
ProxyPass: server.UpstreamName,
}
streamServers = append(streamServers, streamServer)
portSet[server.Port] = struct{}{}
} else {
fmt.Printf("DEBUG: createStreamServers - TCP Server %d: Skipped - upstream not found or no endpoints\n", i)
}
}

// Process UDP servers
for _, server := range conf.UDPServers {
if _, inPortSet := portSet[server.Port]; inPortSet {
continue // Skip if port already in use
}

if u, ok := upstreams[server.UpstreamName]; ok && server.UpstreamName != "" && len(u.Endpoints) > 0 {
streamServer := stream.Server{
Listen: fmt.Sprintf("%d udp", server.Port),
StatusZone: fmt.Sprintf("udp_%d", server.Port),
ProxyPass: server.UpstreamName,
Protocol: "udp",
UDPConfig: &stream.UDPConfig{
ProxyTimeout: "1s",
},
}
streamServers = append(streamServers, streamServer)
portSet[server.Port] = struct{}{}
}
}

return streamServers
}

Expand Down
4 changes: 4 additions & 0 deletions internal/controller/nginx/config/stream_servers_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ server {
{{- if $s.SSLPreread }}
ssl_preread on;
{{- end }}

{{- if and (eq $s.Protocol "udp") $s.UDPConfig }}
proxy_timeout {{ $s.UDPConfig.ProxyTimeout }};
{{- end }}
}
{{- end }}

Expand Down
8 changes: 7 additions & 1 deletion internal/controller/nginx/config/upstreams.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,13 @@ func executeUpstreams(upstreams []http.Upstream) []executeResult {
}

func (g GeneratorImpl) executeStreamUpstreams(conf dataplane.Configuration) []executeResult {
upstreams := g.createStreamUpstreams(conf.StreamUpstreams)
// Combine all stream upstreams: TLS, TCP, and UDP
allUpstreams := make([]dataplane.Upstream, 0, len(conf.StreamUpstreams)+len(conf.TCPUpstreams)+len(conf.UDPUpstreams))
allUpstreams = append(allUpstreams, conf.StreamUpstreams...)
allUpstreams = append(allUpstreams, conf.TCPUpstreams...)
allUpstreams = append(allUpstreams, conf.UDPUpstreams...)

upstreams := g.createStreamUpstreams(allUpstreams)

result := executeResult{
dest: streamConfigFile,
Expand Down
42 changes: 29 additions & 13 deletions internal/controller/provisioner/objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ const (
defaultInitialDelaySeconds = int32(3)
)

type PortInfo struct {
Port int32
Protocol corev1.Protocol
}

Comment on lines +46 to +50
Copy link
Contributor

@shaun-nx shaun-nx Aug 13, 2025

Choose a reason for hiding this comment

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

Just curious, why did you make this struct?
From the way this is being used, it feels like you can reference Protocol on its own.

For example, on line 144, we can define ports := make(map[int32]corev1.Protocol)
Line 155 then becomes ports[int32(listener.Port)] = protocol

Then the loop on line 473 becomes this

for port, protocol := range ports {
  servicePort := corev1.ServicePort{
	  Name:       fmt.Sprintf("port-%d", port),
	  Port:       port,
	  TargetPort: intstr.FromInt32(port),
	  Protocol:   protocol,

Would love to know what you think though. Do please tell me if I'm overlooking anything.

var emptyDirVolumeSource = corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{}}

func (p *NginxProvisioner) buildNginxResourceObjects(
Expand Down Expand Up @@ -136,9 +141,18 @@ func (p *NginxProvisioner) buildNginxResourceObjects(
openshiftObjs = p.buildOpenshiftObjects(objectMeta)
}

ports := make(map[int32]struct{})
ports := make(map[int32]PortInfo)
for _, listener := range gateway.Spec.Listeners {
ports[int32(listener.Port)] = struct{}{}
var protocol corev1.Protocol
switch listener.Protocol {
case gatewayv1.TCPProtocolType:
protocol = corev1.ProtocolTCP
case gatewayv1.UDPProtocolType:
protocol = corev1.ProtocolUDP
default:
protocol = corev1.ProtocolTCP
}
ports[int32(listener.Port)] = PortInfo{Port: int32(listener.Port), Protocol: protocol}
}

service, err := buildNginxService(objectMeta, nProxyCfg, ports, selectorLabels)
Expand Down Expand Up @@ -434,7 +448,7 @@ func (p *NginxProvisioner) buildOpenshiftObjects(objectMeta metav1.ObjectMeta) [
func buildNginxService(
objectMeta metav1.ObjectMeta,
nProxyCfg *graph.EffectiveNginxProxy,
ports map[int32]struct{},
ports map[int32]PortInfo,
selectorLabels map[string]string,
) (*corev1.Service, error) {
var serviceCfg ngfAPIv1alpha2.ServiceSpec
Expand All @@ -456,16 +470,17 @@ func buildNginxService(
}

servicePorts := make([]corev1.ServicePort, 0, len(ports))
for port := range ports {
for _, portInfo := range ports {
servicePort := corev1.ServicePort{
Name: fmt.Sprintf("port-%d", port),
Port: port,
TargetPort: intstr.FromInt32(port),
Name: fmt.Sprintf("port-%d", portInfo.Port),
Port: portInfo.Port,
TargetPort: intstr.FromInt32(portInfo.Port),
Protocol: portInfo.Protocol,
}

if serviceType != corev1.ServiceTypeClusterIP {
for _, nodePort := range serviceCfg.NodePorts {
if nodePort.ListenerPort == port {
if nodePort.ListenerPort == portInfo.Port {
servicePort.NodePort = nodePort.Port
}
}
Expand Down Expand Up @@ -533,7 +548,7 @@ func (p *NginxProvisioner) buildNginxDeployment(
nProxyCfg *graph.EffectiveNginxProxy,
ngxIncludesConfigMapName string,
ngxAgentConfigMapName string,
ports map[int32]struct{},
ports map[int32]PortInfo,
selectorLabels map[string]string,
agentTLSSecretName string,
dockerSecretNames map[string]string,
Expand Down Expand Up @@ -665,18 +680,19 @@ func (p *NginxProvisioner) buildNginxPodTemplateSpec(
nProxyCfg *graph.EffectiveNginxProxy,
ngxIncludesConfigMapName string,
ngxAgentConfigMapName string,
ports map[int32]struct{},
ports map[int32]PortInfo,
agentTLSSecretName string,
dockerSecretNames map[string]string,
jwtSecretName string,
caSecretName string,
clientSSLSecretName string,
) corev1.PodTemplateSpec {
containerPorts := make([]corev1.ContainerPort, 0, len(ports))
for port := range ports {
for _, portInfo := range ports {
containerPort := corev1.ContainerPort{
Name: fmt.Sprintf("port-%d", port),
ContainerPort: port,
Name: fmt.Sprintf("port-%d", portInfo.Port),
ContainerPort: portInfo.Port,
Protocol: portInfo.Protocol,
}
containerPorts = append(containerPorts, containerPort)
}
Expand Down
12 changes: 12 additions & 0 deletions internal/controller/state/change_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ func NewChangeProcessorImpl(cfg ChangeProcessorConfig) *ChangeProcessorImpl {
NginxProxies: make(map[types.NamespacedName]*ngfAPIv1alpha2.NginxProxy),
GRPCRoutes: make(map[types.NamespacedName]*v1.GRPCRoute),
TLSRoutes: make(map[types.NamespacedName]*v1alpha2.TLSRoute),
TCPRoutes: make(map[types.NamespacedName]*v1alpha2.TCPRoute),
UDPRoutes: make(map[types.NamespacedName]*v1alpha2.UDPRoute),
NGFPolicies: make(map[graph.PolicyKey]policies.Policy),
SnippetsFilters: make(map[types.NamespacedName]*ngfAPIv1alpha1.SnippetsFilter),
}
Expand Down Expand Up @@ -211,6 +213,16 @@ func NewChangeProcessorImpl(cfg ChangeProcessorConfig) *ChangeProcessorImpl {
store: newObjectStoreMapAdapter(clusterStore.TLSRoutes),
predicate: nil,
},
{
gvk: cfg.MustExtractGVK(&v1alpha2.TCPRoute{}),
store: newObjectStoreMapAdapter(clusterStore.TCPRoutes),
predicate: nil,
},
{
gvk: cfg.MustExtractGVK(&v1alpha2.UDPRoute{}),
store: newObjectStoreMapAdapter(clusterStore.UDPRoutes),
predicate: nil,
},
{
gvk: cfg.MustExtractGVK(&ngfAPIv1alpha1.SnippetsFilter{}),
store: newObjectStoreMapAdapter(clusterStore.SnippetsFilters),
Expand Down
6 changes: 3 additions & 3 deletions internal/controller/state/change_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3776,7 +3776,7 @@ var _ = Describe("ChangeProcessor", func() {
},
Entry(
"an unsupported resource",
&v1alpha2.TCPRoute{ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "tcp"}},
&apiv1.Pod{ObjectMeta: metav1.ObjectMeta{Namespace: "test", Name: "pod"}},
),
Entry(
"nil resource",
Expand All @@ -3794,8 +3794,8 @@ var _ = Describe("ChangeProcessor", func() {
},
Entry(
"an unsupported resource",
&v1alpha2.TCPRoute{},
types.NamespacedName{Namespace: "test", Name: "tcp"},
&apiv1.Pod{},
types.NamespacedName{Namespace: "test", Name: "pod"},
),
Entry(
"nil resource type",
Expand Down
Loading