This is an automated email from the ASF dual-hosted git repository.

zhangjintao pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix-ingress-controller.git


The following commit(s) were added to refs/heads/master by this push:
     new 8a17eea2 feat: add Gateway UDPRoute (#1278)
8a17eea2 is described below

commit 8a17eea26e96570dd1054f258e484bf7814627eb
Author: lsy <[email protected]>
AuthorDate: Wed Oct 12 10:18:45 2022 +0800

    feat: add Gateway UDPRoute (#1278)
---
 pkg/providers/gateway/gateway_udproute.go          | 224 +++++++++++++++++++++
 pkg/providers/gateway/provider.go                  |  16 ++
 pkg/providers/gateway/translation/gateway.go       |  15 +-
 .../gateway/translation/gateway_udproute.go        |  95 +++++++++
 pkg/providers/gateway/translation/translator.go    |   2 +
 pkg/types/apisix/v1/types.go                       |   4 +
 test/e2e/go.mod                                    |   2 +-
 test/e2e/go.sum                                    |   1 +
 test/e2e/scaffold/ingress.go                       |   1 +
 test/e2e/scaffold/test_backend.go                  |  64 ++++++
 test/e2e/suite-gateway/gateway_udproute.go         |  56 ++++++
 11 files changed, 478 insertions(+), 2 deletions(-)

diff --git a/pkg/providers/gateway/gateway_udproute.go 
b/pkg/providers/gateway/gateway_udproute.go
new file mode 100644
index 00000000..f78a656c
--- /dev/null
+++ b/pkg/providers/gateway/gateway_udproute.go
@@ -0,0 +1,224 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You 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 gateway
+
+import (
+       "context"
+       "time"
+
+       "go.uber.org/zap"
+       k8serrors "k8s.io/apimachinery/pkg/api/errors"
+       "k8s.io/client-go/tools/cache"
+       "k8s.io/client-go/util/workqueue"
+       gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
+
+       "github.com/apache/apisix-ingress-controller/pkg/log"
+       "github.com/apache/apisix-ingress-controller/pkg/providers/translation"
+       "github.com/apache/apisix-ingress-controller/pkg/providers/utils"
+       "github.com/apache/apisix-ingress-controller/pkg/types"
+)
+
+type gatewayUDPRouteController struct {
+       controller *Provider
+       workqueue  workqueue.RateLimitingInterface
+       workers    int
+}
+
+func newGatewayUDPRouteController(c *Provider) *gatewayUDPRouteController {
+       ctrl := &gatewayUDPRouteController{
+               controller: c,
+               workqueue:  
workqueue.NewNamedRateLimitingQueue(workqueue.NewItemFastSlowRateLimiter(1*time.Second,
 60*time.Second, 5), "GatewayUDPRoute"),
+               workers:    1,
+       }
+
+       
ctrl.controller.gatewayUDPRouteInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+               AddFunc:    ctrl.onAdd,
+               UpdateFunc: ctrl.onUpdate,
+               DeleteFunc: ctrl.OnDelete,
+       })
+       return ctrl
+}
+
+func (c *gatewayUDPRouteController) run(ctx context.Context) {
+       log.Info("gateway UDPRoute controller started")
+       defer log.Info("gateway UDPRoute controller exited")
+       defer c.workqueue.ShutDown()
+
+       if !cache.WaitForCacheSync(ctx.Done(), 
c.controller.gatewayUDPRouteInformer.HasSynced) {
+               log.Error("sync Gateway UDPRoute cache failed")
+               return
+       }
+
+       for i := 0; i < c.workers; i++ {
+               go c.runWorker(ctx)
+       }
+       <-ctx.Done()
+}
+
+func (c *gatewayUDPRouteController) runWorker(ctx context.Context) {
+       for {
+               obj, quit := c.workqueue.Get()
+               if quit {
+                       return
+               }
+               err := c.sync(ctx, obj.(*types.Event))
+               c.workqueue.Done(obj)
+               c.handleSyncErr(obj, err)
+       }
+}
+
+func (c *gatewayUDPRouteController) sync(ctx context.Context, ev *types.Event) 
error {
+       key := ev.Object.(string)
+       namespace, name, err := cache.SplitMetaNamespaceKey(key)
+       if err != nil {
+               log.Errorw("found Gateway UDPRoute resource with invalid key",
+                       zap.Error(err),
+                       zap.String("key", key),
+               )
+               return err
+       }
+
+       log.Debugw("sync UDPRoute", zap.String("key", key))
+
+       udpRoute, err := 
c.controller.gatewayUDPRouteLister.UDPRoutes(namespace).Get(name)
+       if err != nil {
+               if !k8serrors.IsNotFound(err) {
+                       log.Errorw("failed to get Gateway UDPRoute",
+                               zap.Error(err),
+                               zap.String("key", key),
+                       )
+                       return err
+               }
+               if ev.Type != types.EventDelete {
+                       log.Warnw("Gateway UDPRoute was deleted before process",
+                               zap.String("key", key),
+                       )
+                       // Don't need to retry.
+                       return nil
+               }
+       }
+
+       if ev.Type == types.EventDelete {
+               if udpRoute != nil {
+                       // We still find the resource while we are processing 
the DELETE event,
+                       // that means object with same namespace and name was 
created, discarding
+                       // this stale DELETE event.
+                       log.Warnw("discard the stale Gateway delete event since 
it exists",
+                               zap.String("key", key),
+                       )
+                       return nil
+               }
+               udpRoute = ev.Tombstone.(*gatewayv1alpha2.UDPRoute)
+       }
+
+       tctx, err := 
c.controller.translator.TranslateGatewayUDPRouteV1Alpha2(udpRoute)
+
+       if err != nil {
+               log.Errorw("failed to translate gateway UDPRoute",
+                       zap.Error(err),
+                       zap.Any("object", udpRoute),
+               )
+               return err
+       }
+
+       log.Debugw("translated UDPRoute",
+               zap.Any("streamroutes", tctx.StreamRoutes),
+               zap.Any("upstreams", tctx.Upstreams),
+       )
+       m := &utils.Manifest{
+               StreamRoutes: tctx.StreamRoutes,
+               Upstreams:    tctx.Upstreams,
+       }
+
+       var (
+               added   *utils.Manifest
+               updated *utils.Manifest
+               deleted *utils.Manifest
+       )
+
+       if ev.Type == types.EventDelete {
+               deleted = m
+       } else if ev.Type == types.EventAdd {
+               added = m
+       } else {
+               var oldCtx *translation.TranslateContext
+               oldObj := ev.OldObject.(*gatewayv1alpha2.UDPRoute)
+               oldCtx, err = 
c.controller.translator.TranslateGatewayUDPRouteV1Alpha2(oldObj)
+               if err != nil {
+                       log.Errorw("failed to translate old UDPRoute",
+                               zap.String("version", oldObj.APIVersion),
+                               zap.String("event_type", "update"),
+                               zap.Any("UDPRoute", oldObj),
+                               zap.Error(err),
+                       )
+                       return err
+               }
+
+               om := &utils.Manifest{
+                       Routes:    oldCtx.Routes,
+                       Upstreams: oldCtx.Upstreams,
+               }
+               added, updated, deleted = m.Diff(om)
+       }
+
+       return utils.SyncManifests(ctx, c.controller.APISIX, 
c.controller.APISIXClusterName, added, updated, deleted)
+}
+
+func (c *gatewayUDPRouteController) handleSyncErr(obj interface{}, err error) {
+       if err == nil {
+               c.workqueue.Forget(obj)
+               
c.controller.MetricsCollector.IncrSyncOperation("gateway_udproute", "success")
+               return
+       }
+       event := obj.(*types.Event)
+       if k8serrors.IsNotFound(err) && event.Type != types.EventDelete {
+               log.Infow("sync gateway UDPRoute but not found, ignore",
+                       zap.String("event_type", event.Type.String()),
+                       zap.String("UDPRoute ", event.Object.(string)),
+               )
+               c.workqueue.Forget(event)
+               return
+       }
+       log.Warnw("sync gateway UDPRoute failed, will retry",
+               zap.Any("object", obj),
+               zap.Error(err),
+       )
+       c.workqueue.AddRateLimited(obj)
+       c.controller.MetricsCollector.IncrSyncOperation("gateway_udproute", 
"failure")
+}
+
+func (c *gatewayUDPRouteController) onAdd(obj interface{}) {
+       key, err := cache.MetaNamespaceKeyFunc(obj)
+       if err != nil {
+               log.Errorw("found gateway UDPRoute resource with bad meta 
namespace key",
+                       zap.Error(err),
+               )
+               return
+       }
+       if !c.controller.NamespaceProvider.IsWatchingNamespace(key) {
+               return
+       }
+       log.Debugw("gateway UDPRoute add event arrived",
+               zap.Any("object", obj),
+       )
+
+       log.Debugw("add UDPRoute", zap.String("key", key))
+       c.workqueue.Add(&types.Event{
+               Type:   types.EventAdd,
+               Object: key,
+       })
+}
+func (c *gatewayUDPRouteController) onUpdate(oldObj, newObj interface{}) {}
+func (c *gatewayUDPRouteController) OnDelete(obj interface{})            {}
diff --git a/pkg/providers/gateway/provider.go 
b/pkg/providers/gateway/provider.go
index 675c80c1..446f1341 100644
--- a/pkg/providers/gateway/provider.go
+++ b/pkg/providers/gateway/provider.go
@@ -80,6 +80,10 @@ type Provider struct {
        gatewayTCPRouteController *gatewayTCPRouteController
        gatewayTCPRouteInformer   cache.SharedIndexInformer
        gatewayTCPRouteLister     gatewaylistersv1alpha2.TCPRouteLister
+
+       gatewayUDPRouteController *gatewayUDPRouteController
+       gatewayUDPRouteInformer   cache.SharedIndexInformer
+       gatewayUDPRouteLister     gatewaylistersv1alpha2.UDPRouteLister
 }
 
 type ProviderOptions struct {
@@ -141,6 +145,9 @@ func NewGatewayProvider(opts *ProviderOptions) (*Provider, 
error) {
        p.gatewayTCPRouteLister = 
gatewayFactory.Gateway().V1alpha2().TCPRoutes().Lister()
        p.gatewayTCPRouteInformer = 
gatewayFactory.Gateway().V1alpha2().TCPRoutes().Informer()
 
+       p.gatewayUDPRouteLister = 
gatewayFactory.Gateway().V1alpha2().UDPRoutes().Lister()
+       p.gatewayUDPRouteInformer = 
gatewayFactory.Gateway().V1alpha2().UDPRoutes().Informer()
+
        p.gatewayController = newGatewayController(p)
 
        p.gatewayClassController, err = newGatewayClassController(p)
@@ -151,6 +158,7 @@ func NewGatewayProvider(opts *ProviderOptions) (*Provider, 
error) {
        p.gatewayHTTPRouteController = newGatewayHTTPRouteController(p)
 
        p.gatewayTLSRouteController = newGatewayTLSRouteController(p)
+       p.gatewayUDPRouteController = newGatewayUDPRouteController(p)
 
        p.gatewayTCPRouteController = newGatewayTCPRouteController(p)
 
@@ -178,6 +186,10 @@ func (p *Provider) Run(ctx context.Context) {
        })
 
        // Run Controller
+       e.Add(func() {
+               p.gatewayUDPRouteInformer.Run(ctx.Done())
+       })
+
        e.Add(func() {
                p.gatewayController.run(ctx)
        })
@@ -194,6 +206,10 @@ func (p *Provider) Run(ctx context.Context) {
                p.gatewayTCPRouteController.run(ctx)
        })
 
+       e.Add(func() {
+               p.gatewayUDPRouteController.run(ctx)
+       })
+
        e.Wait()
 }
 
