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/05/26 14:42:37 UTC

[GitHub] [apisix-ingress-controller] tao12345666333 commented on a diff in pull request #1022: feat: sync CRD and ingress resource to apisix mechanism.

tao12345666333 commented on code in PR #1022:
URL: https://github.com/apache/apisix-ingress-controller/pull/1022#discussion_r881190898


##########
pkg/config/config_test.go:
##########
@@ -154,6 +157,7 @@ func TestConfigWithEnvVar(t *testing.T) {
 	"ingress_publish_service": "",
 	"ingress_status_address": [],
     "enable_profiling": true,
+	"apisix-cache-sync-interval": "200s",

Review Comment:
   Maybe we can format it so that they are aligned



##########
pkg/config/config.go:
##########
@@ -115,15 +116,16 @@ type APISIXConfig struct {
 // default value.
 func NewDefaultConfig() *Config {
 	return &Config{
-		LogLevel:              "warn",
-		LogOutput:             "stderr",
-		HTTPListen:            ":8080",
-		HTTPSListen:           ":8443",
-		IngressPublishService: "",
-		IngressStatusAddress:  []string{},
-		CertFilePath:          "/etc/webhook/certs/cert.pem",
-		KeyFilePath:           "/etc/webhook/certs/key.pem",
-		EnableProfiling:       true,
+		LogLevel:                "warn",
+		LogOutput:               "stderr",
+		HTTPListen:              ":8080",
+		HTTPSListen:             ":8443",
+		IngressPublishService:   "",
+		IngressStatusAddress:    []string{},
+		CertFilePath:            "/etc/webhook/certs/cert.pem",
+		KeyFilePath:             "/etc/webhook/certs/key.pem",
+		EnableProfiling:         true,
+		ApisixCacheSyncInterval: types.TimeDuration{Duration: 6 * time.Second},

Review Comment:
   the default value shoud be 300s, right?



##########
pkg/ingress/controller.go:
##########
@@ -715,3 +719,54 @@ func (c *Controller) checkClusterHealth(ctx context.Context, cancelFunc context.
 		c.MetricsCollector.IncrCheckClusterHealth(c.name)
 	}
 }
+
+func (c *Controller) syncResourceAll() {
+	wg := sync.WaitGroup{}
+	goAttach := func(handler func()) {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			handler()
+		}()
+	}
+	goAttach(func() {
+		c.apisixConsumerController.ResourceSync()
+	})
+	goAttach(func() {
+		c.apisixRouteController.ResourceSync()
+	})
+	goAttach(func() {
+		c.apisixClusterConfigController.ResourceSync()
+	})
+	goAttach(func() {
+		c.apisixPluginConfigController.ResourceSync()
+	})
+	goAttach(func() {
+		c.apisixUpstreamController.ResourceSync()
+	})
+	goAttach(func() {
+		c.apisixTlsController.ResourceSync()
+	})
+	goAttach(func() {
+		c.ingressController.ResourceSync()
+	})
+	wg.Wait()
+}
+
+func (c *Controller) resourceSyncLoop(ctx context.Context, interval time.Duration) {
+	// The interval shall not be less than 60 minutes.

Review Comment:
   When defining this constant, you set it to a minimum of 60s, which is inconsistent here



##########
test/e2e/scaffold/ingress.go:
##########
@@ -268,6 +268,8 @@ spec:
             - debug
             - --log-output
             - stdout
+            - --apisix-cache-sync-interval
+            - 60s

Review Comment:
   should we enable this by default?



##########
pkg/ingress/apisix_cluster_config.go:
##########
@@ -277,3 +277,21 @@ func (c *apisixClusterConfigController) onDelete(obj interface{}) {
 
 	c.controller.MetricsCollector.IncrEvents("clusterConfig", "delete")
 }
+
+func (c *apisixClusterConfigController) ResourceSync() {
+	objs := c.controller.apisixClusterConfigInformer.GetIndexer().List()
+	for _, obj := range objs {
+		key, err := cache.MetaNamespaceKeyFunc(obj)
+		if err != nil {
+			log.Errorf("ApisixClusterConfig sync failed, found ApisixClusterConfig resource with bad meta namespace key: %s", err)
+			continue
+		}
+		if !c.controller.isWatchingNamespace(key) {
+			continue
+		}
+		c.workqueue.Add(&types.Event{
+			Type:   types.EventAdd,

Review Comment:
   Why did you choose to use the `types.EventAdd` event type?



##########
test/e2e/suite-ingress/resourcesync.go:
##########
@@ -0,0 +1,216 @@
+// 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 ingress
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"time"
+
+	"github.com/onsi/ginkgo"
+	"github.com/stretchr/testify/assert"
+
+	"github.com/apache/apisix-ingress-controller/pkg/id"
+	"github.com/apache/apisix-ingress-controller/test/e2e/scaffold"
+)
+
+var _ = ginkgo.Describe("suite-ingress: apisix resource sync", func() {
+	opts := &scaffold.Options{
+		Name:                  "default",
+		Kubeconfig:            scaffold.GetKubeconfig(),
+		APISIXConfigPath:      "testdata/apisix-gw-config.yaml",
+		IngressAPISIXReplicas: 1,
+		HTTPBinServicePort:    80,
+		APISIXRouteVersion:    "apisix.apache.org/v2beta3",
+	}
+	s := scaffold.NewScaffold(opts)
+	ginkgo.JustBeforeEach(func() {
+		backendSvc, backendPorts := s.DefaultHTTPBackend()
+		ar := fmt.Sprintf(`
+apiVersion: apisix.apache.org/v2beta3
+kind: ApisixRoute
+metadata:
+ name: httpbin-route
+spec:
+ http:
+ - name: rule1
+   match:
+     hosts:
+     - httpbin.org
+     paths:
+       - /ip
+   backends:
+   - serviceName: %s
+     servicePort: %d
+`, backendSvc, backendPorts[0])
+		assert.Nil(ginkgo.GinkgoT(), s.CreateResourceFromString(ar))
+		err := s.EnsureNumApisixUpstreamsCreated(1)
+		assert.Nil(ginkgo.GinkgoT(), err, "Checking number of upstreams")
+		err = s.EnsureNumApisixRoutesCreated(1)
+		assert.Nil(ginkgo.GinkgoT(), err, "Checking number of routes")
+
+		ing := fmt.Sprintf(`
+apiVersion: extensions/v1beta1

Review Comment:
   please use `networking.k8s.io/v1` apiVersion



##########
test/e2e/suite-ingress/resourcesync.go:
##########
@@ -0,0 +1,216 @@
+// 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 ingress
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"time"
+
+	"github.com/onsi/ginkgo"
+	"github.com/stretchr/testify/assert"
+
+	"github.com/apache/apisix-ingress-controller/pkg/id"
+	"github.com/apache/apisix-ingress-controller/test/e2e/scaffold"
+)
+
+var _ = ginkgo.Describe("suite-ingress: apisix resource sync", func() {
+	opts := &scaffold.Options{
+		Name:                  "default",
+		Kubeconfig:            scaffold.GetKubeconfig(),
+		APISIXConfigPath:      "testdata/apisix-gw-config.yaml",
+		IngressAPISIXReplicas: 1,
+		HTTPBinServicePort:    80,
+		APISIXRouteVersion:    "apisix.apache.org/v2beta3",
+	}
+	s := scaffold.NewScaffold(opts)
+	ginkgo.JustBeforeEach(func() {
+		backendSvc, backendPorts := s.DefaultHTTPBackend()
+		ar := fmt.Sprintf(`
+apiVersion: apisix.apache.org/v2beta3
+kind: ApisixRoute
+metadata:
+ name: httpbin-route
+spec:
+ http:
+ - name: rule1
+   match:
+     hosts:
+     - httpbin.org
+     paths:
+       - /ip
+   backends:
+   - serviceName: %s
+     servicePort: %d
+`, backendSvc, backendPorts[0])
+		assert.Nil(ginkgo.GinkgoT(), s.CreateResourceFromString(ar))
+		err := s.EnsureNumApisixUpstreamsCreated(1)
+		assert.Nil(ginkgo.GinkgoT(), err, "Checking number of upstreams")
+		err = s.EnsureNumApisixRoutesCreated(1)
+		assert.Nil(ginkgo.GinkgoT(), err, "Checking number of routes")
+
+		ing := fmt.Sprintf(`
+apiVersion: extensions/v1beta1
+kind: Ingress
+metadata:
+  annotations:
+    kubernetes.io/ingress.class: apisix
+  name: ingress-extensions-v1beta1
+spec:
+  rules:
+  - host: local.httpbin.org
+    http:
+      paths:
+      - path: /headers
+        pathType: Exact
+        backend:
+          serviceName: %s
+          servicePort: %d
+`, backendSvc, backendPorts[0])
+		assert.Nil(ginkgo.GinkgoT(), s.CreateResourceFromString(ing))
+
+		err = s.ApisixConsumerKeyAuthCreated("foo", "foo-key")
+		assert.Nil(ginkgo.GinkgoT(), err)
+	})
+
+	ginkgo.It("for modified resource sync consistency", func() {
+		// crd resource sync interval
+		readyTime := time.Now().Add(60 * time.Second)
+
+		routes, _ := s.ListApisixRoutes()
+		assert.Len(ginkgo.GinkgoT(), routes, 2)
+
+		consumers, _ := s.ListApisixConsumers()
+		assert.Len(ginkgo.GinkgoT(), consumers, 1)
+
+		for _, route := range routes {
+			_ = s.CreateApisixRouteByApisixAdmin(id.GenID(route.Name), []byte(`
+{
+	"methods": ["GET"],
+	"uri": "/anything",
+	"plugins": {
+		"key-auth": {}
+	},
+	"upstream": {
+		"type": "roundrobin",
+		"nodes": {
+			"httpbin.org": 1
+		}
+	}
+}`))
+		}
+
+		for _, consumer := range consumers {
+			_ = s.CreateApisixConsumerByApisixAdmin([]byte(fmt.Sprintf(`
+{
+	"username": "%s",
+	"plugins": {
+		"key-auth": {
+			"key": "auth-one"
+		}
+	}
+}`, consumer.Username)))
+		}
+
+		_ = s.NewAPISIXClient().
+			GET("/ip").
+			WithHeader("Host", "httpbin.org").
+			Expect().
+			Status(http.StatusNotFound)
+
+		_ = s.NewAPISIXClient().
+			GET("/headers").
+			WithHeader("Host", "local.httpbin.org").
+			Expect().
+			Status(http.StatusNotFound)
+
+		waitTime := time.Until(readyTime).Seconds()
+		time.Sleep(time.Duration(waitTime) * time.Second)
+
+		_ = s.NewAPISIXClient().
+			GET("/ip").
+			WithHeader("Host", "httpbin.org").
+			Expect().
+			Status(http.StatusOK)
+
+		_ = s.NewAPISIXClient().
+			GET("/headers").
+			WithHeader("Host", "local.httpbin.org").
+			Expect().
+			Status(http.StatusOK)
+
+		consumers, _ = s.ListApisixConsumers()

Review Comment:
   I think we should bind key-auth authentication for a route and then verify, what do you think?



-- 
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