Skip to content

Commit

Permalink
Ensure controller is scoped to namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
ibuildthecloud committed Aug 26, 2020
1 parent 9a28dd6 commit 3edc586
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
20 changes: 19 additions & 1 deletion controller/generic_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"strings"
"time"

"k8s.io/apimachinery/pkg/api/meta"

"github.com/rancher/lasso/pkg/controller"

errors2 "github.com/pkg/errors"
Expand All @@ -28,13 +30,15 @@ type genericController struct {
controller controller.SharedController
informer cache.SharedIndexInformer
name string
namespace string
}

func NewGenericController(name string, controller controller.SharedController) GenericController {
func NewGenericController(namespace, name string, controller controller.SharedController) GenericController {
return &genericController{
controller: controller,
informer: controller.Informer(),
name: name,
namespace: namespace,
}
}

Expand All @@ -52,6 +56,9 @@ func (g *genericController) EnqueueAfter(namespace, name string, after time.Dura

func (g *genericController) AddHandler(ctx context.Context, name string, handler HandlerFunc) {
g.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(func(key string, obj runtime.Object) (runtime.Object, error) {
if ok, err := isNamespace(g.namespace, obj); !ok || err != nil {
return obj, err
}
logrus.Tracef("%s calling handler %s %s", g.name, name, key)
metrics.IncTotalHandlerExecution(g.name, name)
result, err := handler(key, obj)
Expand All @@ -67,6 +74,17 @@ func (g *genericController) AddHandler(ctx context.Context, name string, handler
}))
}

func isNamespace(namespace string, obj runtime.Object) (bool, error) {
if namespace == "" {
return true, nil
}
meta, err := meta.Accessor(obj)
if err != nil {
return false, err
}
return meta.GetNamespace() == namespace, nil
}

func ignoreError(err error, checkString bool) bool {
err = errors2.Cause(err)
if errors.IsConflict(err) {
Expand Down
2 changes: 1 addition & 1 deletion generator/controller_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func (c {{.schema.ID}}Factory) List() runtime.Object {
}
func (s *{{.schema.ID}}Client) Controller() {{.schema.CodeName}}Controller {
genericController := controller.NewGenericController({{.schema.CodeName}}GroupVersionKind.Kind+"Controller",
genericController := controller.NewGenericController(s.ns, {{.schema.CodeName}}GroupVersionKind.Kind+"Controller",
s.client.controllerFactory.ForResourceKind({{.schema.CodeName}}GroupVersionResource, {{.schema.CodeName}}GroupVersionKind.Kind, {{.schema | namespaced}}))
return &{{.schema.ID}}Controller{
Expand Down

0 comments on commit 3edc586

Please sign in to comment.