diff --git a/pkg/providers/gateway/translation/gateway.go 
b/pkg/providers/gateway/translation/gateway.go
index 95045ea2..8b63fdf3 100644
--- a/pkg/providers/gateway/translation/gateway.go
+++ b/pkg/providers/gateway/translation/gateway.go
@@ -27,6 +27,7 @@ import (
 )
 
 const (
+       kindUDPRoute  gatewayv1alpha2.Kind = "UDPRoute"
        kindTCPRoute  gatewayv1alpha2.Kind = "TCPRoute"
        kindTLSRoute  gatewayv1alpha2.Kind = "TLSRoute"
        kindHTTPRoute gatewayv1alpha2.Kind = "HTTPRoute"
@@ -85,7 +86,7 @@ func validateListenerConfigurations(gateway 
*gatewayv1alpha2.Gateway, idx int, a
        listener gatewayv1alpha2.Listener) error {
        // Check protocols and allowedKinds
        protocol := listener.Protocol
-       if protocol == gatewayv1alpha2.HTTPProtocolType || protocol == 
gatewayv1alpha2.TCPProtocolType {
+       if protocol == gatewayv1alpha2.HTTPProtocolType || protocol == 
gatewayv1alpha2.TCPProtocolType || protocol == gatewayv1alpha2.UDPProtocolType {
                // Non-TLS
                if listener.TLS != nil {
                        return errors.New("non-empty TLS conf for protocol " + 
string(protocol))
@@ -98,7 +99,12 @@ func validateListenerConfigurations(gateway 
*gatewayv1alpha2.Gateway, idx int, a
                        if len(allowedKinds) != 1 || allowedKinds[0].Kind != 
kindTCPRoute {
                                return errors.New("TCP protocol must allow 
route type TCPRoute")
                        }
+               } else if protocol == gatewayv1alpha2.UDPProtocolType {
+                       if len(allowedKinds) != 1 || allowedKinds[0].Kind != 
kindUDPRoute {
+                               return errors.New("UDP protocol must allow 
route type UDPRoute")
+                       }
                }
+
        } else if protocol == gatewayv1alpha2.HTTPSProtocolType || protocol == 
gatewayv1alpha2.TLSProtocolType {
                // TLS
                if listener.TLS == nil {
@@ -175,6 +181,13 @@ func getAllowedKinds(listener gatewayv1alpha2.Listener) 
([]gatewayv1alpha2.Route
                                Kind:  kindTCPRoute,
                        },
                }
+       case gatewayv1alpha2.UDPProtocolType:
+               expectedKinds = []gatewayv1alpha2.RouteGroupKind{
+                       {
+                               Group: &group,
+                               Kind:  kindUDPRoute,
+                       },
+               }
        default:
                return nil, errors.New("unknown protocol " + 
string(listener.Protocol))
        }
diff --git a/pkg/providers/gateway/translation/gateway_udproute.go 
b/pkg/providers/gateway/translation/gateway_udproute.go
new file mode 100644
index 00000000..293df79e
--- /dev/null
+++ b/pkg/providers/gateway/translation/gateway_udproute.go
@@ -0,0 +1,95 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 translation
+
+import (
+       "fmt"
+       "strings"
+
+       "github.com/pkg/errors"
+       "go.uber.org/zap"
+       gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
+
+       "github.com/apache/apisix-ingress-controller/pkg/id"
+       "github.com/apache/apisix-ingress-controller/pkg/log"
+       "github.com/apache/apisix-ingress-controller/pkg/providers/translation"
+       "github.com/apache/apisix-ingress-controller/pkg/types"
+       apisixv1 
"github.com/apache/apisix-ingress-controller/pkg/types/apisix/v1"
+)
+
+func (t *translator) TranslateGatewayUDPRouteV1Alpha2(udpRoute 
*gatewayv1alpha2.UDPRoute) (*translation.TranslateContext, error) {
+       ctx := translation.DefaultEmptyTranslateContext()
+
+       // TODO: handle UDPRoute.Spec.ParentRef
+       for i, rule := range udpRoute.Spec.Rules {
+
+               for j, backend := range rule.BackendRefs {
+                       // Spec validation
+                       var kind string
+                       if backend.Kind == nil {
+                               kind = "service"
+                       } else {
+                               kind = strings.ToLower(string(*backend.Kind))
+                       }
+                       if kind != "service" {
+                               log.Warnw(fmt.Sprintf("ignore non-service kind 
at Rules[%v].BackendRefs[%v]", i, j),
+                                       zap.String("kind", kind),
+                               )
+                               continue
+                       }
+
+                       var ns string
+                       if backend.Namespace == nil {
+                               ns = udpRoute.Namespace
+                       } else {
+                               ns = string(*backend.Namespace)
+                       }
+                       //if ns != httpRoute.Namespace {
+                       // TODO: check gatewayv1alpha2.ReferencePolicy
+                       //}
+
+                       if backend.Port == nil {
+                               log.Warnw(fmt.Sprintf("ignore nil port at 
Rules[%v].BackendRefs[%v]", i, j),
+                                       zap.String("kind", kind),
+                               )
+                               continue
+                       }
+
+                       // create apisix Upstream
+                       sr := apisixv1.NewDefaultStreamRoute()
+                       name := apisixv1.ComposeStreamRouteName(ns, 
udpRoute.Name, fmt.Sprintf("%d-%d", i, j))
+                       sr.ID = id.GenID(name)
+                       ups, err := t.KubeTranslator.TranslateService(ns, 
string(backend.Name), "", int32(*backend.Port))
+                       if err != nil {
+                               return nil, errors.Wrap(err, 
fmt.Sprintf("failed to translate Rules[%v].BackendRefs[%v]", i, j))
+                       }
+                       ups.Scheme = apisixv1.SchemeUDP
+                       name = apisixv1.ComposeUpstreamName(ns, 
string(backend.Name), "", int32(*backend.Port), 
types.ResolveGranularity.Endpoint)
+                       ups.ID = id.GenID(name)
+                       sr.UpstreamId = ups.ID
+                       ctx.AddStreamRoute(sr)
+                       if !ctx.CheckUpstreamExist(ups.Name) {
+                               ctx.AddUpstream(ups)
+                       }
+
+                       //if backend.Weight == nil {
+                       // TODO: set Upstream.Nodes roundrobin by 
BackendRef.Weight
+                       //}
+               }
+       }
+       return ctx, nil
+}
diff --git a/pkg/providers/gateway/translation/translator.go 
b/pkg/providers/gateway/translation/translator.go
index da5dab7f..0703ca7a 100644
--- a/pkg/providers/gateway/translation/translator.go
+++ b/pkg/providers/gateway/translation/translator.go
@@ -40,6 +40,8 @@ type Translator interface {
        TranslateGatewayTLSRouteV1Alpha2(tlsRoute *gatewayv1alpha2.TLSRoute) 
(*translation.TranslateContext, error)
        // TranslateGatewayTCPRouteV1Alpha2 translates Gateway API TCPRoute to 
APISIX resources
        TranslateGatewayTCPRouteV1Alpha2(*gatewayv1alpha2.TCPRoute) 
(*translation.TranslateContext, error)
+       // TranslateGatewayUDPRouteV1Alpha2 translates Gateway API UDPRoute to 
APISIX resources
+       TranslateGatewayUDPRouteV1Alpha2(udpRoute *gatewayv1alpha2.UDPRoute) 
(*translation.TranslateContext, error)
 }
 
 // NewTranslator initializes a APISIX CRD resources Translator.
diff --git a/pkg/types/apisix/v1/types.go b/pkg/types/apisix/v1/types.go
index e89de924..20e5d4a7 100644
--- a/pkg/types/apisix/v1/types.go
+++ b/pkg/types/apisix/v1/types.go
@@ -57,6 +57,10 @@ const (
        SchemeHTTPS = "https"
        // SchemeGRPCS represents the GRPCS protocol.
        SchemeGRPCS = "grpcs"
+       // SchemeTCP represents the TCP protocol.
+       SchemeTCP = "tcp"
+       // SchemeUDP represents the UDP protocol.
+       SchemeUDP = "udp"
 
        // HealthCheckHTTP represents the HTTP kind health check.
        HealthCheckHTTP = "http"
diff --git a/test/e2e/go.mod b/test/e2e/go.mod
index f3cbb172..be97dd32 100644
--- a/test/e2e/go.mod
+++ b/test/e2e/go.mod
@@ -14,6 +14,7 @@ require (
        k8s.io/api v0.25.1
        k8s.io/apimachinery v0.25.1
        k8s.io/client-go v0.25.1
+       sigs.k8s.io/gateway-api v0.4.0
 )
 
 require (
@@ -113,7 +114,6 @@ require (
        k8s.io/kube-openapi v0.0.0-20220803164354-a70c9af30aea // indirect
        k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed // indirect
        moul.io/http2curl v1.0.1-0.20190925090545-5cd742060b0e // indirect
-       sigs.k8s.io/gateway-api v0.4.0 // indirect
        sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect
        sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect
        sigs.k8s.io/yaml v1.3.0 // indirect
diff --git a/test/e2e/go.sum b/test/e2e/go.sum
index a9ed447c..4296e831 100644
--- a/test/e2e/go.sum
+++ b/test/e2e/go.sum
@@ -810,6 +810,7 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod 
h1:RxMgew5VJxzue5/jJ
 golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod 
h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod 
h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod 
h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod 
h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f 
h1:Ax0t5p6N38Ga0dThY21weqDEyz2oklo4IvDkpigvkD8=
 golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod 
h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod 
h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
diff --git a/test/e2e/scaffold/ingress.go b/test/e2e/scaffold/ingress.go
index 944efa7a..4766b36f 100644
--- a/test/e2e/scaffold/ingress.go
+++ b/test/e2e/scaffold/ingress.go
@@ -195,6 +195,7 @@ rules:
     - tcproutes
     - gateways
     - gatewayclasses
+    - udproutes
     verbs:
     - get
     - list
diff --git a/test/e2e/scaffold/test_backend.go 
b/test/e2e/scaffold/test_backend.go
index bb4c8ef4..e212c3e1 100644
--- a/test/e2e/scaffold/test_backend.go
+++ b/test/e2e/scaffold/test_backend.go
@@ -18,6 +18,8 @@ import (
        "fmt"
 
        "github.com/gruntwork-io/terratest/modules/k8s"
+       ginkgo "github.com/onsi/ginkgo/v2"
+       "github.com/stretchr/testify/assert"
        corev1 "k8s.io/api/core/v1"
 )
 
@@ -117,6 +119,52 @@ spec:
       protocol: TCP
       targetPort: 50053
   type: ClusterIP
+`
+       _udpDeployment = `
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+  name: coredns
+spec:
+  replicas: 1
+  selector:
+    matchLabels:
+      app: coredns
+  template:
+    metadata:
+      labels:
+        app: coredns
+    spec:
+      containers:
+      - name: coredns
+        image: coredns/coredns:1.8.4
+        livenessProbe:
+          tcpSocket:
+            port: 53
+          initialDelaySeconds: 5
+          periodSeconds: 10
+        readinessProbe:
+          tcpSocket:
+            port: 53
+          initialDelaySeconds: 5
+          periodSeconds: 10
+        ports:    
+        - name: dns
+          containerPort: 53
+          protocol: UDP
+`
+       _udpService = `
+kind: Service
+apiVersion: v1
+metadata:
+  name: coredns
+spec:
+  selector:
+    app: coredns
+  type: ClusterIP
+  ports:
+  - port: 53
+    targetPort: 53
 `
 )
 
@@ -134,3 +182,19 @@ func (s *Scaffold) newTestBackend() (*corev1.Service, 
error) {
        }
        return svc, nil
 }
+
+// NewCoreDNSService creates a new UDP backend for testing.
+func (s *Scaffold) NewCoreDNSService() *corev1.Service {
+       err := k8s.KubectlApplyFromStringE(s.t, s.kubectlOptions, 
_udpDeployment)
+       assert.Nil(ginkgo.GinkgoT(), err, "failed to create CoreDNS deployment")
+
+       err = k8s.KubectlApplyFromStringE(s.t, s.kubectlOptions, _udpService)
+       assert.Nil(ginkgo.GinkgoT(), err, "failed to create CoreDNS service")
+
+       s.EnsureNumEndpointsReady(ginkgo.GinkgoT(), "coredns", 1)
+
+       svc, err := k8s.GetServiceE(s.t, s.kubectlOptions, "coredns")
+       assert.Nil(ginkgo.GinkgoT(), err, "failed to get CoreDNS service")
+
+       return svc
+}
diff --git a/test/e2e/suite-gateway/gateway_udproute.go 
b/test/e2e/suite-gateway/gateway_udproute.go
new file mode 100644
index 00000000..31bd60f5
--- /dev/null
+++ b/test/e2e/suite-gateway/gateway_udproute.go
@@ -0,0 +1,56 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you 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 gateway
+
+import (
+       "context"
+       "fmt"
+
+       "github.com/onsi/ginkgo/v2"
+       "github.com/stretchr/testify/assert"
+
+       "github.com/apache/apisix-ingress-controller/test/e2e/scaffold"
+)
+
+var _ = ginkgo.Describe("suite-gateway: UDP Route", func() {
+       s := scaffold.NewDefaultScaffold()
+
+       ginkgo.It("UDPRoute", func() {
+               // setup udp test service
+               dnsSvc := s.NewCoreDNSService()
+               route := fmt.Sprintf(`
+apiVersion: gateway.networking.k8s.io/v1alpha2
+kind: UDPRoute
+metadata:
+    name: "udp-route-test"
+spec:
+    rules:
+    - backendRefs:
+      - name: %s
+        port: %d
+`, dnsSvc.Name, dnsSvc.Spec.Ports[0].Port)
+               err := s.CreateResourceFromString(route)
+               assert.Nil(ginkgo.GinkgoT(), err, "create UDPRoute failed")
+               assert.Nil(ginkgo.GinkgoT(), 
s.EnsureNumApisixStreamRoutesCreated(1), "Checking number of streamroute")
+               assert.Nil(ginkgo.GinkgoT(), 
s.EnsureNumApisixUpstreamsCreated(1), "Checking number of upstream")
+               // test dns query
+               r := s.DNSResolver()
+               host := "httpbin.org"
+               _, err = r.LookupIPAddr(context.Background(), host)
+               assert.Nil(ginkgo.GinkgoT(), err, "dns query error")
+       })
+})

Reply via email to