Skip to content

Commit

Permalink
feat: consumer controller loop (#516)
Browse files Browse the repository at this point in the history
  • Loading branch information
tao12345666333 committed Jun 2, 2021
1 parent 3337be7 commit f6cb4f9
Show file tree
Hide file tree
Showing 11 changed files with 384 additions and 4 deletions.
2 changes: 2 additions & 0 deletions pkg/apisix/apisix.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ type Cluster interface {
String() string
// HasSynced checks whether all resources in APISIX cluster is synced to cache.
HasSynced(context.Context) error
// Consumer returns a Consumer interface that can operate Consumer resources.
Consumer() Consumer
// HealthCheck checks apisix cluster health in realtime.
HealthCheck(context.Context) error
}
Expand Down
5 changes: 5 additions & 0 deletions pkg/apisix/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,11 @@ func (c *cluster) GlobalRule() GlobalRule {
return c.globalRules
}

// Consumer implements Cluster.Consumer method.
func (c *cluster) Consumer() Consumer {
return c.consumer
}

// HealthCheck implements Cluster.HealthCheck method.
func (c *cluster) HealthCheck(ctx context.Context) (err error) {
if c.cacheSyncErr != nil {
Expand Down
28 changes: 28 additions & 0 deletions pkg/apisix/nonexistentclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func newNonExistentCluster() *nonExistentCluster {
upstream: &dummyUpstream{},
streamRoute: &dummyStreamRoute{},
globalRule: &dummyGlobalRule{},
consumer: &dummyConsumer{},
},
}
}
Expand All @@ -44,6 +45,7 @@ type embedDummyResourceImplementer struct {
upstream Upstream
streamRoute StreamRoute
globalRule GlobalRule
consumer Consumer
}

type dummyRoute struct{}
Expand Down Expand Up @@ -156,6 +158,28 @@ func (f *dummyGlobalRule) Update(_ context.Context, _ *v1.GlobalRule) (*v1.Globa
return nil, ErrClusterNotExist
}

type dummyConsumer struct{}

func (f *dummyConsumer) Get(_ context.Context, _ string) (*v1.Consumer, error) {
return nil, ErrClusterNotExist
}

func (f *dummyConsumer) List(_ context.Context) ([]*v1.Consumer, error) {
return nil, ErrClusterNotExist
}

func (f *dummyConsumer) Create(_ context.Context, _ *v1.Consumer) (*v1.Consumer, error) {
return nil, ErrClusterNotExist
}

func (f *dummyConsumer) Delete(_ context.Context, _ *v1.Consumer) error {
return ErrClusterNotExist
}

func (f *dummyConsumer) Update(_ context.Context, _ *v1.Consumer) (*v1.Consumer, error) {
return nil, ErrClusterNotExist
}

func (nc *nonExistentCluster) Route() Route {
return nc.route
}
Expand All @@ -176,6 +200,10 @@ func (nc *nonExistentCluster) GlobalRule() GlobalRule {
return nc.globalRule
}

func (nc *nonExistentCluster) Consumer() Consumer {
return nc.consumer
}

func (nc *nonExistentCluster) HasSynced(_ context.Context) error {
return nil
}
Expand Down
223 changes: 223 additions & 0 deletions pkg/ingress/apisix_consumer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// 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 (
"context"
"time"

"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"

configv2alpha1 "github.com/apache/apisix-ingress-controller/pkg/kube/apisix/apis/config/v2alpha1"
"github.com/apache/apisix-ingress-controller/pkg/log"
"github.com/apache/apisix-ingress-controller/pkg/types"
)

type apisixConsumerController struct {
controller *Controller
workqueue workqueue.RateLimitingInterface
workers int
}

func (c *Controller) newApisixConsumerController() *apisixConsumerController {
ctl := &apisixConsumerController{
controller: c,
workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.NewItemFastSlowRateLimiter(1*time.Second, 60*time.Second, 5), "ApisixConsumer"),
workers: 1,
}
ctl.controller.apisixConsumerInformer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: ctl.onAdd,
UpdateFunc: ctl.onUpdate,
DeleteFunc: ctl.onDelete,
},
)
return ctl
}

