You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by GitBox <gi...@apache.org> on 2022/09/09 09:04:45 UTC

[GitHub] [apisix-ingress-controller] lingsamuel commented on a diff in pull request #1217: feat: support gateway/tcproute round 1

lingsamuel commented on code in PR #1217:
URL: https://github.com/apache/apisix-ingress-controller/pull/1217#discussion_r966800999


##########
pkg/providers/gateway/gateway_tcproute.go:
##########
@@ -0,0 +1,244 @@
+// 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 gatewayTCPRouteController struct {
+	controller *Provider
+	workqueue  workqueue.RateLimitingInterface
+	workers    int
+}
+
+func newGatewayTCPRouteController(c *Provider) *gatewayTCPRouteController {
+	ctrl := &gatewayTCPRouteController{
+		controller: c,
+		workqueue:  workqueue.NewNamedRateLimitingQueue(workqueue.NewItemFastSlowRateLimiter(1*time.Second, 60*time.Second, 5), "GatewayTCPRoute"),
+		workers:    1,
+	}
+
+	ctrl.controller.gatewayTCPRouteInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+		AddFunc:    ctrl.onAdd,
+		UpdateFunc: ctrl.onUpdate,
+		DeleteFunc: ctrl.OnDelete,
+	})
+	return ctrl
+}
+
+func (c *gatewayTCPRouteController) 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 TCPRoute resource with invalid key",
+			zap.Error(err),
+			zap.String("key", key),
+		)
+		return err
+	}
+	log.Debugw("sync TCPRoute", zap.String("key", key))
+
+	tcpRoute, err := c.controller.gatewayTCPRouteLister.TCPRoutes(namespace).Get(name)
+	if err != nil {
+		if !k8serrors.IsNotFound(err) {
+			log.Errorw("failed to get Gateway TCPRoute",
+				zap.Error(err),
+				zap.String("key", key),
+			)
+			return err
+		}
+		if ev.Type != types.EventDelete {
+			log.Warnw("Gateway TCPRoute was deleted before process",
+				zap.String("key", key),
+			)
+			// Don't need to retry.
+			return nil
+		}
+	}
+	if ev.Type == types.EventDelete {
+		if tcpRoute == 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.Warnf("discard the stale Gateway delete event since the %s exists", key)
+			return nil
+		}
+		tcpRoute = ev.Tombstone.(*gatewayv1alpha2.TCPRoute)
+	}
+	tctx, err := c.controller.translator.TranslateGatewayTCPRouteV1Alpha2(tcpRoute)
+	if err != nil {
+		log.Errorw("failed to translate gateway TCPRoute",
+			zap.Error(err),
+			zap.Any("object", tcpRoute),
+		)
+		return err
+	}
+
+	log.Debugw("translated TCPRoute",
+		zap.Any("stream_routes", 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.TCPRoute)
+		oldCtx, err = c.controller.translator.TranslateGatewayTCPRouteV1Alpha2(oldObj)
+		if err != nil {
+			log.Errorw("failed to translate old TCPRoute",
+				zap.String("version", oldObj.APIVersion),
+				zap.String("event_type", "update"),
+				zap.Any("TCPRoute", oldObj),
+				zap.Error(err),
+			)
+			return err
+		}
+
+		om := &utils.Manifest{
+			StreamRoutes: oldCtx.StreamRoutes,
+			Upstreams:    oldCtx.Upstreams,
+		}
+		added, updated, deleted = m.Diff(om)
+	}
+
+	return utils.SyncManifests(ctx, c.controller.APISIX, c.controller.APISIXClusterName, added, updated, deleted)
+}
+
+func (c *gatewayTCPRouteController) run(ctx context.Context) {
+	log.Info("gateway TCPRoute controller started")
+	defer log.Info("gateway TCPRoute controller exited")
+	defer c.workqueue.ShutDown()
+
+	if !cache.WaitForCacheSync(ctx.Done(), c.controller.gatewayTCPRouteInformer.HasSynced) {
+		log.Error("sync Gateway TCPRoute cache failed")
+		return
+	}
+	for i := 0; i < c.workers; i++ {
+		go c.runWorker(ctx)
+	}
+	<-ctx.Done()
+}
+
+func (c *gatewayTCPRouteController) 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 *gatewayTCPRouteController) handleSyncErr(obj interface{}, err error) {
+	if err == nil {

Review Comment:
   No retry and error logging logic?



##########
pkg/providers/gateway/translation/gateway_tcproute_test.go:
##########
@@ -0,0 +1,196 @@
+// 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_translation
+
+import (
+	"context"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/util/intstr"
+	"k8s.io/client-go/informers"
+	"k8s.io/client-go/kubernetes/fake"
+	"k8s.io/client-go/tools/cache"
+	gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
+
+	"github.com/apache/apisix-ingress-controller/pkg/config"
+	"github.com/apache/apisix-ingress-controller/pkg/kube"
+	fakeapisix "github.com/apache/apisix-ingress-controller/pkg/kube/apisix/client/clientset/versioned/fake"
+	apisixinformers "github.com/apache/apisix-ingress-controller/pkg/kube/apisix/client/informers/externalversions"
+	"github.com/apache/apisix-ingress-controller/pkg/providers/translation"
+)
+
+func mockTCPRouteTranslator(t *testing.T) (*translator, <-chan struct{}) {
+	svc := &corev1.Service{
+		TypeMeta: metav1.TypeMeta{},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "svc",
+			Namespace: "test",
+		},
+		Spec: corev1.ServiceSpec{
+			Ports: []corev1.ServicePort{
+				{
+					Name: "port1",
+					Port: 80,
+					TargetPort: intstr.IntOrString{
+						Type:   intstr.Int,
+						IntVal: 9080,
+					},
+				},
+				{
+					Name: "port2",
+					Port: 443,
+					TargetPort: intstr.IntOrString{
+						Type:   intstr.Int,
+						IntVal: 9443,
+					},
+				},
+			},
+		},
+	}
+	endpoints := &corev1.Endpoints{
+		TypeMeta: metav1.TypeMeta{},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "svc",
+			Namespace: "test",
+		},
+		Subsets: []corev1.EndpointSubset{
+			{
+				Ports: []corev1.EndpointPort{
+					{
+						Name: "port1",
+						Port: 9080,
+					},
+					{
+						Name: "port2",
+						Port: 9443,
+					},
+				},
+				Addresses: []corev1.EndpointAddress{
+					{IP: "192.168.1.1"},
+					{IP: "192.168.1.2"},
+				},
+			},
+		},
+	}
+
+	client := fake.NewSimpleClientset()
+	informersFactory := informers.NewSharedInformerFactory(client, 0)
+	svcInformer := informersFactory.Core().V1().Services().Informer()
+	svcLister := informersFactory.Core().V1().Services().Lister()
+	epLister, epInformer := kube.NewEndpointListerAndInformer(informersFactory, false)
+	apisixClient := fakeapisix.NewSimpleClientset()
+	apisixInformersFactory := apisixinformers.NewSharedInformerFactory(apisixClient, 0)
+
+	_, err := client.CoreV1().Endpoints("test").Create(context.Background(), endpoints, metav1.CreateOptions{})
+	assert.Nil(t, err)
+	_, err = client.CoreV1().Services("test").Create(context.Background(), svc, metav1.CreateOptions{})
+	assert.Nil(t, err)
+
+	tr := &translator{
+		&TranslatorOptions{
+			KubeTranslator: translation.NewTranslator(&translation.TranslatorOptions{
+				EndpointLister: epLister,
+				ServiceLister:  svcLister,
+				ApisixUpstreamLister: kube.NewApisixUpstreamLister(
+					apisixInformersFactory.Apisix().V2beta3().ApisixUpstreams().Lister(),
+					apisixInformersFactory.Apisix().V2().ApisixUpstreams().Lister(),
+				),
+				APIVersion: config.DefaultAPIVersion,
+			}),
+		},
+	}
+
+	processCh := make(chan struct{})
+	svcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+		AddFunc: func(obj interface{}) {
+			processCh <- struct{}{}
+		},
+	})
+	epInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+		AddFunc: func(obj interface{}) {
+			processCh <- struct{}{}
+		},
+	})
+
+	stopCh := make(chan struct{}, 2)
+	defer close(stopCh)
+	go svcInformer.Run(stopCh)
+	go epInformer.Run(stopCh)
+	cache.WaitForCacheSync(stopCh, svcInformer.HasSynced)
+	cache.WaitForCacheSync(stopCh, epInformer.HasSynced)
+
+	return tr, processCh
+}
+
+func TestTranslateGatewayTCPRoute(t *testing.T) {
+	refKind := func(str gatewayv1alpha2.Kind) *gatewayv1alpha2.Kind {

Review Comment:
   good news: we have generic now



##########
pkg/providers/gateway/translation/gateway_tcproute_test.go:
##########
@@ -0,0 +1,196 @@
+// 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_translation
+
+import (
+	"context"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/util/intstr"
+	"k8s.io/client-go/informers"
+	"k8s.io/client-go/kubernetes/fake"
+	"k8s.io/client-go/tools/cache"
+	gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
+
+	"github.com/apache/apisix-ingress-controller/pkg/config"
+	"github.com/apache/apisix-ingress-controller/pkg/kube"
+	fakeapisix "github.com/apache/apisix-ingress-controller/pkg/kube/apisix/client/clientset/versioned/fake"
+	apisixinformers "github.com/apache/apisix-ingress-controller/pkg/kube/apisix/client/informers/externalversions"
+	"github.com/apache/apisix-ingress-controller/pkg/providers/translation"
+)
+
+func mockTCPRouteTranslator(t *testing.T) (*translator, <-chan struct{}) {
+	svc := &corev1.Service{
+		TypeMeta: metav1.TypeMeta{},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "svc",
+			Namespace: "test",
+		},
+		Spec: corev1.ServiceSpec{
+			Ports: []corev1.ServicePort{
+				{
+					Name: "port1",
+					Port: 80,
+					TargetPort: intstr.IntOrString{
+						Type:   intstr.Int,
+						IntVal: 9080,
+					},
+				},
+				{
+					Name: "port2",
+					Port: 443,
+					TargetPort: intstr.IntOrString{
+						Type:   intstr.Int,
+						IntVal: 9443,
+					},
+				},
+			},
+		},
+	}
+	endpoints := &corev1.Endpoints{
+		TypeMeta: metav1.TypeMeta{},
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "svc",
+			Namespace: "test",
+		},
+		Subsets: []corev1.EndpointSubset{
+			{
+				Ports: []corev1.EndpointPort{
+					{
+						Name: "port1",
+						Port: 9080,
+					},
+					{
+						Name: "port2",
+						Port: 9443,
+					},
+				},
+				Addresses: []corev1.EndpointAddress{
+					{IP: "192.168.1.1"},
+					{IP: "192.168.1.2"},
+				},
+			},
+		},
+	}
+
+	client := fake.NewSimpleClientset()
+	informersFactory := informers.NewSharedInformerFactory(client, 0)
+	svcInformer := informersFactory.Core().V1().Services().Informer()
+	svcLister := informersFactory.Core().V1().Services().Lister()
+	epLister, epInformer := kube.NewEndpointListerAndInformer(informersFactory, false)
+	apisixClient := fakeapisix.NewSimpleClientset()
+	apisixInformersFactory := apisixinformers.NewSharedInformerFactory(apisixClient, 0)
+
+	_, err := client.CoreV1().Endpoints("test").Create(context.Background(), endpoints, metav1.CreateOptions{})
+	assert.Nil(t, err)
+	_, err = client.CoreV1().Services("test").Create(context.Background(), svc, metav1.CreateOptions{})
+	assert.Nil(t, err)
+
+	tr := &translator{
+		&TranslatorOptions{
+			KubeTranslator: translation.NewTranslator(&translation.TranslatorOptions{
+				EndpointLister: epLister,
+				ServiceLister:  svcLister,
+				ApisixUpstreamLister: kube.NewApisixUpstreamLister(
+					apisixInformersFactory.Apisix().V2beta3().ApisixUpstreams().Lister(),
+					apisixInformersFactory.Apisix().V2().ApisixUpstreams().Lister(),
+				),
+				APIVersion: config.DefaultAPIVersion,
+			}),
+		},
+	}
+
+	processCh := make(chan struct{})
+	svcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+		AddFunc: func(obj interface{}) {
+			processCh <- struct{}{}
+		},
+	})
+	epInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+		AddFunc: func(obj interface{}) {
+			processCh <- struct{}{}
+		},
+	})
+
+	stopCh := make(chan struct{}, 2)
+	defer close(stopCh)
+	go svcInformer.Run(stopCh)
+	go epInformer.Run(stopCh)
+	cache.WaitForCacheSync(stopCh, svcInformer.HasSynced)
+	cache.WaitForCacheSync(stopCh, epInformer.HasSynced)
+
+	return tr, processCh
+}
+
+func TestTranslateGatewayTCPRoute(t *testing.T) {
+	refKind := func(str gatewayv1alpha2.Kind) *gatewayv1alpha2.Kind {
+		return &str
+	}
+	refNamespace := func(str gatewayv1alpha2.Namespace) *gatewayv1alpha2.Namespace {
+		return &str
+	}
+	refPortNumber := func(i gatewayv1alpha2.PortNumber) *gatewayv1alpha2.PortNumber {
+		return &i
+	}
+	refInt32 := func(i int32) *int32 {
+		return &i
+	}
+	tr, processCh := mockTCPRouteTranslator(t)
+	<-processCh
+	<-processCh
+
+	tcpRoute := &gatewayv1alpha2.TCPRoute{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:      "tcp_route",
+			Namespace: "test",
+		},
+		Spec: gatewayv1alpha2.TCPRouteSpec{
+			Rules: []gatewayv1alpha2.TCPRouteRule{
+				{
+					BackendRefs: []gatewayv1alpha2.BackendRef{
+						{
+							BackendObjectReference: gatewayv1alpha2.BackendObjectReference{
+								Kind:      refKind("Service"),
+								Name:      "svc",
+								Namespace: refNamespace("test"),
+								Port:      refPortNumber(80),
+							},
+							Weight: refInt32(100),
+						},
+					},
+				},
+			},
+		},
+	}
+
+	tctx, err := tr.TranslateGatewayTCPRouteV1Alpha2(tcpRoute)
+	assert.Nil(t, err)
+
+	assert.Equal(t, 1, len(tctx.StreamRoutes))
+	assert.Equal(t, 1, len(tctx.Upstreams))
+
+	r := tctx.StreamRoutes[0]
+	u := tctx.Upstreams[0]
+
+	// Metadata
+	// FIXME

Review Comment:
   Fix what?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org