func (c *apisixConsumerController) run(ctx context.Context) {
log.Info("ApisixConsumer controller started")
defer log.Info("ApisixConsumer controller exited")
if ok := cache.WaitForCacheSync(ctx.Done(), c.controller.apisixConsumerInformer.HasSynced); !ok {
log.Error("cache sync failed")
return
}
for i := 0; i < c.workers; i++ {
go c.runWorker(ctx)
}
<-ctx.Done()
c.workqueue.ShutDown()
}

func (c *apisixConsumerController) 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 *apisixConsumerController) sync(ctx context.Context, ev *types.Event) error {
key := ev.Object.(string)
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
log.Errorf("found ApisixConsumer resource with invalid meta namespace key %s: %s", key, err)
return err
}

ac, err := c.controller.apisixConsumerLister.ApisixConsumers(namespace).Get(name)
if err != nil {
if !k8serrors.IsNotFound(err) {
log.Errorf("failed to get ApisixConsumer %s: %s", key, err)
return err
}
if ev.Type != types.EventDelete {
log.Warnf("ApisixConsumer %s was deleted before it can be delivered", key)
// Don't need to retry.
return nil
}
}
if ev.Type == types.EventDelete {
if ac != 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 ApisixConsumer delete event since the %s exists", key)
return nil
}
ac = ev.Tombstone.(*configv2alpha1.ApisixConsumer)
}

consumer, err := c.controller.translator.TranslateApisixConsumer(ac)
if err != nil {
log.Errorw("failed to translate ApisixConsumer",
zap.Error(err),
zap.Any("ApisixConsumer", ac),
)
c.controller.recorderEvent(ac, corev1.EventTypeWarning, _resourceSyncAborted, err)
c.controller.recordStatus(ac, _resourceSyncAborted, err, metav1.ConditionFalse)
return err
}
log.Debug("got consumer object from ApisixConsumer",
zap.Any("consumer", consumer),
zap.Any("ApisixConsumer", ac),
)

if err := c.controller.syncConsumer(ctx, consumer, ev.Type); err != nil {
log.Errorw("failed to sync Consumer to APISIX",
zap.Error(err),
zap.Any("consumer", consumer),
)
c.controller.recorderEvent(ac, corev1.EventTypeWarning, _resourceSyncAborted, err)
c.controller.recordStatus(ac, _resourceSyncAborted, err, metav1.ConditionFalse)
return err
}

c.controller.recorderEvent(ac, corev1.EventTypeNormal, _resourceSynced, nil)
return nil
}

func (c *apisixConsumerController) handleSyncErr(obj interface{}, err error) {
if err == nil {
c.workqueue.Forget(obj)
return
}
log.Warnw("sync ApisixConsumer failed, will retry",
zap.Any("object", obj),
zap.Error(err),
)
c.workqueue.AddRateLimited(obj)
}

func (c *apisixConsumerController) onAdd(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
log.Errorf("found ApisixConsumer resource with bad meta namespace key: %s", err)
return
}
if !c.controller.namespaceWatching(key) {
return
}
log.Debugw("ApisixConsumer add event arrived",
zap.Any("object", obj),
)

c.workqueue.AddRateLimited(&types.Event{
Type: types.EventAdd,
Object: key,
})
}

func (c *apisixConsumerController) onUpdate(oldObj, newObj interface{}) {
prev := oldObj.(*configv2alpha1.ApisixConsumer)
curr := newObj.(*configv2alpha1.ApisixConsumer)
if prev.ResourceVersion >= curr.ResourceVersion {
return
}
key, err := cache.MetaNamespaceKeyFunc(newObj)
if err != nil {
log.Errorf("found ApisixConsumer resource with bad meta namespace key: %s", err)
return
}
if !c.controller.namespaceWatching(key) {
return
}
log.Debugw("ApisixConsumer update event arrived",
zap.Any("new object", curr),
zap.Any("old object", prev),
)

c.workqueue.AddRateLimited(&types.Event{
Type: types.EventUpdate,
Object: key,
})
}

func (c *apisixConsumerController) onDelete(obj interface{}) {
ac, ok := obj.(*configv2alpha1.ApisixConsumer)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
return
}
ac = tombstone.Obj.(*configv2alpha1.ApisixConsumer)
}

key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err != nil {
log.Errorf("found ApisixConsumer resource with bad meta namespace key: %s", err)
return
}
if !c.controller.namespaceWatching(key) {
return
}
log.Debugw("ApisixConsumer delete event arrived",
zap.Any("final state", ac),
)
c.workqueue.AddRateLimited(&types.Event{
Type: types.EventDelete,
Object: key,
Tombstone: ac,
})
}
26 changes: 24 additions & 2 deletions pkg/ingress/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ type Controller struct {
apisixTlsInformer cache.SharedIndexInformer
apisixClusterConfigLister listersv2alpha1.ApisixClusterConfigLister
apisixClusterConfigInformer cache.SharedIndexInformer
apisixConsumerInformer cache.SharedIndexInformer
apisixConsumerLister listersv2alpha1.ApisixConsumerLister

// resource controllers
podController *podController
Expand All @@ -114,6 +116,7 @@ type Controller struct {
apisixRouteController *apisixRouteController
apisixTlsController *apisixTlsController
apisixClusterConfigController *apisixClusterConfigController
apisixConsumerController *apisixConsumerController
}

// NewController creates an ingress apisix controller object.
Expand Down Expand Up @@ -164,7 +167,8 @@ func NewController(cfg *config.Config) (*Controller, error) {
watchingNamespace: watchingNamespace,
secretSSLMap: new(sync.Map),
recorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: _component}),
podCache: types.NewPodCache(),

podCache: types.NewPodCache(),
}
return c, nil
}
Expand Down Expand Up @@ -235,6 +239,7 @@ func (c *Controller) initWhenStartLeading() {
c.apisixClusterConfigController = c.newApisixClusterConfigController()
c.apisixTlsController = c.newApisixTlsController()
c.secretController = c.newSecretController()
c.apisixConsumerController = c.newApisixConsumerController()
}

// recorderEvent recorder events for resources
Expand Down Expand Up @@ -411,6 +416,9 @@ func (c *Controller) run(ctx context.Context) {
c.goAttach(func() {
c.apisixTlsInformer.Run(ctx.Done())
})
c.goAttach(func() {
c.apisixConsumerInformer.Run(ctx.Done())
})
c.goAttach(func() {
c.podController.run(ctx)
})
Expand All @@ -435,6 +443,9 @@ func (c *Controller) run(ctx context.Context) {
c.goAttach(func() {
c.secretController.run(ctx)
})
c.goAttach(func() {
c.apisixConsumerController.run(ctx)
})

c.metricsCollector.ResetLeader(true)

Expand All @@ -456,7 +467,7 @@ func (c *Controller) namespaceWatching(key string) (ok bool) {
}
ns, _, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
// Ignore resource pkg/types/apisix/v1/plugin_types.gowith invalid key.
// Ignore resource with invalid key.
ok = false
log.Warnf("resource %s was ignored since: %s", key, err)
return
Expand All @@ -480,6 +491,17 @@ func (c *Controller) syncSSL(ctx context.Context, ssl *apisixv1.Ssl, event types
return err
}

func (c *Controller) syncConsumer(ctx context.Context, consumer *apisixv1.Consumer, event types.EventType) (err error) {
clusterName := c.cfg.APISIX.DefaultClusterName
if event == types.EventDelete {
err = c.apisix.Cluster(clusterName).Consumer().Delete(ctx, consumer)
} else if event == types.EventUpdate {
_, err = c.apisix.Cluster(clusterName).Consumer().Update(ctx, consumer)
} else {
_, err = c.apisix.Cluster(clusterName).Consumer().Create(ctx, consumer)
}
return
}
func (c *Controller) checkClusterHealth(ctx context.Context, cancelFunc context.CancelFunc) {
defer cancelFunc()
for {
Expand Down
Loading

0 comments on commit f6cb4f9

Please sign in to comment.